branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import React from "react"; import "./EditView.css"; class EditView extends React.Component { render() { return ( <div className="new-container"> <h5 className="edit-header">Edit Note: </h5> <form className="note-form" onSubmit={this.props.onSubmit}> <div> <input type="text" placeholder="Note Title" name="title" value={this.props.title} onChange={this.props.onChange} className="title-input" /> </div> <div> <textarea type="text" placeholder="Note Content" name="content" value={this.props.content} onChange={this.props.onChange} className="content-input" /> </div> <div> <button type="submit" className="edit-button" > Update </button> </div> </form> </div> ); } } export default EditView; <file_sep>import React from "react"; import NoteCard from "./NoteCard"; const NoteView = props => { return ( <div> <button>edit</button> <button>delete</button> <h5>{props.title}</h5> <p>{props.content}</p> </div> ); }; export default NoteView; <file_sep>import React from "react"; import { Link } from "react-router-dom"; // import ListView from "./ListView"; // import CreateView from "./CreateView"; import "./SideNav.css"; const SideNav = () => { return ( <div className="side-container"> <h2 className="title">Lambda Notes</h2> <div className="side-buttons"> <Link to="/"> <button className="view-button">View Your Notes</button> </Link> <Link to="/create"> <button className="create-button">+ Create New Note</button> </Link> </div> </div> ); }; export default SideNav; <file_sep>import React from "react"; import NoteCard from "./NoteCard"; import "./ListView.css"; const ListView = props => { return ( <div className="note-container"> <h5 className="list-header">Your Notes: </h5> <ul> {props.notes.map((note, i) => { return <NoteCard key={i} notes={note} />; })} </ul> </div> ); }; export default ListView; <file_sep>import React, { Component } from "react"; import "./CreateView.css"; class CreateView extends Component { render() { return ( <div className="new-container"> <h5 className="create-header">Create New Note: </h5> <form className="note-form" onSubmit={this.props.onSubmit}> <div> <input type="text" placeholder="Note Title" name="title" value={this.props.title} onChange={this.props.onChange} className="title-input" /> </div> <div> <textarea type="text" placeholder="Note Content" name="content" value={this.props.content} onChange={this.props.onChange} className="content-input" /> </div> <div> <button type="submit" className="save-button"> Save </button> </div> </form> </div> ); } } export default CreateView; <file_sep>import React from "react"; import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom"; import SideNav from "./components/SideNav"; import ListView from "./components/ListView"; import CreateView from "./components/CreateView"; import NoteView from "./components/NoteView"; import EditView from "./components/EditView"; import DeleteView from "./components/DeleteModal"; import "./App.css"; class App extends React.Component { constructor(props) { super(props); this.state = { title: "", content: "", notes: [] }; } noteHandler = e => { this.setState({ [e.target.name]: e.target.value }); }; submitNewNote = e => { e.preventDefault(); const notes = [ ...this.state.notes, { title: this.state.title, content: this.state.content } ]; // notes.push(myNotes); this.setState({ notes, title: "", content: "" }); }; updateNote = e => { e.preventDefault(); const { notes } = this.state; const updatedNote = { title: this.state.title.id, content: this.state.title.id }; notes.push(updatedNote); this.setState({ notes, updatedNote: "" }); }; // deleteModal = e => {} render() { return ( <Router> <div> <SideNav /> <div> <CreateView title={this.state.title} content={this.state.content} notes={this.state.notes} onChange={this.noteHandler} onSubmit={this.submitNewNote} /> <ListView notes={this.state.notes} /> <NoteView /> <EditView /> <DeleteView /> </div> {/* <Route exact path="/" component={ListView} /> */} <Route path="/create" component={CreateView} /> </div> </Router> ); } } export default App;
e673a121a5ca044a637abc329a00afc2b2952243
[ "JavaScript" ]
6
JavaScript
Davidless/front-end-project-week
5d687f3b4509872b815174ddf1031be783068e8b
ede70cfbe4f47b8af52a2fdb4e3d66f81ce0bf43
refs/heads/master
<file_sep><? include_once 'harness/include.php'; class api_student_Edit extends WebTestCase { function setUp() { $this->POST = array('name' => '<NAME>', 'major' => 'Math', 'GPA' => '3.3', 'id' => 1); Db::query("INSERT INTO student SET name = '<NAME>',". "major = 'CS',". "GPA = '3.1',". "id = 1"); } function tearDown() { Db::query("DELETE FROM student WHERE id = 1"); } function testSuccess() { $this->post( Prop::inst()->utRoot."/api/student/edit", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['major'], 'Math'); $this->assertEqual($STUDENT['GPA'], '3.3'); } function testEmptyName() { $this->POST['name'] = ''; $this->post(Prop::inst()->utRoot."/api/student/edit", json_encode($this->POST)); $this->assertText('{"status":"error"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], '<NAME>'); } function testEmptyMajor() { $this->POST['major'] = ''; $this->post(Prop::inst()->utRoot."/api/student/edit", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); //StrUtil::echo($STUDENT, 'STUDENT'); $this->assertEqual($STUDENT['major'], ''); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['GPA'], '3.3'); } function testEmptyGPA() { $this->POST['GPA'] = ''; $this->post(Prop::inst()->utRoot."/api/student/edit", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); //StrUtil::echo($STUDENT, 'STUDENT'); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['major'], 'Math'); $this->assertEqual($STUDENT['GPA'], 0.0); } } HrTools::run(new api_student_Edit()); ?><file_sep><? class Edit extends JsonResponse { /* [{ * "name": "<NAME>", * "major": "CS", * "GPA": "3.1", * "id": "23" * }] * ------------------------- */ public function __construct($oPost) { $this->oPost = $oPost; } function main() { $this->updateValues(); $this->echoStatus(); } function updateValues() { try { Assert::false(empty($this->oPost->name), 'name is empty'); Db::query("UPDATE student SET name = '".Db::esc($this->oPost->name) ."',". "major = '".Db::esc($this->oPost->major)."',". "GPA = '".Db::esc($this->oPost->GPA) ."' ". "WHERE id = ".$this->oPost->id); } catch (Exception $ex) { echo $ex->asStr(); $this->setError("error in Create::saveValues()"); } } } ?><file_sep>import { shallowMount } from '@vue/test-utils' import { mount } from '@vue/test-utils' import Home from '@/views/Home.vue' describe('Home test suite', () => { // test('sanity test true', () => { // expect(true).toBe(true) // }) // test('sanity test false', () => { // expect(false).toBe(false) // }) // test('show button', () => { // const wrapper = mount(Home) // expect(wrapper.find('button').isVisible()).toBe(false) // }) // test('show ', () => { // const wrapper = mount(Home) // expect(wrapper.html()).toContain('button') // }) test('conditionally show Vuetify logo', async () => { const wrapper = mount(Home) wrapper.setData({ bShowLogo: false }) await wrapper.vm.$nextTick() expect(wrapper.find('button').isVisible()).toBe(false) }) }) <file_sep><? include_once 'harness/include.php'; class api_student_Delete extends WebTestCase { function setUp() { $this->POST = array('id' => 1); Db::query("INSERT INTO student SET name = '<NAME>',". "major = 'CS',". "GPA = '3.1',". "id = 1"); } function tearDown() { Db::query("DELETE FROM student WHERE id = 1"); } function testSuccess() { $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['id'], 1); $this->post( Prop::inst()->utRoot."/api/student/delete", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertTrue(empty($STUDENT)); } function testNoneExistingId() { $this->POST = array('id' => 456); $this->post( Prop::inst()->utRoot."/api/student/delete", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE id = 1"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['major'], 'CS'); $this->assertEqual($STUDENT['GPA'], '3.1'); } } HrTools::run(new api_student_Delete()); ?><file_sep><? class Delete extends JsonResponse { /* [{ * "id": "232" * }] * ------------------------- */ public function __construct($oPost) { $this->oPost = $oPost; } function main() { $this->deleteStudent(); $this->echoStatus(); } function deleteStudent() { try { Assert::false(empty($this->oPost->id), 'id is empty'); Db::query("DELETE FROM student WHERE id = ".$this->oPost->id); } catch (Exception $ex) { echo $ex->asStr(); $this->setError("error in Delete()"); } } } ?><file_sep>import Vue from 'vue' const store = Vue.observable({ /* --- state variables --- */ id: '', name: '', major: '', GPA: '', students: [], /* --- methods ---- */ getStudent(id) { for (var index = 0; index < this.students.length; index++) { if (id == this.students[index].id) { console.log('found student='+this.students[index]); return this.students[index] } } }, deleteStudent(id) { for (var i = 0; i < this.students.length; i++) { if (this.students[i].id == id) { this.students.splice(i, 1); } } } }) export default store;<file_sep><? class Json { const SESSION_ID_NAME = 'UD5fxQ'; // use to preserve the session when redirecting from localhost:8080 -> 127.0.0.1 protected $status = 'success'; protected $errmsg = ''; public function getPostAsObj() { /* The data/properties from the HTTP POST arrive in form or json encoded strings. * Retrieve the data from the HTTP POST and convert it into an object. * ------------------------------------------------------------------- */ $rawJsonData = file_get_contents('php://input'); $oDecodedJsonData = json_decode($rawJsonData); // Debug::echo(StrUtil::asStr($oDecodedJsonData, 'api received POST')); return $oDecodedJsonData; } public function setError($errmsg) { /* Sets the * 1) status to error and the * 2) error string for use in status reporting * ------------------------------------------- */ $this->status = 'error'; $this->errmsg .= StrUtil::exConcat($this->errmsg, ' - ', $errmsg); } public function echoStatus() { /* Echo the * 1) status and * 2) error message unless status is success. * ------------------------------------------ */ if ($this->status == 'success') { $aReturnStatus = array('status' => 'success', self::SESSION_ID_NAME => session_id()); echo json_encode($aReturnStatus); } else { $this->echoError(); } } public function echoResponse($RESPONSE) { if ($this->status == 'success') { //header('x-total-count: '.count($RESPONSE)); echo json_encode($RESPONSE); } else { $this->echoError(); } } private function echoError() { $aReturnStatus = array('status' => 'error', 'errmsg' => $this->errmsg); echo json_encode($aReturnStatus); } } ?> <file_sep><? class Create extends JsonResponse { /* [{ * "name": "<NAME>", * "major": "CS", * "GPA": "3.1" * }] * ------------------------- */ public function __construct($oPost) { $this->oPost = $oPost; } function main() { $this->saveValues(); $this->echoStatus(); } function saveValues() { try { Assert::false(empty($this->oPost->name), 'name is empty'); Db::query("INSERT INTO student SET name = '".Db::esc($this->oPost->name) ."',". "major = '".Db::esc($this->oPost->major)."',". "GPA = '".Db::esc($this->oPost->GPA) ."' "); } catch (Exception $ex) { //echo $ex->asStr(); $this->setError("error in Create::saveValues()"); } } } ?><file_sep>import { mount } from '@vue/test-utils' import Vue from "vue"; import Vuetify from "vuetify"; Vue.config.productionTip = false; Vue.use(Vuetify); import Menu from '@/components/Menu.vue' describe('Menu test suite', () => { test('#1 - click create button', async () => { const wrapper = mount(Menu) const button = wrapper.find('[data-testid="create-button"]') button.trigger('click') await wrapper.vm.$nextTick() expect(wrapper.html()).toContain("Enter new student's data") }) }) <file_sep><? class JsonResponse { const SESSION_ID_NAME = 'UD5fxQ'; // use to preserve the session when redirecting from localhost:8080 -> 127.0.0.1 protected $status = 'success'; protected $errmsg = ''; public function setError($errmsg) { /* Sets the * 1) status to error and the * 2) error string for use in status reporting * ------------------------------------------- */ $this->status = 'error'; $this->errmsg = StrUtil::exConcat($this->errmsg, ' - ', $errmsg); } public function echoStatus() { /* Echo the * 1) status and * 2) error message unless status is success. * ------------------------------------------ */ if ($this->status == 'success') { $aReturnStatus = array('status' => 'success', self::SESSION_ID_NAME => session_id()); echo json_encode($aReturnStatus); } else { $this->echoError(); } } public function echoResponse($RESPONSE) { if ($this->status == 'success') { //header('x-total-count: '.count($RESPONSE)); echo json_encode($RESPONSE); } else { $this->echoError(); } } private function echoError() { $aReturnStatus = array('status' => 'error', 'errmsg' => $this->errmsg); echo json_encode($aReturnStatus); } } ?> <file_sep><? include_once 'harness/include.php'; class api_student_ListAll extends WebTestCase { function setUp() { Db::query("INSERT INTO student SET name = '<NAME>',". "major = 'CS',". "GPA = '3.1',". "id = 1"); } function tearDown() { Db::query("TRUNCATE TABLE student"); } function testSuccess() { $this->get( Prop::inst()->utRoot."/api/student/list"); $this->assertText('{"id":"1"'); $this->assertText('"name":"<NAME>"'); $this->assertText('"major":"CS"'); } function testNonStudentInDB() { Db::query("TRUNCATE TABLE student"); $this->get( Prop::inst()->utRoot."/api/student/list"); $this->assertNoText(' '); } } HrTools::run(new api_student_ListAll()); ?> <file_sep><? include 'api/Json.php'; include 'api/JsonPost.php'; include 'api/JsonResponse.php'; include 'api/ApiDispatcher.php'; include 'api/reg/PrimeLocation.php'; include 'api/reg/ExtraLocations.php'; include 'api/login/ApiLogin.php'; include 'api/post/Post.php'; include 'api/post/Neu.php'; include 'api/post/App.php'; include 'api/post/AppId.php'; include 'api/post/Place.php'; include 'api/post/Begin.php'; include 'api/post/Frequency.php'; include 'api/post/HourlyPay.php'; include 'api/post/PaymentOption.php'; include 'api/post/MeetingType.php'; include 'api/post/Subject.php'; include 'api/post/Location.php'; include 'api/post/Message.php'; include 'api/post/Name.php'; include 'api/post/Email.php'; include 'api/post/Phone.php'; include 'api/post/Callback.php'; include 'api/post/MatchPermit.php'; include 'api/post/Complete.php'; include 'api/student/Student.php'; include 'api/student/Create.php'; include 'api/student/Edit.php'; include 'api/student/Delete.php'; include 'api/student/ListAll.php'; include 'api/rwv/RealWorldView.php'; include 'api/rwv/PersistentEvents.php'; ?><file_sep><? class ListAll extends JsonResponse { /* GET /api/student/list * [ * {"id":"1","name":"<NAME>","major":"CS","GPA","3.1"}, * {"id":"2","name":"<NAME>","major":"Math","GPA","3.3"}, * ... * ] * ----------------------------------------------------------- */ public function main() { try { $recs = Db::query("SELECT * FROM student"); $aSTUDENT = Db::fetchAll($recs); $this->echoResponse($aSTUDENT); } catch (Exception $ex) { echo $ex->asStr(); $this->setError("error in Get::fetchStudents()"); } } } ?><file_sep><? header('content-type: application/json; charset=utf-8'); header('Access-Control-Allow-Origin: *'); // avoid 'blocked by CORS policy' in GET header('Access-Control-Allow-Headers: *'); // avoid 'blocked by CORS policy' in POST include 'core/init/init.php'; include 'sys/tor/TorPrimeLocation.php'; include 'sys/tor/TorExtraLocation.php'; include 'sys/job/JobLocationRefinery.php'; include 'sys/tee/TeeImporter.php'; include 'sys/mail/include.php'; include 'api/include.php'; $apiDispatcher = new ApiDispatcher(); $apiDispatcher->run(); ?><file_sep><? class Student extends JsonPost { /* Dispatches the API calls for the /student API * --------------------------------------------- */ function list() { /* fetches all entries in table student for listing. * ---------------------------------------------- */ Debug::echo("GET /api/student/list"); $listAll = new ListAll(); $listAll->main(); } function create() { /* creates a new student entries. * ---------------------------------------------- */ Debug::echo("POST /api/student/create"); $create = new Create($this->postAsObj()); $create->main(); } function edit() { /* edits a student entry. * ---------------------------------------------- */ Debug::echo("POST /api/student/edit"); $edit = new Edit($this->postAsObj()); $edit->main(); } function delete() { /* deletes a student entry. * ---------------------------------------------- */ Debug::echo("POST /api/student/delete"); $delete = new Delete($this->postAsObj()); $delete->main(); } } ?><file_sep>import { shallowMount } from '@vue/test-utils' import { mount } from '@vue/test-utils' import Vue from "vue"; import Vuetify from "vuetify"; Vue.config.productionTip = false; Vue.use(Vuetify); import { getByText, getByTestId, } from '@testing-library/jest-dom' import Home from '@/views/Home.vue' describe('Home test suite', () => { // test('sanity test true', () => { // expect(true).toBe(true) // }) // test('sanity test false', () => { // expect(false).toBe(false) // }) // test('show button', () => { // const wrapper = mount(Home) // expect(wrapper.find('button').isVisible()).toBe(false) // }) // test('show ', () => { // const wrapper = mount(Home) // expect(wrapper.html()).toContain('button') // }) //#1 - isVisible is depricated // test('conditionally turn button off', async () => { // const wrapper = mount(Home) // wrapper.setData({ bShowLogo: false }) // await wrapper.vm.$nextTick() // expect(wrapper.find('button').isVisible()).toBe(false) // }) // #2 - getByText // test('jest-dom', () => { // const wrapper = mount(Home) // expect(getByText("<span>Dave</span>")).isVisible() // }) // #3 - getByTestId // test('jest-dom', () => { // const wrapper = mount(Home) // expect(getByTestId('button')).toBeVisible() // }) // #4 findComponent // test('conditionally turn button off - findComponent', async () => { // const wrapper = mount(Home) // const home = wrapper.findComponent(Home) // expect(home.exists()).toBe(true) // // does not work - expect(home.button.exists()).toBe(true) // }) }) <file_sep><? header('content-type: application/json; charset=utf-8'); header('Access-Control-Allow-Origin: *'); // avoid 'blocked by CORS policy' in GET header('Access-Control-Allow-Headers: *'); // avoid 'blocked by CORS policy' in POST include 'core/init/init.php'; include 'api/JsonResponse.php'; $call = $_GET['call']; if (empty($call)) { $errmsg = "no api call given"; } else { $errmsg = "no such api call '$call'"; } $jsonResponse = new JsonResponse(); $jsonResponse->setError($errmsg); $jsonResponse->echoStatus(); ?><file_sep>import axios from 'axios' import store from '@/store.js' const apiClient = axios.create({ baseURL: 'http://127.0.0.1/api/student', withCredentials: false, headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }) export default { /* --------------------------------------------------------------- * gets all students to list * --------------------------------------------------------------- */ async list() { try { // console.log('apiClient::list()') const response = await apiClient.get('/list') if (response.data.status == 'error') { console.log("axios response.status='error' upon GET /list. errmsg='" + response.data.errmsg+"'") } else { // console.log("response: " + JSON.stringify(response)) store.students = response.data console.log("success GET /list") } } catch (error) { console.log("Caught exception in GET /list " + error.response) } }, /* ------------------- * POST create * ------------------- */ async create() { try { let payload = { name: store.name, major: store.major, GPA: store.GPA } console.log('apiClient.create()') const response = await apiClient.post('/create', payload) // console.log("response: " + JSON.stringify(response)) if (response.data.status == 'error') { console.log("axios response.status='error' upon POST /create. errmsg='" + response.data.errmsg+"'") console.log("response: " + JSON.stringify(response)) } else { console.log('success POST /create') } } catch (error) { console.log("Caught exception in POST /create: " + error.response) } }, /* ------------------- * POST edit * ------------------- */ async edit() { try { let payload = { id: store.id, name: store.name, major: store.major, GPA: store.GPA } const response = await apiClient.post('/edit', payload) if (response.data.status == 'error') { console.log("axios response.status='error' upon POST /edit. errmsg='" + response.data.errmsg+"'") console.log("response: " + JSON.stringify(response)) } else { console.log('success POST /edit') } } catch (error) { console.log("Caught exception in POST /edit: " + error.response) } }, /* ------------------- * POST delete * ------------------- */ async delete(id) { try { console.log('apiClient::delete() id='+id) let payload = { id: id } const response = await apiClient.post('/delete', payload) if (response.data.status == 'error') { console.log("axios response.status='error' upon POST /delete. errmsg='" + response.data.errmsg+"'") console.log("response: " + JSON.stringify(response)) } else { console.log('success POST /delete') } } catch(error) { console.log("Error posting /delete. " + error.response) } } } <file_sep><? include_once 'simpletest/unit_tester.php'; $suite = new TestSuite(); $suite->addFile('api/student/ut/utCreate.php'); $suite->addFile('api/student/ut/utEdit.php'); $suite->addFile('api/student/ut/utDelete.php'); $suite->addFile('api/student/ut/utListAll.php'); ?> <file_sep><? class JsonPost { public function postAsObj() { /* The data/properties from the HTTP POST arrive in form or json encoded strings. * Retrieve the data from the HTTP POST and convert it into an object. * ------------------------------------------------------------------- */ $rawPostData = file_get_contents('php://input'); $oPostData = json_decode($rawPostData); Debug::echo(StrUtil::asStr($oPostData, 'POST')); return $oPostData; } } ?> <file_sep><? include_once 'harness/include.php'; class api_student_Create extends WebTestCase { function setUp() { $this->POST = array('name' => '<NAME>', 'major' => 'CS', 'GPA' => '3.1'); } function tearDown() { Db::query("DELETE FROM student WHERE name = '<NAME>'"); } function testSuccess() { $this->post( Prop::inst()->utRoot."/api/student/create", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE name = '<NAME>'"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['major'], 'CS'); $this->assertEqual($STUDENT['GPA'], '3.1'); } function testEmptyName() { $this->POST['name'] = ''; $this->post(Prop::inst()->utRoot."/api/student/create", json_encode($this->POST)); $this->assertText('{"status":"error"'); $this->assertText('error in Create::saveValues()'); $rec = Db::query("SELECT * FROM student WHERE name = ''"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], ''); } function testEmptyMajor() { $this->POST['major'] = ''; $this->post(Prop::inst()->utRoot."/api/student/create", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE name = '<NAME>'"); $STUDENT = mysqli_fetch_assoc($rec); //StrUtil::echo($STUDENT, 'STUDENT'); $this->assertEqual($STUDENT['major'], ''); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['GPA'], '3.1'); } function testGPA() { $this->POST['GPA'] = ''; $this->post(Prop::inst()->utRoot."/api/student/create", json_encode($this->POST)); $this->assertText('{"status":"success"'); $rec = Db::query("SELECT * FROM student WHERE name = '<NAME>'"); $STUDENT = mysqli_fetch_assoc($rec); $this->assertEqual($STUDENT['name'], '<NAME>'); $this->assertEqual($STUDENT['major'], 'CS'); $this->assertEqual($STUDENT['GPA'], 0.0); } } HrTools::run(new api_student_Create()); ?>
b94cc072654f13dca16f2775d1fe6b98a0af1684
[ "JavaScript", "PHP" ]
21
PHP
wagiboy/student-mgm-in-vue
6b1a167f5c5ebf0b6aef236831df161b07e962c9
9c88eb660305dc0b28e76903ce545b58d2400c73
refs/heads/master
<repo_name>walterdis/oop4fun<file_sep>/index.php <?php require_once 'vendor/autoload.php'; $pizzaFactory = new \Pizza\Brazil\BrazilPizzaFactory(); $store = new \Store\PizzaStore($pizzaFactory); $store->order('garlic'); echo '<hr />'; $store->order('oyster'); <file_sep>/src/Pizza/AbstractPizza.php <?php namespace Pizza; use Pizza\Ingredient\AbstractIngredient; use Store\Cook; abstract class AbstractPizza { /** * @var PizzaIngredientFactoryInterface */ private $ingredientFactory; /** * @var String */ private $name; /** * @var AbstractIngredient */ private $dough; /** * @var AbstractIngredient */ private $sauce; /** * @var AbstractIngredient */ private $cheese; /** * @var \Store\Cook */ private $cook; private $toppings = array() ; public function __construct() { $this->cook = new Cook(); $this->cook->setBakingMinute(1); $this->cook->setBakingSecond(10); } /** * @return void */ public function prepare() { $dough = $this->getIngredientFactory()->createDough(); $this->setDough($dough); $sauce = $this->getIngredientFactory()->createSauce(); $this->setSauce($sauce); $cheese = $this->getIngredientFactory()->createCheese(); $this->setCheese($cheese); echo 'Dough: <strong>'.$this->getDough()->getName().'</strong><br />'; echo 'Sauce: <strong>'.$this->getSauce()->getName().'</strong><br />'; echo 'Cheese: <strong>'.$this->getCheese()->getName().'</strong><br /><br />'; } public function bake() { $this->cook->bake(); } public function cut() { echo 'Cutting pizza <br />'; } public function box() { echo 'Boxing pizza <br />'; } /** * @return String */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name = '') { $this->name = $name; } /** * @return \Store\Cook */ public function getCook() { return $this->cook; } /** * @param AbstractIngredient $cheese */ public function setCheese(AbstractIngredient $cheese) { $this->cheese = $cheese; } /** * @return AbstractIngredient */ public function getCheese() { return $this->cheese; } /** * @param AbstractIngredient $dough */ public function setDough(AbstractIngredient $dough) { $this->dough = $dough; } /** * @return AbstractIngredient */ public function getDough() { return $this->dough; } /** * @param AbstractIngredient $sauce */ public function setSauce(AbstractIngredient $sauce) { $this->sauce = $sauce; } /** * @return AbstractSauce */ public function getSauce() { return $this->sauce; } /** * @param PizzaIngredientFactoryInterface $ingredientFactory */ public function setIngredientFactory(PizzaIngredientFactoryInterface $ingredientFactory) { $this->ingredientFactory = $ingredientFactory; } /** * @return PizzaIngredientFactoryInterface */ public function getIngredientFactory() { return $this->ingredientFactory; } } <file_sep>/src/Pizza/Type/OysterPizza.php <?php namespace Pizza\Type; use Pizza\AbstractPizza; use Pizza\PizzaIngredientFactoryInterface; class OysterPizza extends AbstractPizza { /** * @param PizzaIngredientFactoryInterface $ingredientFactory * @param String $pizzaName */ public function __construct(PizzaIngredientFactoryInterface $ingredientFactory, $pizzaName = 'Oyster Pizza') { parent::__construct(); $this->setIngredientFactory($ingredientFactory); $this->setName($pizzaName); $this->getCook()->setBakingMinute(2); $this->getCook()->setBakingSecond(27); } /** * @return void */ public function prepare() { $dough = $this->getIngredientFactory()->createDough(); $this->setDough($dough); $sauce = $this->getIngredientFactory()->createSauce(); $this->setSauce($sauce); $cheese = $this->getIngredientFactory()->createCheese(); $this->setCheese($cheese); echo 'Dough: <strong>'.$this->getDough()->getName().'</strong><br /><br />'; echo '<strong>The cheese comes first in this pizza</strong><br />'; echo 'Cheese: <strong>'.$this->getCheese()->getName().'</strong><br /><br />'; echo 'Sauce: <strong>'.$this->getSauce()->getName().'</strong><br />'; } }<file_sep>/src/Pizza/Brazil/BrazilPizzaIngredientFactory.php <?php namespace Pizza\Brazil; use Pizza\Ingredient\Cheese\MozzarellaCheese; use Pizza\Ingredient\Dough\ThinCrustDough; use Pizza\Ingredient\Sauce\SpicySauce; use Pizza\PizzaIngredientFactoryInterface; class BrazilPizzaIngredientFactory implements PizzaIngredientFactoryInterface { /** * @return ThinCrustDough */ public function createDough() { return new ThinCrustDough('Brazil Thin Dough'); } /** * @return SpicySauce */ public function createSauce() { return new SpicySauce(); } /** * @return MozzarellaCheese */ public function createCheese() { return new MozzarellaCheese('Dat Mozza Cheese'); } } <file_sep>/src/Pizza/Brazil/BrazilPizzaFactory.php <?php namespace Pizza\Brazil; use Pizza\AbstractPizzaFactory; use Pizza\Type\GarlicPizza; use Pizza\Type\OysterPizza; class BrazilPizzaFactory extends AbstractPizzaFactory { public function __construct() { parent::__construct(new BrazilPizzaIngredientFactory()); } /** * @param string $pizzaType * @throws \Exception * @return \Pizza\AbstractPizza */ public function create($pizzaType = null) { switch($pizzaType) { case 'garlic': return new GarlicPizza($this->getIngredientFactory(), 'Nose Destroyer (Garlic)'); break; case 'oyster': return new OysterPizza($this->getIngredientFactory()); break; default: throw new \Exception('Erro ao criar pizza'); } } } <file_sep>/src/Pizza/PizzaIngredientFactoryInterface.php <?php namespace Pizza; interface PizzaIngredientFactoryInterface { public function createDough(); public function createSauce(); public function createCheese(); } <file_sep>/src/Pizza/Ingredient/Cheese/MozzarellaCheese.php <?php namespace Pizza\Ingredient\Cheese; use Pizza\Ingredient\AbstractIngredient; class MozzarellaCheese extends AbstractIngredient { /** * @param string $name */ public function __construct($name = 'Mozzarella Cheese') { $this->setName($name); } }<file_sep>/src/Pizza/Ingredient/Dough/ThinCrustDough.php <?php namespace Pizza\Ingredient\Dough; use Pizza\Ingredient\AbstractIngredient; class ThinCrustDough extends AbstractIngredient { /** * @param string $name */ public function __construct($name = 'Thin Crust Dough') { $this->setName($name); } }<file_sep>/src/Pizza/Ingredient/Sauce/SpicySauce.php <?php namespace Pizza\Ingredient\Sauce; use Pizza\Ingredient\AbstractIngredient; class SpicySauce extends AbstractIngredient { /** * @param string $name */ public function __construct($name = 'Spicy Sauce') { $this->setName($name); } } <file_sep>/src/Store/PizzaStore.php <?php namespace Store; class PizzaStore { /** * @var \Pizza\AbstractPizzaFactory */ private $pizzaFactory; /** * @param \Pizza\AbstractPizzaFactory $pizzaFactory */ public function __construct($pizzaFactory) { $this->pizzaFactory = $pizzaFactory; } /** * @param \Pizza\AbstractPizzaFactory $pizzaFactory */ public function setPizzaFactory($pizzaFactory) { $this->pizzaFactory = $pizzaFactory; } /** * @param string $pizzaType * @return \Pizza\AbstractPizza */ public function order($pizzaType = null) { $pizza = $this->pizzaFactory->create($pizzaType); echo 'Creating <strong>'.$pizza->getName().'</strong><br><br>'; $pizza->prepare(); $pizza->bake(); $pizza->cut(); $pizza->box(); return $pizza; } }<file_sep>/src/Pizza/AbstractPizzaFactory.php <?php namespace Pizza; abstract class AbstractPizzaFactory { /** * @var PizzaIngredientFactoryInterface */ private $ingredientFactory; public function __construct(PizzaIngredientFactoryInterface $ingredientFactory) { $this->ingredientFactory = $ingredientFactory; } /** * @return PizzaIngredientFactoryInterface */ public function getIngredientFactory() { return $this->ingredientFactory; } /** * @return AbstractPizza */ abstract public function create($pizzaType = null); }<file_sep>/src/Store/Cook.php <?php namespace Store; class Cook { private $bakingHour = 0; private $bakingMinute = 0; private $bakingSecond = 0; private $temperature = 180; public function bake() { $bakeTime = new \DateInterval("PT{$this->bakingHour}H{$this->bakingMinute}M{$this->bakingSecond}S"); echo "Baking... <br />"; echo "Time {$bakeTime->format('%H:%I:%S')} <br />"; echo "Temperature {$this->temperature} (temperatur format not implemented)"; } /** * @param mixed $bakingHour */ public function setBakingHour($bakingHour) { $this->bakingHour = $bakingHour; } /** * @return mixed */ public function getBakingHour() { return $this->bakingHour; } /** * @param mixed $bakingMinute */ public function setBakingMinute($bakingMinute) { $this->bakingMinute = $bakingMinute; } /** * @return mixed */ public function getBakingMinute() { return $this->bakingMinute; } /** * @param mixed $bakingSecond */ public function setBakingSecond($bakingSecond) { $this->bakingSecond = $bakingSecond; } /** * @return mixed */ public function getBakingSecond() { return $this->bakingSecond; } /** * @param int $temperature */ public function setTemperature($temperature) { $this->temperature = $temperature; } /** * @return int */ public function getTemperature() { return $this->temperature; } } <file_sep>/src/Pizza/Type/GarlicPizza.php <?php namespace Pizza\Type; use Pizza\AbstractPizza; use Pizza\PizzaIngredientFactoryInterface; class GarlicPizza extends AbstractPizza { /** * @param PizzaIngredientFactoryInterface $ingredientFactory * @param String $pizzaName */ public function __construct(PizzaIngredientFactoryInterface $ingredientFactory, $pizzaName = 'Garlic Pizza') { parent::__construct(); $this->setIngredientFactory($ingredientFactory); $this->setName($pizzaName); } }
0d24bb76beb89ef5d810a552e75e851d4e818b27
[ "PHP" ]
13
PHP
walterdis/oop4fun
ede08daf95918a83f0400d4a0a3d871c835fc515
645648278b5e07ffe6412eb8d8a032dcd057788c
refs/heads/master
<repo_name>tom-ando/presentext<file_sep>/generate.py import sys import fileinput import os from random import randint from shutil import copyfile from base64 import b64encode customMode = False backgroundAdded = False colors = { "red": [255, 0, 0], "pink": [255, 193, 203], "orange": [255, 165, 0], "yellow": [255, 195, 0], "purple": [128, 0, 128], "green": [0, 255, 0], "blue": [0, 0, 255], "brown": [165, 42, 42], "white": [255, 255, 255], "gray": [128, 128, 128] } template = {} # Returns a base64 string of an image def encodeImage(imagePath): print("[+] Encoding image from {}".format(imagePath)) with open(imagePath, "rb") as f: return "data:image/jpeg;base64," + str(b64encode(f.read()))[2:-1] # Keeps prompting for response until valid response def getInput(prompt, allowed): while True: userInput = input(prompt) if userInput in allowed: return userInput # Stops the script if something is missing def checkPath(path): if not os.path.exists(path): print("[!] Missing file/directory or insufficent permissions: {}".format(path)) sys.exit() # Returns the substring between two placeholders def extractString(string, placeholder): return string.split(placeholder)[1] # Saves a files def saveFile(filePath, content): with open(filePath, "w+") as f: f.write(content) # Saves all the files in one file def saveSingle(): global html, css, js print("[+] Writing to ./output/index.html") html = html.replace("[~css]", "<style>" + css + "</style>") html = html.replace("[~script]", "<script>" + js + "</script>") saveFile("./output/index.html", html) # Splits the files up into each language def saveMultiple(): global html, css, js print("[+] Writing to files in ./output") html = html.replace("[~css]", '<link rel="stylesheet" type="text/css" href="main.css"/>') html = html.replace("[~script]", '<script src="main.js"></script>') saveFile("./output/index.html", html) saveFile("./output/main.css", css) saveFile("./output/main.js", js) # Returns a random RGB color def generateRgb(): return [randint(0,255), randint(0,255), randint(0,255)] # Checks for all the files and folders required def checkFiles(): print("[+] Checking if includes exist") checkPath(sys.argv[1]) checkPath("./template/html.txt") checkPath("./template/css.txt") checkPath("./template/js.txt") # Checks for output directory and creates one if needed if not os.path.exists("./output"): print("[-] Output directory not found. Creating") os.makedirs("./output") # Opens template files def loadTemplate(templateFile): print("[+] Loading templates") global template with open(templateFile) as f: f = f.read() template["html"] = extractString(f, "[~html]") template["slide"] = extractString(f, "[~slide]") template["heading"] = extractString(f, "[~heading]") template["contentSection"] = extractString(f, "[~contentSection]") template["content"] = extractString(f, "[~content]") template["controls"] = extractString(f, "[~controlSection]") print("[+] Loaded all templates") # Parses the input file def parseInputFile(inputFilePath): global template print("[+] Parsing input file") # Holds the html file parsedFile = template["html"] firstLine = True slideCounter = 0 for line in fileinput.input(inputFilePath): line = list(line) # Finds where the "-" is, signifying what type of dot point it is for counter in range(len(line)): if line[counter] == "-": break elif line[counter] != " ": counter = -1 break # Removes dashes and extra spaces from start of line and newline from end line = "".join(line)[counter + 1:len(line) - 1].strip() if firstLine: # Line type is a title if counter == -1: title = line # No heading supplied else: title = "Presentation" # Puts the heading in the page parsedFile = parsedFile.replace("[~title]", title) firstLine = False # Slide heading (automatically makes new slide) if counter == 0: # Clears tags from previous slide parsedFile = parsedFile.replace("[~contentSectionContent]", "") # Adds a new slide parsedFile = parsedFile.replace("[~slideSection]", template["slide"] + "[~slideSection]") # Puts in slide ID parsedFile = parsedFile.replace("[~slideId]", str(slideCounter)) # Adds a heading to the slide and adds the ul element to house the points parsedFile = parsedFile.replace("[~slideContent]", template["heading"].replace("[~headingContent]", line) + template["contentSection"]) slideCounter += 1 # Content elif counter == 1: # Adds another point and puts the line in the content section parsedFile = parsedFile.replace("[~contentSectionContent]", template["content"] + "[~contentSectionContent]").replace("[~contentContent]", line) print("[+] Successfully parsed input file") return parsedFile # Adds a background image def setImageBackground(imagePath): global html, backgroundAdded if customMode: while True: imageMode = input(" [+] Have images [s]eperate or in [f]ile (default in file): ") if imageMode in ("f", "F", ""): imagePath = encodeImage(imagePath) break elif imageMode in ("s", "S"): print(" [+] Copying image from {} to ./output/background.jpg".format(imagePath)) copyfile(imagePath, "./output/background.jpg") break else: imagePath = encodeImage(imagePath) html = html.replace("[~background]", '<img id="background" src="' + imagePath + '"/>') backgroundAdded = True # Removes all the placeholders def removePlaceholder(): global html html = html.replace("[~contentSectionContent]", "").replace("[~slideSection]", "").replace("[~background]", "").replace("[~controls]", "") def determineTextColor(backgroundColor): # 383 = (255 * 3) / 2 if sum(backgroundColor[0:len(backgroundColor)]) < 383: textColor = "white" else: textColor = "black" return textColor # Generates either a random or custom theme depending on customMode def generateTheme(): global customMode, colors, html, css print("[+] Generating theme") # Makes a rgb color if customMode: # Not using getInput function because of custom rules while True: backgroundColor = input(" [+] Pick a background color (basic color name or rgb value or enter for random): ") # A valid pre-known color if backgroundColor in colors: backgroundColor = colors[backgroundColor] break # Custom rgb color elif backgroundColor[:3] == "rgb": # No input if backgroundColor == "": break # Set to false if loop needs to be rerun valid = True try: backgroundColor = [int(i) for i in backgroundColor[4:].split(" ") if (int(i) <= 255) and (int(i) >= 0)] except: valid = False print(" [-] Not a valid rgb value") backgroundColor = generateRgb() if valid: break # No input elif backgroundColor == "": backgroundColor = generateRgb() break else: print(" [-] Not a valid rgb value") # Setting opacity for background if '<img id="background"' in html: defaultOpacity = 0.4 else: defaultOpacity = 1 # Not using getInput function because of custom rules while True: try: opacity = float(input(" [+] Opacity for background (between 0-1. Default {}): ".format(defaultOpacity))) except: opacity = defaultOpacity if opacity >= 0 and opacity <= 1: break else: print(" [-] Not a number between 0-1") else: backgroundColor = generateRgb() if '<img id="background"' in html: opacity = 0.4 else: opacity = 1 textColor = determineTextColor(backgroundColor) backgroundColor = "rgba(" + str(backgroundColor)[1:-1] + ", " + str(opacity) + ")" print(" [+] Using " + backgroundColor + " with " + textColor + " text") # Applies theme to css css = css[0] + textColor + css[1] + backgroundColor + css[2] + textColor + css[3] def loadFile(filePath): with open(filePath) as f: return f.read() def addControls(): global html, template html = html.replace("[~controls]", template["controls"]) if len(sys.argv) < 2: print("Usage: {} /path/to/file [-c]".format(sys.argv[0])) print(" -c: Custom mode. Gives options to change things like background color") else: # If custom flag set it will leave options for custom changes if len(sys.argv) == 3: if sys.argv[2] == "-c": customMode = True checkFiles() loadTemplate("./template/html.txt") print("[+] Opening css and js template files") css = loadFile("./template/css.txt").split("[~]") js = loadFile("./template/js.txt") # Parses the input file html = parseInputFile(sys.argv[1]) if customMode: # Add controls controls = getInput("[+] Add controls to bottom of page? Y/n (default n): ", ("Y", "y", "N", "n", "")) if controls in ("Y", "y"): print(" [+] Adding controls") addControls() while True: imagePath = input("[+] Image path for background (blank for background.jpg or none): ") if imagePath != "": if os.path.exists(imagePath): setImageBackground(imagePath) break else: print(" [!] Image doesn't exist or invalid permissions") # User inputted nothing else: break if not backgroundAdded: if os.path.exists("background.jpg"): print("[+] background.jpg found in current folder") setImageBackground("background.jpg") removePlaceholder() generateTheme() # Writing to files if customMode: saveMode = getInput("[+] Save files in a [s]ingle file or [m]ultiple (blank for single): ", ("s", "S", "m", "M", "")) if saveMode in ("single", "s", ""): saveSingle() elif saveMode in ("multiple", "m"): saveMultiple() else: saveSingle() print("[+] Completed") <file_sep>/README.md # presentext A Python script which when given a text file and a template, will generate a colorful HTML slide-show. The text file involves very simple formatting and indentation (think a cousin of markdown) which will be interpreted as a heading or a title or a dot point, and included as it should be. The final file should be usable as a presentation in place of a PowerPoint or a Keynote. ## Getting started The easiest way to run the script is to clone the repo or download the zip. Make sure Python 3.x is installed (untested on Python 2.x). ``` git clone https://github.com/tom-ando/presentext.git cd ./presentext python3 ./generate.py test.txt ``` The final file can be found in `./output/index.html`. This file can be sent off or moved and needs no dependencies other than itself. ### Templates The scripts reads 3 templates from `./template`, `css.txt`, `js.txt` and `html.txt`. They can all be modified to any extent. Please not, placeholders (look like `[~placeholder]`) must still be included, although they can be moved around to other places to change the functionality and look of the slide-show. A fresh set of the templates can always be found on this GitHub page. ### Images as backgrounds Exactly as it sounds. Images can be used as a background for the slide-show. Either have an image in the base directory called `background.jpg` or specify a particular one with the custom mode. ### Input file The syntax of the input file is very simple. No indentation or hyphens for a title, one hyphen for a slide heading (and consequently a new slide) and a space and a hyphen for a dot point on the slide. ``` Title of presentation (can only be used once) - Heading of slide 1 - Dot point on slide 1 - Another dot point - Another slide - More dot points ``` ### Slide show The slide show can be navigated with arrow keys, clicking on one of the sides of a slide or with the spacebar. The script will generate a random color to use as the background of the slides, which can be customised in custom mode. ### Custom mode Custom mode can be used with a `-c` on the end of the command. ```python3 ./generate.py test.txt -c``` When run any part of the script can be changed, when prompted. Custom locations for images can be used, along with specific colors for backgrounds and options for controls. Take a look! ## Bugs/Ideas If you want to get in touch with me I can be found at `<EMAIL>`.
9ecb6987c8218ca2197d4463a67eae0020ea0a66
[ "Markdown", "Python" ]
2
Python
tom-ando/presentext
2a948a03acbf74a16fd3ee4f8bbf8f59e84bc924
84cbbb3ae3f4306260912acb2cbb3039b69d853e
refs/heads/master
<repo_name>mastanpatel/HealthClaimProcessor-API<file_sep>/HclaimProcessor/HclaimProcessor/Controllers/HomeController.cs using System; using System.Data.Entity.Validation; using System.Linq; using System.Web.Mvc; using System.Web.Security; namespace HclaimProcessor.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(userprofile objUser) { if (IsValid(objUser.UserName, objUser.Password)) { FormsAuthentication.SetAuthCookie(objUser.UserName, true); return RedirectToAction("UserDashBoard", "Home"); } else { ModelState.AddModelError("", "Login details are wrong."); } //if (ModelState.IsValid) //{ //using (mydbEntities db = new mydbEntities()) // { // var obj = db.userprofiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.<PASSWORD>)).FirstOrDefault(); // if (obj != null) // { // Session["userid"] = obj.UserId; // Session["username"] = obj.UserName; // return RedirectToAction("userdashboard"); // } // else // { // ModelState.AddModelError("", "Login details are wrong."); // } // } //} return View(objUser); } public ActionResult UserDashBoard() { //if (Session["SessionId"] != null) if(User.Identity.IsAuthenticated) { return View(); } else { return RedirectToAction("Login"); } } [HttpGet] public ActionResult Register() { return View(); } [HttpPost] public ActionResult Register(userprofile user) { try { if (ModelState.IsValid) { //mydbEntities db = new mydbEntities() using (var db = new mydbEntities()) { var newUser = db.userprofiles.Create(); newUser.UserName = user.UserName; newUser.Password = <PASSWORD>; newUser.IsActive = true; db.userprofiles.Add(newUser); db.SaveChanges(); return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "Data is not correct"); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } return View(); } public ActionResult LogOut() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } private bool IsValid(string username, string password) { var crypto = new SimpleCrypto.PBKDF2(); bool IsValid = false; using (var db = new mydbEntities()) { var user = db.userprofiles.FirstOrDefault(u => u.UserName == username); if (user != null) { // if (user.Password == crypto.Compute(password, user.PasswordSalt)) // { IsValid = true; //} } } return IsValid; } } }<file_sep>/HclaimProcessor/HclaimProcessor/Global.asax.cs using System; using System.Security.Principal; using System.Threading; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; namespace HclaimProcessor { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } //private void Application_AuthenticateRequest(object sender, EventArgs e) //{ // HttpCookie decryptedCookie = // Context.Request.Cookies[FormsAuthentication.FormsCookieName]; // FormsAuthenticationTicket ticket = // FormsAuthentication.Decrypt(decryptedCookie.Value); // var identity = new GenericIdentity(ticket.Name); // var principal = new GenericPrincipal(identity, null); // HttpContext.Current.User = principal; // Thread.CurrentPrincipal = HttpContext.Current.User; //} } }
fdeb9c06c783a9c13ff0bd5625f08d81e50cdf06
[ "C#" ]
2
C#
mastanpatel/HealthClaimProcessor-API
75a01f4b472bc4feac4fb3e462a5fb4474f16fe9
e03fd4a667728e1f4c9bab654289872ad6d4851b
refs/heads/master
<file_sep># MutiLevelTableView 多层级可展开的TableView 对嵌套数据模型的递归处理 ![](mutliLevelGif.gif) <file_sep>// // HomeViewController.swift // Demo-MultiTable // // Created by 梅霖 on 2019/1/9. // Copyright © 2019 梅霖. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var regionButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func regionButtonClicked(_ sender: UIButton) { let regionVC = TreeViewController() regionVC.selectedRegionBlock = { selectedNode in self.regionButton.setTitle(selectedNode.name, for: .normal) } self.navigationController?.pushViewController(regionVC, animated: true) } override func viewWillAppear(_ animated: Bool) { if let encodeData = UserDefaults.standard.object(forKey: "TEST_ARCHIVE") as? Data { let node = NSKeyedUnarchiver.unarchiveObject(with: encodeData) as! JKNodeModel print("local archived node" + node.description) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // JKMultiLevelTableView.swift // Demo-MultiTable // // Created by 梅霖 on 2019/1/3. // Copyright © 2019 梅霖. All rights reserved. // import UIKit class JKMultiLevelTableView: UITableView { var preservation: Bool = false var rootID: String! /// 原始的节点数据 var nodes: [JKNodeModel]! /// 当前显示的节点数据 var tempNodes: [JKNodeModel]! /// 需要插入或删除的RowIndex var reloadArray: [IndexPath]? var selectBlock:((JKNodeModel) -> Void)? var selectedNodeID:String? static let cellHeight:CGFloat = 45.0 // MARK: - init convenience init(frame:CGRect, nodes:[JKNodeModel], rootID:String?, selectBlock:((JKNodeModel) -> Void)?) { self.init(frame: frame, style: .plain) self.rootID = rootID ?? "-1" self.selectBlock = selectBlock self.preservation = false configNodes(nodes: nodes) } override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.backgroundColor = UIColor.white tempNodes = [JKNodeModel]() reloadArray = [IndexPath]() self.separatorStyle = .none self.dataSource = self self.delegate = self self.rowHeight = JKMultiLevelTableView.cellHeight self.register(UINib.init(nibName: "JKMultiLevelCell", bundle: nil), forCellReuseIdentifier: "JKMultiLevelCell") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { print("JKMultiLevelTableView deinit ---~~~---") } // MARK: - Nodes Config func configNodes(nodes:[JKNodeModel]) { self.nodes = nodes // judgeLeafAndRootNodes() updateNodesLevel() addFirstLoadNodes() reloadData() } func addNodesFromRequest(newNodes:[JKNodeModel]) { nodes.append(contentsOf: newNodes) updateNodesLevel() } //项目自带root、leaf属性 /* func judgeLeafAndRootNodes() { for node in nodes { var isLeaf = true var isRoot = true for anotherNode in nodes { if anotherNode.parentID == node.childrenID { isLeaf = false } if anotherNode.childrenID == node.parentID { isRoot = false } if (isLeaf == false && isRoot == false) { break } } node.isRoot = isRoot node.isLeaf = isLeaf } } */ func updateNodesLevel() { setDepthWithParentIdAndChildrenNodes(nodeLevel: 1, parentIDs: [rootID], childrenNodes: nodes) } func setDepthWithParentIdAndChildrenNodes(nodeLevel:Int, parentIDs:[String], childrenNodes:[JKNodeModel]) { var newParentIDs = [String]() var leftNodes = childrenNodes for node in childrenNodes { if parentIDs.contains(node.parentID) { node.level = nodeLevel leftNodes = leftNodes.filter({ (leftNode) -> Bool in leftNode.childrenID != node.childrenID }) newParentIDs.append(node.childrenID) } } if leftNodes.count > 0 { let nextLevel = nodeLevel + 1 setDepthWithParentIdAndChildrenNodes(nodeLevel: nextLevel, parentIDs: newParentIDs, childrenNodes: leftNodes) } } func addFirstLoadNodes() { for node in nodes { if node.isRoot == true { tempNodes.append(node) } } reloadArray = [IndexPath]() } func updateSelectedNode(nodeID:String) { selectedNodeID = nodeID nodes.forEach { (node) in if node.childrenID != selectedNodeID { node.isSelected = false } else { node.isSelected = true } } reloadData() } } // MARK: - UITableViewDataSource,UITableViewDelegate extension JKMultiLevelTableView : UITableViewDataSource,UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tempNodes?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JKMultiLevelCell") as! JKMultiLevelCell cell.node(node: tempNodes[indexPath.row]) cell.cellIndicatorBlock = {[weak self] node in if self?.selectBlock != nil { self?.selectBlock!(node) } self?.updateSelectedNode(nodeID: node.childrenID) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let node = tempNodes[indexPath.row] as JKNodeModel if node.isLeaf { //1.LeafNode处理点击事件 if selectBlock != nil { selectBlock!(node) } updateSelectedNode(nodeID: node.childrenID) return } else { node.isExpand = !node.isExpand } //单独刷新一次cell tableView.reloadRows(at: [indexPath], with: .none) reloadArray?.removeAll() if node.isExpand { //2.展开节点 //2.1新增网络请求判断 /* if needRequestExpandNodes(node: node) { FakeNetwork.shared.queryChildrenRegion(region: node.childrenID) {[weak self] (bool, nodeArray) in if bool { self?.addNodesFromRequest(newNodes: nodeArray!) self?.expandNodesFor(parentID: node.childrenID!, insertIndex: indexPath.row) tableView.insertRows(at: (self?.reloadArray)!, with: .none) } } } else { expandNodesFor(parentID: node.childrenID!, insertIndex: indexPath.row) tableView.insertRows(at: reloadArray!, with: .none) } */ expandNodesFor(parentID: node.childrenID!, insertIndex: indexPath.row) tableView.insertRows(at: reloadArray!, with: .none) } else { //3.收起节点 foldNodesFor(level: node.level!, currentIndex: indexPath.row) tableView.deleteRows(at: reloadArray!, with: .none) } } } // MARK: - Cells Expand or Fold extension JKMultiLevelTableView { func needRequestExpandNodes(node: JKNodeModel) -> Bool { for everyNode in nodes { if everyNode.parentID == node.childrenID { return false } } return true } func expandNodesFor(parentID:String, insertIndex: Int) -> Void { var theInsertIndex = insertIndex for node in nodes { if node.parentID == parentID { node.isExpand = false theInsertIndex = theInsertIndex + 1 tempNodes.insert(node, at: theInsertIndex) reloadArray?.append(IndexPath.init(row: theInsertIndex, section: 0)) } } } func foldNodesFor(level:Int, currentIndex:Int) -> Void { if currentIndex + 1 < tempNodes.count { let copyTempNodes = tempNodes! for i in stride(from: currentIndex + 1, to: tempNodes.count, by: 1) { if copyTempNodes[i].level! <= copyTempNodes[currentIndex].level! { break } else { tempNodes = tempNodes.filter({ (node) -> Bool in node.childrenID != copyTempNodes[i].childrenID }) reloadArray?.append(IndexPath.init(row: i, section: 0)) } } } } } <file_sep>// // FakeNetwork.swift // Demo-MultiTable // // Created by 梅霖 on 2019/1/9. // Copyright © 2019 梅霖. All rights reserved. // import Foundation class FakeNetwork { static let shared = FakeNetwork() func queryChildrenRegion(region: String, compeletion:@escaping (Bool,[JKNodeModel]?) -> Void ) -> Void { if fakeData(region: region) != nil { compeletion(true, fakeData(region: region)) } else { compeletion(false,nil) } } func fakeData(region: String) -> [JKNodeModel]? { let wholeList = [["parentID":"-1", "name":"Node1", "ID":"1", "hasChildrenRegion":"1"], ["parentID":"1", "name":"Node10", "ID":"10", "hasChildrenRegion":"1"], ["parentID":"1", "name":"Node11", "ID":"11", "hasChildrenRegion":"1"], ["parentID":"10", "name":"Node100", "ID":"100", "hasChildrenRegion":"0"], ["parentID":"10", "name":"Node101", "ID":"101", "hasChildrenRegion":"0"], ["parentID":"11", "name":"Node110", "ID":"110", "hasChildrenRegion":"0"], ["parentID":"11", "name":"Node111", "ID":"111", "hasChildrenRegion":"1"], ["parentID":"111", "name":"Node1110", "ID":"1110", "hasChildrenRegion":"0"], ["parentID":"111", "name":"Node1111", "ID":"1111", "hasChildrenRegion":"0"], ["parentID":"-1", "name":"Node2", "ID":"2", "hasChildrenRegion":"1"], ["parentID":"2", "name":"Node20", "ID":"20", "hasChildrenRegion":"1"], ["parentID":"20", "name":"Node200", "ID":"200", "hasChildrenRegion":"0"], ["parentID":"20", "name":"Node201", "ID":"201", "hasChildrenRegion":"0"], ["parentID":"20", "name":"Node202", "ID":"202", "hasChildrenRegion":"0"], ["parentID":"2", "name":"Node21", "ID":"21", "hasChildrenRegion":"1"], ["parentID":"21", "name":"Node210", "ID":"210", "hasChildrenRegion":"0"], ["parentID":"21", "name":"Node211", "ID":"211", "hasChildrenRegion":"1"], ["parentID":"21", "name":"Node212", "ID":"212", "hasChildrenRegion":"0"], ["parentID":"211", "name":"Node2110", "ID":"2110", "hasChildrenRegion":"0"], ["parentID":"211", "name":"Node2111", "ID":"2111", "hasChildrenRegion":"0"]] let node2List = [["parentID":"2", "name":"Node20", "ID":"20", "hasChildrenRegion":"1"], ["parentID":"2", "name":"Node21", "ID":"21", "hasChildrenRegion":"1"]] let node21List = [["parentID":"21", "name":"Node210", "ID":"210", "hasChildrenRegion":"0"], ["parentID":"21", "name":"Node211", "ID":"211", "hasChildrenRegion":"1"], ["parentID":"21", "name":"Node212", "ID":"212", "hasChildrenRegion":"0"]] var list = [[String:String]]() switch region { case "-1": list = wholeList case "2": list = node2List case "21": list = node21List default: return [JKNodeModel]() } var array = [JKNodeModel]() for dic in list { if let pID = dic["parentID"],let name = dic["name"],let id = dic["ID"],let hasChild = dic["hasChildrenRegion"] { let node = JKNodeModel.init(parentID: pID, name: name, childrenID: id, hasChildrenRegion: hasChild) array.append(node) } } return array as [JKNodeModel] } func searchNodes(nodeName: String) -> [JKNodeModel]? { let originNodes = FakeNetwork.shared.fakeData(region: "-1") var result = [JKNodeModel]() for eveNode in originNodes! { if eveNode.name!.contains(nodeName) { result.append(eveNode) } } return result } } <file_sep>// // JKNodeModel.swift // Demo-MultiTable // // Created by 梅霖 on 2019/1/3. // Copyright © 2019 梅霖. All rights reserved. // import Foundation class JKNodeModel:NSObject,NSCoding { var hasChildrenRegion: String! var parentID: String! var childrenID: String! var name: String? var isExpand: Bool = false var level: Int? var isLeaf: Bool = false var isRoot: Bool = false var isSelected: Bool = false func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObject(forKey: "name") as? String } convenience init(parentID:String, name:String, childrenID:String, hasChildrenRegion:String) { self.init(parentID: parentID, name: name, childrenID: childrenID, level: nil, hasChildrenRegion: hasChildrenRegion) } init (parentID:String, name:String, childrenID:String, level:Int?, hasChildrenRegion:String) { self.parentID = parentID self.name = name self.childrenID = childrenID self.level = level self.hasChildrenRegion = hasChildrenRegion //项目特性可以直接判断 self.isRoot = parentID == "-1" ? true : false self.isLeaf = hasChildrenRegion == "0" ? true : false } override var description: String { return "parentID:\(String(describing: parentID)) childrenID:\(String(describing: childrenID)) name:\(String(describing: name)) level:\(String(describing: level)) isExpand:\(isExpand)" } } // MARK: - Important: Always use the same properties in both your == and hash(into:) methods // MARK: - NSObject已经遵守了Hashable协议 extension JKNodeModel { override var hash:Int { var hasher = Hasher() hasher.combine(parentID) hasher.combine(childrenID) hasher.combine(name) return hasher.finalize() } } // MARK: - NSObject已经遵守了Equatable协议 extension JKNodeModel { override func isEqual(_ object: Any?) -> Bool { guard let other = object as? JKNodeModel else { return false } return self.parentID == other.parentID && self.childrenID == other.childrenID && self.name == other.name } } <file_sep>// // TreeViewController.swift // Demo-MultiTable // // Created by 梅霖 on 2019/1/2. // Copyright © 2019 梅霖. All rights reserved. // import UIKit class TreeViewController: UIViewController { var displayLevelView: JKMultiLevelTableView? var selectedRegionBlock: ((JKNodeModel)->Void)? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. initUI() } deinit { print("TreeViewController deinit ---~~~---") } func initUI() { self.view.backgroundColor = UIColor.white let frame = self.view.frame let rect = CGRect.init(x: 0, y: 20, width: frame.width, height: frame.height - 40) let fakeNodes = fakeData() displayLevelView = JKMultiLevelTableView.init(frame: rect, nodes: fakeNodes, rootID: nil, selectBlock: { (selectedNode) in print("选中节点" + (selectedNode.name ?? "name is nil")) if self.selectedRegionBlock != nil { self.selectedRegionBlock!(selectedNode) if fakeNodes.contains(selectedNode) { print("selected node contained in fakeNodes") } else { print("selected node not contained!") } let equalNodesArr = fakeNodes.filter({ (node) -> Bool in node == selectedNode }) for (i,node) in equalNodesArr.enumerated() { print("equalNodesArr \(i) \(node.description)") } } //FIXME: test local save do { let encodeData = try NSKeyedArchiver.archivedData(withRootObject: selectedNode, requiringSecureCoding: false) UserDefaults.standard.set(encodeData, forKey: "TEST_ARCHIVE") } catch let error { print("archived error:\(error)") } }) self.view.addSubview(displayLevelView!) let searchItem = UIBarButtonItem.init(barButtonSystemItem: .search, target: self, action: #selector(searchAction)) self.navigationItem.rightBarButtonItem = searchItem } @objc func searchAction() -> Void { //todo - 数据源来源分离 if let resultNodes = FakeNetwork.shared.searchNodes(nodeName: "11") { for node in resultNodes { print("\(node.description)\n") } } } func fakeData() -> [JKNodeModel] { let list = [["parentID":"-1", "name":"Node1", "ID":"1", "hasChildrenRegion":"1"], ["parentID":"1", "name":"Node10", "ID":"10", "hasChildrenRegion":"1"], ["parentID":"1", "name":"Node11", "ID":"11", "hasChildrenRegion":"1"], ["parentID":"10", "name":"Node100", "ID":"100", "hasChildrenRegion":"0"], ["parentID":"10", "name":"Node101", "ID":"101", "hasChildrenRegion":"0"], ["parentID":"11", "name":"Node110", "ID":"110", "hasChildrenRegion":"0"], ["parentID":"11", "name":"Node111", "ID":"111", "hasChildrenRegion":"1"], ["parentID":"111", "name":"Node1110", "ID":"1110", "hasChildrenRegion":"0"], ["parentID":"111", "name":"Node1111", "ID":"1111", "hasChildrenRegion":"0"], ["parentID":"-1", "name":"Node2", "ID":"2", "hasChildrenRegion":"1"], ["parentID":"2", "name":"Node20", "ID":"20", "hasChildrenRegion":"1"], ["parentID":"20", "name":"Node200", "ID":"200", "hasChildrenRegion":"0"], ["parentID":"20", "name":"Node201", "ID":"201", "hasChildrenRegion":"0"], ["parentID":"20", "name":"Node202", "ID":"202", "hasChildrenRegion":"0"], ["parentID":"2", "name":"Node21", "ID":"21", "hasChildrenRegion":"1"], ["parentID":"21", "name":"Node210", "ID":"210", "hasChildrenRegion":"0"], ["parentID":"21", "name":"Node211", "ID":"211", "hasChildrenRegion":"1"], ["parentID":"21", "name":"Node212", "ID":"212", "hasChildrenRegion":"0"], ["parentID":"211", "name":"Node2110", "ID":"2110", "hasChildrenRegion":"0"], ["parentID":"211", "name":"Node2111", "ID":"2111", "hasChildrenRegion":"0"]] // let list = [["parentID":"-1", "name":"Node1", "ID":"1", "hasChildrenRegion":"1"], // ["parentID":"-1", "name":"Node2", "ID":"2", "hasChildrenRegion":"1"]] var array = [JKNodeModel]() for dic in list { if let pID = dic["parentID"],let name = dic["name"],let id = dic["ID"],let hasChild = dic["hasChildrenRegion"] { let node = JKNodeModel.init(parentID: pID, name: name, childrenID: id, hasChildrenRegion: hasChild) array.append(node) } } return array as [JKNodeModel] } }
8f71aba46364c6182c43e389d246a0a426dbc7fb
[ "Markdown", "Swift" ]
6
Markdown
soulwell32/MultiLevelTableView
1c1189d19fef618cd599538e3b49df74bacb55d8
9b545422e7f5210f508aac62db6841c3ffd8e598
refs/heads/master
<repo_name>strategicpause/CrossfitFelix<file_sep>/dataAccess.js 'use strict'; var AWS = require('aws-sdk'); var data = require('./data'); // Key Prefixes var WORKOUT_PREFIX = "workout"; var ANNOUNCEMENT_PREFIX = "announcement"; // Constants var TODAY = 'Today'; var TOMORROW = 'Tomorrow'; var PST_OFFSET = -8; var DATE_MAP = { Today: () => { var date = new Date(); date.setHours(date.getHours() + PST_OFFSET); return formatDate(date); }, Tomorrow: () => { var date = new Date(); date.setDate(date.getDate() + 1); date.setHours(date.getHours() + PST_OFFSET); return formatDate(date); } }; var getWorkout = function(options) { getPayload(Object.assign(options, {type: WORKOUT_PREFIX})); } var getAnnouncements = function(options) { getPayload(Object.assign(options, {type: ANNOUNCEMENT_PREFIX})); } var getPayload = function(options) { var date = getDate(options.time); console.log('Fetching ' + options.type + ' for ' + date); if (data[options.type] && data[options.type][date]) { var payload = data[options.type][date]; console.log('Found payload for ' + options.type + '.' + date); options.onSuccess(payload); } else { console.error('No entry for ' + options.type + '.' + date); options.onError(); } }; var formatDate = function(date) { return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear(); }; var getDate = function(time) { if (!(time in DATE_MAP)) { console.error("Invalid Time: " + time); time = TODAY; } var dateFunction = DATE_MAP[time]; return dateFunction(); }; module.exports = { getWorkout: getWorkout, getAnnouncements: getAnnouncements, TODAY: TODAY, TOMORROW: TOMORROW };<file_sep>/build.sh node index.js && rm -f Archive.zip && zip -qr Archive.zip *.js node_modules/ && echo "Build Complete" <file_sep>/data.js module.exports = { workout: { '4-23-2017': { readoutText: '%t\'s WOD is coaches choice.' }, '4-24-2017': { readoutText: '%ts WOD, Running Game, consists of an 800 meter run, followed by 30 Pushups and 30 Kettle Bell Snatches. Repeat with a 400 meter run, 20 push ups and 20 kettle bell snatches. On the last round perform a 200 meter run, followed by 10 push ups, and 10 kettle bell snatches.', title: 'Running Game', displayText: '800m Run\n30 Push-ups FB: 20 HSPU\n30 KB Snatches 53/35\n400m Run\n20 Push-ups FB: 15 HSPU\n20 KB Snatches\n200m Run\n10 Push-ups FB: 10 HSPU\n10 KB Snatches' }, '4-25-2017': { readoutText: '%ts WOD, Power Driven, consists of 3 movements: 15 toes to bar, 10 burpees over the bar, and 5 power clean. Perform five rounds of each movement, each round decreasing the number of toes to bar by 3, the number of burpees by 2 and the number of power cleans by 1.', title: 'Power Driven', displayText: '15 - 12 - 9 - 6 - 3\nToes-2-Bar\n10 - 8 - 6 - 4 - 2\nBurpee Over the Barbell\n5 - 4 - 3 - 2 - 1\nPower Cleans 125/85' }, '4-26-2017': { readoutText: '%ts WOD, out of the comfort zone, consists of 4 rounds of dumbell thrusters, full snatches, and box jumps. In the first round you will perform 27 reps of each movement, followed by 21, 15, and finally 9.', title: 'Out of the Comfort Zone', displayText: '27-21-15-9\nDB Thrusters 35/25 FB: 40/30 FB+: 1 Arm\nAlternating DB Full Snatch (choose appropriate weight)\nBox Jumps 24/20' }, '4-27-2017': { readoutText: '%ts WOD, Intervals, you will perform the following movements every minutes for four sets: 400 meter run, 12 burpees and 6 power snatches.', title: 'Intervals', displayText: 'Every 4 mins for 4 sets:\n400m Run\n12 Burpees\n6 Power Snatch 115/75 FB: 135/95\n(rest remaining time...)' }, '4-28-2017': { readoutText: '%ts WOD, Blend of Capacities, is a 12 minute AMRAP of the following movements: 8 pullups, 16 kettlebell swings, 24 wallballs, and finally 32 double unders.', title: 'Blend of Capacities', displayText: '12 Min AMRAP\n8 Pullups FB: 4 Bar MUs\n16 KB Swings 53/35 FB: 70/53\n24 Wall Balls 20/14 FB: 30/20\n32 Double Unders' }, '4-29-2017': { readoutText: '%t\'s WOD is coaches choice.' }, '4-30-2017': { readoutText: '%t\'s WOD is coaches choice.' } }, announcement: { } };
c6de448ac30a6b82cd05915ff2223915fbf564f3
[ "JavaScript", "Shell" ]
3
JavaScript
strategicpause/CrossfitFelix
484c440066ab63e3e7e3936a28e35cbbf8db3ca1
339b918bac3b8ecb655024fd61d70674771846db
refs/heads/master
<repo_name>pvqa/Proformas<file_sep>/principal/models.py #encoding:utf-8 from django.db import models class Cliente(models.Model): nombre = models.CharField(max_length=20) apellido = models.CharField(max_length=20) def __unicode__(self): return self.nombre class Proforma(models.Model): cliente = models.ForeignKey(Cliente) nombre = models.CharField(max_length=50, unique=True) iva = models.FloatField(max_length=10) subtotal = models.FloatField(max_length=10) total = models.FloatField(max_length=10) def __unicode__(self): return self.nombre def calcular_subtotal(self): return self.subtotal def calcular_iva(self): return (calcular_subtotal() * self.proforma.iva) / 100 def calcular_total(self): return calcular_iva() + calcular_subtotal() class Categoria(models.Model): categoria = models.CharField(max_length=100, unique=True) def __unicode__(self): return self.categoria class Producto(models.Model): descripcion = models.CharField(max_length=100) precio = models.FloatField(max_length=10) def __unicode__(self): return self.descripcion class Detalle(models.Model): proforma = models.ForeignKey(Proforma) producto = models.ForeignKey(Producto) cantidad = models.IntegerField(max_length=10) class Producto_Categoria(models.Model): producto = models.ForeignKey(Producto) categoria = models.ForeignKey(Categoria) <file_sep>/principal/admin.py from principal.models import Cliente, Producto, Proforma, Categoria from django.contrib import admin admin.site.register(Cliente) admin.site.register(Categoria) admin.site.register(Producto) admin.site.register(Proforma) <file_sep>/proforma/urls.py from django.conf.urls import patterns, include, url from principal.views import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'proforma.views.home', name='home'), # url(r'^proforma/', include('proforma.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$','principal.views.ingresar'), #url(r'^ingresar/$','principal.views.ingresar'), url(r'^privado/$','principal.views.privado'), url(r'^cerrar/$','principal.views.cerrar'), ) <file_sep>/principal/forms.py #encoding:utf-8 from django.forms import ModelForm from principal.models import Cliente, Producto, Proforma, Categoria from django import forms class ClienteForm(ModelForm): class Meta: model = Cliente class CategoriaForm(ModelForm): class Meta: model = Categoria class ProductoForm(ModelForm): class Meta: model = Producto class ProformaForm(ModelForm): class Meta: model = Proforma
07e4723f58c42a95def4df3dba46f91ea760d427
[ "Python" ]
4
Python
pvqa/Proformas
b62407717f5ff8c3d1ba56c03c501d3e3410a9c7
67864b6bbea5860cb5c4b45d449740d9a5ddb542
refs/heads/master
<file_sep>MARK ==== ### A 2D multiplayer turn based strategy game written in Javascript ![Screenshot of the game](screenshot.png) Quick start ---------- - Make sure Node and npm are installed - Run `npm install` and `npm start` - Navigate to localhost:3000 in two browser windows Rules ----- The objective of the game is to remove your opponents VIP token while protecting yours. Initially the type of each token is hidden to the opponent, however each can be revealed to perform a specific action. ### Current tokens: - A / Assassin - Once activated can move to and capture any enemy token two tiles away from it. - B / Bomber - When activated the bomber capture itself and **any** other tokens within a small radius around it. Its activation will be triggered on death, even if hidden. Hence, one bomber going off can set of a chain reaction. - S / Shooter - Once activated can capture an enemy token it has an onobstructed horizontal or vertical line to. - VIP - The VIPs primary active ability it surrender, which immediately captures itself forfiets the game. It however has a secondary ability where is can swap positions with other tiles to allow quick movement of different tokens across the board when needed. <file_sep>(function(exports){ //TokenVIP var TokenVIP = function(owner, x, y, game) { this.type = "TokenVIP"; this.game = game; this.owner = owner this.captured = false; this.targetable = false; this.revealed = false; this.actionAvaliable = false; this.reference = ""; this.x = x; this.y = y; } TokenVIP.prototype.capture = function() { this.captured = true; this.game.turnActions.push({ action: 'capture', x: this.x, y: this.y }); }; TokenVIP.prototype.tileTargetable = function(x, y) { if (this.x == x && this.y == y) return true; else return false; } TokenVIP.prototype.tileInRange = function(x, y) { if (this.x == x && this.y == y) return true; else return false; } TokenVIP.prototype.activate = function() { this.game.turnActions.push({ action: 'capture', x: this.x, y: this.y }); this.capture(); } exports.TokenVIP = TokenVIP; //TokenBomber var TokenBomber = function(owner, x, y, game) { this.type = "TokenBomber"; this.game = game; this.owner = owner; this.captured = false; this.targetable = false; this.revealed = false; this.actionAvaliable = false; this.reference = ""; this.x = x; this.y = y; } TokenBomber.prototype.capture = function() { this.game.turnActions.push({ action: 'animate', animation: 'explode', x: this.x, y: this.y }); this.game.turnActions.push({ action: 'capture', x: this.x, y: this.y }); this.captured = true; for (var i = 0; i < this.game.tokens.length; i++) { var token = this.game.tokens[i]; if (this.tileInRange(token.x, token.y) && token.captured == false) { token.capture(); token.captured = true; } } }; TokenBomber.prototype.activate = function() { this.capture(); } TokenBomber.prototype.tileTargetable = function(x, y) { if (this.game.isTokenAt(x, y) && this.tileInRange(x, y)) { return true } return false; } TokenBomber.prototype.tileInRange = function(x, y) { if (Math.ceil(Math.sqrt(Math.pow((x-this.x), 2) + Math.pow((y-this.y), 2))) <= 2) return true; else return false; } exports.TokenBomber = TokenBomber; //TokenShooter var TokenShooter = function(owner, x, y, game) { this.type = "TokenShooter"; this.game = game; this.owner = owner this.targetable = true; this.captured = false; this.revealed = false; this.actionAvaliable = false; this.reference = ""; this.x = x; this.y = y; } TokenShooter.prototype.capture = function() { this.game.turnActions.push({ action: 'capture', x: this.x, y: this.y }); }; TokenShooter.prototype.tileTargetable = function(x, y, tokenList) { //Severside if (tokenList === undefined) { if (this.game.isTokenAt(x, y) && this.tileInRange(x, y)) { var target = this.game.getTokenAt(x, y); if (target.owner != this.owner) return true; } } //Clientside else { for (var index = 0; index < tokenList.length; index++) { var token = tokenList[index]; if (token.x == x && token.y == y) { if (token.owner != this.owner && this.tileInRange(token.x, token.y, tokenList)) return true; } } } return false; } TokenShooter.prototype.tileInRange = function(x, y, tokenList) { if (!(x == this.x || y == this.y)) return false; if (this.x == x && this.y == y) return true; var x1 = Math.min(x, this.x); var x2 = Math.max(x, this.x); var y1 = Math.min(y, this.y); var y2 = Math.max(y, this.y); var obstructed = false; if (x1 == x1) { //Check along y } else if (y1 == y2) { //Check along x } if (x1 == x2) { //Along the Y axis, scan accordingly for (var yCoord = y1; yCoord < y2; yCoord++) { var xCoord = x; if (yCoord != this.y && yCoord != y) { if (tokenList === undefined) { //Serverside check if (this.game.getTokenAt(xCoord, yCoord)) obstructed = true; } else { //Client side check for (var index = 0; index < tokenList.length; index++) { var token = tokenList[index]; if (token.x == xCoord && token.y == yCoord) { console.log('There is a token here, obstructed'); obstructed = true; } } } } } } else if (y1 == y2) { //Along the X axis, scan accordingly for (var xCoord = x1; xCoord < x2; xCoord++) { var yCoord = y; if (xCoord != this.x && xCoord != x) { if (tokenList === undefined) { //Serverside check if (this.game.getTokenAt(xCoord, yCoord)) obstructed = true; } else { //Clientside check for (var index = 0; index < tokenList.length; index++) { var token = tokenList[index]; if (token.x == xCoord && token.y == yCoord) { obstructed = true; } } } } } } return !obstructed; } TokenShooter.prototype.activate = function(x, y) { this.actionAvaliable = false; this.game.turnActions.push({ action: 'fatigue', x: this.x, y: this.y}); if (this.tileTargetable(x, y)) { for (var index = 0; index < this.game.tokens.length; index++) { var t = this.game.tokens[index]; if (t.owner != this.owner && t.x == x && t.y == y) this.game.captureToken(t); } } } exports.TokenShooter = TokenShooter; //TokenAssassin var TokenAssassin = function(owner, x, y, game) { this.type = "TokenAssassin"; this.game = game; this.owner = owner this.targetable = true; this.captured = false; this.revealed = false; this.actionAvaliable = false; this.reference = ""; this.x = x; this.y = y; } TokenAssassin.prototype.capture = function() { this.game.turnActions.push({ action: 'capture', x: this.x, y: this.y }); }; TokenAssassin.prototype.tileTargetable = function(x, y, tokenList) { if (tokenList === undefined) { if (this.game.isTokenAt(x, y) && this.tileInRange(x, y)) { var target = this.game.getTokenAt(x, y); if (target.owner != this.owner) return true; } } else { for (var index = 0; index < tokenList.length; index++) { var token = tokenList[index] if (token.x == x && token.y == y) { if (token.owner != this.owner && this.tileInRange(token.x, token.y)) return true; } } } return false; } TokenAssassin.prototype.tileInRange = function(x, y, tokenList) { var xDiff = Math.abs(this.x-x); var yDiff = Math.abs(this.y-y); if (xDiff <= 2 && yDiff <= 2) { return true; } return false; } TokenAssassin.prototype.activate = function(x, y) { this.actionAvaliable = false; this.game.turnActions.push({ action: 'fatigue', x: this.x, y: this.y}); if (this.tileTargetable(x, y)) { var xorig = this.x; var yorig = this.y this.x = x; this.y = y; for (var index = 0; index < this.game.tokens.length; index++) { var t = this.game.tokens[index]; if (t.owner != this.owner && t.x == x && t.y == y) this.game.captureToken(t); } this.game.turnActions.push({ action: 'move', x1: xorig, y1: yorig, x2: x, y2: y}); } } exports.TokenAssassin = TokenAssassin; exports.serialize = function(token) { return { "type": token.type, "owner": token.owner, "revealed": token.revealed, "actionAvaliable": token.actionAvaliable, "reference": token.reference, "x": token.x, "y": token.y } } exports.deserialize = function(obj, game) { var token = new exports[obj.type](obj.owner, obj.x, obj.y, game); token.revealed = obj.revealed; token.actionAvaliable = obj.actionAvaliable; token.reference = obj.reference; return token; } var TokenBlank = function(owner, x, y, game) { this.type = "TokenBlank"; this.game = game; this.owner = owner this.targetable = false; this.captured = false; this.revealed = false; this.actionAvaliable = false; this.reference = ""; this.x = x; this.y = y; } exports.TokenBlank = TokenBlank; })(typeof exports === 'undefined'? this['tokens']={}: exports);<file_sep>/* global io */ /* global tokens */ /* global strings */ /* global setMessage */ /* global openMenu */ /* global closeMenu, createActionMenu, closeActionMenu, gameScale, tokenOffset */ /* global $token, $tile, boardCoord, moveTo, setupActions, $, setScale */ var socket = null; var states = { "Waiting": 0, "Setup": 1, "Begin": 2, "Placing": 3, "Playing": 4, "Confirmation": 8, "Targeting": 9, "Shuffling": 10 } var playerId = 0; var state = states.Waiting; var turn = 1; var config = {}; var tokenList = []; var inputLocked = false; var transitioning = false; var referenceCount = 0; function animate(func, expectedDuration) { inputLocked = true; transitioning = true; func(); if (expectedDuration != null) { setTimeout(function() { inputLocked = false; transitioning = false; }, expectedDuration); } else { inputLocked = false; transitioning = false; } } function generatePlacement() { tokenList = []; $('.placement-sub-container').empty(); for (var i = 0; i < config.defaultTokens.length; i++) { var x = (5 + (gameScale * i)).toString(); $('.template>.'+config.defaultTokens[i]).clone() .appendTo('.placement-sub-container') .css('top', 5+'px') .css('left', x + 'px') .addClass('placement-token') } $('.placement-token').mousedown(function() { onTokenSelected($(this)) }) } function setState(newState) { state = newState if (state == states.Setup) { $('.game').fadeOut(0); genBoard(config.board.width, config.board.height); generatePlacement(); socket.emit('confirm'); //Notify bubble } else if (state == states.Begin) { animate(function() { setTimeout(function() { $('.title').addClass('titleToggled'); $('.info-box').addClass('info-box-toggled'); $('.game').fadeIn(500); socket.emit('confirm'); }, 500) }, 1000); } else if (state == states.Placing) { startPlacementRound(); } else if (state == states.Playing) { startRound(); } else if (state == states.Targeting) { //TODO TARGETING INFORMATION createActionMenu('temp-container', { text: 'Select a target to ' + strings[selection.type].actionVerb.toLowerCase(), buttons: [ { text: 'Cancel', handler: function() { //setState(states.Playing); clearBoard(); state = states.Playing; highlightBoard(movementHighlight, {x: selection.x, y: selection.y}); setupActions(selection); } } ] }); highlightBoard(function(x, y, info) { if (info.tileInRange(x, y, tokenList)) return { paint: true, class: 'targetable' } }, selection); highlightBoard(function(x, y, info) { if (info.tileTargetable(x, y, tokenList)) return { paint: true, class: 'selectable' } }, selection); } else if (state == states.Shuffling) { highlightBoard(function(x, y, info) { var token = getTokenAt(x, y); if (token != null && token != selection) { if (token.owner == playerId && !token.revealed) { return { paint: true, class: 'selectable' } } } }); createActionMenu('temp-container', { text: 'Select a target to swap positions with', buttons: [ { text: 'Cancel', handler: function() { //setState(states.Playing); clearBoard(); state = states.Playing; highlightBoard(movementHighlight, {x: selection.x, y: selection.y}); setupActions(selection); } } ] }); } else if (state == states.Confirmation) { highlightBoard(function(x, y, info) { if (info.tileInRange(x, y, tokenList)) { return { paint: true, class: 'targetable' } } else { return { paint: false } } }, selection); //SHOW CONFIRMATION DIALOG $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 500); var thing = $('.template>.action-confirm').clone().addClass('action-sub-container-pre').appendTo('.action-container'); setTimeout(function() { thing.removeClass('action-sub-container-pre'); }, 10); thing.find('.confirm-text').html(strings[selection.type].confirmation); thing.find('.bind-confirm').html(strings[selection.type].actionVerb).click(function() { finalizeAction(selection); }); thing.find('.bind-cancel').click(function() { $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 500); //setState(states.Playing); var tokenObj = $token(selection); clearBoard(); state = states.Playing; highlightBoard(movementHighlight, {x: selection.x, y: selection.y}); //$('.action-container').addClass('toggled'); setupActions(selection); }); } } function genBoard(width, height) { $('.board').remove(); $('.game').append('<table class="board"></table>'); for (var y = 0; y < height; y++) { var element = ""; for (var x = 0; x < width; x++) { element = element + '<td class="tile tileTransition'+Math.floor(1 + Math.random() * 4)+'" data-x="'+x+'" data-y="'+y+'"></td>'; } element = '<tr>' + element + '</tr>'; $('.board').append(element); } $('.tile').mousedown(function() { if (!inputLocked) { var x = parseInt($(this).data('x')); var y = parseInt($(this).data('y')); onTileClick(x, y); } }); } function distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2)); } function createToken(owner, type, x, y) { referenceCount = referenceCount + 1; var token = new tokens[type](owner, x, y, null); var position = boardCoord(x, y); token.reference = '#'+referenceCount; tokenList.push(token); var instance = $('.template>.'+type).clone().appendTo('.board').attr('data-ref', '#'+referenceCount) .css('top', position.y) .css('left', position.x); instance.mousedown(function() { onTokenClick(token.x, token.y, token); }) if (owner != playerId) instance.addClass('enemy'); if (!token.revealed) instance.addClass('fogged'); log(logToken(token) + ' placed at ' + logPosition(x, y)); return token; } function modify(token, data) { var obj = $token(token.reference); if ("type" in data && data.type !== undefined) { var newType = data['type']; token.type = newType; var oldType = obj.data('type'); obj.attr("data-type", newType); obj.addClass('flip'); setTimeout(function() { obj.removeClass('flip'); obj.html($('.template>.'+newType).html()); obj.removeClass(oldType); obj.addClass(newType); }, 300); } if ("revealed" in data && data.revealed !== undefined) { token.revealed = data['revealed']; obj.addClass('flip') if (token.revealed) { setTimeout(function() { obj.removeClass('flip'); obj.removeClass('fogged'); }, 300); } else { setTimeout(function() { obj.addClass('fogged'); obj.removeClass('flip'); }, 300); if (token.owner != playerId) { modify(token, {type: 'TokenBlank'}); } } } if ("actionAvaliable" in data && data.actionAvaliable !== undefined) { token.actionAvaliable = data['actionAvaliable']; if (token.revealed && !token.actionAvaliable) { obj.addClass('fatigued'); } else { obj.removeClass('fatigued'); } //TODO display action avaliable } } function getTokenAt(x, y) { for (var i = 0; i < tokenList.length; i++) { if (tokenList[i].x == x && tokenList[i].y == y) return tokenList[i]; } return null; } function highlightBoard(criteria, info) { for (var y = 0; y < config.board.height; y++) { for (var x = 0; x < config.board.width; x++) { var data = criteria(x, y, info); if (data == null) data = { paint: false }; if (data.paint) { clearClasses($tile(x, y)).addClass(data.class); } } } } function flicker() { $('.tile').addClass('flicker'); setTimeout(function() { $('.tile').removeClass('flicker').removeClass('tileTransition1').removeClass('tileTransition2').removeClass('tileTransition3').removeClass('tileTransition4') .each(function() { $(this).addClass('tileTransition'+Math.floor(1 + Math.random() * 4)); }); }, 150); } function clearClasses(tile) { return tile.removeClass('selected') .removeClass('selectable') .removeClass('illegal') .removeClass('movable') .removeClass('highlight') .removeClass('targetable'); } function clearBoard() { for (var y = 0; y < config.board.height; y++) { for (var x = 0; x < config.board.width; x++) { clearClasses($tile(x, y)); } } } function isPlacementIllegal(x, y) { if (getTokenAt(x, y) != null) { return true } else { for (var i = 0; i < tokenList.length; i++) { if (distance(x, y, tokenList[i].x, tokenList[i].y) < 2 && tokenList[i].owner != playerId) { return true; } } } return false; } function onTileClick(x, y) { if (turn == playerId) { if (state == states.Placing && selectedToken != null) { var type = selectedToken.data('type'); if (!isPlacementIllegal(x, y)) { selectedToken.remove(); selectedToken = null; $('.placement-token').removeClass('placement-token-selected'); var token = createToken(playerId, type, x, y) clearBoard(); finalizePlacement(token); } } if (state == states.Playing && selection != null) { if (distance(x, y, selection.x, selection.y) < 2 && getTokenAt(x, y) == null) { finalizeMovement(selection, x, y); } } } } function finalizePlacement(token) { turn = -1; closeMenu('.placement-container') setMessage('Ending turn...') var finished = false; if ($('.placement-token').size() <= 0) finished = true; socket.emit('placed-unit', {token: tokens.serialize(token), finished: finished}); } function finalizeShuffle(vip, target) { turn = -1; closeMenu('.action-container'); socket.emit('turn', { action: 'shuffle', x1: vip.x, y1: vip.y, x2: target.x, y2: target.y }); setMessage('Submitting move...') clearBoard(); } function finalizeAction(token, target) { turn = -1; closeMenu('.action-container') if (target != null) { socket.emit('turn', { action: 'activate', x1: token.x, y1: token.y, x2: target.x, y2: target.y }); } else { socket.emit('turn', { action: 'activate', x1: token.x, y1: token.y }); } setMessage('Submitting move...') clearBoard(); highlightBoard(function(x, y, info) { if ((x == info.x && y == info.y)) { // || (x == info.x2 && y == info.y2) return { paint: true, class: 'targetable' } } return { paint: false } }, {x: selection.x, y: selection.y, x2: selection.x, y2: selection.y}) selection = null; } function finalizeMovement(token, x, y) { turn = -1; closeMenu('.action-container') socket.emit('turn', { action: 'move', x1: selection.x, y1: selection.y, x2: x, y2: y }) setMessage('Submitting move...') clearBoard(); highlightBoard(function(x, y, info) { if ((x == info.x && y == info.y)) { // || (x == info.x2 && y == info.y2) return { paint: true, class: 'movable' } } return { paint: false } }, {x: x, y: y, x2: selection.x, y2: selection.y}) selection = null; } var selectedToken = null; var placementMode = "Select" function onTokenSelected(token) { if (token.hasClass('placement-token-selected')) { selectedToken = null; $('.placement-token').removeClass('placement-token-selected'); clearBoard(); setMessage("It's your turn to place a unit") } else { $('.placement-token').removeClass('placement-token-selected'); token.addClass('placement-token-selected'); //if (selectedToken != null) flicker(); selectedToken = token; setMessage('Select a location to place your ' + strings[token.data('type')].namelower); highlightBoard(function(x, y, info) { return { 'paint': true, 'class': 'selectable' } }); highlightBoard(function(x, y, info) { if (isPlacementIllegal(x, y)) return { paint: true, class: 'illegal' } else return { paint: false } }) } } function startPlacementRound() { if (state == states.Placing) { if (turn == playerId) { setMessage("It's your turn to place a unit"); openMenu('.placement-container'); } else { setMessage("It's your opponents turn to place a unit"); closeMenu('.placement-container'); } } } function movementHighlight(x, y, info) { var valid = true; if (getTokenAt(x, y) != null) { if (getTokenAt(x, y).owner == playerId) return true; } if (valid || (x == info.x && y == info.y)) { if (distance(x, y, info.x, info.y) < 2) { return { paint: true, class: 'movable' } } } return { paint: false } } var selection = null function onTokenClick(x, y, token) { //Let the magic begin if (turn == playerId && state == states.Playing) { var tokenObj = $token(token.reference); if (token.owner == playerId) { if (selection != null) { if (selection == token) { $('.token').removeClass('highlight'); selection = null; clearBoard(); $('.action-container').addClass('toggled'); } else { selection = token //CHANGED SELECTION $('.token').removeClass('highlight'); tokenObj.addClass('highlight'); clearBoard(); highlightBoard(movementHighlight, {x: x, y: y}); $('.action-container').addClass('toggled'); //setTimeout(function() { setupActions(token); //}, 800); } } else { //NEW SELECTION selection = token $('.action-container>.action-sub-container').remove() $('.token').removeClass('highlight'); tokenObj.addClass('highlight'); highlightBoard(movementHighlight, {x: x, y: y}); $('.action-container').addClass('toggled'); setupActions(token); //setTimeout(function() { // setupActions(token); //}, 800); } } else { if (state == states.Playing && selection != null) { if (distance(x, y, selection.x, selection.y) < 2) { finalizeMovement(selection, x, y); } } } } else if (turn == playerId && state == states.Targeting) { if (selection.tileTargetable(x, y, tokenList)) { finalizeAction(selection, token); } } else if (turn == playerId && state == states.Shuffling) { if (!token.revealed && token.owner == playerId && selection.type == "TokenVIP") { finalizeShuffle(selection, token) } } } function onReveal() { turn = -1; closeMenu('.action-container') socket.emit('turn', { action: 'reveal', x: selection.x, y: selection.y }) setMessage('Submitting move...') clearBoard(); highlightBoard(function(x, y, info) { if ((x == info.x && y == info.y)) { // || (x == info.x2 && y == info.y2) return { paint: true, class: 'movable' } } return { paint: false } }, {x: selection.x, y: selection.y}) selection = null; } function onActivate() { if (selection != null) { clearBoard(); if (selection.targetable) setState(states.Targeting); else setState(states.Confirmation); } } function onShuffle() { if (selection != null) { clearBoard(); setState(states.Shuffling); } } function startRound() { clearBoard(); //$('.token').removeClass('highlight'); //selection = null; log('---'); closeMenu('.action-container') if (turn == playerId) { setMessage("It's your turn"); } else setMessage("It's your opponents turn"); } function purgeCaptured() { var purgeList = []; for (var index = 0; index < tokenList.length; index++) { if (tokenList[index].captured) { var token = tokenList[index] var tokenObj = $token(token.reference); tokenObj.remove(); purgeList.push(token); } } for (var index = 0; index < purgeList.length; index++) { tokenList.splice(tokenList.indexOf(purgeList[index]), 1); } } function processTurn(data) { setMessage('Processing turn...') if (data.action == 'move') { var token = getTokenAt(data.x1, data.y1); animate(function() { moveTo(token, data.x2, data.y2); }, 450); log(logToken(token) + ' moved from ' + logPosition(data.x1, data.y1) + ' to ' + logPosition(data.x2, data.y2)); } else if (data.action == 'reveal') { var token = getTokenAt(data.x, data.y) if (data.revealed) { modify(token, { type: data.type, revealed: data.revealed, actionAvaliable: true }); log(logToken(token) + ' was revealed'); } else { modify(token, { type: data.type, revealed: data.revealed, actionAvaliable: false }); log(logToken(token) + ' was hidden'); } //TODO flash 'token' } else if (data.action == 'shuffle') { if (data.player == playerId) { var vip = getTokenAt(data.vipx, data.vipy); var token = getTokenAt(data.x, data.y); moveTo(vip, data.x, data.y); moveTo(token, data.vipx, data.vipy); log('Swapped positions of ' + logToken(vip) + logPosition(data.vipx, data.vipy) + ' and ' + logToken(token) + logPosition(data.x, data.y)); } else { log('Enemy VIP was swapped from ' + logPosition(data.vipx, data.vipy)); var t = getTokenAt(data.vipx, data.vipy); var tobj = $token(t.reference); console.log(t); console.log(tobj); tobj.addClass('log-view'); setTimeout(function() { tobj.removeClass('log-view'); }, 600); } } else if (data.action == 'chain') { for (var i = 0; i < data.steps.length; i++) { var action = data.steps[i]; if (action.action == 'animate') { var token = getTokenAt(action.x, action.y) if (action.animation == 'explode') { var tokenObj = $token(token.reference); tokenObj.addClass('block-anim').addClass('explode-anim'); log(logToken(token) + ' exploded at ' + logPosition(action.x, action.y)); } } else if (action.action == 'capture') { var token = getTokenAt(action.x, action.y) token.captured = true; var tokenObj = $token(token.reference) if (!tokenObj.hasClass('block-anim')) tokenObj.addClass('block-anim').addClass('capture-anim'); log(logToken(token) + ' was captured at ' + logPosition(action.x, action.y)); } else if (action.action == 'move') { var token = getTokenAt(action.x1, action.y1); animate(function() { moveTo(token, action.x2, action.y2); }, 450); log(logToken(token) + ' moved from ' + logPosition(action.x1, action.y1) + ' to ' + logPosition(action.x2, action.y2)); } else if (action.action == 'fatigue') { var token = getTokenAt(action.x, action.y); token.actionAvaliable = false; modify(token, { actionAvaliable: false }); log(logToken(token) + ' was activated'); } } setTimeout(function() { purgeCaptured(); }, 500) } clearBoard(); $('.token').removeClass('highlight'); socket.emit('confirm'); } function run() { socket = io.connect() setMessage('Connecting to server...'); socket.on('assigned-game', function(data) { playerId = data.slot; config = data.config; if (data.setup) { setMessage('Setting up game...'); setState(states.Setup); } else setMessage('Waiting for opponent...'); }); socket.on('setup-game', function(data) { setMessage('Setting up game...'); setState(states.Setup); }); socket.on('game-begin', function(data) { turn = data.turn; setMessage(null); setState(states.Begin); }); socket.on('game-place', function(data) { turn = data.turn; setState(states.Placing); }); socket.on('game-win', function(data) { var winner = data.winner; setTimeout(function() { $('.game').fadeOut(500); $('.title').removeClass('titleToggled'); $('.info-box').removeClass('info-box-toggled'); closeMenu('.placement-container'); }, 1500); if (winner == 0) { setMessage('The game was a draw!'); log('') log('The game was a draw'); } else if (winner == playerId) { setMessage('You won the game!'); log('') log('You won the game!'); } else { setMessage('You lost the game!'); log('') log('You lost the game!'); } }) socket.on('player-disconnect', function(data) { animate(function() { $('.game').fadeOut(500); $('.title').removeClass('titleToggled'); $('.info-box').removeClass('info-box-toggled'); closeMenu('.placement-container'); }, 500); setMessage('Your opponent has disconnected'); }); socket.on('token-placed', function(data) { if (data.owner != playerId) { createToken(data.owner, "TokenBlank", data.x, data.y); } setMessage('Finalizing turn...'); socket.emit('confirm'); }); socket.on('game-turn', function(data) { turn = data.turn; setState(states.Playing); }); socket.on('on-turn', function(data) { processTurn(data); }); } function bindActions() { $('.bind-reveal').click(function() { if (turn == playerId && !$(this).hasClass('action-disabled')) { onReveal(); } }); $('.bind-activate').click(function() { if (turn == playerId && !$(this).hasClass('action-disabled')) { onActivate(); } }); $('.bind-shuffle').click(function() { if (turn == playerId && !$(this).hasClass('action-disabled')) { onShuffle(); } }) } $(document).ready(function() { $('#startButton').click(function() { $('#startButton').fadeOut(400); setTimeout(function() { run(); }, 500); }); $('#close-log').click(function() { $('.combat-log').addClass('combat-log-hidden'); }); $('#open-log').click(function() { $('.combat-log').removeClass('combat-log-hidden'); }) bindActions(); if ($(window).width() < 500) { if (gameScale != 30) { setScale(30, 2) } } else { if (gameScale != 50) { setScale(50, 5); } } $(document).resize(function() { if ($(window).width() < 500) { if (gameScale != 30) { setScale(30, 2) } } else { if (gameScale != 50) { setScale(50, 5); } } }) }); //Combat Log Functions function log(string) { var element = $('<span class="log">' + string + '</span>').appendTo('.log-container'); element.find('.position-reference').mouseenter(function() { clearHighlights(); var x = $(this).data('x'); var y = $(this).data('y'); $tile(x, y).addClass('log-view'); }).mouseleave(function() { clearHighlights(); }) element.find('.token-reference').mouseenter(function() { clearHighlights(); var ref = $(this).data('ref'); $token(ref).addClass('log-view'); }).mouseleave(function() { clearHighlights(); }) } function logPosition(x, y) { return '<span class="log-int position-reference" data-x="'+ x +'" data-y="' + y + '">('+x+', '+y+')</span>'; } function logToken(token) { var type = strings[token.type].name; var append = ""; if (token.owner != playerId) append += "ref-enemy"; else append += "ref-friend"; return '<span class="log-int token-reference '+append+'" data-ref="' + token.reference + '">(' + type + ')</span>'; } function clearHighlights() { $('.token').removeClass('log-view'); $('.tile').removeClass('log-view'); }<file_sep>/* global $, strings, bindActions */ var gameScale = 50; var tokenOffset = 5; function openMenu(query) { $(query).removeClass('hidden'); setTimeout(function() { $(query).removeClass('toggled'); }, 100); } function closeMenu(query) { $(query).addClass('toggled'); $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 750); setTimeout(function() { if ($(query).hasClass('dynamic')) { $(query).remove() } else $(query).addClass('hidden'); }, 300); } function createActionMenu(menuName, data) { $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 500); var container = $('<section class="container ' + menuName + ' dynamic action-sub-container action-sub-container-pre"></section>').appendTo('.action-container'); if ('text' in data) { container.append('<p class="container-text">' + data.text + '</p>'); } if ('buttons' in data) { var buttons = data.buttons for (var index = 0; index < buttons.length; index++) { var button = buttons[index]; var classes = 'action-button'; if ('other' in button) { classes = classes + ' ' + button.other } var buttonObj = container.append('<a class="'+classes+'">' + button.text + '</a>'); buttonObj.mousedown(button.handler); } } setTimeout(function() { container.removeClass('action-sub-container-pre'); }, 10); } function closeActionMenu() { $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 500); } function setMessage(message) { $('.info').addClass('info-post'); if (!(message == "" || message == null)) { $('<h2 class="info info-pre">' + message + '</h2>').appendTo('.info-box'); setTimeout(function() { $('.info-pre').removeClass('info-pre'); }, 10); } setTimeout(function() { $('.info-post').remove() }, 800); } function setupActions(token) { $('.action-container>.action-sub-container').addClass('action-sub-container-post'); setTimeout(function() { $('.action-sub-container-post').remove(); }, 500); var thing = $('.template>.action-init').clone().addClass('action-sub-container-pre').appendTo('.action-container'); setTimeout(function() { thing.removeClass('action-sub-container-pre'); }, 10); if (!token.revealed) { thing.find('.bind-reveal').html(strings.Generic.reveal) } else { thing.find('.bind-reveal').html(strings.Generic.hide) } thing.find('.bind-activate').html(strings[token.type].actionVerb); if (token.actionAvaliable && token.revealed) { thing.find('.bind-activate').removeClass('action-disabled').addClass('action-button'); } else { thing.find('.bind-activate').addClass('action-disabled').removeClass('action-button'); } //TODO condition shuffle if (token.type == 'TokenVIP') { thing.find('.bind-shuffle').removeClass('action-disabled').addClass('action-button').show(); } else { thing.find('.bind-shuffle').addClass('action-disabled').removeClass('action-button').hide(); } openMenu('.action-container'); bindActions(); } function $tile(x, y) { return $(".tile[data-x='" + x + "'][data-y='" + y + "']"); } function $token(ref) { return $('.token[data-ref="'+ref+'"]'); } function boardCoord(x, y) { return { 'x': ((x*gameScale) + tokenOffset), 'y': ((y*gameScale) + tokenOffset) } } function setScale(scale, offset) { gameScale = scale; tokenOffset = offset } function moveTo(obj, x, y) { obj.x = x; obj.y = y; var position = boardCoord(x, y); $token(obj.reference) .css('top', position.y) .css('left', position.x); }<file_sep>/* global $, config */ function genBoard(width, height) { $('.board').remove(); $('.game').append('<table class="board"></table>'); for (var y = 0; y < height; y++) { var element = ""; for (var x = 0; x < width; x++) { element = element + '<td class="tile " data-x="'+x+'" data-y="'+y+'"></td>'; } element = '<tr>' + element + '</tr>'; $('.board').append(element); } $('.tile').mousedown(function() { //On tile click $(this).toggleClass('tileBlocked'); }); } genBoard(10, 10);<file_sep>module.exports = { board: { width: 10, height: 10 }, defaultTokens: [ "TokenAssassin", "TokenAssassin", "TokenAssassin", "TokenShooter", "TokenBomber", "TokenBomber", "TokenVIP" ] // defaultTokens: ["TokenBomber", "TokenVIP"] }<file_sep>var strings = { TokenBlank: { name: 'Unknown' }, TokenVIP: { name: 'VIP', namelower: 'VIP', actionVerb: 'Surrender', confirmation: 'Are you sure you want to surrender? (You will lose the game)' }, TokenBomber: { name: 'Bomber', namelower: 'bomber', actionVerb: 'Explode', confirmation: 'Are you sure you want to detonate your bomber?' }, TokenShooter: { name: 'Shooter', namelower: 'shooter', actionVerb: 'Shoot' }, TokenAssassin: { name: 'Assassin', namelower: 'assassin', actionVerb: 'Assassinate' }, Generic: { reveal: "Reveal", hide: "Hide" } }
d6f2adeb5a36af5bf1bd2dbdb64e30d918987b08
[ "Markdown", "JavaScript" ]
7
Markdown
MBRobertson/MARK
4a075b2b269199e1eecada8a7e317c8cebd7b06e
7f2b54ffb58bb9cb7abcc51b1ef25e46fbaf02a5
refs/heads/main
<file_sep># Si obtenemos los números enteros inferiores a 10 múltiplos de 3 y de 5 en una lista. # Tendremos el siguiente resultado: [3,5,6,9]. # La suma de todos estos múltiplos es 23. # Así mismo, obtenga la suma de todos los múltiplos de 3 y de 5 inferiores a 1000. list_of_numbers = range(1, 1000) list_items = [] for i in list_of_numbers: if i % 3 == 0 or i % 5 == 0: list_items.append(i) print(list_items) sum = 0 for i in list_items: sum += i print("La suma de todos los dígitos es:", sum)<file_sep>Mi repositorio de ejercicios diarios Un lugar donde guardar mi progreso a través de los días en la programación. Lenguaje de programación: Python 3 Primer ejercicio: "Si tenemos los números enteros inferiores a 10, multiplos de 3 y de 5 en una lista. Tendremos el siguientes resultado: [3, 5, 6, 9]. La suma de todos estos múltiplos es de 23. Así mismo, obtenga la suma de todos los múltiplos de 3 y de 5 inferiores a 1000." Segundo ejercicio: "Cada nuevo termino en la sucesión de Fibonacci se genera sumando los dos términos previos. Si comenzamos con 1 y 2, los primeros 10 términos serán: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Si consideramos los términos de la sucesión de Fibonacci cuyos valores no excedan los 4 millones, determine la suma de todos los valores pares." Tercer ejercicio: "Los factores primos de 13195 son 5, 7, 13 y 29. ¿Cuál es el factor primo más grande del número 600851475143?" Cuarto ejercicio: "Un número palindrómico se lee igual en ambos sentidos. El palíndromo más grande hecho del producto de dos números de 2 dígitos es 9009 = 91 × 99. Encuentra el palíndromo más grande hecho del producto de dos números de 3 dígitos." Quinto ejercicio: "2520 es el número más pequeño que se puede dividir por cada uno de los números del 1 al 10 sin ningún resto. ¿Cuál es el número positivo más pequeño que es divisible por todos los números del 1 al 20?" Sexto ejercicio: "La suma de los cuadrados de los primeros diez números naturales es, 1 ^ 2 + 2 ^ 2 + ... + 10 ^ 2 = 385 El cuadrado de la suma de los primeros diez números naturales es, (1 + 2 + ... + 10) ^ 2 = 55 ^ 2 = 3025 Por lo tanto, la diferencia entre la suma de los cuadrados de los primeros diez números naturales y el cuadrado de la suma es, 3025 - 385 = 2640 Calcula la diferencia entre la suma de los cuadrados de los primeros cien números naturales y el cuadrado de la suma."<file_sep># Cada nuevo termino en la sucesión de Fibonacci se genera sumando los dos términos previos. # Si comenzamos con 1 y 2, los primeros 10 términos serán: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # Si consideramos los términos de la sucesión de Fibonacci cuyos valores no excedan los 4 millones, determine la suma de todos los valores pares. list = [1, 2,] for i in range(2, 32): list.append(list[i-1] + list[i-2]) fibonacci_list = list sum = 0 for i in fibonacci_list: if i % 2 == 0: sum += i print(fibonacci_list) print("suma:", sum) # [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578] # suma: 4613732<file_sep>dict = {} for i in range(100, 1000): for j in range(100, 1000): key = f"{<KEY> value = i*j dict[key] = value list = [] for i in dict: string = str(dict[i]) if string != string[::-1]: list.append(i) print("Len List:",len(list)) print("Len Dict:",len(dict)) for i in list: dict.pop(i) print("Len Dict:",len(dict)) print(max(dict.values()))<file_sep>counter = 1 validator = [] l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] while True: for i in l: if counter % i == 0: validator.append(True) if len(validator) == len(l): break else: validator = [] counter += 1 print(counter)<file_sep>sumA = 0 for i in range(1,101): sumA += i**2 print("La suma de los cuadrados es:", sumA) sumB = 0 for i in range(1,101): sumB += i sumB **= 2 print("El cuadrado de la suma es:", str(sumB)) print("La diferencia es:", str(sumB-sumA))<file_sep># Los factores primos de 13195 son 5, 7, 13 y 29. ¿Cuál es el factor primo más grande del número 600851475143? def primos(): prs = [] lista = 100 cont = 0 for i in range(2, lista + 1): primos = True for j in range(2,11): if i == j: break elif i%j == 0: primos = False else: continue if primos == True: prs.append(i) cont += 1 return prs num = int(input("Número: ")) list_primes = primos() counter = 0 item = 0 index = 0 while True: item = list_primes[index] if num % item == 0: counter += 1 num /= item print("factor", counter, ":", str(item)) elif item > len(list_primes)-1 : break elif item < 2: break else: index += 1
bb9d804f796fc9d43013f7eacbce8670d3fbbd49
[ "Markdown", "Python" ]
7
Python
porgetit-0/Daily-exercises
06216cdc1b3469113c03f94045b7b3b516409460
e4114dc09a0edc65c4bf624cfecd1f519527d1d2
refs/heads/master
<file_sep>/* * ATTiny, Arduino and ESP8266 library to interface with PCF8574 * install TinyWireM library https://github.com/adafruit/TinyWireM * ATTiny85 I2C interface: SDA - pin P0 (0) and SCL - pin 2 (2); pull up to VCC (resistor 10kOm) * Arduino Nano I2C interface: SDA - pin A4 and SCL - pin A5 * ESP8266 I2C interface: SDA - pin GPIO4 and SCL - pin GPIO5 * * by <NAME> */ #pragma once #include "Arduino.h" #define Max_PCF8574_h #define INPUT_BIT 1 #define OUTPUT_BIT 0 class Max_PCF8574 { public: Max_PCF8574(); void begin(uint8_t address); void setBitMode(uint8_t bit, uint8_t mode); void setBitModeMask(uint8_t bitModeMask); void setBit(uint8_t bit, bool value); void setByte(uint8_t value); bool getBit(uint8_t bit); uint8_t getByte(); void pinMode(uint8_t pin, uint8_t mode); void digitalWrite(uint8_t pin, bool value); void write(uint8_t value); bool digitalRead(uint8_t pin); uint8_t read(); private: int _address; uint8_t _currentByte; uint8_t _bitModeMask; void i2cWrite(uint8_t value); uint8_t i2cRead(); };<file_sep>#include "Max_PCF8574.h" #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) #define TINY_WIRE #include <TinyWireM.h> #else #define WIRE #include <Wire.h> #endif Max_PCF8574::Max_PCF8574() { _address = 0; _bitModeMask = B11111111; } void Max_PCF8574::begin(uint8_t address) { _address = address; #if defined (TINY_WIRE) TinyWireM.begin(); #else Wire.begin(); #endif } void Max_PCF8574::setBitMode(uint8_t bit, uint8_t mode) { if (bit < 0 || bit > 7) { return; } switch (mode) { case INPUT_BIT: _bitModeMask |= (1 << bit); break; case OUTPUT_BIT: _bitModeMask &= ~(1 << bit); break; } } void Max_PCF8574::setBitModeMask(uint8_t bitModeMask) { _bitModeMask = bitModeMask; } void Max_PCF8574::setBit(uint8_t bit, bool value) { if (bit < 0 || bit > 7) { return; } if (value) { setByte(_currentByte | (1 << bit)); } else { setByte(_currentByte & ~(1 << bit)); } } void Max_PCF8574::setByte(uint8_t value) { if (_address == 0) { return; } _currentByte = value | _bitModeMask; i2cWrite(_currentByte); } uint8_t Max_PCF8574::getByte() { return i2cRead(); } bool Max_PCF8574::getBit(uint8_t bit) { if (bit < 0 || bit > 7) { return 0; } uint8_t byteValue = getByte(); return (byteValue & (1<<bit)) != 0; } void Max_PCF8574::pinMode(uint8_t pin, uint8_t mode) { setBitMode(pin, mode); } void Max_PCF8574::digitalWrite(uint8_t pin, bool value) { setBit(pin, value); } void Max_PCF8574::write(uint8_t value) { setByte(value); } bool Max_PCF8574::digitalRead(uint8_t pin) { return getBit(pin); } uint8_t Max_PCF8574::read() { return getByte(); } void Max_PCF8574::i2cWrite(uint8_t value) { #if defined (TINY_WIRE) TinyWireM.beginTransmission(_address); TinyWireM.write(value); TinyWireM.endTransmission(); #else Wire.beginTransmission(_address); Wire.write(value); Wire.endTransmission(); #endif } uint8_t Max_PCF8574::i2cRead() { #if defined (TINY_WIRE) TinyWireM.requestFrom(_address, 1); return TinyWireM.read(); #else Wire.requestFrom(_address, 1); return Wire.read(); #endif }<file_sep>#include <Max_PCF8574.h> /* * ATtiny85: * SDA_PIN 0 // pullup (10kOm to VCC) * SCL_PIN 2 // pullup (10kOm to VCC) * * Arduino: * SDA_PIN A4 * SCL_PIN A5 * * ESP8266: * SDA_PIN GPIO4 * SCL_PIN GPIO5 */ #define PCF8574_ADDRESS (0x20) // A0 - A1 - A2 (pins on PCF8574) are connected to GND #define LED_PIN 0 // (PCF8574 (0))--[R >= 330 Om]--(-)|LED|(+)----(VCC) // pin on PCF8574; cathode; resistor >= 330 Om #define BUTTON_PIN 1 // (VCC)--[R 10 kOm]--(PCF8574 (1))----|BUTTON|----(GND) //pin on PCF8574; pullup (10kOm to VCC) Max_PCF8574 expander; void setup() { expander.begin(PCF8574_ADDRESS); expander.setBitMode(LED_PIN, OUTPUT_BIT); expander.setBitMode(BUTTON_PIN, INPUT_BIT); // expander.setBitModeMask(0b01000000); // void; INPUT_BIT = 1; OUTPUT_BIT = 0; // expander.pinMode(LED_PIN, OUTPUT_BIT); // void } void loop() { byte bitValue = expander.getBit(BUTTON_PIN); if(bitValue == 0) { expander.setBit(LED_PIN, LOW); } else { expander.setBit(LED_PIN, HIGH); } // expander.getByte(); // returns byte // expander.setByte(0b00000000); // void // // expander.digitalRead(BUTTON_PIN); // returns bool // expander.read(); // returns byte // expander.digitalWrite(LED_PIN, LOW); // void // expander.write(0b00000000); // void } <file_sep># ATTiny85 library to interface with PCF8574 Install TinyWireM library https://github.com/adafruit/TinyWireM I2C interface: SDA - pin P0 (0) and SCL - pin 2 (2); pull up to VCC (resistor 10kOm)<file_sep># My libraries <file_sep># ATTiny, Arduino and ESP8266 library to interface with PCF8574 Install TinyWireM library https://github.com/adafruit/TinyWireM ATTiny85 I2C interface: SDA - pin P0 (0) and SCL - pin 2 (2); pull up to VCC (resistor 10kOm)<br/> Arduino Nano I2C interface: SDA - pin A4 and SCL - pin A5<br/> ESP8266 I2C interface: SDA - pin GPIO4 and SCL - pin GPIO5<br/>
ea416ad50938039052a1f9c75e8f040dd35b2b52
[ "Markdown", "C++" ]
6
C++
MaksKliuba/Libraries
7c04c77b1a0aad08d3f2cec9e9725c3210cc2323
04073fa3ce0519e20e70172fb93567644ef92b6f
refs/heads/master
<repo_name>rbrcurtis/proxy-hem<file_sep>/README.md #Because Hem is awesome but missing one thing... When playing around with [SpineJS](http://spinejs.com) I also discovered [Hem](https://github.com/maccman/hem). I immediately loved it and really wanted to use it with all my projects, everything I build for work and home is coffeescript and stylus. The only thing missing was built in support for the models to make ajax calls to an API or CRUD server. That's where proxy-hem comes in. Proxy-hem really only does one thing, it runs hem and it runs http-proxy. All requests for static content: images, stylesheets, javascript, etc... are directed to Hem. Everything else is passed through to the default server. #Installation npm install -g proxy-hem #Usage The proxy server will setup to run at http://localhost:3000 by default. Configuration for this is coming soon. Proxy-hem should be run from the directory where the slug.json file exists. You can specify a port for Hem to use using -p. Otherwise, the only Hem command used is 'server'. The API server is expected to be running at https://localhost:4000. Configuration for this is coming soon. For Hem usage, see [Hem guide](http://spinejs.com/docs/hem) <file_sep>/index.js #!/usr/bin/env node require(__dirname+'/node_modules/coffee-script'); require(__dirname+'/src/proxy-hem').exec();
50ba19d3969527cd91dff53550d105f7c5b93fd3
[ "Markdown", "JavaScript" ]
2
Markdown
rbrcurtis/proxy-hem
1dfb253ea87cb4cdca931dd63035c822c2509be0
651f54013c1156dfec55342cf947d6fbf19efeb8
refs/heads/master
<file_sep>import React from "react"; import { NavLink } from "react-router-dom"; import "./ClassRoomListItem.css"; // import MainPanelContent from "../../../MainPanel/MainPanelContent/MainPanelContent"; const ClassRoomListItem = props => ( <div className="ClassRoomListItem"> <NavLink to={`/${props.classname}`} className="classname" activeClassName="is-active" > <p className="classname">{props.classname}</p> </NavLink> </div> ); export default ClassRoomListItem; <file_sep>import React from "react"; import MainPanelContent from "./MainPanelContent/MainPanelContent"; import "./MainPanel.css"; export default class MainPanel extends React.Component { // constructor(props) { // super(props); // } render() { console.log(this.props); return ( <div className="mainPanel"> {this.props.match.path === "/" ? ( <h1>Select a Class </h1> ) : ( <MainPanelContent {...this.props} /> )} </div> ); } } <file_sep>import React from "react"; import Layout from "../components/Layout/Layout"; import ClassRoomListItem from "../components/SidePanel/ClassRoomList/ClassRoomListItem/ClassRoomListItem"; import { BrowserRouter, Route, Switch, Link } from "react-router-dom"; import Header from "../components/Header/Header"; import MainPanel from "../components/MainPanel/MainPanel"; const NotFound = () => ( <div> 404 eRROR <Link to="/">Go Home</Link> </div> ); const AppRouter = () => ( <BrowserRouter> <div> <Header /> <Switch> <Route path={`/`} component={MainPanel} exact={true} /> <Route path={`/:id`} component={Layout} /> <Route component={NotFound} /> </Switch> </div> </BrowserRouter> ); export default AppRouter; <file_sep>import React from "react"; import "./App.css"; import Header from "./components/Header/Header"; import data from "./classroom_data.json"; export default class App extends React.Component { // constructor(props) { // super(props); // } render() { console.log({ data }); // Use this data to render this page return ( <div> <Header /> </div> ); } } <file_sep>## Assignment Scaffolding ##Result ***User Flow*** 1. User Lands on the first view where no classRoom is selected ![front](https://user-images.githubusercontent.com/28656259/63886555-5f552a00-c9f8-11e9-928e-d49f8c68696f.PNG) 2. Clicking on a Class User can see the full view of that class ![classInfo](https://user-images.githubusercontent.com/28656259/63886587-798f0800-c9f8-11e9-8a60-df3b4983ce41.PNG) 3. Clicking on a 'Show Average' can see the Average of marks of all students in that class ![classAverage](https://user-images.githubusercontent.com/28656259/63886602-7e53bc00-c9f8-11e9-9c38-1de2e2d0ae30.PNG) ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode. Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits. You will also see any lint errors in the console. <file_sep>import React from "react"; import { NavLink } from "react-router-dom"; import SidePanel from "../SidePanel/SidePanel"; import "./Header.css"; import MainPanel from "../MainPanel/MainPanel"; const Header = () => ( <header className="Header"> <SidePanel /> </header> ); export default Header; <file_sep>import React from "react"; import "./AverageClass.css"; const AverageClass = (props) => ( <div className="AverageClass"> <p>Classroom Average Performance: {props.score}% </p> </div> ); export default AverageClass; <file_sep>import data from "../classroom_data.json"; import { createStore } from "redux"; const store = createStore((state = { data: null },action) => { return state; }); console.log(store.getState()); console.log(data); <file_sep>export const showClass = () => ({ type: "SHOW_CLASS" }); <file_sep>import data from "../classroom_data.json"; const classroomReducerDefaultState = data; const classroomReducer = (state = classroomReducerDefaultState, action) => { switch (action.type) { case "SHOW_CLASS": return [...state]; default: return state; } }; export default classroomReducer; <file_sep>import React from "react"; import { NavLink } from "react-router-dom"; import MainPanel from "../MainPanel/MainPanel"; import SidePanel from "../SidePanel/SidePanel"; import "./Layout.css"; export default class Layout extends React.Component { // constructor(props) { // super(props); // } state = { classClicked: false }; classIsClicked = () => { this.setState({ classClicked: true }); }; render() { console.log(this.props); return ( <div className="Layout"> <SidePanel classIsClicked={this.classIsClicked} /> <MainPanel {...this.props} /> </div> ); } } <file_sep>import React, { Component } from "react"; import { Line } from "rc-progress"; import "./StudentInfo.css"; class StudentInfo extends Component { render() { return ( <div className="StudentInfo"> <div className="right"> <p className="name">{this.props.name}</p> <p className="percent"> {Math.round( this.props.average )} % </p> </div> <div className="right"> <p className="subject">Maths</p> <Line percent={this.props.maths} strokeWidth="4" trailWidth="4" strokeColor="#7174cf" trailColor="#d9d9d9" style={{ width: 150, height: 8, marginTop: 20 }} /> <p className="subjectpercent">{this.props.maths}%</p> </div> <div className="right"> <p className="subject">Science</p> <Line percent={this.props.science} strokeWidth="4" trailWidth="4" strokeColor="#7174cf" trailColor="#d9d9d9" style={{ width: 150, height: 8, marginTop: 20 }} /> <p className="subjectpercent">{this.props.science}%</p> </div> <div className="right"> <p className="subject">English</p> <Line percent={this.props.english} trailWidth="4" strokeWidth="4" strokeColor="#7174cf" trailColor="#d9d9d9" style={{ width: 150, height: 8, marginTop: 20 }} /> <p className="subjectpercent">{this.props.english}%</p> </div> </div> ); } } export default StudentInfo;
728b9162fdb7e24ff07dd5cd847dd1ff4811eff4
[ "JavaScript", "Markdown" ]
12
JavaScript
tanisha2398/Assessment_spotMentor
10cf2b85efad60df4301026aa01572d8b8d31605
de06bf8ba85cf2126a48b7d800e9eb41dd69f5fe
refs/heads/master
<file_sep>/** * Created by wenpeng.guo on 9/26/16. */ import {Component} from '@angular/core'; @Component({ selector: 'my-heroes', templateUrl: 'app/accordion.component.html', styleUrls: ['app/accordion.component.css'], }) export class AccordionComponent{ }<file_sep>/** * Created by wenpeng.guo on 9/23/16. */ export class Hero{ id: number; name: string; }<file_sep>/** * Created by wenpeng.guo on 9/23/16. */ import {Component} from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <router-outlet></router-outlet> <nav> <a routerLink="/dashboard" routerLinkActive="active">Home</a> <a routerLink="/accordion" routerLinkActive="active">Accordion</a> <a routerLink="/button" routerLinkActive="active">Button</a> </nav> `, styleUrls: ['app/app.component.css'] }) export class AppComponent { title = 'Angular2 NG Bootstrap'; }<file_sep>/** * Created by wenpeng.guo on 9/21/16. */ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {FormsModule} from '@angular/forms'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import {routing} from './app.routing'; import {AppComponent} from './app.component'; import {DashboardComponent} from "./dashboard.component"; import {AccordionComponent} from "./accordion.component"; import {ButtonComponent} from "./button.component"; @NgModule({ imports: [ BrowserModule, FormsModule, NgbModule, routing ], declarations: [ AppComponent, DashboardComponent, AccordionComponent, ButtonComponent ], bootstrap: [AppComponent] }) export class AppModule { }<file_sep>/** * Created by wenpeng.guo on 9/23/16. */ import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; @Component({ selector: 'my-dashboard', templateUrl: 'app/dashboard.component.html', styleUrls:['app/dashboard.component.css'], }) export class DashboardComponent { }<file_sep>/** * Created by wenpeng.guo on 9/23/16. */ import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {DashboardComponent} from './dashboard.component'; import {AccordionComponent} from './accordion.component'; import {ButtonComponent} from './button.component'; const appRoutes: Routes = [ { path: 'accordion', component: AccordionComponent }, { path: 'button', component: ButtonComponent }, { path: 'dashboard', component: DashboardComponent }, { path: '', redirectTo: '/dashboard', pathMatch: 'full' } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);<file_sep>/** * Created by wenpeng.guo on 9/26/16. */ import {Component} from '@angular/core'; @Component({ selector: 'my-heroes', templateUrl: 'app/button.component.html' // styleUrls: ['app/accordion.component.css'], }) export class ButtonComponent{ model = { left: true, middle: false, right: false }; }<file_sep># angular2-practice 1. npm install 2. npm run typings install # How to run ```bash npm start ``` feature
f9e67697ef5d5d91cc175d891d9da4a81aa0d48a
[ "Markdown", "TypeScript" ]
8
TypeScript
smallg/angular2-practice
f71044765344587dc1955c864a184a7c23899a0a
c8866ea77eb98208013ea1c4a602947de22a1525
refs/heads/main
<repo_name>wuzhuangtai00/PDC-Project<file_sep>/problem_2.sh g++ Cholesky.cpp -o problem_2 -std=c++11 -mcmodel=large -O2 -fopenmp <file_sep>/normal.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<ctime> #include<vector> #include<set> #include<cmath> #include<sys/time.h> #define rep(i, a, b) for(int i = (a); i <= (b); i++) #define per(i, a, b) for(int i = (a); i >= (b); i--) using namespace std; #define pb push_back #define mk make_pair #define w1 first #define w2 second typedef pair<int,int> pin; FILE* l,* u; inline void read(int &x){ char ch = getchar(); while(ch == '%') { while(ch != '\n') ch = getchar(); ch = getchar(); } x=0;int f=1; while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} x*=f; } int n, m; const double eps = 1e-5; const int maxn = 86000; double a[maxn][maxn]; vector<int> pos[maxn]; namespace unions{ int fa[maxn]; inline void init(int n){ rep(i, 1, n) fa[i] = i; } inline int find(int x) { if (fa[x] == x) return x; int f = find(fa[x]); fa[x] = f; return f; } inline void setfa(int x, int y) { fa[find(x)] = find(y); } } inline void init() { read(n); read(n); read(m); rep(i, 1, m) { int x, y; double z; read(x); read(y); scanf("%lf", &z); if(fabs(z) < eps) continue; a[x][y] = z; a[y][x] = z; if(x < y) swap(x, y); pos[x].pb(y); } unions::init(n); } int cur[maxn], parent[maxn], nmsl[maxn]; double val[maxn]; inline void solve() { fprintf(l, "%d\n", n); fprintf(u, "%d\n", n); rep(i, 1, n) { for(auto x: pos[i]) { int w = unions::find(x); if(w == i) continue; parent[w] = i; unions::setfa(w, i); } } // rep(i,1,n)parent[i] = i+1;parent[n] = 0; rep(i, 1, n) { // printf("!%d\n", i); int cnt = 0, x = i; while(x) { // printf("%d\n", x); cur[++cnt] = x; x = parent[x]; }int cnm = 0; rep(p, 1, cnt) { int j = cur[p]; if (fabs(a[i][j])>1e-3){ // fprintf(u, "%d %d %.15lf\n", i, j, a[i][j]); nmsl[++cnm] = j; val[cnm] = a[i][j]; } } fprintf(l, "%d %d %.12f\n", i, i, 1.0); if(fabs(a[i][i]) < eps) continue; if(a[i][i] == 0) continue; rep(p, 2, cnt) { int k = cur[p]; if(fabs(a[k][i])<1e-3) continue; // if (fabs(a[k][i] / a[i][i]) < 1e-10) continue; // if (a[k][i] == 0) continue; double d = a[k][i] / a[i][i]; // fprintf(l, "%d %d %.15lf\n", k, i, d); rep(t, 1, cnm){ int j = nmsl[t]; a[k][j] -= val[t] * d; } } } } struct timeval starts, endsss; int main(int argc, char** argv) { gettimeofday(&starts, NULL); puts(argv[0]); freopen(argv[1], "r", stdin); l = fopen(argv[2], "w"); u = fopen(argv[3], "w"); init(); gettimeofday(&endsss, NULL); double delta = ((endsss.tv_sec - starts.tv_sec) * 1000000u + endsss.tv_usec - starts.tv_usec) / 1.e6; printf("Init: %.4f\n", delta); gettimeofday(&starts, NULL); solve(); gettimeofday(&endsss, NULL); delta = ((endsss.tv_sec - starts.tv_sec) * 1000000u + endsss.tv_usec - starts.tv_usec) / 1.e6; printf("Solve: %.4f\n", delta); // fclose(l); // fclose(u); // output(); }<file_sep>/Cholesky.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<ctime> #include<map> #include<vector> #include<set> #include<cmath> #include<cassert> #define rep(i, a, b) for(int i = (a); i <= (b); i++) #define per(i, a, b) for(int i = (a); i >= (b); i--) using namespace std; #define pb push_back #define mk make_pair #define w1 first #define w2 second typedef pair<int,int> pin; const double eps = 1e-3; typedef pair<int, double> info; const int maxm = 2000000000; info pool1[6000000000ll]; info *ptr; set<pin> rec; inline void read(int &x){ char ch = getchar(); while(ch == '%') { while(ch != '\n') ch = getchar(); ch = getchar(); } x=0;int f=1; while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} x*=f; } const int maxn = 86334; int n, m; namespace unions{ int fa[maxn]; inline void init(int n){ rep(i, 1, n) fa[i] = i; } inline int find(int x) { if (fa[x] == x) return x; int f = find(fa[x]); fa[x] = f; return f; } inline void setfa(int x, int y) { fa[find(x)] = find(y); } } vector<pair<int,double> > pos[maxn]; vector<pair<int,double> > all[maxn]; int parent[maxn]; //The father in the elinimation tree. map<int, double> w[maxn]; inline void init() { read(n); read(n); read(m); rep(i, 1, m) { int x, y; double z; read(x); read(y); scanf("%lf", &z); if(fabs(z) <= eps) continue; if(x < y) swap(x, y); w[x][y] = z; w[y][x] = z; assert(fabs(z) > 1e-8); pos[x].pb(mk(y, z)); rec.insert(mk(x, y)); } unions::init(n); rep(i, 1, n) { // sort(all[i].begin(), all[i].end()); sort(pos[i].begin(), pos[i].end()); } ptr = pool1; } vector<int> son[maxn]; int stpos[maxn]; int size[maxn]; info* Left[maxn]; info* Right[maxn]; int upper[maxn]; clock_t pre; bool vis[maxn]; long long cnt = 0; inline info* mlc(int sz) { cnt += sz; if(cnt > 6000000000ll) { // ptr = pool2; assert(0); } info* tmp = ptr; ptr = ptr + sz; return tmp; } inline void dfs(int x, int sz) { vis[x] = 1; upper[x] = sz; // printf("%d\n", size[x]); // assert(sz <= n); Left[x] = (info*)mlc(size[x]); Right[x] = (info*)mlc(sz); if(parent[x]){ rep(i, 0, sz - 2) Right[x][i] = Right[parent[x]][i]; Right[x][sz - 1] = mk(parent[x], 0); } Left[x][0] = mk(x, 0); int cur = 1; for(auto y: son[x]) { dfs(y, sz + 1); stpos[y] = cur; cur += size[y]; rep(i, stpos[y], cur - 1) { Left[x][i] = Left[y][i - stpos[y]]; } } } pair<pin, double> U[50000000]; int cntL, cntU; int poshis[maxn]; inline void printLeft(int x, int y) { printf("Left[%d][%d].w1 = %d Left[%d][%d].w2 = %.3f, Size [%d] = %d\n", x, y, Left[x][y].w1, x, y, Left[x][y].w2, x, size[x]); } inline void printRight(int x, int y) { printf("Right[%d][%d].w1 = %d Right[%d][%d].w2 = %.3f, RightSize [%d] = %d\n", x, y, Right[x][y].w1, x, y, Right[x][y].w2, x, upper[x] - 1); } inline void solve() { rep(i, 1, n) { for(auto x: pos[i]) { int y = x.w1; int w = unions::find(y); if(w == i) continue; // printf("%d %d\n", w, i); parent[w] = i; son[i].pb(w); unions::setfa(w, i); } } rep(i, 1, n) size[i] = 1; rep(i, 1, n) if(parent[i]) size[parent[i]] += size[i]; // int ppp = 0; // rep(i, 1, n) ppp += size[i]; // printf("%d\n", ppp); // return; per(i, n, 1) { if (vis[i]) continue; dfs(i, 0); } // rep(i, 1, n) { // printf("%d %d\n", stpos[i], parent[i]); // } printf("Block1: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); printf("Total Used: %lld\n", cnt); rep(i, 1, n) { unsigned j = 0; rep(k, 0, size[i] - 1) { if (w[i].count(Left[i][k].w1)) Left[i][k].w2 = w[i][Left[i][k].w1]; } rep(k, 0, upper[i] - 1) { if (w[i].count(Right[i][k].w1)) Right[i][k].w2 = w[i][Right[i][k].w1]; } } printf("Block2: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); rep(x, 1, n) { assert(Left[x][0].w2 > 0); double www = sqrt(Left[x][0].w2); cntU++; U[cntU] = mk(mk(x, x), www); // printRight(1, 0); vector<int> nz; nz.clear(); rep(k, 0, upper[x] - 1) { info w = Right[x][k]; if(fabs(w.w2) > 1e-7) { cntU++; U[cntU] = mk(mk(x, w.w1), w.w2 / www); nz.pb(k); } } int y = parent[x]; int curpos = stpos[x]; int poscnt = 0; if(fabs(Left[x][0].w2) < 1e-9) continue; while(y) { // printf("%d\n", y); poshis[++poscnt] = y; // printf("Size:%d\n", size[y]); // printLeft(y, 0); // printLeft(y, 1); // printf("%d %d %.3f\n",Left[y][curpos].w1, x, Left[y][curpos].w2); // putchar('!');printLeft(y, curpos); double d = Left[y][curpos].w2 / Left[x][0].w2; if (fabs(d) > 1e-8) { cntL++; // printf("%.10f %.10f\n", Left[y][curpos].w2, Left[x][0].w2); // printf("%.10f\n", d); for(unsigned i = 0; i < nz.size(); i++) { int k = nz[i]; if (k >= upper[y]) break; Right[y][k].w2 -= Right[x][k].w2 * d; } int wpos = 0; int iter = poscnt - 1; // printf("%d %d\n", upper[x], upper[y]); rep(i, upper[y], upper[x] - 1) { // printf("%d %d\n", Left[y][wpos].w1, Right[x][i].w1); // assert(Left[y][wpos].w1 == Right[x][i].w1); Left[y][wpos].w2 -= Right[x][i].w2 * d; // printLeft(y, wpos); wpos += stpos[poshis[iter]]; iter--; } // printf("?%d\n", curpos); Left[y][curpos].w2 -= Left[x][0].w2 * d; // printLeft(3, 1); } curpos += stpos[y]; y = parent[y]; // printf("???%d\n", stpos[y]); } } } /* inline void check_ans() { static vector<pair<int, double> > Ls[maxn], Ul[maxn]; rep(i, 1, cntL) { pair<pin, double> x = L[i]; Ls[x.w1.w2].pb(mk(x.w1.w1, x.w2)); } rep(i, 1, cntU) { pair<pin, double> x = U[i]; Ul[x.w1.w1].pb(mk(x.w1.w2, x.w2)); } rep(j, 1, n) { for(auto i: Ls[j]) for(auto k: Ul[j]) { w[i.w1][k.w1] -= i.w2 * k.w2; } } bool flag = 1; rep(i, 1, n) { for(pair<int, double> v : w[i]) { if(fabs(v.w2) > eps) { flag = 0; printf("%d %d %.10f\n", i, v.w1, v.w2); } } } // printf("%d\n", flag); if(flag) puts("Correct!"); else puts("Error!"); } inline void output() { printf("%d\n", cntL); rep(i, 1, cntL) { pair<pin, double> x = L[i]; printf("%d %d %.8f\n", x.w1.w1, x.w1.w2, x.w2); } puts(""); printf("%d\n", cntU); rep(i, 1, cntU) { pair<pin, double> x = U[i]; printf("%d %d %.8f\n", x.w1.w1, x.w1.w2, x.w2); } } */ int main() { pre = clock(); init(); printf("Init: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); solve(); printf("Solve: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); // check_ans(); printf("Check Ans: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); // output(); printf("Output: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); }<file_sep>/brute_force.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<ctime> #include<vector> #include<set> #include<cmath> #define rep(i, a, b) for(int i = (a); i <= (b); i++) #define per(i, a, b) for(int i = (a); i >= (b); i--) using namespace std; #define pb push_back #define mk make_pair #define w1 first #define w2 second typedef pair<int,int> pin; inline void read(int &x){ char ch = getchar(); while(ch == '%') { while(ch != '\n') ch = getchar(); ch = getchar(); } x=0;int f=1; while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} x*=f; } int n, m; const double eps = 1e-5; const int maxn = 85000; double a[maxn][maxn]; double pra[maxn][maxn]; set<pin> pos; inline void init() { read(n); read(n); read(m); rep(i, 1, m) { int x, y; double z; read(x); read(y); scanf("%lf", &z); a[x][y] = z; a[y][x] = z; // pos.insert(mk(x, y)); } } struct data{ int x, y; double v; data(int _x, int _y, double _z) { x = _x; y = _y; v = _z; } }; vector<data> L, U; inline void solve() { rep(i, 1, n) { rep(k, i, n) { if(a[i][k] != 0) { U.pb(data(i, k, a[i][k])); } } L.pb(data(i, i, 1)); if(a[i][i] == 0) continue; rep(j, i + 1, n) { if (a[j][i] == 0) continue; double d = a[j][i] / a[i][i]; L.pb(data(j, i, d)); rep(k, i, n) a[j][k] -= d * a[i][k]; } } } double Lm[maxn][maxn], Um[maxn][maxn]; set<int> Ls[maxn], Ul[maxn]; inline void check_ans() { } FILE *u, *l; inline void output() { fprintf(l, "%d\n", n); for(unsigned i = 0; i < L.size(); i++) { data x = L[i]; fprintf(l, "%d %d %.20lf\n", x.x, x.y, x.v); } // puts(""); fprintf(u, "%d\n", n); for(unsigned i = 0; i < U.size(); i++) { data x = U[i]; fprintf(u, "%d %d %.20lf\n", x.x, x.y, x.v); } } int main(int argc, char** argv) { clock_t pre = clock(); freopen(argv[1], "r", stdin); l = fopen(argv[2], "w"); u = fopen(argv[3], "w"); init(); printf("Init: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); solve(); printf("Solve: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); pre = clock(); // check_ans(); pre = clock(); output(); printf("Check Ans: %.4f\n", (clock() - pre)/(double)CLOCKS_PER_SEC); }<file_sep>/test_par.sh rm problem_3 g++ faq.cpp -o problem_3 -mcmodel=medium -std=c++11 -fopenmp -O2 ./problem_3 1138_bus.mtx l1.txt u1.txt # ./check 1138_bus.mtx l1.txt u1.txt ./problem_3 bcsstk18.mtx l1.txt u1.txt # ./check bcsstk18.mtx l1.txt u1.txt<file_sep>/README.md # PDC-Project Code of the L<file_sep>/problem_3.sh g++ faq.cpp -o problem_3 -std=c++11 -mcmodel=large -O2 -fopenmp <file_sep>/gen.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<ctime> #include<map> #include<vector> #include<set> #include<cmath> #define rep(i, a, b) for(int i = (a); i <= (b); i++) #define per(i, a, b) for(int i = (a); i >= (b); i--) using namespace std; #define pb push_back #define mk make_pair #define w1 first #define w2 second const int n = 3000; const int maxn = 10005; int a[maxn][maxn], b[maxn][maxn], c[maxn][maxn]; int main(){ srand(time(NULL)); rep(i, 1, n) rep(j, 1, i) { if(rand() % 100 == 0){ int w = rand() % 100 + 1; a[i][j] = b[j][i] = w; } } rep(i, 1, n) rep(j, 1, n) rep(k, 1, n) c[i][k] += a[i][j] * b[j][k]; vector<pair<pair<int,int>,int> > v; rep(i, 1, n) rep(j, 1, i) { if (c[i][j]) v.pb(mk(mk(i, j), c[i][j])); } printf("%d %d %d\n", n, n, (int)v.size()); for(auto x:v) { printf("%d %d %d\n", x.w1.w1, x.w1.w2, x.w2); } }<file_sep>/mac.sh g++ faq.cpp -o problem_3 -mcmodel=medium -I /usr/local/opt/libomp/include/ -L /usr/local/opt/libomp/lib -lomp -O2 -std=c++11 ./problem_3 1138_bus.mtx l1.txt u1.txt ./check 1138_bus.mtx l1.txt u1.txt ./problem_3 bcsstk18.mtx l1.txt u1.txt ./check bcsstk18.mtx l1.txt u1.txt<file_sep>/test.sh g++ normal.cpp -o normal -O2 -mcmodel=medium -std=c++11 ./normal 1138_bus.mtx l3.txt u3.txt ./check 1138_bus.mtx l3.txt u3.txt ./normal bcsstk18.mtx l3.txt u3.txt ./check bcsstk18.mtx l3.txt u3.txt<file_sep>/problem_1.sh g++ brute_force.cpp -o problem_1 -std=c++11 -mcmodel=medium -O2 <file_sep>/check.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<ctime> #include<vector> #include<set> #include<cmath> #include<sys/time.h> #define rep(i, a, b) for(int i = (a); i <= (b); i++) #define per(i, a, b) for(int i = (a); i >= (b); i--) using namespace std; #define pb push_back #define mk make_pair #define w1 first #define w2 second typedef pair<int,int> pin; FILE* l,* u; inline void read(int &x){ char ch = getchar(); while(ch == '%') { while(ch != '\n') ch = getchar(); ch = getchar(); } x=0;int f=1; while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} x*=f; } int n, m; const double eps = 1e-2; const int maxn = 88000; double a[maxn][maxn]; vector<pair<int,double> > Lh[maxn], Ur[maxn]; inline void init() { read(n); read(n); read(m); // memset(a, 0, sizeof(a)); // memset(res, 0, sizeof(res)); rep(i, 1, m) { int x, y; double z; read(x); read(y); scanf("%lf", &z); a[x][y] = z; a[y][x] = z; } fscanf(l, "%d", &n); int x, y; double z; while(fscanf(l, "%d %d %lf", &x, &y, &z)!=EOF) { Lh[y].pb(mk(x, z)); // l[x][y] = z; } fscanf(u, "%d", &n); while(fscanf(u, "%d %d %lf", &x, &y, &z)!=EOF) { Ur[x].pb(mk(y, z)); } } int cur[maxn]; inline void solve() { rep(j, 1, n) { for(pair<int,double> x: Lh[j]) for(pair<int,double> y: Ur[j]) { a[x.w1][y.w1] -= x.w2 * y.w2; } } bool flag = 1; rep(i, 1, n) rep(j, 1, n) { if (fabs(a[i][j]) > eps) { printf("%.10f\n", a[i][j]); flag = 0; break; } } if(flag)puts("Correct!");else puts("Error("); } struct timeval starts, endsss; int main(int argc, char** argv) { gettimeofday(&starts, NULL); puts(argv[0]); freopen(argv[1], "r", stdin); l = fopen(argv[2], "r"); u = fopen(argv[3], "r"); init(); gettimeofday(&endsss, NULL); double delta = ((endsss.tv_sec - starts.tv_sec) * 1000000u + endsss.tv_usec - starts.tv_usec) / 1.e6; printf("Init: %.4f\n", delta); gettimeofday(&starts, NULL); solve(); gettimeofday(&endsss, NULL); delta = ((endsss.tv_sec - starts.tv_sec) * 1000000u + endsss.tv_usec - starts.tv_usec) / 1.e6; printf("Solve: %.4f\n", delta); fclose(l); fclose(u); // output(); }
2be971005d068dfd8498776cb08f6d6c0fabe2a3
[ "Markdown", "C++", "Shell" ]
12
Shell
wuzhuangtai00/PDC-Project
b2c4247f4805e47c38ba6e5fb49963fae5aff19d
ace465d5def8343a6cee76199fc190a3be18f8d3
refs/heads/master
<repo_name>EDWINSOM/ucd-csi2312-pa2<file_sep>/main.cpp #include <iostream> #include "Point.h" #include "Cluster.h" #include "KMeans.h" #include "Exceptions.h" #include <forward_list> #include <fstream> #include <sstream> using namespace std; using namespace Clustering; const double KMeans::SCORE_DIFF_THRESHOLD = 10; int main() { KMeans instance; ifstream myFile("/home/marisa/Projects/interm program/pa2/points.txt"); if (myFile.is_open()) { myFile >> instance; } else if (myFile.fail()) { cout << "File didn't open"; } instance.clusteringAlgor(instance); myFile.close(); return 0; } <file_sep>/KMeans.h // // Created by marisa on 11/8/15. // #ifndef PA2_KMEANS_H #define PA2_KMEANS_H #include "Cluster.h" namespace Clustering { typedef Cluster* ClusterPtr; class KMeans { ClusterPtr point_space = nullptr; PointPtr centroidSelection = nullptr; unsigned k = 0; unsigned dimension = 0; public: // used in a termination condition static const double SCORE_DIFF_THRESHOLD; KMeans(); KMeans(unsigned kValue, unsigned dim); ~KMeans(){delete point_space;} double computeClusteringScore(Cluster []); friend std::istream &operator>>(std::istream &, KMeans &); double clusteringAlgor(KMeans & means); }; } #endif //PA2_KMEANS_H <file_sep>/Cluster.cpp // DO NOT: 1. dereference head pointer 2. dereference nullptr! #include "Cluster.h" #include <iostream> #include <cassert> #include <fstream> #include <sstream> #include <algorithm> #include <iomanip> using namespace std; static unsigned int idtracker = 0; namespace Clustering { // Copy Constructor // Cluster c2(c1) Cluster::Cluster(Cluster &cluster) : size(cluster.size), dimension(cluster.dimension), __centroid(cluster.dimension) { this->validCentroid = false; if (cluster.size == 0) // if cluster is empty, set new cluster's head to null pointer and size 0; { head.clear(); (this->__id) = (this->idGenerate()); return; } this->head = cluster.head; this->__centroid = head.front(); (this->__centroid) = (this->computeCentroid()); return; } // Assignment Operator Cluster &Cluster::operator=( Cluster &cluster) { if (this == &cluster) // does not let self assignment occur { return *this; } head.clear(); (this->size) = cluster.size; // set size equal to cluster's size (this->dimension) = cluster.dimension; if (size == 0) // if cluster is empty, set new cluster's head to null pointer { head.clear(); return (*this); } head = cluster.head; this->__centroid = cluster.head.front(); (this->__centroid) = (this->computeCentroid()); return (*this); } // Destructor Cluster::~Cluster() { head.clear(); } // Set functions: They allow calling c1.add(c2.remove(p)); // remove a point and return it so we can add it to another cluster void Cluster::remove(const Point &unwantedPoint) throw (RemoveFromEmptyEx) { this->validCentroid = false; try { if(this->size == 0) throw RemoveFromEmptyEx("remove"); std::forward_list<Point>::iterator it = this->head.begin(); if (size == 1) { Point test = *it; if ( (test) == (unwantedPoint) ) { head.clear(); --size; } else { cout << endl << "Such a point isn't contained in this cluster. Returning unwanted point" << endl; } } if (size == 2) { Point test2 = *it; if ((test2) == (unwantedPoint)) { head.pop_front(); --size; (this->__centroid) = this->computeCentroid(); } ++it; Point test3 = *it; if ((test3) == (unwantedPoint)) { head.remove(*it); --size; (this->__centroid) = this->computeCentroid(); } else { cout << endl << "Such a point isn't contained in this cluster. Returning unwanted point" << endl; } } it = head.begin(); Cluster copy; for (it; it!= head.end(); ++it) { Point test4 = *it; if ((test4) != (unwantedPoint)) { copy.add(*it); } } (*this) = copy; (this->__centroid) = this->computeCentroid(); } catch(RemoveFromEmptyEx stringName) { cout << stringName; cout << endl << "Cluster is already empty. No points to remove" << endl << endl; } } void Cluster::add(const Point &point) // add a point { NodePtr newNode = new Node; this->validCentroid = false; if (size == 0) // if this is an empty cluster { head.push_front(point); ++size; (this->dimension) = point.getDimension(); this->__centroid = head.front(); return; } std::forward_list<Point>::iterator it = head.begin(); Point test = (*it); if (size == 1) { if (test < (point) ) { head.insert_after(it ,point); ++size; (this->__centroid) = (this->computeCentroid()); return; } else { head.push_front(point); ++size; (this->__centroid) = this->computeCentroid(); return; } } std::forward_list<Point>::iterator it2 = head.begin(); // find lexicographic appropriate place to place new Node with Point passed in for (std::forward_list<Point>::iterator it3 = head.begin(); it3 != head.end(); it3++) { Point test2 = *it2; Point test3 = *it3; if ( (test3) == (point) ) { head.insert_after(it3, point); ++size; (this->__centroid) = this->computeCentroid(); return; } else if ( (test3) > (point) ) { head.insert_after(it2,point); ++size; (this->__centroid) = this->computeCentroid(); return; } it2 = it3; } // if we have reached (end of list), add our new node as last node in list head.insert_after(it2,point); ++size; (this->__centroid) = this->computeCentroid(); return; } ostream &operator<<(std::ostream &os, const Cluster &cluster) { // Print contents of each node (their Points) contained within cluster os << endl << "This cluster is of size " << cluster.size << endl; if (cluster.size == 0) { return os; } os << "Each point has " << cluster.dimension << " dimensions." << endl; os << "The points contained are as follows:" << endl << endl; for (auto it = cluster.head.begin(); it != cluster.head.end() ; ++it) { os << *it << (Cluster::POINT_CLUSTER_ID_DELIM) << " " << cluster.__id << endl; } return os; } Point &Cluster::operator[](unsigned index) throw (OutOfBoundsEx) { auto it = head.begin(); try { if (index < (this->size) ) { if (index == 0) { return head.front(); } else { for(int counter = 0; (it != head.end()) && (counter < index) ; counter++) { ++it; } return (*it); } } else { throw OutOfBoundsEx("[] operator"); } } catch (OutOfBoundsEx stringName) { cout << stringName; cout << endl << "Index is invalid. No such index available in this cluster." << endl << endl; exit(1); } } bool operator==(const Cluster &lhs, const Cluster &rhs) { bool result = false; if (lhs.size != rhs.size) { cout << endl << "Clusters are not the same size, and therefore are not equal" << endl; return false; } if( lhs.head == rhs.head) { result = true; } return result; } // union // increases size of calling object to fit both its previous set and the addition of all the Points in the set of rhs Cluster &Cluster::operator+=(const Cluster &rhs) { if (rhs.size == 0) { return (*this); } this->validCentroid = false; auto it = rhs.head.begin(); for (it; it != rhs.head.end(); it++) { (*this).add(*it); } (this->__centroid) = this->computeCentroid(); return (*this); } // union of sets lhs and rhs const Cluster operator+(Cluster &lhs, Cluster &rhs) { Cluster sendBack(lhs); sendBack += rhs; sendBack.validCentroid = false; (sendBack.__centroid) = sendBack.computeCentroid(); return sendBack; } // (asymmetric) difference Cluster &Cluster::operator-=(const Cluster &rhs) { this->validCentroid = false; auto it = rhs.head.begin(); while (it != rhs.head.end()) { (*this).remove(*it); ++it; } (this->__centroid) = this->computeCentroid(); return (*this); } const Cluster operator-(Cluster &lhs, Cluster &rhs) { Cluster m(lhs); m -= rhs; m.validCentroid = false; m.__centroid = m.computeCentroid(); return m; } // add point Cluster &Cluster::operator+=(const Point &rhs) { this->validCentroid = false; PointPtr copy = new Point(rhs); this->add(*copy); (this->__centroid) = this->computeCentroid(); return (*this); } // remove point Cluster &Cluster::operator-=(const Point &rhs) { this->validCentroid = false; PointPtr copy = new Point(rhs); this->remove(*copy); (this->__centroid) = this->computeCentroid(); return (*this); } const Cluster operator+(Cluster &lhs, PointPtr &rhs) { Cluster funcCluster(lhs); PointPtr copy = new Point(*rhs); funcCluster.add(*copy); funcCluster.validCentroid = false; funcCluster.__centroid = funcCluster.computeCentroid(); return funcCluster; } const Cluster operator-(Cluster &lhs, PointPtr &rhs) { Cluster funcCluster(lhs); PointPtr copy = new Point(*rhs); funcCluster.remove(*copy); funcCluster.validCentroid = false; funcCluster.__centroid = funcCluster.computeCentroid(); return funcCluster; } istream &operator>>(std::istream &os, Cluster & cluster) { string line; while(getline(os,line)) { unsigned d = (unsigned) std::count(line.begin(), line.end(), ','); PointPtr ptr = new Point(d+1); std::stringstream lineStream(line); lineStream >> (*ptr); cluster.add(*ptr); cluster.dimension = (d+1); } cluster.validCentroid = false; cluster.__centroid = (cluster.head.front()); cluster.__centroid = cluster.computeCentroid(); // CENTROID return os; } const Point& Cluster::setCentroid(const Point & point) { this->validCentroid = true; if ((point.getDimension()) == (this->dimension)) { this->__centroid = point; return this->__centroid; } else { cout << "Setting of centroid failed. Dimensionality error. " << endl; return this->__centroid; } } const Point Cluster::getCentroid() const { return this->__centroid; } const Point& Cluster::computeCentroid() throw (RemoveFromEmptyEx) { try { if(this->size == 0) throw RemoveFromEmptyEx("computeCentroid"); this->validCentroid = true; if (this->size == 1) { return this->__centroid; } (this->__centroid) /= (this->size); auto it = head.begin(); while (it != head.end()) { (this->__centroid) += ((*it) / (this->size)); ++it; } this->setCentroid(this->__centroid); return (this->__centroid); } catch (RemoveFromEmptyEx stringName) { cout << stringName; cout << endl << "Cluster is empty. No centroid available" << endl << endl; return this->__centroid; } } unsigned int Cluster::idGenerate() { ++idtracker; return idtracker; } Cluster::Move::Move(const Point & ptr, Cluster* &from, Cluster* &to) { from->validCentroid = false; to->validCentroid = false; (this->toMove) = ptr; (this->destination) = (to); (this->origin) = (from); cout << endl << endl << "Moving point " << ptr << " from point space to cluster number " << to->__id << endl << endl; perform(); } void Cluster::Move::perform() { (*destination).add( (this->toMove) ); (*origin).remove( (this->toMove) ); } void Cluster::pickPoints(int k , Point pointArray []) { cout << endl << "Entering pickPoints " << endl; auto it = head.begin(); unsigned arrayTracker = 0; unsigned count = 1; // Checks to see if k is greater than the number of points in the cluster if(k > size) { k = size; cout << endl << "k is greater than size of cluster, setting k to size of cluster" << endl << endl; } else if (k < size) { cout << endl << "k is less than size of cluster" << endl; } else cout << endl << "k is equal to size of cluster" << endl; if (k != size) { unsigned interval = (size)/k; if (interval % 2) { ++interval; } pointArray[arrayTracker] = (head.front()); ++it; ++arrayTracker; while ((it != head.end()) && (arrayTracker != k)) { if (count == interval) { pointArray[arrayTracker] = (*(it)); count = 0; ++arrayTracker; } ++count; ++it; } } else { while (it != head.end()) { pointArray[arrayTracker] = (*(it)); ++arrayTracker; ++it; } } } unsigned Cluster::getSize() { return this->size; } // sum of the distances between every two points in the cluster. Hint: This // can be done in a double loop through the points of the cluster. However, // this will count every distance twice, so you need to divide the sum by 2 before returning it. double Cluster::intraClusterDistance() { double sum = 0; auto it = this->head.begin(); if (it == head.end()) { return sum; } auto next = it; ++next; if (next != head.end()) { for (it; it != head.end(); ++it) { for (next; next != head.end(); ++next) { sum += ((*it)).distanceTo((*next)); } next = this->head.begin(); } } return sum/2.0; } // sum of the distances between every point in two clusters double interClusterDistance(Cluster &c1, Cluster &c2) { double sum = 0; auto it_first = c1.head.begin(); auto it_second = c2.head.begin(); for (it_first; it_first != c1.head.end() ; ++it_first) { for (it_second ; it_second != c2.head.end() ; ++it_second) { sum += (*(it_first)).distanceTo(*(it_second)); } it_second = c2.head.begin(); } return sum/2.0; } // returns the number of distinct point pairs, or edges, in a cluster. (That is, // every two distinct points have an imaginary edge between them. Its length is // the distance between the two points.) This is simply size * (size - 1) / 2, // where size is the size of the cluster. int Cluster::getClusterEdges() { return size * (size - 1) / 2; } double interClusterEdges(const Cluster &c1, const Cluster &c2) { return (c1.size * c2.size / 2); } unsigned Cluster::getDimension() { return dimension; } bool Cluster::contains(const Point &point) { if (this->size == 0) { cout << endl << "Cluster is empty. Contains no points." << endl << endl; return false; } auto it = this->head.begin(); for (it ; it != head.end() ; ++it) { if ((*(it)) == point) { return true; } } return false; } } <file_sep>/Exceptions.h // // Created by marisa on 11/25/15. // #ifndef PA2_EXCEPTIONS_H #define PA2_EXCEPTIONS_H #include <string> namespace Clustering { class DimensionalityMismatchEx { std::string name; public: DimensionalityMismatchEx() {} DimensionalityMismatchEx(std::string identification): name(identification) {} std::string getName() const { return name; } friend std::ostream &operator<<(std::ostream &, const DimensionalityMismatchEx &); }; class OutOfBoundsEx { std::string name; public: OutOfBoundsEx() {} OutOfBoundsEx(std::string nameAssigned): name(nameAssigned) {} std::string getName() const {return name;}; friend std::ostream &operator<<(std::ostream &, const OutOfBoundsEx &); }; class RemoveFromEmptyEx { std::string name; public: RemoveFromEmptyEx() {} RemoveFromEmptyEx(std::string firstName): name(firstName) {} std::string getName() const {return name;} friend std::ostream &operator<<(std::ostream &, const RemoveFromEmptyEx &); }; } #endif //PA2_EXCEPTIONS_H <file_sep>/Point.h /* Since the dimension could be potentially very large, you have to allocate it dynamically, and take care of all cleanup. Memory leaks will be penalized. */ #ifndef PA2_POINT_H #define PA2_POINT_H // A 3-dimensional point class! // Coordinates are double-precision floating point. #include <iostream> #include <vector> #include "Exceptions.h" using namespace std; namespace Clustering { class Point { unsigned m_Dims; // number of dimensions of the point vector<double> m_values; // values of the point's dimensions unsigned int __id; public: static unsigned int idGenerate(); static void rewindIdGen(); static const char POINT_VALUE_DELIM = ',' ; // Constructors Point(); // default constructor Point(unsigned d); // custom constructor, takes 1 argument Point(unsigned, double *); // custom constructor, takes 2 arguments // Big three: cpy ctor, overloaded operator=, dtor ~Point(); Point(const Point &); // object initialized with another object Point &operator=(const Point &) throw (DimensionalityMismatchEx); // object assigned to another object // Accessor Functions double getValue(unsigned) const; // gets coordinate of dimension of interest unsigned getDimension() const; // gets number of dimensions of a Point object double &operator[](unsigned) throw (OutOfBoundsEx); // Overloaded [] index operator // Mutator Functions void setValue(unsigned, double) throw (DimensionalityMismatchEx); // sets value of dimension passed in // Functions double distanceTo(Point &) throw (DimensionalityMismatchEx); // function calculates the distance between two points // Overloaded Operators Point &operator*= (double); // modifies Point on the left Point &operator/= (double); // modifies Point on the left const Point operator*(double) const; // prevent (p1 * 2) = p2, returns a temporary point const Point operator/(double) const; // returns a temporary point //Friends friend Point &operator+=(Point &, const Point &) throw (DimensionalityMismatchEx); // modifies Point on the left friend Point &operator-=(Point &, const Point &) throw (DimensionalityMismatchEx); // modifies Point on the left friend const Point operator+(const Point &, const Point &) throw (DimensionalityMismatchEx); // returns temporary Point friend const Point operator-(const Point &, const Point &) throw (DimensionalityMismatchEx); // returns temporary Point friend bool operator==(const Point &, const Point &) throw (DimensionalityMismatchEx); friend bool operator!=(const Point &, const Point &) throw (DimensionalityMismatchEx); friend bool operator<(const Point &, const Point &) throw (DimensionalityMismatchEx); friend bool operator>(const Point &, const Point &) throw (DimensionalityMismatchEx); friend bool operator<=(const Point &, const Point &) throw (DimensionalityMismatchEx); friend bool operator>=(const Point &, const Point &) throw (DimensionalityMismatchEx); friend std::ostream &operator<<(std::ostream &, const Point &); friend std::istream &operator>>(std::istream &, Point &) throw (DimensionalityMismatchEx); }; } #endif //PA2_POINT_H <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.3) project(pa2) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(SOURCE_FILES main.cpp Point.cpp Point.h Cluster.cpp Cluster.h KMeans.cpp KMeans.h Exceptions.cpp Exceptions.h) add_executable(pa2 ${SOURCE_FILES}) <file_sep>/README.md # ucd-csi2312-pa3 KMeans Clustering Algorithm Programmer: <NAME> Complier: gcc,gnu The principal objective of this assignment was to implement the widely used KMeans Algorithm to sort out an accumulation of points into respective clusters as to sort and organize them based on proximity to central reference points (centroids). The centroid of a cluster is an imaginary point which is the mean of all the points in the cluster. The methods of implementation are based on our previously developed Point and Cluster classes. In this particular project, the points to be sorted are stored and read in from a comma seperated value file (CSV file). The code presented here is designed to handle any number of points with any number of dimensions. The setter method that allows for the reading in of points from a file involves an overloaded insertion operator (>>). Also, we introduce a new class, the KMeans class, which is the destination of point reading. Once the KMeans methods are implemented, the sorted points are outputted to a text file which will display their respective clusters via an id tag. The outputted file is also a CSV file. <file_sep>/Exceptions.cpp // // Created by marisa on 11/25/15. // #include "Exceptions.h" #include <iostream> using namespace std; namespace Clustering { ostream &operator<<(std::ostream &ostream, const DimensionalityMismatchEx &ex) { cout << endl << "DimensionalityMismatchEx( " << ex.getName() << " )"; return ostream; } ostream &operator<<(std::ostream &ostream1, const OutOfBoundsEx &ex) { cout << endl << "OutOfBoundsEx( " << ex.getName() << " )"; return ostream1; } ostream &operator<<(std::ostream &ostream2, const RemoveFromEmptyEx &ex) { cout << endl << "RemoveFromEmptryEx( " << ex.getName() << " )"; return ostream2; } } <file_sep>/Cluster.h // Can have arbitrary number of Nodes that hold one Point each #ifndef CLUSTERING_CLUSTER_H #define CLUSTERING_CLUSTER_H #include <forward_list> #include "Point.h" #include "Exceptions.h" using namespace std; namespace Clustering { typedef Point *PointPtr; typedef struct Node *NodePtr; struct Node { PointPtr pointPointer; // Pointer to each Node's Point object NodePtr nextNode; // Pointer to next node in the list }; class Cluster { unsigned size; // number of nodes in cluster (# of Point objects) std::forward_list<Point> head; // pointer to first node unsigned dimension; Point __centroid; bool validCentroid = false; unsigned int __id; public: friend class KMeans; static const char POINT_CLUSTER_ID_DELIM = ':'; Cluster() : size(0), dimension(0), __centroid(dimension), __id(idGenerate()) { head.clear(); } Cluster(unsigned dim) : size(0), dimension(dim), __centroid(dim), __id(idGenerate()) { head.clear(); } static unsigned int idGenerate(); // The big three: cpy ctor, overloaded operator=, dtor Cluster(Cluster &); Cluster &operator=(Cluster &); ~Cluster(); // Set functions: They allow calling c1.add(c2.remove(p)); void add(const Point &); void remove(const Point &) throw (RemoveFromEmptyEx); const Point& setCentroid(const Point &); const Point getCentroid() const; const Point& computeCentroid() throw (RemoveFromEmptyEx); // Overloaded operators Point &operator[](unsigned) throw (OutOfBoundsEx); // Overloaded [] index operator // Set-preserving operators (do not duplicate points in the space) // - Friends friend bool operator==(const Cluster &lhs, const Cluster &rhs); // - Members Cluster &operator+=(const Cluster &rhs); // union Cluster &operator-=(const Cluster &rhs); // (asymmetric) difference Cluster &operator+=(const Point &rhs); // add point Cluster &operator-=(const Point &rhs); // remove point // Set-destructive operators (duplicate points in the space) // - Friends friend const Cluster operator+(Cluster &lhs, Cluster &rhs); friend const Cluster operator-(Cluster &lhs, Cluster &rhs); friend const Cluster operator+(Cluster &lhs, PointPtr &rhs); friend const Cluster operator-(Cluster &lhs, PointPtr &rhs); friend std::ostream &operator<<(std::ostream &, const Cluster &); friend std::istream &operator>>(std::istream &, Cluster &); void pickPoints(int k, Point [] ); unsigned getSize(); unsigned getDimension(); double intraClusterDistance(); friend double interClusterDistance(Cluster &c1, Cluster &c2); int getClusterEdges(); friend double interClusterEdges(const Cluster &c1, const Cluster &c2); bool contains(const Point &); class Move { public: Move(){} Move(const Point &ptr, Cluster* &from, Cluster* &to); private: void perform(); // helper functions Point toMove; Cluster* origin; Cluster* destination; }; } ; } #endif //CLUSTERING_CLUSTER_H <file_sep>/KMeans.cpp // // Created by marisa on 11/8/15. // #include "KMeans.h" #include <fstream> #include <sstream> #include <iostream> #include <cmath> using namespace std; namespace Clustering { KMeans::KMeans() { point_space = new Cluster; // cout << endl << "point_space assigned a cluster" << endl; } KMeans::KMeans(unsigned kValue, unsigned dim): k(kValue) , dimension(dim) { point_space = new Cluster(dimension); cout << endl << "point space assigned cluster with dimension: " << dim << " k value: " << k << endl; } // will implement the so called Beta-CV criterion (stands for coefficient of variation). // This is an internal criterion, that is, it only uses the data in the clustering, and // no external data. Beta-CV is a ratio of the mean intra-cluster (inside the cluster) // distance to the mean inter-cluster (between cluster) distance. The smaller it is, the better. double KMeans::computeClusteringScore(Cluster myClusters []) { double dIn(0) , dOut(0) , pIn(0) , pOut(0) , betaCV(0); double denomenator(0) , numerator(0); // cout << endl << "Entering computeClusteringScore" << endl; for (int i = 0; i < k ; i++) { dIn += ( myClusters[i].intraClusterDistance() ); } // cout << endl << " dIn: " << dIn << endl; for (int j = 0 ; j < k; j++) { for (int m = 0 ; m < k; m++) { dOut += ( interClusterDistance( (myClusters[j] ) , myClusters[m] ) ); } } // cout << endl << "dOut: " << dOut << endl; for (int n = 0; n < k; n++) { pIn += ( myClusters[n].getClusterEdges() ); } // cout << endl << "pIn: " << pIn << endl; for (int p = 0 ; p < k; p++) { for (int q = 0 ; q < k; q++) { pOut += ( interClusterEdges( myClusters[p],myClusters[q] ) ); } } // cout << endl << "pOut: " << pOut << endl; denomenator = dOut/pOut; numerator = dIn / pIn; betaCV = numerator/denomenator; // cout << endl << "score = " << betaCV << endl; return betaCV; } std::istream &operator>>(istream &istream1, KMeans & means) { istream1 >> (*(means.point_space)); cout << endl << "File done transferring points. Our KMeans cluster is of "; means.dimension = (*(means.point_space)).getDimension(); cout << means.dimension << " dimensions. " << endl; cout << endl << "Point Space:" << *means.point_space << endl; return istream1; } double KMeans::clusteringAlgor(KMeans & means) { if (k == 0) { unsigned getK; cout << "Please set k ( the number of clusters to seperate data into) : "; cin >> getK; k = getK; } else cout << endl << "k equals " << k << endl; Point fillCentroid[k]; Point *pointer = fillCentroid; for (int e = 0; e < k ; e++) { fillCentroid[e] = Point(means.dimension); } means.point_space->pickPoints(k ,pointer); cout << endl << "Pick points result: "; for (int counter = 0; counter < k ; counter++) { cout << endl << fillCentroid[counter] << endl; } Cluster emptyClusters[k]; for (int f = 0; f < k ; f++) { emptyClusters[f].dimension = means.dimension; } for (int i = 0; i < k; i++) { emptyClusters[i].setCentroid(fillCentroid[i]); cout << endl << "Empty Cluster " << i+1 << " has centroid: " << emptyClusters[i].__centroid << endl; } double score=0; double scoreDiff = SCORE_DIFF_THRESHOLD + 1; double minDistance = 10000; double readDistance = 0; Point pointToMove; ClusterPtr toCluster = nullptr; int w = 0; if (k == 1) { emptyClusters[w] = *means.point_space; } else { for (scoreDiff; scoreDiff > SCORE_DIFF_THRESHOLD; scoreDiff = (abs(scoreDiff - score))) { for (std::forward_list<Point>::iterator it = means.point_space->head.begin(); it != means.point_space->head.end(); it = means.point_space->head.begin()) { for (int j = 0; j < k; j++) { readDistance = (*it).distanceTo(emptyClusters[j].__centroid); cout << endl << " Distance between " << (*it) << " and " << emptyClusters[j].__centroid << " = " << readDistance << endl; if (readDistance < minDistance) { pointToMove = *it; toCluster = (emptyClusters+j); minDistance = readDistance; cout << endl << " new minDistance = " << minDistance << endl; } } Cluster::Move(pointToMove, means.point_space, toCluster); means.point_space->head.pop_front(); --means.point_space->size; minDistance = 10000; } score = computeClusteringScore(emptyClusters); cout << endl << "score = " << score << endl; if (score == 0) break; } } ofstream outStream; outStream.open("/home/marisa/Projects/interm program/pa2/ClusterData.txt") ; if (outStream.fail() ) { cout << "Output file opening failed.\n" ; } else { cout << endl << "Output file opened" << endl; for (int z = 0; z < k; z++) { outStream << emptyClusters[z] << endl; } } outStream.close(); return scoreDiff; } } <file_sep>/Point.cpp // // Created by marisa on 9/12/15. // #include "Point.h" #include "Exceptions.h" #include <cmath> #include <fstream> #include <sstream> #include <iomanip> // iostream using std::cout; using std::endl; // fstream using std::ifstream; // sstream using std::stringstream; using std::string; using namespace std; static unsigned int pointIDtracker = 0; namespace Clustering { unsigned int Point::idGenerate() { ++pointIDtracker; return pointIDtracker; } void Point::rewindIdGen() { --pointIDtracker; } /* * Constructors */ // Default // Constructors are initializing newly constructed objects Point::Point() { m_Dims = 2; m_values.resize(2); __id = idGenerate(); } Point::Point(unsigned d) { if (d == 0) d = 2; m_Dims = d; m_values.resize(m_Dims); __id = idGenerate(); } // takes in n dimensions // double * coordinates is an array of doubles Point::Point(unsigned dimensions, double *coordinates) { if (dimensions == 0) dimensions = 2; m_Dims = dimensions; m_values.resize(m_Dims); // copy double * coordinates into m_values for (int i = 0; i < m_Dims; i++) { m_values[i] = coordinates[i]; } __id = idGenerate(); } /* * The Big Three */ // Destructor Point::~Point() { m_values.clear(); } // Copy constructor works on something that has already been created (exists already) Point::Point(const Point &existingPoint) { m_Dims = existingPoint.m_Dims; // want same number of dimensions m_values.resize(m_Dims); for (int i = 0; i < m_Dims; i++) // want to copy the values { m_values[i] = existingPoint.m_values[i]; } } // Overloaded assignment operator // const argument so you don't modify what is being passed in Point &Point::operator=(const Point &rhs) throw (DimensionalityMismatchEx) { if (this == &rhs) // Prevents self-assignment return *this; else m_values.clear(); // if calling Point already exists, clear member data m_Dims = rhs.m_Dims; m_values.resize(m_Dims); // new set of member data, equal to member data of rhs try { if (this->m_Dims != rhs.m_Dims) { throw DimensionalityMismatchEx("= operator"); } } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't assign a Point to another when their dimensions do not match " << endl << endl; } for (int i = 0; i < m_Dims; i++) { m_values[i] = rhs.m_values[i]; } return *this; // return calling Point } /* * Accessor Member Functions */ // gets coordinate of dimension of interest double Point::getValue(unsigned dimension) const { if (dimension >= 1 && dimension <= m_Dims) return m_values.at(dimension - 1); else { cout << endl << "Invalid dimension for this Point. Terminating Program" << endl; exit(1); } } // gets number of dimensions of a Point object unsigned Point::getDimension() const { if (this == nullptr) return 0; return m_Dims; } // Overloaded [] index operator // returns coordinate at index double &Point::operator[](unsigned index) throw (OutOfBoundsEx) { try { if (index < m_Dims) return m_values[index - 1]; else { throw OutOfBoundsEx("[] operator"); } } catch(OutOfBoundsEx stringName) { cout << stringName; cout << endl << "This coordinate does not exist" << endl << endl; exit(1); } } /* * Mutator Member Functions */ // set coordinate of dimension passed in void Point::setValue(unsigned dimension, double value) throw (DimensionalityMismatchEx) { try { if ((dimension >= 1) && (dimension <= m_Dims)) { m_values[dimension - 1] = value; return; } else { throw DimensionalityMismatchEx("setValue"); } } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Not a valid dimension for this Point, setting of value failed" << endl << endl; return; } } /* * Functions */ /* Calculates distance between 2 points (the point calling the member function and the point passed in by reference) sqrt() is square root function defined in <cmath> */ double Point::distanceTo(Point &point2) throw (DimensionalityMismatchEx) { try { if (point2.m_Dims == m_Dims) // both Points must have same number of dimensions { double sum = 0; for (int i = 0; i < m_Dims; i++) { double diff = m_values[i] - point2.m_values[i]; // coordinate-wise subtraction sum += (diff * diff); } return sqrt(sum); } else { throw DimensionalityMismatchEx("distanceTo"); } } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't compute distance between points with different number of dimensions. Returning 0." << endl << endl; return 0.0; } } /* * Overloaded Operators */ // modifies Point on the left Point & Point::operator*=(double rhs) { for (int i = 0; i < m_Dims; i++) { m_values[i] *= rhs; } return *this; } // modifies Point on the left Point &Point::operator/=(double rhs) { if (rhs == 0) { cout << "Undefined. Can't divide by 0 " << endl; return *this; } else { for (int i = 0; i < m_Dims; i++) { m_values[i] /= rhs; } } return *this; } // prevent (p1 * 2) = p2, returns a temporary point const Point Point::operator*(double d) const { Point copy(*this); for (int i = 0; i < m_Dims; i++) { copy.m_values[i] *= d; } return copy; } // returns a temporary point const Point Point::operator/(double d) const { Point copy(*this); if (d == 0) { cout << endl << "Division by 0 not allowed. First Point object is returned." << endl; return (copy); } for (int i = 0; i < m_Dims; i++) { copy.m_values[i] /= d; } return copy; } /* * Friends */ // modifies Point on the left Point &operator+=(Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { try { if (&lhs == &rhs) // adding Point to itself return lhs *= 2; else if (lhs.m_Dims == rhs.m_Dims) { for (int i = 0; i < lhs.m_Dims; i++) { lhs.m_values[i] += rhs.m_values[i]; } } else throw DimensionalityMismatchEx("+= operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Points need to have same number of dimensions. No change to either point." << endl << endl; } return lhs; } // modifies Point on the left Point &operator-=(Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { try { if (&lhs == &rhs) return lhs *= 0; else if (lhs.m_Dims == rhs.m_Dims) { for (int i = 0; i < lhs.m_Dims; i++) { lhs.m_values[i] -= rhs.m_values[i]; } } else throw DimensionalityMismatchEx("-= operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Points need to have same number of dimensions. No change to either point." << endl << endl; } return lhs; } // returns temporary Point const Point operator+(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { try { if (lhs.m_Dims == rhs.m_Dims) { Point p(lhs.m_Dims); for (int i = 0; i < lhs.m_Dims; i++) { p.m_values[i] = (lhs.m_values[i] + rhs.m_values[i]); } return p; } else throw DimensionalityMismatchEx("+ operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't add two points when their dimensions are different. No change to any point." << endl << endl; } return lhs; } // returns temporary Point const Point operator-(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { try { if (lhs.m_Dims == rhs.m_Dims) { Point p(lhs.m_Dims); for (int i = 0; i < lhs.m_Dims; i++) { p.m_values[i] = (lhs.m_values[i] - rhs.m_values[i]); } return p; } else throw DimensionalityMismatchEx("- operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't subtract two points when their dimensions are different. No change to any point." << endl << endl; } return lhs; } // returns true if both points contain same coordinates // Overloaded == operator bool operator==(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { bool equal = false; try { if (lhs.m_Dims == rhs.m_Dims) { equal = true; for (int i = 0; i < lhs.m_Dims; i++) { if (lhs.m_values[i] != rhs.m_values[i]) { equal = false; break; } } if (lhs.__id != rhs.__id) { equal = false; } } else throw DimensionalityMismatchEx("== operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can only compare points with same number of dimensions" << endl << endl; } return equal; } // returns true if the coordinates of the two points are different // Overloaded != operator bool operator!=(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { bool equalCatch = (lhs == rhs); return !equalCatch; } // return true is left side Point is less than Point on right hand side // Overloaded < operator bool operator<(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { bool lessThen = true; try { if (lhs == rhs) { lessThen = false; return lessThen; } if (lhs.m_Dims == rhs.m_Dims) { int i = lhs.m_Dims; int index = 0; while (i > 0) { if (lhs.m_values[index] < rhs.m_values[index]) { return lessThen; } else if (lhs.m_values[index] > rhs.m_values[index]) { lessThen = false; return lessThen; } ++index; --i; } lessThen = false; return lessThen; } else throw DimensionalityMismatchEx("< operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't compare two Points when they have different number of dimensions." << endl << endl; return 0; } } // return true is left side Point is greater than Point on right hand side // Overloaded > operator bool operator>(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { bool greaterThen = true; try { if (lhs == rhs) { greaterThen = false; return greaterThen; } if (lhs.m_Dims == rhs.m_Dims) { int i = lhs.m_Dims; int index = 0; while (i > 0) { if (lhs.m_values[index] > rhs.m_values[index]) { return greaterThen; } else if (lhs.m_values[index] < rhs.m_values[index]) { greaterThen = false; return greaterThen; } ++index; --i; } greaterThen = false; return greaterThen; } else throw DimensionalityMismatchEx("> operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't compare two Points when they have different number of dimensions." << endl << endl; return 0; } } bool operator<=(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { try { bool lessEqual = true; if (lhs == rhs) // checks if they are equal. { return lessEqual; } if (lhs.m_Dims == rhs.m_Dims) { lessEqual = (lhs < rhs); return lessEqual; } else throw DimensionalityMismatchEx("<= operator"); } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Can't compare two Points when they have different number of dimensions." << endl << endl; return 0; } } bool operator>=(const Point &lhs, const Point &rhs) throw (DimensionalityMismatchEx) { bool greaterEqual = false; if (lhs == rhs) // checks if they are equal. { greaterEqual = true; return greaterEqual; } greaterEqual = (lhs > rhs); //uses overloaded > to check if lhs is greater than rhs return greaterEqual; } ostream &operator<<(std::ostream &os, const Point &point) { int i = 0; for ( i ; i < (point.m_Dims - 1); i++) { os << std::fixed << std::setprecision(1) << point.m_values[i] << Point::POINT_VALUE_DELIM << ' '; } os << point.m_values[i]; return os; } istream &operator>>(std::istream &os, Point &point) throw (DimensionalityMismatchEx) { try { string line; unsigned counter = 0; while (getline(os, line)) { stringstream lineStream(line); string value; double d; unsigned i = 1; while (getline(lineStream, value, Point::POINT_VALUE_DELIM)) { d = stod(value); point.setValue(i++, d); } counter = i-1; } if (point.m_Dims != counter) { throw DimensionalityMismatchEx(">> operator"); } } catch (DimensionalityMismatchEx stringName) { cout << stringName; cout << endl << "Number of values read in does not equal Point's dimensionality. Bad read-in" << endl << endl; point.rewindIdGen(); } } }
5d074ffc25f2830d85f0e8275108725224be7ffb
[ "Markdown", "CMake", "C++" ]
11
C++
EDWINSOM/ucd-csi2312-pa2
3f7ee4e34945463b01134585e8f2c12830429151
5464437e079b45e9684c05581b752674f99da342
refs/heads/master
<repo_name>Tluyen/git-remote-add-origin-https---github.com-Tluyen-p6<file_sep>/Foothill.java import java.util.*; import java.lang.Math; public class Foothill { private final static int MAX_PULL = 3; private final static String BARS = "Bars"; private final static String CHERRIES = "Cherries"; private final static String SPACE = "Space"; private final static String SEVEN = "7"; public void main (String args[]) { int theBet; TripleString tripleStr; int myPay; do { theBet = getBet(); tripleStr = pull(); myPay = getPayMultiplier(tripleStr); } while (theBet !=0); } public static int getBet() { Scanner keyboard = new Scanner(System.in); String userInput; int theBet; System.out.println("How much would you like to bet (1 - 100) or 0 to quit? " ); userInput = keyboard.next(); theBet = Integer.parseInt(userInput); keyboard.close(); return theBet; } public static TripleString pull() { int i; String randstr; TripleString tripleStr = new TripleString(); for (i=0; i < MAX_PULL; i++) { randstr = randString(); tripleStr.setString(randstr); } //str.set return tripleStr; } public static String randString() { int result; result = (int) Math.random() * 100; if ( result <= 50) return BARS; else if(result <= 25) return CHERRIES; else if (result <= 13) return SPACE; else if( result > 87) return SEVEN; return null; } public int getPayMultiplier(TripleString thePull) { if (thePull.getString1() == CHERRIES && thePull.getString2() == CHERRIES && thePull.getString3() == CHERRIES) return 30; else if (thePull.getString1() == BARS && thePull.getString2() == BARS && thePull.getString3() == BARS) return 50; else if (thePull.getString1() == SEVEN && thePull.getString2() == SEVEN && thePull.getString3() == SEVEN) return 100; else if (thePull.getString1() == CHERRIES && thePull.getString2().equals(CHERRIES)== false && thePull.getString3().equals(CHERRIES)== false ) return 5; else if (thePull.getString1() == CHERRIES && thePull.getString2().equals(CHERRIES)== true && thePull.getString3().equals(CHERRIES)== false ) return 15; return 0; } void display (TripleString thePull, int winnings) { System.out.print("Whrrrrr.... and your pull is ....\n"); System.out.println(thePull.getString()); if (winnings > 0) System.out.print("Congratulations! You Win: " + winnings); else System.out.print("Sorry, you lost..."); } }
6ee3c65bf890dea27c36cd9c6c86a1ca51a28f00
[ "Java" ]
1
Java
Tluyen/git-remote-add-origin-https---github.com-Tluyen-p6
08b4caa41c01d65f67b087cfd5e98310e4c1b326
2108e6cd20b98d337e06993c5c9e8a58441c2741
refs/heads/master
<file_sep>// Users going to be purely in memory const users = {}; // function to respond with a json object const respondJSON = (request, response, status, object) => { response.writeHead(status, { 'Content-Type': 'application/json' }); response.write(JSON.stringify(object)); response.end(); }; // function to respond w/o json body const respondJSONMeta = (request, response, status) => { response.writeHead(status, { 'Content-Type': 'application/json' }); response.end(); }; // return user objects as JSON const getUsers = (request, response) => { const responseJSON = { users, }; respondJSON(request, response, 200, responseJSON); }; // meta for object w/ 200 const getUsersMeta = (request, response) => respondJSONMeta(request, response, 200); // function to add a user from a POST body const addUser = (request, response, body) => { // default json message const responseJSON = { message: 'Name and age are both required.', }; // We need to check to make sure the user has put in both fields // Should probably have more validation // Either way, send 400 error if these are triggered if (!body.name || !body.age) { responseJSON.id = 'missingParams'; return respondJSON(request, response, 400, responseJSON); } // default code to 201 let responseCode = 201; // created // if user already exists, update w/ 204 if (users[body.name]) { responseCode = 204; } else { users[body.name] = {}; // not a great way to store this in general } // add/update fields users[body.name].name = body.name; users[body.name].age = body.age; // Set created message w/ JSON if (responseCode === 201) { responseJSON.message = 'Created Successfully'; return respondJSON(request, response, responseCode, responseJSON); } // 204 otherwise return respondJSONMeta(request, response, responseCode); }; // Basically the same as notFound 100% // Not real w/ JSON message and id // const notReal = (request, response) => { // const responseJSON = { // message: 'The page you are looking for was not found', // id: 'notFound', // }; // return respondJSON(request, response, 404, responseJSON); // }; // // Not real w/ meta // const notRealMeta = (request, response) => { // respondJSONMeta(request, response, 404); // }; // Standard 404 message const notFound = (request, response) => { const responseJSON = { message: 'The page you are looking for was not found.', id: 'notFound', }; return respondJSON(request, response, 404, responseJSON); }; // 404 meta const notFoundMeta = (request, response) => { respondJSONMeta(request, response, 404); }; module.exports = { getUsers, getUsersMeta, addUser, // notReal, // notRealMeta, notFound, notFoundMeta, };
1c2fe124850e6b49fb4b1b2e3aed57d7973c1a27
[ "JavaScript" ]
1
JavaScript
alc7546/http-api-assignment-ii
394dbdcc19c6ee2c15d2459f34fba2097df306fe
81ffced7a5be41c7acddbab7c404c0ec4502812d
refs/heads/master
<repo_name>Slava37/Hello_world<file_sep>/myFunctions.js /** * Возврящает заднный массив в случайном порядкею * @param {*} myArr */ var randomArr = function (myArr) { for (var count = myArr.length - 1; count > 0; count--) { var randomNum = Math.floor(Math.random() * (count + 1)); var valueOfT = myArr[randomNum]; myArr[randomNum] = myArr[count]; myArr[count] = valueOfT; } return myArr; }; /** * Возврящает случайное целое число в диапазоне. * @param {*} min * @param {*} max */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min + 1)); }; /** * Возврящает случайный индекс массива. * @param {*} arr */ var getRandomIndex = function (arr) { var value = getRandomNumber(0, arr.length - 1); return value; };
ed420022b82466fd0e7ee83119fb6905b02e9550
[ "JavaScript" ]
1
JavaScript
Slava37/Hello_world
d6b04afcf8c55d7b3c5962fb1439e8a83f8749b6
ebf7e3ee8b572dc9b2d134ff017ca6e53c57a945
refs/heads/master
<repo_name>rbarzegar/webpackpostcssREACTjune2018<file_sep>/postcss.config.js module.exports = { plugins: { "postcss-easy-import": { prefix: "_", extensions: ".css" }, "postcss-nested": {}, "postcss-sassy-mixins": {}, "postcss-simple-vars": {}, "postcss-cssnext": {}, "rucksack-css": { responsiveType: true, shorthandPosition: false, quantityQueries: false, alias: false, inputPseudo: false, clearFix: true, fontPath: true, hexRGBA: true, easings: true }, "postcss-pxtorem": { rootValue: 16, unitPrecision: 3, propList: [ "font", "font-size", "line-height", "letter-spacing", "padding", "margin" ], selectorBlackList: [], replace: true, mediaQuery: false, minPixelValue: 0 }, "clean-css": {} } }
554a9b86a3266eb1520b049433e5f259a2a4aaad
[ "JavaScript" ]
1
JavaScript
rbarzegar/webpackpostcssREACTjune2018
5e7da408437efce216cbe51c4ff8718c00cf594e
eefc50359e62584f5c7150d4441983dea23bd242
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninject; using Ninject.Web.Common; using _4tegroup.Mailer.Contracts; using _4tegroup.Mailer.Service; using _4tegroup.Mailer.Data; using _4tegroup.Mailer.DataEF; namespace _4tegroup.Mailer.Common { public static class IoC { public static dynamic Container { get; private set; } private static IKernel _kernel = new StandardKernel(); static IoC() { var connectionString = ConfigurationManager.ConnectionStrings[1].ConnectionString; _kernel.Bind<IUnitOfWork>() .To<EFUnitOfWork>() .InRequestScope() .WithConstructorArgument("connectionString", connectionString); _kernel.Bind<IContentService>().To<ContentService>().WithConstructorArgument("unitOfWork", GetInstance<IUnitOfWork>()); _kernel.Bind<IEmailService>().To<EmailService>(); _kernel.Bind<IEmailTemplateRepository>().To<EmailTemplateRepository>(); } public static TService GetInstance<TService>() { return _kernel.Get<TService>(); } } } <file_sep>using System.Diagnostics; using _4tegroup.Mailer.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using _4tegroup.Mailer.Domain; using _4tegroup.Mailer.Service.Helpers; namespace _4tegroup.Mailer.Service { public class EmailService : IEmailService { private const int Port = 587; public void SendEmail(string from, string to, string subject, string body, string password) { var emailHelper = new EmailHelper(); var fromAddress = new MailAddress(from); var toAddress = new MailAddress(to); var host = emailHelper.GenerateSmtpServerAddress(from); var smtp = new SmtpClient { Host = host, Port = Port, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, password) }; var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, IsBodyHtml = true, }; try { smtp.Send(message); } catch (SmtpFailedRecipientException ex) { throw new Exception("Error occured send email: ", ex); } catch (Exception ex) { throw new Exception(ex.Message); } finally { message.Dispose(); smtp.Dispose(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Contracts { public interface IEmailService { void SendEmail(string from, string to, string subject, string body, string password); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Contracts { public interface IService : IDisposable { } public interface IService<TEntity> where TEntity : Entity { } } <file_sep>using _4tegroup.Mailer.Data; using _4tegroup.Mailer.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.DataEF { public class EmailTemplateRepository : BaseRepository<EmailTemplate, Guid>, IEmailTemplateRepository { public EmailTemplateRepository(EmailerContext context) : base(context) { } public EmailTemplate GetByName(string name) { try { return Context.EmailTemplates.FirstOrDefault(template => template.Name.Equals(name)); } catch (Exception) { return null; } } } } <file_sep>using System; using _4tegroup.Mailer.Data; namespace _4tegroup.Mailer.DataEF { public class EFUnitOfWork : UnitOfWork { private readonly EmailerContext _context; private string _connectionString; private bool _isDisposed; public EFUnitOfWork(string connectionString) { _connectionString = connectionString; _context = new EmailerContext(connectionString); AddRepository<IEmailTemplateRepository>(() => new EmailTemplateRepository(_context)); } public EmailerContext Context { get { return _context; } } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public override void Commit() { try { Context.SaveChanges(); } catch (Exception ex) { throw new Exception(ex.Message); } } private void Dispose(bool disposing) { if (!_isDisposed && disposing) { _context.Dispose(); } _isDisposed = true; } ~EFUnitOfWork() { Dispose(false); } } }<file_sep>using _4tegroup.Mailer.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Data { public interface IEmailTemplateRepository : IRepository<EmailTemplate, Guid> { EmailTemplate GetByName(string name); } } <file_sep> using System; using System.Collections.Generic; using System.Linq; using System.Web; using AutoMapper; using _4tegroup.Mailer.Domain; using _4tegroup.Mailer.WebUI.Models; namespace _4tegroup.Mailer.WebUI { public class MapConfig { public static void RegisterMap() { Mapper.CreateMap<EmailTemplate, TemplateViewModel>(); Mapper.CreateMap<TemplateViewModel, EmailTemplate>() .AfterMap((x, y) => { y.Created = DateTime.UtcNow; if(x.Id.Equals(Guid.Empty)) y.Id = Guid.NewGuid(); }); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Contracts; using _4tegroup.Mailer.Data; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Service { public class BaseService : IService { public BaseService(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } public IUnitOfWork UnitOfWork { get; set; } protected TRepository GetRepository<TRepository>() where TRepository : IRepository { return UnitOfWork.GetRepository<TRepository>(); } protected void Save<TRepository, TEntity, TKey>(TEntity entity, TKey key) where TRepository : IRepository<TEntity, TKey> where TEntity : Entity { try { var repository = UnitOfWork.GetRepository<TRepository>(); if(repository.Get(key) == null ) { repository.Create(entity); } else { repository.Update(entity); } UnitOfWork.Commit(); } finally { } } public void Dispose() { UnitOfWork.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AutoMapper; using _4tegroup.Mailer.Common; using _4tegroup.Mailer.Contracts; using _4tegroup.Mailer.Domain; using _4tegroup.Mailer.WebUI.App_LocalResources; using _4tegroup.Mailer.WebUI.Models; using _4tegroup.Mailer.WebUI.Models.Helpers; namespace _4tegroup.Mailer.WebUI.Controllers { public class EmailTemplateController : Controller { // GET: EmailTemplate [HttpGet] public ActionResult Index(int page = 1, string sort = "name") { var service = IoC.GetInstance<IContentService>(); var templates = service.GetAllTemplates(); var list = new List<EmailTemplate>(); if (templates != null) { switch (sort) { case "name": list = templates.OrderBy(template => template.Name).ToList(); break; case "date": list = templates.OrderBy(template => template.Created).ToList(); break; default: list = templates.OrderBy(template => template.Name).ToList(); break; } } var viewModels = Mapper.Map<IList<EmailTemplate>, IList<TemplateViewModel>>(list); var onPage = new PageableData<TemplateViewModel>(viewModels.AsQueryable(), page, 3); return View(onPage); } [HttpGet] public ViewResult Create() { return View(); } [HttpPost] public ActionResult Create(TemplateViewModel viewModel) { if (viewModel == null || !ModelState.IsValid) { ModelState.AddModelError("Duplicate template name", string.Format("Something bad")); return View(); } var service = IoC.GetInstance<IContentService>(); var template = Mapper.Map<TemplateViewModel, EmailTemplate>(viewModel); if (!service.CreateEmailTemplate(template)) { ModelState.AddModelError("Duplicate template name", string.Format(GlobalRes.DuplicateTemplate, template.Name)); return View(); } return RedirectToAction("Index", "EmailTemplate"); } [HttpGet] public ActionResult Details(string id) { Guid guid; Guid.TryParse(id, out guid); if (guid.Equals(Guid.Empty)) { ModelState.AddModelError("EmtpyId", GlobalRes.EmtpyId); return View(); } try { var service = IoC.GetInstance<IContentService>(); var template = service.GetById(guid); if (template == null) { ModelState.AddModelError("TemplateMissing", GlobalRes.TemplateMissing); return View(); } var viewModel = Mapper.Map<EmailTemplate, TemplateViewModel>(template); return View(viewModel); } catch (Exception ex) { ModelState.AddModelError("TemplateMissing", GlobalRes.TemplateMissing); return View(); } } [HttpGet] public ActionResult Edit(string id) { Guid guid; Guid.TryParse(id, out guid); if (guid.Equals(Guid.Empty)) { ViewBag.Message = GlobalRes.TemplateMissing; return View("~/Views/Shared/Error.cshtml"); } try { var service = IoC.GetInstance<IContentService>(); var template = service.GetById(guid); if (template == null) { ViewBag.Message = GlobalRes.TemplateMissing; return View("~/Views/Shared/Error.cshtml"); } return View(Mapper.Map<EmailTemplate, TemplateViewModel>(template)); } catch (Exception) { ModelState.AddModelError("Error", GlobalRes.Error); return View(); } } [HttpPost] public ActionResult Edit(TemplateViewModel viewModel) { if (!ModelState.IsValid) { ModelState.AddModelError("InvalidModel", GlobalRes.InvalidModel); return View(viewModel); } var service = IoC.GetInstance<IContentService>(); var template = service.GetById(viewModel.Id); if (template == null) { ModelState.AddModelError("Error", GlobalRes.Error); return View(viewModel); } template = Mapper.Map<TemplateViewModel, EmailTemplate>(viewModel); var temp = service.GetByName(template.Name); if (temp != null && temp.Id != template.Id) { ModelState.AddModelError("Error", string.Format(GlobalRes.DuplicateTemplate, template.Name)); return View(viewModel); } if (!service.UpdateTemplate(template)) { ModelState.AddModelError("Error", GlobalRes.Error); return View(viewModel); } return RedirectToAction("Index", "EmailTemplate"); } [HttpGet] public ActionResult Delete(string id) { Guid guid; Guid.TryParse(id, out guid); if (guid.Equals(Guid.Empty)) { ModelState.AddModelError("EmptyId", GlobalRes.EmtpyId); return View(); } try { var service = IoC.GetInstance<IContentService>(); var template = service.GetById(guid); if (template == null) { ModelState.AddModelError("TemplateMissing", GlobalRes.TemplateMissing); return View(); } return View(Mapper.Map<EmailTemplate, TemplateViewModel>(template)); } catch (Exception) { ModelState.AddModelError("Error", GlobalRes.Error); return View(); } } [HttpPost] public ActionResult Delete(Guid id) { var service = IoC.GetInstance<IContentService>(); try { if (!service.Delete(id)) { ModelState.AddModelError("","BAAD"); return View(); } return RedirectToAction("Index"); } catch (Exception ex) { ModelState.AddModelError("Error", ex.Message); return View(); } } [HttpPost] public JsonResult SendEmail(string fromaddress, string toaddress, string password, string name) { var service = IoC.GetInstance<IContentService>(); try { var template = service.GetByName(name); if (template == null) return Json(new { status = "fail", message = "Template not found" }); template.Body = FormatBody(template.Body, template.Signature); var sendService = IoC.GetInstance<IEmailService>(); sendService.SendEmail(fromaddress, toaddress, template.Subject, template.Body, password); return Json(new { status = "ok", message = GlobalRes.SuccessSend }); } catch (Exception ex) { return Json(new { status = "fail", message = ex.Message }); } } private string FormatBody(string body, string signature) { return string.Format("{0}<p>{1}</p>", body, signature); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Data { public interface IUserRepository : IRepository<User, Guid> { User GetByEmail(string email); User GetByLogin(string login); } } <file_sep>var source; function quickSend(name) { if (name) { source = name; $('#send-modal').modal('toggle'); } } $(document).ready(function () { $('#send-modal').modal({ keyboard: false, backdrop: false, show: false, remote: false }); $('#closebutton').on('click', function(event) { $('#send-modal').hide(); $("#status_notification").hide(); $('#fromaddress').val(''); $('#toaddress').val(''); $('#password').val(''); }); $('#sendbutton').on('click', function (event) { var obj = { name: source, fromaddress: $('#fromaddress').val(), toaddress: $('#toaddress').val(), password: <PASSWORD>() }; var uri = '/emailtemplate/sendemail'; if (!source) { obj["name"] = $('#Name').val(); } $('#sendbutton').attr('disabled', 'disabled'); $('#closebutton').attr('disabled', 'disabled'); $.ajax({ url: uri, type: "POST", data: (obj), dataType: "json", success: sendEmailHandler }); $('#spinner').fadeIn(); }); function sendEmailHandler(response) { $('#sendbutton').removeAttr('disabled', 'disabled'); $('#closebutton').removeAttr('disabled', 'disabled'); $('#spinner').hide(); if (response) { var panel = $("#status_notification"); panel.fadeIn(); panel.text(response["message"]); if (response["status"] == "ok") { panel.attr('class', "bg-success"); } else { panel.attr('class', 'bg-danger'); } } } });<file_sep>eMailer ======= Email template utility <file_sep>using _4tegroup.Mailer.Contracts; using _4tegroup.Mailer.Data; using _4tegroup.Mailer.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Service { public class ContentService : BaseService, IContentService { public ContentService(IUnitOfWork unitOfWork) : base(unitOfWork) { } public IList<EmailTemplate> GetAllTemplates() { var repo = UnitOfWork.GetRepository<IEmailTemplateRepository>(); return repo.All(); } public bool CreateEmailTemplate(EmailTemplate template) { var repo = GetRepository<IEmailTemplateRepository>(); try { if (repo.GetByName(template.Name) != null) { return false; } repo.Create(template); UnitOfWork.Commit(); return true; } catch(Exception ex) { throw new Exception("Exception", ex); } } public EmailTemplate GetById(Guid id) { if (id.Equals(Guid.Empty)) { return null; } try { var repo = GetRepository<IEmailTemplateRepository>(); var template = repo.Get(id); return template; } catch (Exception) { //logging return null; } } public EmailTemplate GetByName(string name) { if (string.IsNullOrEmpty(name)) { return null; } try { var repo = GetRepository<IEmailTemplateRepository>(); var template = repo.GetByName(name); return template; } catch (Exception) { //logging return null; } } public bool UpdateTemplate(EmailTemplate template) { if (template == null) return false; var repo = GetRepository<IEmailTemplateRepository>(); try { if (!repo.Update(template)) return false; UnitOfWork.Commit(); return true; } catch (Exception) { //logging return false; } } public bool Delete(Guid id) { if (string.Equals(id, Guid.Empty)) { return false; } var repo = UnitOfWork.GetRepository<IEmailTemplateRepository>(); try { repo.Delete(id); UnitOfWork.Commit(); return true; } catch (Exception) { return false; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Domain { public class User : Entity { } } <file_sep>using System; using System.Collections.Generic; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Contracts { public interface IContentService : IService { IList<EmailTemplate> GetAllTemplates(); bool CreateEmailTemplate(EmailTemplate template); EmailTemplate GetById(Guid id); EmailTemplate GetByName(string name); bool UpdateTemplate(EmailTemplate template); bool Delete(Guid id); } }<file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using _4tegroup.Mailer.WebUI.App_LocalResources; namespace _4tegroup.Mailer.WebUI.Models { public class TemplateViewModel { [HiddenInput] public Guid Id { get; set; } [Required(ErrorMessageResourceType = typeof (GlobalRes), ErrorMessageResourceName = "Required")] public string Name { get; set; } [Required(ErrorMessageResourceType = typeof (GlobalRes), ErrorMessageResourceName = "Required")] public string Subject { get; set; } [AllowHtml] [Required(ErrorMessageResourceType = typeof (GlobalRes), ErrorMessageResourceName = "Required")] public string Body { get; set; } [AllowHtml] public string Signature { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.DataEF { public class EmailerContext : DbContext { public EmailerContext(string connectionString) : base("DefaultConnection") { } public DbSet<EmailTemplate> EmailTemplates { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Domain { public class EmailTemplate : Entity { public string Name { get; set; } public string Subject { get; set; } public string Body { get; set; } public string Signature { get; set; } public DateTime Created { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Domain { public class Entity<TKey> { public TKey Id { get; set; } } public class Entity : Entity<Guid> { public Entity() { Id = Guid.NewGuid(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; namespace _4tegroup.Mailer.WebUI { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Content/js/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Content/js/jquery.validate.min.js", "~/Content/js/jquery.validate.unobtrusive.min.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Content/js/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Content/js/bootstrap.js", "~/Content/js/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/css/bootstrap.css", "~/Content/css/site.css")); bundles.Add(new StyleBundle("~/bundles/script").Include( "~/Content/js/script.js")); bundles.Add(new StyleBundle("~/bundles/metro-css").Include( "~/Content/cs/metro-bootstrap-responsive.min.css", "~/Content/cs/metro-bootstrap.min.css")); bundles.Add(new StyleBundle("~/bundles/metro-js").Include( "~/Content/js/metro.min.js")); // Set EnableOptimizations to false for debugging. For more information, // visit http://go.microsoft.com/fwlink/?LinkId=301862 BundleTable.EnableOptimizations = false; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Data { public abstract class UnitOfWork : IUnitOfWork, IDisposable { private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); public TRepository GetRepository<TRepository>() where TRepository : IRepository { var repositoryType = typeof(TRepository); if (!_repositories.ContainsKey(repositoryType)) { throw new DataException("Repository is not found."); } try { return ((Lazy<TRepository>)_repositories[repositoryType]).Value; } catch (Exception ex) { throw new DataException("Repository is not found.", ex); } } public abstract void Commit(); protected void AddRepository<TRepository>(Func<TRepository> repositoryConstructor) { if (repositoryConstructor == null) return; var repositoryType = typeof(TRepository); if (!_repositories.ContainsKey(repositoryType)) { _repositories.Add(repositoryType, new Lazy<TRepository>(repositoryConstructor)); } } public virtual void Dispose() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Data { public interface IRepository { } public interface IRepository<TEntity, in TKey> : IRepository where TEntity : Entity { bool Create(TEntity entity); TEntity Get(TKey key); IList<TEntity> All(); bool Update(TEntity entity); bool Delete(TKey key); } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.Service.Helpers { public class EmailHelper { public string GenerateSmtpServerAddress(string email) { const string host = "smtp.{0}"; if (!IsValidEmail(email)) return string.Empty; var domain = email.Split(new string[] {"@"}, StringSplitOptions.None)[1]; return string.Format(host, domain); } public bool ValidateEmail(Email email) { if (email == null) return false; return IsValidEmail(email.From) && IsValidEmail(email.To) && !string.IsNullOrEmpty(email.Body); } bool invalid = false; public bool IsValidEmail(string strIn) { invalid = false; if (String.IsNullOrEmpty(strIn)) return false; try { strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200)); } catch (RegexMatchTimeoutException) { return false; } if (invalid) return false; try { return Regex.IsMatch(strIn, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)); } catch (RegexMatchTimeoutException) { return false; } } private string DomainMapper(Match match) { IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using _4tegroup.Mailer.Data; using _4tegroup.Mailer.Domain; namespace _4tegroup.Mailer.DataEF { public abstract class BaseRepository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity : Entity { protected const string ErrorMessage = "Some critical issue are founded."; private readonly EmailerContext _context; protected EmailerContext Context { get { return _context; } } protected BaseRepository(EmailerContext context) { _context = context; } public bool Create(TEntity entity) { try { Context.Set<TEntity>().Add(entity); return true; } catch (Exception) { //logging return false; } } public TEntity Get(TKey key) { try { return Context.Set<TEntity>().Find(key); } catch (Exception) { throw; } } public IList<TEntity> All() { try { return Context.Set<TEntity>().ToList(); } catch (Exception) { throw; } } public bool Update(TEntity entity) { var contextEntry = Context.Entry(entity); if (contextEntry != null) { var oldEntity = Context.Set<TEntity>().Find(entity.Id); if (oldEntity != null) { var contextOldEntry = Context.Entry(oldEntity); contextOldEntry.CurrentValues.SetValues(entity); contextOldEntry.State = EntityState.Modified; return true; } } return false; } /* var contextEntry = Context.Entry(entity); if (contextEntry != null) { var oldEntity = Context.Set<TEntity>().Find(entity.Id); if (oldEntity != null) { var contextOldEntry = Context.Entry(oldEntity); contextOldEntry.CurrentValues.SetValues(entity); contextOldEntry.State = EntityState.Modified; return true; } } return false;*/ public bool Delete(TKey key) { try { var entity = Context.Set<TEntity>().Find(key); if (entity != null) { Context.Set<TEntity>().Remove(entity); return true; } return false; } catch (Exception) { //logging return false; throw; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4tegroup.Mailer.Data { public interface IUnitOfWork : IDisposable { TRepository GetRepository<TRepository>() where TRepository : IRepository; void Commit(); } }
b94afb31fa0bd777a0aa08b4ee174b97808288de
[ "JavaScript", "C#", "Markdown" ]
26
C#
bger/eMailer
2df124d598374f008915116f421e807f080061c3
81356f3ecee227132cb85a9ed968500f054ec9b5
refs/heads/master
<file_sep># PySimpleGUI_Snake_Games A game made from pysimple for my little project *Warning Since the keyboard module requires root to access raw input data there is a second verion using built in buttons called snake_game_linux.py My goals: familar to using arrays and extracting the values for meaningful purposes in the game accessing and storing data through a bsaic text file(High scores) Getting better with just basc value storing and accesing across the entire game <file_sep>def main(): def leader_board_scores(): from collections import namedtuple things = [] f = open('scores/high_score', 'r') contents = f.read() if len(contents) > 0: cool = list(contents.split('\n')) f.close() cool.pop(len(cool) - 1) scores = namedtuple('scores', 'name score') for i in range(len(cool)): name, value = str(cool[i - 1]).split(':') things.append(scores(name, value)) final = sorted(things, key=lambda x: getattr(x, 'score'), reverse=True) if len(things) >= 3: for i in range(3): name3, value3 = final[i] window[str(i) + '-'].update(f'{name3}: {value3}') else: for i in range(len(final)): name3, value3 = final[i] window[str(i) + '-'].update(f'{name3}: {value3}') def high_scores(score): import PySimpleGUI as sg a = sg.PopupGetText('Name') + ':' + str(score) f = open('scores/high_score', 'a') f.write(str(a)+'\n') f.close() import PySimpleGUI as sg import random as r import time sg.theme('DarkPurple6') grid_size = 20 snake = [] head = [] colors = ['red', 'blue', 'orange'] score = 0 x, y = 5, 5 food = (10, 10) cx, cy = 0, 0 segments = 3 score_temp = sg.T(str(score), key='-score-', size=(20, 2), justification='center', font=('arial', 10), text_color='white') body = sg.Text('Snake', font=('arial', 20), justification='center', size=(60, 0)) grid = ([sg.Button(key=(row, column), size=(2, 1), button_color=('white', 'black')) for row in range(grid_size)] for column in range(grid_size)) top3 = ([sg.Text(' ', key=f'{i}-', font=('Bold', 15), justification='center', size=(10, 2))] for i in range(3)) controlpanel = [[sg.B('⇧',size=(2,0) ,font=('arial',20),key='up')], [sg.B('⇦',size=(2,0), font=('arial',20), key='left'),sg.B('⇨',size=(2,0), font=('arial',20), key='right')], [sg.B('⇩',size=(2,0), font=('arial',20), key='down')] ] leaderboard = [[sg.Text('Score', justification='center', size=(20, 0))], [score_temp], [sg.Column(top3)], [sg.Frame('hi',controlpanel,element_justification='center')] ] layout = [[body], [sg.Frame('game', grid, size=(300,200)), sg.Frame('Stats', leaderboard, font=('Bolded', 15), border_width=10, size=(200, 750), element_justification='center', vertical_alignment='top-center', background_color='DarkBlue')]] window = sg.Window('hi', layout, finalize=True, size=(900, 800)) leader_board_scores() window[food].update(button_color=('green', 'green')) while True: event, value = window.read(50) if x >= grid_size or x < 0 or y < 0 or y >= grid_size: high_scores(score) break else: if event == 'up' and event != 'down': cx = 0 cy = -1 if event == 'down' and event != 'up': cx = 0 cy = 1 if event == 'left' and event != 'right': cx = -1 cy = 0 if event == 'right' and event != 'left': cx = 1 cy = 0 oldx, oldy = x, y x, y = x + cx, y + cy if x != oldx or y != oldy: snake.insert(0, (oldx, oldy)) head = snake[0] if len(snake) > segments: window[snake[-1]].update(button_color=('white', 'black')) snake.pop(len(snake)-1) window[snake[0]].update(button_color=('blue', colors[r.randint(0, 2)])) if head == food: while food in snake: food = (r.randint(0, grid_size - 1), r.randint(0, grid_size - 1)) else: segments = segments + 1 window[food].update(button_color=('green', 'green')) score = score + 1 window['-score-'].update('score: ' + str(score)) if head in snake[1:-1]: # death break time.sleep(0.025) window.close() if __name__ in "__main__": main() <file_sep>keyboard==0.13.5 PySimpleGUI==4.34.0
7bf8bf12a42b6c41eeab9951878528f4a4c232a1
[ "Markdown", "Python", "Text" ]
3
Markdown
NeoPrint3D/PySimpleGUI_Snake_Games
226ee7a1951f11a59198f062bac3589af5172323
d2a501af48651d263d73d68185664c3d5b5cad54
refs/heads/master
<file_sep># Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import inference_pb2 as inference__pb2 class InferenceAPIStub(object): """The inference api service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetClassification = channel.unary_unary( "/inference.InferenceAPI/GetClassification", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.ImageClassification.FromString, ) self.GetFashionDetection = channel.unary_unary( "/inference.InferenceAPI/GetFashionDetection", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionDetection.FromString, ) self.GetFashionMatchingMNIST = channel.unary_unary( "/inference.InferenceAPI/GetFashionMatchingMNIST", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionMatchingMNIST.FromString, ) self.GetFashionMatchingBottom = channel.unary_unary( "/inference.InferenceAPI/GetFashionMatchingBottom", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionMatchingBottom.FromString, ) self.GetFashionMatchingTop = channel.unary_unary( "/inference.InferenceAPI/GetFashionMatchingTop", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionMatchingTop.FromString, ) self.GetFashionMatchingFull = channel.unary_unary( "/inference.InferenceAPI/GetFashionMatchingFull", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionMatchingFull.FromString, ) self.GetFashionRecommendations = channel.unary_unary( "/inference.InferenceAPI/GetFashionRecommendations", request_serializer=inference__pb2.ImageRequest.SerializeToString, response_deserializer=inference__pb2.FashionRecommendations.FromString, ) class InferenceAPIServicer(object): """The inference api service definition. """ def GetClassification(self, request, context): """Get classification """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionDetection(self, request, context): """Get fashion detection """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionMatchingMNIST(self, request, context): """Get fashion matching embedding for fashion-MNIST """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionMatchingBottom(self, request, context): """Get fashion matching embedding for dive-dataset-bottom """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionMatchingTop(self, request, context): """Get fashion matching embedding for dive-dataset-top """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionMatchingFull(self, request, context): """Get fashion matching embedding for dive-dataset-full """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetFashionRecommendations(self, request, context): """Get fashion crop and Get the matching embedding(top/ bottom/ full) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def add_InferenceAPIServicer_to_server(servicer, server): rpc_method_handlers = { "GetClassification": grpc.unary_unary_rpc_method_handler( servicer.GetClassification, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.ImageClassification.SerializeToString, ), "GetFashionDetection": grpc.unary_unary_rpc_method_handler( servicer.GetFashionDetection, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionDetection.SerializeToString, ), "GetFashionMatchingMNIST": grpc.unary_unary_rpc_method_handler( servicer.GetFashionMatchingMNIST, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionMatchingMNIST.SerializeToString, ), "GetFashionMatchingBottom": grpc.unary_unary_rpc_method_handler( servicer.GetFashionMatchingBottom, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionMatchingBottom.SerializeToString, ), "GetFashionMatchingTop": grpc.unary_unary_rpc_method_handler( servicer.GetFashionMatchingTop, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionMatchingTop.SerializeToString, ), "GetFashionMatchingFull": grpc.unary_unary_rpc_method_handler( servicer.GetFashionMatchingFull, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionMatchingFull.SerializeToString, ), "GetFashionRecommendations": grpc.unary_unary_rpc_method_handler( servicer.GetFashionRecommendations, request_deserializer=inference__pb2.ImageRequest.FromString, response_serializer=inference__pb2.FashionRecommendations.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( "inference.InferenceAPI", rpc_method_handlers ) server.add_generic_rpc_handlers((generic_handler,)) <file_sep>""" Inference client (python)""" from __future__ import print_function import logging import grpc import sys sys.path.append("inf-ser/stubs/") import inference_pb2 import inference_pb2_grpc def get_image_in_bytes(img_path): """ This function converts the image to bytes. Parameters: img_path(str) : path to the image. Returns: bytes : image in bytes. """ with open(img_path, "rb") as f: img = f.read() return img def run(img_path): """ This function performs model inference and prints the result. Parameters: img_path(str) : path to the image. """ with grpc.insecure_channel("localhost:6060") as channel: stub = inference_pb2_grpc.InferenceAPIStub(channel) for _ in range(0, 1): response = stub.GetFashionDetection( inference_pb2.ImageRequest(image=get_image_in_bytes(img_path)) ) detect = response.detections status = response.error if len(detect) <= 0: print("No Detections") else: print(detect) print(status) def get_args(): """ Gets the path to the image from the user. Returns: str : image path entered by the user """ parser = argparse.ArgumentParser(description='Inference client.') parser.add_argument("--img_path", required=True, type=str, help="Path to the image for inference.") args = parser.parse_args() return args.img_path if __name__ == "__main__": logging.basicConfig() img_path = get_args() run(img_path)
9e33f5154809ea48a68ee413390b500ceb669c97
[ "Python" ]
2
Python
Rathna21/tensorrt-inference-server
97abde96be79384faadf7f8b582d2feca2a97c7f
72c1d73a880bcb26907aa9572b04197b22142549
refs/heads/main
<file_sep>package Eatables; public class Magnum implements Eatables { MagnumType type; public Magnum(){ } public Magnum(MagnumType type){ this.type=type; } public void eat(){ System.out.println("I'm eating a " + type + " Magnum."); } public MagnumType getType(){ return type; } } <file_sep>package sellers; import Eatables.*; public class PriceList { double ballPrice = 1.00; double rocketPrice = 1.2; double magnumStandardPrice = 2; public PriceList(){ } public PriceList(double ballPrice, double rocketPrice, double magnumStandardPrice){ } public double getBallPrice() { return ballPrice; } public void setBallPrice(double ballPrice) { this.ballPrice = ballPrice; } public double getRocketPrice() { return rocketPrice; } public void setRocketPrice(double rocketPrice) { this.rocketPrice = rocketPrice; } public double getMagnumStandardPrice(MagnumType magnum) { switch(magnum){ case ROMANTICSTRAWBERRIES: case ALPINENUTS: return magnumStandardPrice*1.5; case MILKCHOCOLATE: case WHITECHOCOLATE: case BLACKCHOCOLATE: default: return magnumStandardPrice; } } public void setMagnumStandardPrice(double magnumStandardPrice) { this.magnumStandardPrice = magnumStandardPrice; } } <file_sep>package application; import Eatables.Eatables; import sellers.IceCreamSalon; import sellers.IceCreamSeller; import sellers.PriceList; import sellers.*; import Eatables.*; public class IceCreamApp2 { public static void main(String[] args) throws NoMoreIceCreamException { //Create a pricelist and stock to use for our icecreamcar PriceList pricelist = new PriceList(1.00, 1.2, 2); Stock stock = new Stock(0, 10, 10, 10); //Instantiating new icecreamcar with our created pricelist and stock IceCreamSeller car = new IceCreamCar(pricelist, stock); //Creating array to fill orders Eatables[] order = new Eatables[100]; //Order different items and try to catch exceptions for every order try { order[0] = car.orderIceRocket(); } catch (NoMoreIceCreamException nmice) { System.out.println(nmice.getMessage());} try { order[1] = car.orderMagnum(MagnumType.ALPINENUTS); } catch (NoMoreIceCreamException nmice) { System.out.println(nmice.getMessage()); } try { order[2] = car.orderMagnum(MagnumType.ALPINENUTS); } catch (NoMoreIceCreamException nmice){ System.out.println(nmice.getMessage()); } try { order[3] = car.orderCone(new Flavor[]{Flavor.BANANA, Flavor.LEMON, Flavor.MOKKA}); } catch (NoMoreIceCreamException nmice) { System.out.println(nmice.getMessage()); } //Print the array of orders with for each loop and catch the empty indexes for (Eatables o : order) { if (o != null) { o.eat(); } } //Print total profit accumulated System.out.println("Total profit is: " + car.getProfit() + " euro."); } } <file_sep>package sellers; import Eatables.*; public class IceCreamSalon implements IceCreamSeller{ PriceList priceList = new PriceList(); double totalProfit = 0; public IceCreamSalon(PriceList priceList){ this.priceList = priceList; } public double getProfit(){ return totalProfit; } public Cone orderCone(Flavor[] balls){ Cone cone = new Cone(balls); totalProfit += balls.length* priceList.getBallPrice(); return cone; } public IceRocket orderIceRocket(){ IceRocket icerocket = new IceRocket(); totalProfit += priceList.getRocketPrice(); return icerocket; } public Magnum orderMagnum(MagnumType type){ Magnum magnum = new Magnum(type); totalProfit += priceList.getMagnumStandardPrice(type); return magnum; } @Override public String toString() { return "IceCreamSalon{" + "priceList=" + priceList + ", totalProfit=" + totalProfit + '}'; } } <file_sep>package application; import sellers.*; import Eatables.*; public class IceCreamApp { public static void main(String[] args) throws NoMoreIceCreamException { //Create an pricelist to use for our salon PriceList pricelist = new PriceList(1.00,1.2,2); //Instantiate our new salon with our created pricelist IceCreamSeller salon = new IceCreamSalon(pricelist); //Creating an array and instantiate with orders Eatables[] order = { salon.orderIceRocket(), salon.orderMagnum(MagnumType.WHITECHOCOLATE), salon.orderMagnum(MagnumType.ALPINENUTS), salon.orderCone(new Flavor[]{Flavor.BANANA, Flavor.LEMON, Flavor.MOKKA}) }; //Print out the order array for (Eatables o: order){ o.eat(); } //Print out the profit System.out.println("Total profit is : " + salon.getProfit() + " euro."); } } <file_sep>package sellers; import Eatables.*; public class IceCreamCar implements IceCreamSeller{ PriceList priceList; Stock stock; double profit; public IceCreamCar(PriceList priceList, Stock stock){ this.priceList = priceList; this.stock = stock; } public Cone orderCone(Flavor[] balls) throws NoMoreIceCreamException{ return prepareCone(balls); } public Cone prepareCone (Flavor[]balls) throws NoMoreIceCreamException{ Cone cone = new Cone(balls); if (stock.getBalls() < balls.length || stock.getCones() < 1) { throw new NoMoreIceCreamException("Not enough balls or cones in inventory."); } else { stock.cones -= 1; stock.balls -= balls.length; profit += balls.length * priceList.ballPrice; } return cone; } public IceRocket orderIceRocket() throws NoMoreIceCreamException{ return prepareIceRocket(); } public IceRocket prepareIceRocket() throws NoMoreIceCreamException{ IceRocket icerocket = new IceRocket(); if (stock.getIceRockets()<1){ throw new NoMoreIceCreamException("No more Icerockets in stock."); }else { stock.iceRockets -= 1; profit += priceList.getRocketPrice(); return icerocket; } } public Magnum orderMagnum(MagnumType type) throws NoMoreIceCreamException{ return prepareMagnum(type); } public Magnum prepareMagnum(MagnumType type) throws NoMoreIceCreamException{ Magnum magnum = new Magnum(type); if(stock.getMagni()<1){ throw new NoMoreIceCreamException("No more magnums in stock."); }else { stock.magni -= 1; profit += priceList.getMagnumStandardPrice(type); return magnum; } } public double getProfit(){ return profit; } } <file_sep>package Eatables; public interface Eatables { void eat(); } <file_sep>package Eatables; public enum MagnumType { MILKCHOCOLATE, WHITECHOCOLATE, BLACKCHOCOLATE, ALPINENUTS, ROMANTICSTRAWBERRIES; }
c9c9c409ff7b9b04eaf96b0fe7b4c7537c0f1010
[ "Java" ]
8
Java
nikocodings/IceCreamShop
023473ccc108ea9af8e66ff7fc1b818d3e433c6f
78ef4f598649790e2a2f39f14f5f564449779930
refs/heads/main
<file_sep>const port = 3003; const bodyParser = require('body-parser') const express = require('express'); const { modelNames } = require('mongoose'); const server = express() const allowCors = require('./cors') //AQUI IREMOS IMPORTA O EXPRESS QUERY INT QUE SERÁ RESPONSÁVEL POR CONVERTER //O SKIP DA PAGINAÇÃO DOS NOS RESGISTROS RETORNADOS PELO MONGO O MESMO TAMBÉM TRABALHA COMO UM MIDDLEWARE const queryParser = require('express-query-int') server.use(bodyParser.urlencoded({ extended: true })) server.use(bodyParser.json()) server.use(allowCors) server.use(queryParser()) server.listen(port, function() { console.log(`Servidor está rodando na porta ${port}`) }) module.exports = server<file_sep>export function selectTab(tabId) { return { type: 'TAB_SELECTED', payload: tabId } } export function showTabs(...tabIds) { //O QUE ESTAMOS UTILIZANDO ACIMA É UM OPERADOR DO TIPO REST ONDE EU PEGO TODOS OS PARAMETROS PASSADOS //PARA A FUNÇÃO E JUNTO ISSO EM UM ARRAY ONDE EU CONSIGO UTLIZAR E MANIPULAR DENTRO DESSA MINHA FUNÇÃO DIFEENTE DO SPREAD // QUE PEGA UM ARRAY E TRANFORMA EM PARAMETROS. const tabsToShow = {} tabIds.forEach(e => tabsToShow[e] = true) return { type: 'TAB_SHOWED', payload: tabsToShow } }
2101c9474048cc158edb7749c113463dcb18bf7b
[ "JavaScript" ]
2
JavaScript
LucasFbatista/Dashboard_pagamentos
19588adba147109c0093d09383511489f23426df
86162b8a73b2b8dda3311bd15b86d565b386a012
refs/heads/master
<file_sep>{% extends '_base.html' %} {% block title %}Courses{% endblock %} {% block content %} <h1 class="title is-size-1">Courses</h1> <hr><br> {% if course_list %} {% for course in course_list %} <h4 class="title is-size-4">{{ course.title }}</h4> <p>{{ course.description }}</p> <br> <p><a href="{% url 'course_detail' course.slug %}" class="button is-info">Purchase</a></p> <br><br><br> {% endfor %} {% else %} <p>No courses!</p> {% endif %} {% endblock %} <file_sep>from django.contrib import admin from django.urls import path, include from django.contrib.auth.views import LoginView, LogoutView from django.views.generic.base import TemplateView from django.conf import settings urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('login/', LoginView.as_view(template_name='login.html'), name='login'), path('logout/', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'), path('courses/', include('apps.courses.urls')), path('users/', include('apps.users.urls')), path('admin/', admin.site.urls), ] <file_sep>import json import stripe from django.urls import reverse from django.views.generic import ListView, DetailView from django.http import HttpResponseRedirect from django.conf import settings from django.views import View from django.http import JsonResponse from .models import Course class CourseListView(ListView): model = Course template_name = 'courses/course_list.html' def get_context_data(self, *args, **kwargs): context = super(CourseListView, self).get_context_data(*args, **kwargs) return context def render_to_response(self, context, **response_kwargs): if not self.request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) return super(CourseListView, self).render_to_response(context, **response_kwargs) class CourseDetailView(DetailView): model = Course template_name = 'courses/course_detail.html' def get_context_data(self, *args, **kwargs): context = super(CourseDetailView, self).get_context_data(*args, **kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def render_to_response(self, context, **response_kwargs): if not self.request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) return super(CourseDetailView, self).render_to_response(context, **response_kwargs) ################# # direct charge # ################# # class CourseChargeView(View): # def post(self, request, *args, **kwargs): # stripe.api_key = settings.STRIPE_SECRET_KEY # json_data = json.loads(request.body) # course = Course.objects.filter(id=json_data['course_id']).first() # fee_percentage = .01 * int(course.fee) # try: # customer = get_or_create_customer( # self.request.user.email, # json_data['token'], # course.seller.stripe_access_token, # course.seller.stripe_user_id, # ) # charge = stripe.Charge.create( # amount=json_data['amount'], # currency='usd', # customer=customer.id, # description=json_data['description'], # application_fee=int(json_data['amount'] * fee_percentage), # stripe_account=course.seller.stripe_user_id, # ) # if charge: # return JsonResponse({'status': 'success'}, status=202) # except stripe.error.StripeError as e: # return JsonResponse({'status': 'error'}, status=500) # # helpers # def get_or_create_customer(email, token, stripe_access_token, stripe_account): # stripe.api_key = stripe_access_token # connected_customers = stripe.Customer.list() # for customer in connected_customers: # if customer.email == email: # print(f'{email} found') # return customer # print(f'{email} created') # return stripe.Customer.create( # email=email, # source=token, # stripe_account=stripe_account, # ) ###################### # destination charge # ###################### class CourseChargeView(View): def post(self, request, *args, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY json_data = json.loads(request.body) course = Course.objects.filter(id=json_data['course_id']).first() fee_percentage = .01 * int(course.fee) try: customer = get_or_create_customer( self.request.user.email, json_data['token'], ) charge = stripe.Charge.create( amount=json_data['amount'], currency='usd', customer=customer.id, description=json_data['description'], destination={ 'amount': int(json_data['amount'] - (json_data['amount'] * fee_percentage)), 'account': course.seller.stripe_user_id, }, ) if charge: return JsonResponse({'status': 'success'}, status=202) except stripe.error.StripeError as e: return JsonResponse({'status': 'error'}, status=500) # helpers def get_or_create_customer(email, token): stripe.api_key = settings.STRIPE_SECRET_KEY connected_customers = stripe.Customer.list() for customer in connected_customers: if customer.email == email: print(f'{email} found') return customer print(f'{email} created') return stripe.Customer.create( email=email, source=token, ) <file_sep># Generated by Django 2.1 on 2018-12-21 21:43 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('slug', models.SlugField(max_length=255)), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ('fee', models.PositiveIntegerField(default=50)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ] <file_sep>from django.urls import path from .views import CourseListView, CourseDetailView, CourseChargeView urlpatterns = [ path('', CourseListView.as_view(), name='course_list'), path('charge/', CourseChargeView.as_view(), name='charge'), path('<slug:slug>/', CourseDetailView.as_view(), name='course_detail'), ] <file_sep># Setting up Stripe Connect with Django ## Want to learn how to build this? Check out the [post](https://testdriven.io/blog/setting-up-stripe-connect-with-django/). ## Want to use this project? 1. Fork/Clone 1. Create a virtual environment and install the dependencies: ```sh $ pipenv shell $ pipenv install ``` 1. Apply the migrations, create a superuser, and add the fixtures to the DB: ```sh $ python manage.py migrate $ python manage.py createsuperuser $ python manage.py loaddata fixtures/users.json $ python manage.py loaddata fixtures/courses.json ``` 1. Add your Stripe test secret and test publishable keys along with your Connect client id to the bottom of the *settings.py* file: ```python STRIPE_PUBLISHABLE_KEY = '<your test publishable key here>' STRIPE_SECRET_KEY = '<your test secret key here>' STRIPE_CONNECT_CLIENT_ID = '<your test connect client id here>' ``` 1. Run the server: ```sh $ python manage.py runserver ``` <file_sep>from django.contrib import admin from .models import Course class CourseAdmin(admin.ModelAdmin): list_display = ( 'id', 'title', 'price', 'fee', 'seller', 'created_at', 'updated_at', ) readonly_fields = ('id',) admin.site.register(Course, CourseAdmin)
d517202575191a2f50fc2ee54793b40a592a857f
[ "Markdown", "Python", "HTML" ]
7
HTML
yds05238/django-stripe-connect
70d616b97d0cd1bc553209b33aa32fa435c1713a
a240addeb03b764f0021fbe635539969e32b6215
refs/heads/main
<repo_name>ogulcanpirim/Block-Game<file_sep>/Assets/Scripts/Player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private bool nextBullet; public float bulletSpeed; private Vector2 screen; private float crossLoc; private float playerSpeed; private float playerSize; private GameObject cross, crossParent; public GameObject bullet; void Start() { bulletSpeed = 0.1f; nextBullet = true; playerSpeed = 5.0f; cross = GameObject.Find("Cross"); crossParent = GameObject.Find("CrossParent"); crossLoc = cross.GetComponent<SpriteRenderer>().bounds.size.y / 2; playerSize = this.GetComponent<SpriteRenderer>().bounds.size.x; screen = ScreenSize.screenSize; } void Update() { Vector3 pos = transform.position; if (Input.GetKey(KeyCode.W)) pos.y += playerSpeed * Time.deltaTime; if (Input.GetKey(KeyCode.S)) pos.y -= playerSpeed * Time.deltaTime; if (Input.GetKey(KeyCode.D)) pos.x += playerSpeed * Time.deltaTime; if (Input.GetKey(KeyCode.A)) pos.x -= playerSpeed * Time.deltaTime; bool notInside = pos.x + playerSize / 2 > screen.x || pos.x - playerSize / 2 < -screen.x || pos.y + playerSize / 2 > screen.y || pos.y - playerSize / 2 < -screen.y; if (!notInside) transform.position = pos; crossParent.transform.position = pos; cross.transform.localPosition = new Vector3(0,-crossLoc,0); Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position); Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition); float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen); crossParent.transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle - 90)); //Constant shoot with bulletSpeed /* if (nextBullet) StartCoroutine(shoot()); */ if (Input.GetKeyDown(KeyCode.Mouse0)) { Vector3 bulletPos = pos - crossParent.transform.up * playerSize; Instantiate(bullet, bulletPos, crossParent.transform.rotation); } } IEnumerator shoot() { if (nextBullet) { this.GetComponent<AudioSource>().Play(); Vector3 bulletPos = transform.position - crossParent.transform.up * playerSize; Instantiate(bullet, bulletPos, crossParent.transform.rotation); nextBullet = false; } yield return new WaitForSeconds(bulletSpeed); nextBullet = true; } float AngleBetweenTwoPoints(Vector3 a, Vector3 b) { return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg; } } <file_sep>/Assets/Scripts/DestroyObject.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DestroyObject : MonoBehaviour { private Vector2 screen; private GameObject explosion; public GameObject EnemyExplosion; void Start() { screen = ScreenSize.screenSize; explosion = GameObject.Find("eExplosion"); } void Update() { foreach(GameObject go in GameObject.FindObjectsOfType<GameObject>()) { if (go.gameObject.name == "Bullet(Clone)") { if (outOfBounds(go.transform.position)) Destroy(go); } if (go.gameObject.name.StartsWith("Enemy")) { if (go.GetComponent<Enemy>().getHealth() <= 0) { explosion = Instantiate(EnemyExplosion, go.transform.position, Quaternion.identity); explosion.GetComponent<ParticleSystem>().Play(); Destroy(go); } } if (go.gameObject.name.Contains("Explosion")) { if (!go.GetComponent<ParticleSystem>().IsAlive()) Destroy(go); } } } bool outOfBounds(Vector3 pos) { if (pos.x > screen.x || pos.x < -screen.x || pos.y > screen.y || pos.y < -screen.y) return true; return false; } } <file_sep>/Assets/Scripts/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { private float enemyHealth; private float enemySpeed; private GameObject player; void Start() { player = GameObject.Find("Player"); enemySpeed = 0.5f; enemyHealth = 10.0f; } // Update is called once per frame void Update() { Vector3 playerPos = player.transform.position; transform.position = (Vector3) Vector2.MoveTowards(transform.position, playerPos, enemySpeed * Time.deltaTime); } private void OnTriggerEnter2D(Collider2D collision) { this.GetComponent<AudioSource>().Play(); float damage = Bullet.bulletDamage; enemyHealth -= damage; if (collision.gameObject.name.Contains("Bullet")) Destroy(collision.gameObject); StartCoroutine(changeColor()); } public float getHealth() { return enemyHealth; } IEnumerator changeColor() { Color curr = this.GetComponent<SpriteRenderer>().color; Color colorChange; ColorUtility.TryParseHtmlString("#D28080", out colorChange); this.GetComponent<SpriteRenderer>().color = colorChange; yield return new WaitForSeconds(0.1f); this.GetComponent<SpriteRenderer>().color = curr; } } <file_sep>/Assets/Scripts/ScreenSize.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScreenSize : MonoBehaviour { public static Vector2 screenSize = Vector2.zero; void Awake() { Vector3 screen = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0)); screenSize = (Vector2) screen; } void Update() { } } <file_sep>/Assets/Scripts/Bullet.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { private GameObject bExplosion; public GameObject bulletExplosion; public static float bulletDamage; private GameObject crossParent; private float bulletSpeed; void Start() { bulletSpeed = 7.5f; crossParent = GameObject.Find("CrossParent"); bulletDamage = 3.0f; } void Update() { transform.position += -transform.up * bulletSpeed * Time.deltaTime; } private void OnTriggerEnter2D(Collider2D collision) { bExplosion = Instantiate(bulletExplosion, this.transform.position, Quaternion.identity); bExplosion.GetComponent<ParticleSystem>().Play(); } } <file_sep>/Assets/Scripts/HealthBar.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthBar : MonoBehaviour { private GameObject bar; private GameObject parent; void Start() { parent = transform.parent.gameObject; } void Update() { } }
9f73d7934329e477a733b63900abf8dbe4bec235
[ "C#" ]
6
C#
ogulcanpirim/Block-Game
06e77c35d8a5ff963e5c9d919b8ea2842e459421
70a78bc20f9c943ba477a8c102fdad75211efe27
refs/heads/master
<repo_name>caricaMilca/CertificateGeneratorHttps<file_sep>/src/main/java/com/example/servis/CertificateCSRServis.java package com.example.servis; import com.example.data.CertificateCSR; public interface CertificateCSRServis { CertificateCSR save(CertificateCSR c); } <file_sep>/src/main/java/com/example/modeli/Korisnik.java package com.example.modeli; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Inheritance(strategy=InheritanceType.JOINED) public class Korisnik{ @Id @GeneratedValue public Long id; @Enumerated(EnumType.STRING) public UlogaKorisnika uloga; //@Size(min = 3, max = 30) //@Pattern(regexp = "^[A-Z][a-z_ A-Z]*") public String ime; //@Size(min = 3, max = 30) //@Pattern(regexp = "^[A-Z][a-z_ A-Z]*") public String prezime; //@Pattern(regexp="\\w*") //@NotNull //@Size(min = 3, max = 30) //@Column(unique=true,nullable=false) public String korisnickoIme; //@Pattern(regexp="\\w*") //@NotNull //@Size(min = 3, max = 30) //@Column(nullable=false) public String lozinka; @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "Korisnicke_roles", joinColumns = @JoinColumn( name = "korisnik_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn( name = "role_id", referencedColumnName = "id")) @JsonIgnore public Collection<Role> roles; public Korisnik(String ime, String prezime, String korisnickoIme, String lozinka) { super(); this.ime = ime; this.prezime = prezime; this.korisnickoIme = korisnickoIme; this.lozinka = lozinka; } public Korisnik() { super(); // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/example/repository/KorisnikRepozitorijum.java package com.example.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.modeli.Korisnik; public interface KorisnikRepozitorijum extends JpaRepository<Korisnik, Long> { Korisnik findByKorisnickoImeAndLozinka(String korisnickoIme, String lozinka); } <file_sep>/src/main/resources/data.sql insert into Korisnik(korisnicko_ime, lozinka, uloga) values ('ceks', 'ceks', 'Zaposleni'); insert into Korisnik(korisnicko_ime, lozinka, uloga) values ('ceks1', 'ceks', 'Zaposleni'); insert into Korisnik(korisnicko_ime, lozinka, uloga) values ('ceks2', 'ceks', 'Zaposleni'); insert into Korisnik(korisnicko_ime, lozinka, uloga) values ('ceks3', 'ceks', 'Klijent'); insert into Zaposleni(id, ulogaZ) values (1, 'Salterusa'); insert into Zaposleni(id, ulogaZ) values (2, 'Super_salterusa'); insert into Zaposleni(id, ulogaZ) values (3, 'Administrator'); insert into Klijent(id, vrsta) values (4, 'F'); insert into Privilege(name) values ('promenaLozinke'); insert into Privilege(name) values ('registracijaSalteruse'); insert into Privilege(name) values ('registracijaKlijentaFizicko'); insert into Privilege(name) values ('registracijaKlijentaPravno'); insert into Privilege(name) values ('preuzmiZaposlenog'); insert into Privilege(name) values ('preuzmiKlijenta'); insert into Role(name) values ('klijentRole'); insert into Role(name) values ('adminRole'); insert into Role(name) values ('salterusaRole'); insert into Role(name) values ('superSalterusaRole'); insert into Roles_privileges(role_id, privilege_id) values (1, 1); insert into Roles_privileges(role_id, privilege_id) values (1, 6); insert into Roles_privileges(role_id, privilege_id) values (2, 2); insert into Roles_privileges(role_id, privilege_id) values (2, 1); insert into Roles_privileges(role_id, privilege_id) values (3, 1); insert into Roles_privileges(role_id, privilege_id) values (3, 3); insert into Roles_privileges(role_id, privilege_id) values (4, 1); insert into Roles_privileges(role_id, privilege_id) values (4, 4); insert into Roles_privileges(role_id, privilege_id) values (2, 5); insert into Roles_privileges(role_id, privilege_id) values (3, 5); insert into Roles_privileges(role_id, privilege_id) values (4, 5); insert into Korisnicke_roles(korisnik_id, role_id) values (1, 3); insert into Korisnicke_roles(korisnik_id, role_id) values (2, 4); insert into Korisnicke_roles(korisnik_id, role_id) values (3, 2); insert into Korisnicke_roles(korisnik_id, role_id) values (4, 1); <file_sep>/src/main/java/com/example/actions/CertificateInfoGenerator.java package com.example.actions; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.SecureRandom; import java.util.Date; import java.util.Random; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; import com.example.data.CertificateInfo; import com.example.data.IssuerData; import com.example.data.SubjectData; public class CertificateInfoGenerator { public IssuerData generateIssuerData(PrivateKey issuerKey, CertificateInfo info) { X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.CN, info.commonName); builder.addRDN(BCStyle.SURNAME, info.surname); builder.addRDN(BCStyle.GIVENNAME, info.givenName); builder.addRDN(BCStyle.O, info.organization); builder.addRDN(BCStyle.OU, info.organizationUnit); builder.addRDN(BCStyle.C, info.country); builder.addRDN(BCStyle.E, info.email); // Kreiraju se podaci za issuer-a, sto u ovom slucaju ukljucuje: // - privatni kljuc koji ce se koristiti da potpise sertifikat koji se // izdaje // - podatke o vlasniku sertifikata koji izdaje nov sertifikat return new IssuerData(issuerKey, builder.build()); } public SubjectData generateSubjectData(CertificateInfo info) { KeyPair keyPairSubject = generateKeyPair(info.keyAlgorithm, info.keySize); // Serijski broj sertifikata String sn= Long.toString(System.currentTimeMillis()); // klasa X500NameBuilder pravi X500Name objekat koji predstavlja podatke // o vlasniku X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.CN, info.commonName); builder.addRDN(BCStyle.SURNAME, info.surname); builder.addRDN(BCStyle.GIVENNAME, info.givenName); builder.addRDN(BCStyle.O, info.organization); builder.addRDN(BCStyle.OU, info.organizationUnit); builder.addRDN(BCStyle.C, info.country); builder.addRDN(BCStyle.E, info.email); // Kreiraju se podaci za sertifikat, sto ukljucuje: // - javni kljuc koji se vezuje za sertifikat // - podatke o vlasniku // - serijski broj sertifikata // - od kada do kada vazi sertifikat return new SubjectData(keyPairSubject.getPublic(), builder.build(), sn, info.validFrom, info.validTo); } public KeyPair generateKeyPair(String keyAlgorithm, int keySize) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(keySize, random); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } return null; } } <file_sep>/src/main/resources/static/js/app.js var app = angular.module('bezbednost', [ 'ngRoute', 'ngNotify']); // routeProvider app.config(function($routeProvider, $locationProvider) { $routeProvider.when('/index', { templateUrl : 'index.html', controller : 'indexController' }).when('/generate', { templateUrl : 'html/generate.html', controller : 'generateController' }).when('/search', { templateUrl: 'html/search.html', controller: 'generateController' }).when('/withdraw', { templateUrl: 'html/withdraw.html', controller: 'generateController' }).when('/status', { templateUrl: 'html/status.html', controller: 'generateController' }).when('/admin', { templateUrl: 'html/admin.html', controller: 'generateController' }).when('/generateCSR', { templateUrl : 'html/generateCRS.html', controller : 'generateController' })/*.when('/changePassword', { templateUrl : 'changePassword.html', controller : 'bidderController' })*/ });<file_sep>/src/main/java/com/example/modeli/UlogaZaposlenog.java package com.example.modeli; public enum UlogaZaposlenog { Salterusa, Super_salterusa, Administrator; } <file_sep>/src/main/java/com/example/servis/Impl/KorisnikServisImpl.java package com.example.servis.Impl; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.modeli.Korisnik; import com.example.repository.KorisnikRepozitorijum; import com.example.servis.KorisnikServis; @Service @Transactional public class KorisnikServisImpl implements KorisnikServis { @Autowired KorisnikRepozitorijum korisnikRepozitorijum; @Autowired HttpSession sesija; @Override public Korisnik logovanje(String korisnickoIme, String lozinka) { return korisnikRepozitorijum.findByKorisnickoImeAndLozinka(korisnickoIme, lozinka); } @Override public void promenaLozinke(String l) { // TODO Auto-generated method stub Korisnik k = (Korisnik) sesija.getAttribute("korisnik"); k.lozinka = l; korisnikRepozitorijum.save(k); } @Override public Korisnik save(Korisnik k) { // TODO Auto-generated method stub return korisnikRepozitorijum.save(k); } @Override public Korisnik preuzmiKorisnika(Long id) { // TODO Auto-generated method stub return korisnikRepozitorijum.findOne(id); } } <file_sep>/src/main/java/com/example/servis/KlijentServis.java package com.example.servis; import com.example.modeli.Klijent; public interface KlijentServis { Klijent registracijaKlijenta(Klijent k); Klijent registracijaKlijentaF(Klijent k); Klijent preuzmiKlijenta(Long id); } <file_sep>/src/main/java/com/example/repository/ZaposleniRepozitorijum.java package com.example.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.modeli.Zaposleni; public interface ZaposleniRepozitorijum extends JpaRepository<Zaposleni, Long> { } <file_sep>/src/main/java/com/example/controllers/CertificateController.java package com.example.controllers; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.CertIOException; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.example.actions.CertificateGenerator; import com.example.actions.CertificateInfoGenerator; import com.example.data.CertificateCSR; import com.example.data.CertificateInfo; import com.example.data.CsrRequest; import com.example.data.IssuerData; import com.example.data.SubjectData; import com.example.data.WithdrawCert; import com.example.keyStore.KeyStoreReader; import com.example.keyStore.KeyStoreWriter; import com.example.servis.CertificateCSRServis; import com.example.servis.WithdrawCertServis; @Controller @RequestMapping("/certificate") public class CertificateController { private KeyStore keyStore; @Autowired public WithdrawCertServis ws; @Autowired public CertificateCSRServis ccsrs; private static String UPLOADED_FOLDER = "C:/Users/Stefan/Desktop/proba"; public CertificateInfoGenerator cig = new CertificateInfoGenerator(); public CertificateGenerator cg = new CertificateGenerator(); public KeyStoreWriter ksw = new KeyStoreWriter(); public KeyStoreReader ksr = new KeyStoreReader(); @RequestMapping(value = "/getValidCertificates", method = RequestMethod.GET) @ResponseBody public ArrayList<String> getValidCertificates() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { return ksr.getValidCertificates("keystore.jks", "password"); } @RequestMapping(value = "/statusCertificate/{serial}", method = RequestMethod.GET) @ResponseBody public ArrayList<String> statusCertificate(@PathVariable("serial") String serialNumber) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { String sta = ksr.getCertificateStatus(serialNumber, "keystore.jks", "password"); if (sta == null) { WithdrawCert w = ws.findbySerial(serialNumber); if (w == null) { sta = "Certifikat ne postoji!"; } else { sta = "povucen"; } } ArrayList<String> sp = new ArrayList<String>(); sp.add(sta); return sp; } @RequestMapping(value = "/getCertificate/{serial}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<Certificate> getCertificate(@PathVariable("serial") String serialNumber) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { Certificate c = ksr.getOrDeleteCertificateBySerialNumber(serialNumber, false, "keystore.jks", "<PASSWORD>"); String alias = ksr.getAlias(c); if(c == null){ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } X509Certificate xcert = (X509Certificate)c; ksw.save(xcert, "./exported/"+alias); File file = new File("./exported/"+alias+".cer"); Path path = Paths.get("./exported/"+alias+".cer"); byte[] data = Files.readAllBytes(path); Path putanja = Paths.get("C:/Users/Stefan/Desktop/proba" +alias+".cer"); Files.write(putanja, data); /* byte[] bytes = c.getEncoded(); Path path = Paths.get(UPLOADED_FOLDER + c.getType()); Files.write(path, bytes); */ return new ResponseEntity<>(HttpStatus.OK); } @RequestMapping(value = "/deleteCertificate/{serial}", method = RequestMethod.DELETE) @ResponseBody public ResponseEntity<Certificate> deleteCertificate(@PathVariable("serial") String serialNumber) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { ArrayList<Certificate> ce = ksr.deleteCert(serialNumber, true, "keystore.jks", "password"); if(ce == null){ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } for (int i = 0; i < ce.size(); i++) { X509Certificate c = (X509Certificate) ce.get(i); WithdrawCert w = new WithdrawCert(c.getSerialNumber().toString()); ws.save(w); } return new ResponseEntity<>(HttpStatus.OK); } @RequestMapping(value = "/generateCertificate", method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> generateCertificate(@RequestBody CertificateInfo info) throws NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException, KeyStoreException, CertificateException, FileNotFoundException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ksw.loadKeyStore("keystore.jks", "<PASSWORD>".toCharArray()); System.out.println(info.certificationAuthority); KeyPair keyPairIssuer = cig.generateKeyPair(info.keyAlgorithm, info.keySize); SubjectData subjectData = cig.generateSubjectData(info); X509Certificate cer; if (info.root) { info.issuerName = info.commonName; IssuerData issuerData = cig.generateIssuerData(keyPairIssuer.getPrivate(), info); cer = cg.generateCertificate(subjectData, issuerData, info.root, info.issuerName, "keystore.jks", info.certificationAuthority); } else { IssuerData id = ksr.readIssuerFromStore("keystore.jks", info.issuerName, "<PASSWORD>".toCharArray(), "<PASSWORD>".toCharArray()); cer = cg.generateCertificate(subjectData, id, info.root, info.issuerName, "keystore.jks", info.certificationAuthority); } System.out.println("Prilikom upisa: " + cer.getSerialNumber()); ksw.write(info.commonName, keyPairIssuer.getPrivate(), "<PASSWORD>".toCharArray(), cer); ksw.saveKeyStore("keystore.jks", "<PASSWORD>".toCharArray()); return new ResponseEntity<>(HttpStatus.OK); } @RequestMapping(value= "/generateCRSCertificate",method = RequestMethod.POST) public ResponseEntity<?> certificateSigningRequest(@RequestBody CsrRequest info) throws OperatorCreationException, InvalidKeyException, NoSuchAlgorithmException, IOException, CertificateEncodingException, KeyStoreException{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); System.out.println(info.csr); String signer = info.issuerName; String csrString = info.csr; //Long days = Long.parseLong(requestInfo.getDays()); PKCS10CertificationRequest csr = ksr.convertPemToPKCS10CertificationRequest(csrString); //rand System.out.println(csr); X500Name x500NameSubject = csr.getSubject(); JcaPKCS10CertificationRequest jcaCertRequest = new JcaPKCS10CertificationRequest(csr.getEncoded()).setProvider("BC"); // System.out.println("x500Name is: " + x500Name + "\n"); // KeyStoreReader ksr = new KeyStoreReader(); //vadimo iz keystora certifikat koji ce biti issuer i potpisivac end certifikatu //TODO: Sifra keystora treba se unositi rucno Certificate issuer = ksr.readCertificate("keystore.jks","<PASSWORD>", info.issuerName); X509Certificate xcert = (X509Certificate)issuer; //javni kljuc iz pem-a PublicKey subjectPublicKey = jcaCertRequest.getPublicKey(); X500Name x500Issuer = new JcaX509CertificateHolder(xcert).getSubject(); //Javni kljuc izdavaoca PublicKey authorityPublicKey = xcert.getPublicKey(); KeyPair keyPairIssuer = ksr.generateKeyPair(); //TODO: DA LI SE GENERISE NOVI ILI SE KORISTI STARI IssuerData issuerData=new IssuerData(keyPairIssuer.getPrivate(), x500Issuer); System.out.println("IDID: "+ issuerData); IssuerData issuerDatad = ksr.readIssuerFromStore("keystore.jks", info.issuerName, "<PASSWORD>".toCharArray(), "<PASSWORD>".toCharArray()); System.out.println("ID: " + issuerDatad); //Serijski broj sertifikata String sn= Long.toString(System.currentTimeMillis()); SubjectData sdata = new SubjectData(); sdata.setPublicKey(subjectPublicKey); sdata.setX500name(x500NameSubject); sdata.setSerialNumber(sn); sdata.setStartDate(new Date(System.currentTimeMillis())); int days = 20; sdata.setEndDate(new Date(System.currentTimeMillis()+days *86400000)); CertificateGenerator cg = new CertificateGenerator(); //za kreiranje izgenerisani novi kljucevi i prosledjen privatni kljuc izdavaoca radi potpisa //PrivateKey issuerPrivate = ksr.readPrivateKey("keystore.jks", "<PASSWORD>", signer, "private"); PrivateKey issuerPrivate = issuerData.getPrivateKey(); X509Certificate cert = cg.generateEndCertificate(sdata, issuerData, issuerPrivate, subjectPublicKey); KeyStoreWriter keyStoreWriter = new KeyStoreWriter(); //SIFRU UNOSITI keyStoreWriter.loadKeyStore("keystore.jks", "password".toCharArray()); String certpassword = "<PASSWORD>"; keyStoreWriter.write(info.keyAlias, issuerPrivate, certpassword.toCharArray(), cert); String keystorepassword = "<PASSWORD>"; keyStoreWriter.saveKeyStore("keystore.jks","password".toCharArray() ); CertificateCSR cer =null; cer = new CertificateCSR(Long.parseLong(sn), info.keyAlias,true); System.out.println(cer); ccsrs.save(cer); return new ResponseEntity<> (HttpStatus.OK); } } <file_sep>/src/main/resources/static/js/indexController.js var app = angular.module('bezbednost'); app.run([ 'ngNotify', function(ngNotify) { ngNotify.config({ position : 'bottom', duration : 1000, theme : 'pitchy', sticky : false, }); } ]); app.config([ '$qProvider', function($qProvider) { $qProvider.errorOnUnhandledRejections(false); } ]); app.controller('appController',['$rootScope','$scope','$location',function($rootScope,$scope,$location){ }]); app.controller('generateController',['$rootScope','ngNotify','$scope','$location', 'ServiceGenerate', function($rootScope,ngNotify,$scope,$location, serviceGenerate){ $scope.submitLogin = function() { serviceGenerate .logIn($scope.logovanje) .then( function(response) { if (response.status == 200) if (response.data.uloga === "Klijent") serviceGenerate .preuzmiKlijenta() .then( function( response) { if (response.status == 200) { ngNotify.set('Uspjesno logovanje' , { type : 'success' }); $rootScope.korisnik = response.data; $location .path('/Klijent/klijent'); } }); else serviceGenerate .preuzmiZaposlenog() .then( function( response) { if (response.status == 200) { ngNotify.set('Uspjesno logovanje' , { type : 'success' }); $rootScope.korisnik = response.data; if (response.data.ulogaZ === "Salterusa") $location .path('/obicnaSalterusa/registracijaKlijenataObicna'); else if (response.data.ulogaZ === "Super_salterusa") $location .path('/salterusa/registracijaKlijenta'); else $location .path('/admin'); } }); }).catch(function(response) { ngNotify.set('Korisnik ne postoji' , { type : 'error', sticky: true }); console.error('Gists error', response.status, response.data) }); } $scope.changePassword = function() { if($scope.lozinka.stara == $rootScope.korisnik.lozinka){ serviceGenerate.changePassword($scope.lozinka.nova).then(function(response){ $location.path('/index'); }); } else { lozinka.nova = ''; lozinka.stara = ''; $location.path('/changePassword') } } $scope.logout = function(){ serviceGenerate.logout().then(function(response){ $rootScope.korisnik = ''; $location.path('/login'); $scope.logovanje = null; }); } $scope.caCertificate = function() { serviceGenerate.caCertificate().then( function(response) { $scope.caCertificate = response.data; }); } $scope.generateCertificate= function(){ serviceGenerate.generateCertificate($scope.cert).then(function(response){ if(response.status == 200){ ngNotify.set('Uspesno generisanje' , { type : 'success' }); $scope.error = false; //$location.path('/index'); $scope.cert = null; } else { $scope.error = true; } }); } $scope.generateCRSCertificate= function(){ serviceGenerate.generateCRSCertificate($scope.ccrs).then(function(response){ if(response.status == 'OK'){ ngNotify.set('Uspesno generisanje' , { type : 'success' }); $scope.error = false; $location.path('/index') } else { $scope.error = true; } }); } $scope.getCertificate = function(){ serviceGenerate.getCertificate($scope.serial).then(function(response){ }); } $scope.delCertificate = function(){ serviceGenerate.delCertificate($scope.serial).then(function(response){ }); } $scope.statusCertificate = function() { serviceGenerate.statusCertificate($scope.serial).then( function(response) { $scope.status = response.data; }); } }]);
5bbb214b41e590caf9ddbf1001cc7c2354a03bc0
[ "JavaScript", "Java", "SQL" ]
12
Java
caricaMilca/CertificateGeneratorHttps
1c2ea86e6f5fd894e74b25ccc31624dac7a99b83
ff69da11cffe4e09a2a89201440f0d1620f13692
refs/heads/master
<file_sep># Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'MyCalendarApp' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for MyCalendarApp pod 'FSCalendar', :git=> 'https://github.com/WenchaoD/FSCalendar' pod 'CalculateCalendarLogic' # Pods for Calendar target 'CalendarTests' do pod 'RealmSwift' end <file_sep>// // EventViewController.swift // MyCalendarApp // // Created by <NAME> on 2019/10/08. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class EventViewController: NSObject { } <file_sep>// // AddEvent.swift // MyCalendarApp // import UIKit import RealmSwift class AddEvent: UIViewController,UITextFieldDelegate { @IBOutlet weak var selectLabel: UILabel! @IBOutlet weak var eventTF: UITextField! @IBOutlet weak var datePicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() self.eventTF.delegate = self // Do any additional setup after loading the view. print(Realm.Configuration.defaultConfiguration.fileURL!) datePicker.datePickerMode = UIDatePicker.Mode.date datePicker.timeZone = NSTimeZone.local datePicker.locale = NSLocale(localeIdentifier: "ja_JP") as Locale datePicker.addTarget(self, action: #selector(picker(_:)), for: .valueChanged) view.addSubview(selectLabel) selectLabel.text = getToday(format: "yyyy/MM/dd") } func getToday(format:String = "yyyy/MM/dd") -> String{ let now = Date() let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: now as Date) } @objc func picker(_ sender:UIDatePicker){ let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd" selectLabel.text = formatter.string(from: sender.date) view.addSubview(selectLabel) } @IBAction func addEvent(_ sender: Any) { print("データ書き込み開始") let realm = try! Realm() try! realm.write { //日付表示の内容とスケジュール入力の内容が書き込まれる let inEventTF = eventTF.text!.trimmingCharacters(in: .whitespaces) print(eventTF.text) print(inEventTF) if inEventTF == "" { let alert = UIAlertController(title: "エラー", message: "スケジュールが空白です", preferredStyle: UIAlertController.Style.alert) let okButton = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (action) in print("OK") } alert.addAction(okButton) present(alert, animated: true, completion: nil) } else { let Events = [Event(value: ["date": selectLabel.text, "event": eventTF.text])] realm.add(Events) print("データ書き込み中") } } print("データ書き込み完了") eventTF.text = "" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } //リターンキーでキーボードが閉じる func textFieldShouldReturn(_ textField: UITextField) -> Bool { //キーボードが閉じる textField.resignFirstResponder() return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // ViewController.swift // MyCalendarApp // //完成版 import UIKit import FSCalendar import CalculateCalendarLogic import RealmSwift class ViewController: UIViewController,FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance { @IBOutlet weak var labelDate: UILabel! @IBOutlet weak var calendar: FSCalendar! @IBOutlet weak var scheduleLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.calendar.dataSource = self self.calendar.delegate = self labelDate.text = getToday(format: "yyyy/MM/dd") let realm = try! Realm() var result = realm.objects(Event.self) result = result.filter("date = '\(labelDate.text!)'") print(result) for ev in result { if ev.date == labelDate.text! { scheduleLabel.text = ev.event scheduleLabel.textColor = .black view.addSubview(scheduleLabel) } } if scheduleLabel.text == ""||scheduleLabel.text == "スケジュール内容"{ scheduleLabel.text = "スケジュールはありません" scheduleLabel.textColor = .lightGray view.addSubview(scheduleLabel) } } func getToday(format:String = "yyyy/MM/dd") -> String{ let now = Date() let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: now as Date) } override func viewWillAppear(_ animated: Bool) {//VCが表示されるごとにスケジュールの予定を表示 let realm = try! Realm() var result = realm.objects(Event.self) result = result.filter("date = '\(labelDate.text!)'") print(result) for ev in result { if ev.date == labelDate.text! { scheduleLabel.text = ev.event scheduleLabel.textColor = .black view.addSubview(scheduleLabel) } } } fileprivate let gregorian: Calendar = Calendar(identifier: .gregorian) fileprivate lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() // 祝日判定を行い結果を返すメソッド func judgeHoliday(_ date : Date) -> Bool { //祝日判定用のカレンダークラスのインスタンス let tmpCalendar = Calendar(identifier: .gregorian) // 祝日判定を行う日にちの年、月、日を取得 let year = tmpCalendar.component(.year, from: date) let month = tmpCalendar.component(.month, from: date) let day = tmpCalendar.component(.day, from: date) let holiday = CalculateCalendarLogic() return holiday.judgeJapaneseHoliday(year: year, month: month, day: day) } // date型 -> 年月日をIntで取得 func getDay(_ date:Date) -> (Int,Int,Int){ let tmpCalendar = Calendar(identifier: .gregorian) let year = tmpCalendar.component(.year, from: date) let month = tmpCalendar.component(.month, from: date) let day = tmpCalendar.component(.day, from: date) return (year,month,day) } //曜日判定 func getWeekIdx(_ date: Date) -> Int{ let tmpCalendar = Calendar(identifier: .gregorian) return tmpCalendar.component(.weekday, from: date) } // 土日や祝日の日の文字色を変える func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? { //祝日判定をする if self.judgeHoliday(date){ return UIColor.red } //土日の判定 let weekday = self.getWeekIdx(date) if weekday == 1 { return UIColor.red } else if weekday == 7 { return UIColor.blue } return nil } func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition){ scheduleLabel.text = "スケジュールはありません" scheduleLabel.textColor = .lightGray view.addSubview(scheduleLabel) let tmpDate = Calendar(identifier: .gregorian) let year = tmpDate.component(.year, from: date) let month = tmpDate.component(.month, from: date) let day = tmpDate.component(.day, from: date) let m = String(format: "%02d", month) let d = String(format: "%02d", day) let da = "\(year)/\(m)/\(d)" //クリックしたら、日付が表示される。 labelDate.text = "\(year)/\(m)/\(d)" view.addSubview(labelDate) //スケジュール取得 let realm = try! Realm() var result = realm.objects(Event.self) result = result.filter("date = '\(da)'") print(result) for ev in result { if ev.date == da { scheduleLabel.text = ev.event scheduleLabel.textColor = .black view.addSubview(scheduleLabel) } } if scheduleLabel.text == ""{ scheduleLabel.text = "スケジュールはありません" scheduleLabel.textColor = .lightGray view.addSubview(scheduleLabel) } } @IBAction func deleteButton(_ sender: Any) { if labelDate.text! == ""||scheduleLabel.text == "スケジュールはありません"||scheduleLabel.text == ""{ }else{//削除ボタンを押下した際のアラート・削除の制御 let alert = UIAlertController(title: "\(labelDate.text!)の予定を削除します", message: "削除しますか?", preferredStyle: UIAlertController.Style.alert) let defaultAction = UIAlertAction(title: "削除", style: UIAlertAction.Style.default,handler:{ (UIAlertAction) in print("Delete") let realm = try! Realm() let results = realm.objects(Event.self).filter("event='\(self.scheduleLabel.text!)'")//データベースの予定=scheduleLabelになるものをクエリ print(results) try! realm.write { realm.delete(results) } self.scheduleLabel.text = "スケジュールはありません" self.scheduleLabel.textColor = .lightGray }) let cancelAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel) { (UIAlertAction) in print("Cancel") } alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } } }
62636e1cff6dea86e7fb6a3d79d99045a086e175
[ "Swift", "Ruby" ]
4
Ruby
yoshoda-masato/calendar
6ce754f97d6f59972aa9484b5b41a836084cff3f
4285775c86f311a5485559e495f6937c613ac319
refs/heads/master
<repo_name>zerolethanh/next.classfunc.com<file_sep>/next.config.js /** * Created by ZE on 2017/04/07. */ // next.config.js module.exports = { /* config options here */ distDir: 'next_build' }<file_sep>/pages/tepco.js /** * Created by ZE on 2017/04/12. */ var exec = require('child_process').exec; import Header from '../components/Header' const Page = ({stdout}) => <div> <Header title=""/> Next stars: {stdout}</div> Page.getInitialProps = async ({req}) => { await exec('ls -l ./', function (err, stdout, stderr) { return stdout; }); } export default Page <file_sep>/next_build/dist/pages/webhook.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _keys = require('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _typeof2 = require('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Header = require('../components/Header'); var _Header2 = _interopRequireDefault(_Header); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Created by ZE on 2017/04/09. */ var objKeyList = function objKeyList(obj) { var result = []; if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3.default)(obj)) === "object") { (0, _keys2.default)(obj).forEach(function (k) { console.log(k, obj[k]); result.push(k + " "); }); } return result; }; var _class = function (_React$Component) { (0, _inherits3.default)(_class, _React$Component); function _class() { (0, _classCallCheck3.default)(this, _class); return (0, _possibleConstructorReturn3.default)(this, (_class.__proto__ || (0, _getPrototypeOf2.default)(_class)).apply(this, arguments)); } (0, _createClass3.default)(_class, [{ key: 'render', // static async getInitialProps(props) { // return props; // } value: function render() { return _react2.default.createElement('div', null, _react2.default.createElement(_Header2.default, { title: 'Webhook from GitHub' }), this.props && console.log(objKeyList(this.props))); } }]); return _class; }(_react2.default.Component); exports.default = _class;<file_sep>/pages/index.js /** * Created by ZE on 2017/04/07. */ import Header from '../components/Header' import Link from 'next/link' export default () => { return <div className="content"> <Header title="Index"/> Hello, I am Index <br/> Have a good day! <br/> <Link href="/about"><a href="">About Me</a></Link> <br/> <Link href="/link"><a href="">Link</a></Link> <br/> <Link href="/req"><a href="">Request</a></Link> <br/> <Link href="/fetch"><a href="">Fetch</a></Link> <Link href="/tepco"><a href="">Tepco</a></Link> <style jsx> {` .content { text-align: center; color: blue } ` } </style> </div> }<file_sep>/pages/title.js /** * Created by ZE on 2017/04/07. */ import Head from 'next/head' import Header from '../components/Header' export default () => ( <div> <Header title="Title"/> <p>Title title</p> </div> )<file_sep>/next_build/dist/components/Header.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _link = require('next/dist/lib/link.js'); var _link2 = _interopRequireDefault(_link); var _head = require('next/dist/lib/head.js'); var _head2 = _interopRequireDefault(_head); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _jsxFileName = '/Users/thanhlevan/IdeaProjects/next.classfunc.com/components/Header.js'; /** * Created by ZE on 2017/04/08. */ var links = ['index', 'about', 'link', 'req', 'title', 'fetch', 'webhook']; var listStyle = { display: 'inline', margin: '0 10px 0 0' }; exports.default = function (props) { return _react2.default.createElement('nav', { __source: { fileName: _jsxFileName, lineNumber: 20 } }, _react2.default.createElement(_head2.default, { __source: { fileName: _jsxFileName, lineNumber: 21 } }, _react2.default.createElement('title', { __source: { fileName: _jsxFileName, lineNumber: 22 } }, props.title || 'Next'), props.children), _react2.default.createElement('ul', { __source: { fileName: _jsxFileName, lineNumber: 25 } }, links.map(function (link) { return _react2.default.createElement('li', { style: listStyle, key: link, __source: { fileName: _jsxFileName, lineNumber: 27 } }, _react2.default.createElement(_link2.default, { href: link, __source: { fileName: _jsxFileName, lineNumber: 28 } }, _react2.default.createElement('a', { __source: { fileName: _jsxFileName, lineNumber: 29 } }, link))); }))); };
dfd54f774bb128bd407102722927c8ca956df443
[ "JavaScript" ]
6
JavaScript
zerolethanh/next.classfunc.com
8907f886387a2c090ca87fad59e0a8e84d066036
3535aae7c26461893ac294ac9d8ccfcb28080c5e
refs/heads/master
<file_sep>import React, {useEffect, useState} from "react"; import axios from "axios"; import { Table, Typography, notification, Button } from "antd"; import { Link, useHistory } from "react-router-dom"; const {Text, Title} = Typography; const Home = () => { const history = useHistory(); const [userRecipes, setUserRecipes] = useState(); const fetchRecipes = async () => { try { const response = await axios({ method: "GET", url: process.env.REACT_APP_API_ENDPOINT + "/v1/recipes", headers: {"Authorization": sessionStorage.getItem("auth")} }); // console.log(response); setUserRecipes(response.data); } catch(err) { // console.log(err.response); if(err.response.status == 404) { notification["info"]({ message: 'No recipes found', description: 'No recipes were found for this user. You can create one by clicking the Create New Recipe button.', }); } } } useEffect(() => { fetchRecipes(); }, []); const handleDelete = async (recipeId) => { try { const response = await axios({ method: "DELETE", url: process.env.REACT_APP_API_ENDPOINT + `/v1/recipe/${recipeId}`, headers: {"Authorization": sessionStorage.getItem("auth")} }); notification["success"]({ message: "Deletion sucess", description: `Recipe with id ${recipeId} successfully deleted` }); } catch(err) { notification["error"]({ message: "Deletion error", description: err.response.data, }); return; } fetchRecipes(); } const columns = [{ title: "Title", dataIndex: "title", key: "title" }, { title: "Cuisine", dataIndex: "cusine", key: "cusine" }, { title: "Created At", dataIndex: "created_ts", key: "created_ts", render: (ts) => <Text>{new Date(ts).toString()}</Text> }, { title: "Updated At", dataIndex: "updated_ts", key: "updated_ts", render: (ts) => <Text>{new Date(ts).toString()}</Text> }, { title: 'Action', key: 'action', render: (text, record) => ( <span> <Link to={`/recipe/${record.id}`} style={{ marginRight: 16 }}>View</Link> <Button type="link" onClick={() => handleDelete(record.id)}>Delete</Button> </span> ), }]; return (<div style={{minHeight: "calc(100vh - 134px)", padding: "50px 50px 0 50px"}}> <Button type="primary" style={{marginBottom: 10}} onClick={() => history.push("/add")}>Create New Recipe</Button> <Table dataSource={userRecipes} columns={columns} rowKey="id"/> </div>) } export default Home;<file_sep>This is the frontend for my Recipe Management API repository (https://github.com/suhas1602/recipe-management-system). This is a SPA made with React.js. ## Development Create a .env folder with the following value REACT_APP_API_ENDPOINT=<value>, where value is the endpoint where the backend is hosted. Then run `npm start`. The app will run on port 3001 by default. You can change the value in the scripts section of package.json. ## Build Running `npm run build` will create a build folder with a production build of the app. I am running the app on an Apache HTTP server. For more details on how to deploy see https://create-react-app.dev/docs/deployment/ <file_sep>import React from "react"; import { Form, Input, Button, message } from 'antd'; import { Redirect, useHistory } from "react-router-dom"; import axios from "axios"; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; const Signup = () => { const history = useHistory(); const onFinish = async values => { try { const response = await axios({ method: "POST", url: process.env.REACT_APP_API_ENDPOINT + "/v1/user", headers: {"Content-Type": "application/json"}, data: { email: values.email, password: <PASSWORD>, firstname: values.firstname, lastname: values.lastname, } }); // console.log(response); history.replace("/login"); } catch (err) { // console.log(err.response); message.error(err.response.data); } }; const onFinishFailed = errorInfo => { console.log('Failed:', errorInfo); }; return sessionStorage.getItem("auth") !== null ? (<Redirect to={{pathname: "/"}} />) : (<div style={{minHeight: "calc(100vh - 134px)", padding: "50px 50px 0 50px"}}> <div style={{width: "50vw"}}> <Form {...layout} name="login" onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item label="Email Address" name="email" rules={[{ required: true, message: 'Please input your email address!' }]} > <Input /> </Form.Item> <Form.Item label="First Name" name="firstname" rules={[{ required: true, message: 'Please input your first name!' }]} > <Input /> </Form.Item> <Form.Item label="Last Name" name="lastname" rules={[{ required: true, message: 'Please input your last name!' }]} > <Input /> </Form.Item> <Form.Item label="Password" name="password" rules={[{ required: true, message: 'Please input your password!' }]} > <Input.Password /> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> </div> </div>) } export default Signup;<file_sep>import React, {useState, useEffect} from "react"; import { useParams, Link } from "react-router-dom"; import axios from "axios"; import { notification, Descriptions, Typography } from "antd"; const {Text, Title} = Typography; const Recipe = () => { const { id } = useParams(); const [recipe, setRecipe] = useState(null); useEffect(() => { const fetchRecipe = async () => { try { const response = await axios({ method: "GET", url: process.env.REACT_APP_API_ENDPOINT + `/v1/recipe/${id}`, headers: {"Authorization": sessionStorage.getItem("auth")} }); console.log(response.data); setRecipe(response.data); } catch(err) { console.log(err.response); if(err.response.status === 404) { notification["error"]({ message: "No recipe found", description: "No recipe was found for this id." }); } } } fetchRecipe(); }, []); return (<div style={{minHeight: "calc(100vh - 134px)", padding: "50px 50px 0 50px", backgroundColor: "white"}}> {recipe !== null ? ( <Descriptions title="Recipe" bordered> <Descriptions.Item label="Id">{recipe.id}</Descriptions.Item> <Descriptions.Item label="Title">{recipe.title}</Descriptions.Item> <Descriptions.Item label="Cuisine">{recipe.cusine}</Descriptions.Item> <Descriptions.Item label="Created At">{new Date(recipe.created_ts).toString()}</Descriptions.Item> <Descriptions.Item label="Updated At">{new Date(recipe.updated_ts).toString()}</Descriptions.Item> <Descriptions.Item label="Total Time (mins)">{recipe.total_time_in_min}</Descriptions.Item> <Descriptions.Item span={3} label="Ingrdients">{recipe.ingredients.map((item, index) => ( <React.Fragment key={`ingredient-${index}`}> {item} <br /> </React.Fragment> ) )} </Descriptions.Item> <Descriptions.Item span={3} label="Steps"><ul>{recipe.steps.sort((a, b) => a.position < b.position).map((item, index) => ( <li key={`steps-${item.position}`}>{item.items}</li> ) )}</ul> </Descriptions.Item> <Descriptions.Item span={3} label="Nutrition Information"> <Text strong>Calories: </Text>{recipe.nutrition_information[0].calories} <br /> <Text strong>Cholesterol (mg): </Text>{recipe.nutrition_information[0].cholestrol_in_mg} <br /> <Text strong>Sodium (mg): </Text>{recipe.nutrition_information[0].sodium_in_mg} <br /> <Text strong>Carbohydrates (grams): </Text>{recipe.nutrition_information[0].carbohydrates_in_grams} <br /> <Text strong>Proteins (grams): </Text>{recipe.nutrition_information[0].protein_in_grams} </Descriptions.Item> </Descriptions>) : ( <Link to="/recipe">Go to all recipes</Link>) } </div>); } export default Recipe;
f7e76f198392ff4ec1341003838fb0bc0e9c4ed0
[ "JavaScript", "Markdown" ]
4
JavaScript
suhas1602/recipe-management-system-frontend
b94b9a7f28470e9d2f9212bf19cf54e345677cea
dd379a1c71ef40d7e306e465a4e57e06409cd6bd
refs/heads/master
<file_sep>// // NewPasswordViewController.swift // Swap // // Created by <NAME> on 4/13/17. // // import Foundation class NewPasswordViewController: UIViewController{ @IBOutlet var newPasswordField: UITextField! @IBOutlet var showPasswordButton: UIButton! var passwordSecure = true @IBAction func togglePasswordEncryption(_ sender: Any) { passwordSecure = !newPasswordField.isSecureTextEntry newPasswordField.isSecureTextEntry = passwordSecure if (passwordSecure){ showPasswordButton.setTitle("Show Password", for: .normal) } else{ showPasswordButton.setTitle("Hide Password", for: .normal) } } @IBAction func didTapDone(_ sender: Any) { guard (newPasswordField.text != nil) && (newPasswordField.text?.characters.count)! >= 6 else { UIAlertView(title: "Invalid Password", message: "Password must be at least 6 characters.", delegate: nil, cancelButtonTitle: "Ok").show() return } let new_password = newPasswordField.text! confirmForgotPassword(username: getSavedUsername() ?? "", confirmation: getVerificationCodeForForgotPassword() ?? "", new: new_password) { (didSucceed) in guard didSucceed else{ UIAlertView(title: "Invalid Verification Code", message: "Something went wrong, try again.", delegate: nil, cancelButtonTitle: "Ok").show() DispatchQueue.main.async { // Go back to sign in screen // self.performSegue(withIdentifier: "leaveForgotPassword", sender: nil) self.navigationController?.popToRootViewController(animated: true) } return } if didSucceed{ let message = UIAlertController(title: "Success", message: "Your password has been changed.", preferredStyle: .alert) message.addAction(UIAlertAction(title: "Ok", style: .default){ (action) in /// Password successfully reset DispatchQueue.main.async { // Go back to sign in screen // self.performSegue(withIdentifier: "leaveForgotPassword", sender: nil) self.navigationController?.popToRootViewController(animated: true) } }) self.present(message, animated: true, completion: nil) } } } } <file_sep>// // TabBarController.swift // Swap // // Created by <NAME> on 6/20/17. // // Use this class to reposition the tab bar on the view // import Foundation import UIKit class TabBarController: UITabBarController{ let kBarHeight = CGFloat(20) override func viewWillLayoutSubviews() { var tabFrame = self.tabBar.frame // tabFrame.size.height = kBarHeight tabFrame.origin.y = tabFrame.origin.y - 0.5 self.tabBar.frame = tabFrame } } <file_sep>// // SwappedAnnotation.swift // Swap // // Created by <NAME> on 7/11/17. // // import Foundation import MapKit class SwapsAnnotation: MKPointAnnotation { var pinImage: UIImage? } class SwapsAnnotationView: MKAnnotationView { var title: String? override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(false, animated: animated) if (selected){ print("PIN SELECTED: \(title!)") NotificationCenter.default.post(name: .showPinInfo, object: nil) } } } <file_sep>// // setPhoneNumber.swift // Swap // // Created by <NAME> on 3/14/17. // // import Foundation import PhoneNumberKit import CountryPicker class setPhoneNumberViewController: UIViewController, CountryPickerDelegate { @IBOutlet var phoneNumberField: PhoneNumberTextField! @IBOutlet var picker: CountryPicker! @IBOutlet var countryCodeButton: UIButton! @IBOutlet var blurView: UIVisualEffectView! var effect: UIVisualEffect! @IBOutlet var popUp: UIView! @IBOutlet var popUpLabel: UILabel! @IBOutlet var sendSMSButton: UIButton! var phoneNumber: String! var PhoneCode: String! var COUNTRYCODE: String! override func viewDidLoad() { super.viewDidLoad() phoneNumberField.becomeFirstResponder() //blurview blurView.isHidden = true //get current country let locale = Locale.current let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String? //init Picker picker.countryPickerDelegate = self picker.showPhoneNumbers = true picker.setCountry(code!) } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func didTapNext(_ sender: Any) { phoneNumber = "\(PhoneCode ?? "") \(phoneNumberField.text ?? "")" guard phoneNumber.isPhoneNumber else { UIAlertView(title: "Invalid Phone Number", message: "Please enter a valid phone number.", delegate: self, cancelButtonTitle: "Ok").show() return } savePhonenumber(phone: "+\(phoneNumber.digits)") print("the number is .... +\(phoneNumber.digits)") view.endEditing(true) self.view.addSubview(popUp) popUp.backgroundColor = UIColor.clear popUp.center = self.view.center popUp.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3) popUp.alpha = 0 popUpLabel.text = "Send Confirmation Code to \(phoneNumber ?? "")?" UIView.animate(withDuration: 0.4){ self.blurView.isHidden = false self.blurView.alpha = 0.5 self.popUp.alpha = 1 self.popUp.transform = CGAffineTransform.identity } } @IBAction func didTapSendSMS(_ sender: Any) { sendSMSButton.isEnabled = false // Create an account createAccount(username: getUsernameOfSignedInUser(), password: <PASSWORD>(), email: getSavedEmail(), phonenumber: getPhoneNumber(), failedToCreateAccount: { signUpError in DispatchQueue.main.async { switch signUpError{ case .EmptyFields: // Tell the user to enter required fields UIAlertView(title: "Could Not Create Account", message: "Please ensure you completed the sign up process and try again.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidEmail: // Tell the user to enter a valid email address UIAlertView(title: "Invalid Email Address", message: "Please enter a valid email address.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidPhonenumber: // Tell the user to enter a valid phone number UIAlertView(title: "Invalid Phone Number", message: "Please enter a valid phone number.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidUsername: // Tell the user to enter a valid username format UIAlertView(title: "Invalid Username", message: "Usernames can be no longer than 18 characters and cannot contain special characters.", delegate: nil, cancelButtonTitle: "Ok").show() break case .PasswordTooShort: // Tell the user that his/her password is too short - Must be at least 6 characters UIAlertView(title: "Invalid Password", message: "Password must be at least 6 characters.", delegate: nil, cancelButtonTitle: "Ok").show() break case .UsernameTaken: // Tell the user to enter a different username UIAlertView(title: "Username Taken", message: "Please enter a different username.", delegate: nil, cancelButtonTitle: "Ok").show() break case .UnknownSignUpError: // Some unknown error has occured ... Tell the user to try again UIAlertView(title: "Try Again", message: "Check internet connection and try again.", delegate: nil, cancelButtonTitle: "Ok").show() break } self.sendSMSButton.isEnabled = true } }, didCreateAccount: { // created an account print("Created An Account") DispatchQueue.main.async { self.performSegue(withIdentifier: "toConfirmAccount", sender: nil) } }) } @IBAction func didTapCancel(_ sender: Any) { UIView.animate(withDuration: 0.2){ self.popUp.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3) self.popUp.alpha = 0 self.blurView.isHidden = true } } @IBAction func didChangeCountryCode(_ sender: Any) { view.endEditing(false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // a picker item was selected public func countryPhoneCodePicker(_ picker: CountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage) { PhoneCode = phoneCode countryCodeButton.setTitle(countryCode + " " + phoneCode, for: .normal) COUNTRYCODE = phoneCode } } extension String { var isPhoneNumber: Bool { do { let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count)) if let res = matches.first { return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count } else { return false } } catch { return false } } } <file_sep>// // Analytics.swift // Swap // // Created by <NAME> on 1/23/17. // // import Foundation import Answers import Crashlytics class Analytics { class func didSignUp() { Answers.logSignUp(withMethod: "Swap", success: true, customAttributes: nil) } class func didSignIn(){ Answers.logLogin(withMethod: "Swap", success: true, customAttributes: nil) } class func didSignOut(){ Answers.logCustomEvent(withName: "Sign Out", customAttributes: nil) } ///-todo: For some reason, in analytics, the custom attributes are not being recorded. Fix. class func didSwap(byMethod: SwapMethod, isPrivate: Bool = false, didShareSpotify: Bool = false, didSharePhone: Bool = false, didShareEmail: Bool = false, didShareInstagram: Bool = false, didShareReddit: Bool = false, didShareTwitter: Bool = false, didShareYouTube: Bool = false, didShareSoundCloud: Bool = false, didSharePinterest: Bool = false, didShareGitHub: Bool = false, didShareVimeo: Bool = false){ var method = "" if byMethod == .username{ method = "Username" } else if byMethod == .scan{ method = "Scan" } else if byMethod == .upload{ method = "Upload" } if isPrivate{ Answers.logCustomEvent(withName: "Swap", customAttributes: [ "Method" : method, "Private Swap Request": true.toString() ]) } else{ Answers.logCustomEvent(withName: "Swap", customAttributes: [ "Method" : method, "Spotify": didShareSpotify.toString(), "Phone Number": didSharePhone.toString(), "Email": didShareEmail.toString(), "Instagram": didShareInstagram.toString(), "Reddit" : didShareReddit.toString(), "Twitter" : didShareTwitter.toString(), "YouTube": didShareYouTube.toString(), "SoundCloud": didShareSoundCloud.toString(), "Pinterest": didSharePinterest.toString(), "GitHub": didShareGitHub.toString(), "Vimeo": didShareVimeo.toString(), "Private Swap Request" : false.toString() ]) } } } enum SwapMethod { case username case scan case upload } extension Bool{ func toString() -> String { if self{ return "Shared" } else{ return "Not Shared" } } } <file_sep>// // YouTubeMedia.swift // Swap // // Created by <NAME> on 2/7/17. // // import Foundation import SwiftyJSON class YouTubeMedia { var videoID: String = "" var datePublished: Date = Date() var channelID: String = "" var title: String = "" var description: String = "" var defaultThumbnail: String = "" var highResThumbnail: String = "" var channelTitle: String = "" var linkToYouTubeVideo: String = "" var webview: UIWebView? init(youtubeMediaJSON: JSON) { // create youtube object from JSON self.videoID = youtubeMediaJSON["id"]["videoId"].string ?? "" self.datePublished = (youtubeMediaJSON["snippet"]["publishedAt"].string ?? "2015-01-01T00:00:00.000Z").dateFromISO8601! self.channelID = youtubeMediaJSON["snippet"]["channelId"].string ?? "" self.title = youtubeMediaJSON["snippet"]["title"].string ?? "" self.description = youtubeMediaJSON["snippet"]["description"].string ?? "" self.defaultThumbnail = youtubeMediaJSON["snippet"]["thumbnails"]["default"]["url"].string ?? "" self.highResThumbnail = youtubeMediaJSON["snippet"]["thumbnails"]["high"]["url"].string ?? "" self.channelTitle = youtubeMediaJSON["snippet"]["channelTitle"].string ?? "" self.linkToYouTubeVideo = "https://youtube.com/watch?v=\(self.videoID)" } } extension JSON{ func toYouTubeMedias() -> [YouTubeMedia] { var medias: [YouTubeMedia] = [] let jsonResponse = self guard jsonResponse["items"].array != nil else { return [] } let arrayOfJSONs = jsonResponse["items"].array! for json in arrayOfJSONs{ let media = YouTubeMedia(youtubeMediaJSON: json) medias.append(media) } return medias } } extension Formatter { static let iso8601: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter }() } extension Date { var iso8601: String { return Formatter.iso8601.string(from: self) } static let dateShortFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.short dateFormatter.timeStyle = DateFormatter.Style.none return dateFormatter }() var stringValueShort: String { return Date.dateShortFormatter.string(from: self) } } extension String { var dateFromISO8601: Date? { return Formatter.iso8601.date(from: self) // "Mar 22, 2017, 10:22 AM" } } <file_sep>// // IGComment.swift // Swap // // Created by <NAME> on 2/2/17. // // import Foundation import SwiftyJSON class IGComment { var date_created: Date = Date() var text: String = "" var from_username: String = "" var from_profile_picture: URL? var from_id: String = "" var from_full_name: String = "" // Initialize Comment Object With JSOn init(commentJSON: JSON) { } } <file_sep>// // PrivacyPolicyView.swift // Swap // // Created by <NAME> on 1/15/17. // // import Foundation class PrivacyPolicy: UIViewController { @IBOutlet var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.async { let privacyPolicyURL = NSURL(string: "http://www.getswap.net/private-policy") let webRequest = NSURLRequest(url: privacyPolicyURL! as URL) self.webView.loadRequest(webRequest as URLRequest) } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // SetUsernameViewController.swift // Swap // // Created by <NAME> on 3/23/17. // // import Foundation class SetUsernameViewController: UIViewController, UITextFieldDelegate { @IBOutlet var usernameTextField: UITextField! @IBOutlet var availabilityView: UIView! @IBOutlet var availabilityLabel: UILabel! var canUseUsername: Bool = false override func viewDidLoad() { usernameTextField.becomeFirstResponder() availabilityLabel.isHidden = true usernameTextField.delegate = self availabilityLabel.adjustsFontSizeToFitWidth = true usernameTextField.autocorrectionType = .no } @IBAction func didChangeUsername(_ sender: Any) { availabilityLabel.isHidden = false usernameTextField.text?.validate(completion: { (isValid, text) in DispatchQueue.main.async { if isValid { self.canUseUsername = true self.availabilityView.backgroundColor = UIColor.green self.availabilityLabel.text = "Username is available." } else{ self.canUseUsername = false self.availabilityView.backgroundColor = UIColor.red self.availabilityLabel.text = text } } }) } @IBAction func didTapNext(_ sender: Any) { //save the username if canUseUsername{ self.performSegue(withIdentifier: "toPasswordController", sender: nil) saveUsername(username: usernameTextField.text) } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // ContainerViewController.swift // // // Created by <NAME> on 7/31/16. // Copyright © 2016 Swap. All rights reserved. // import Foundation var refreshControl: UIRefreshControl! var isRefreshing = false class ContainerViewController: UIViewController, UIScrollViewDelegate, UITabBarControllerDelegate{ var scrollView: UIScrollView! var SwapCenterButton: UIButton! var lastContentOffset: CGFloat! override func viewDidLoad() { SC super.viewDidLoad(); print("Container will load") //initialize refresh control refreshControl = UIRefreshControl() refreshControl.tintColor = .white refreshControl.isHidden = true refreshControl.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "Header1")) self.view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "Header1")) refreshControl.addTarget(self, action: #selector(ContainerViewController.refresh), for: .valueChanged) let Storyboard = self.storyboard // 1) Create the two views used in the swipe container view let AVc = Storyboard?.instantiateViewController(withIdentifier: "ProfileView") let BVc = Storyboard?.instantiateViewController(withIdentifier: "ScannerView") // 2) Add in each view to the container view hierarchy // Add them in opposite order since the view hieracrhy is a stack self.addChildViewController(BVc!); BVc!.didMove(toParentViewController: self); self.addChildViewController(AVc!); AVc!.didMove(toParentViewController: self); scrollView = UIScrollView(frame: view.bounds) if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.never } let scrollWidth: CGFloat = self.view.frame.width let scrollHeight: CGFloat = 2 * self.view.frame.size.height scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight); scrollView.addSubview(BVc!.view); scrollView.addSubview(AVc!.view); scrollView.bounces = true scrollView.alwaysBounceVertical = true scrollView.showsVerticalScrollIndicator = false scrollView.isPagingEnabled = true scrollView.isUserInteractionEnabled = true // 3) Set up the frames of the view controllers to align // with eachother inside the container view var adminFrame :CGRect = AVc!.view.frame; adminFrame.origin.y = adminFrame.height; BVc!.view.frame = adminFrame; var BFrame :CGRect = BVc!.view.frame; BFrame.origin.y = BFrame.origin.y - 1334; // CVc.view.frame = BFrame; view.addSubview(scrollView) scrollView.delegate = self scrollView.addSubview(refreshControl) SwapCenterButton = UIButton(frame: getSwapButtonFrame()) /* var menuButtonFrame = SwapCenterButton.frame menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2 SwapCenterButton.frame = menuButtonFrame*/ // SwapCenterButton.layer.cornerRadius = SwapCenterButton.height/2 SwapCenterButton.layer.zPosition = 2 view.addSubview(SwapCenterButton) SwapCenterButton.setImage(UIImage(named: "SwapButton"), for: .normal) SwapCenterButton.addTarget(self, action: #selector(SwapButtonAction(sender:)), for: .touchUpInside) //notification listens when to disable reloading NotificationCenter.default.addObserver(self, selector: #selector(self.disableReloading), name: .disableReloading, object: nil) } func getSwapButtonFrame() -> CGRect{ var buttonRect: CGRect? switch(self.storyboard?.value(forKey: "name") as! String){ case "Main": buttonRect = CGRect(x: self.view.frame.size.width*0.42, y: self.view.frame.size.height*0.9, width: 62, height: 60) break case "IPhone7Plus": buttonRect = CGRect(x: 177, y: 665, width: 65, height: 65) break case "IPhoneSE": buttonRect = CGRect(x: 134, y: 510, width: 56, height: 55) break case "IPhoneX": buttonRect = CGRect(x: 157, y: 700, width: 65, height: 65) break case "IPad": buttonRect = CGRect(x: 135, y: 422, width: 51, height: 50) break default: buttonRect = CGRect(x: self.view.frame.size.width*0.42, y: self.view.frame.size.height*0.9, width: 62, height: 60) break } return buttonRect! } @objc private func SwapButtonAction(sender: UIButton) { let scrollViewOffset = self.view.frame.height if scrollView.contentOffset.y != scrollViewOffset{ //show camera NotificationCenter.default.post(name: .didShowScanner, object: nil) scanner.startScan() scrollView.setContentOffset(CGPoint(x: 0, y: self.view.frame.height), animated: true) } else { //reset to default position scanner.stopScan() scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.lastContentOffset = scrollView.contentOffset.y; } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard self.lastContentOffset != nil else { return } if (self.lastContentOffset < scrollView.contentOffset.y) { // print("On scanner") NotificationCenter.default.post(name: .didShowScanner, object: nil) scanner.startScan() } else if (self.lastContentOffset > scrollView.contentOffset.y) { //print("On Profile") //Stop Scanner scanner.stopScan() } else { // didn't move } } func scrollViewDidScroll(_ scrollView: UIScrollView) { view.endEditing(true) SwapCenterButton.alpha = 1 + (0.2*scrollView.contentOffset.y) if scrollView.contentOffset.y > 100{ scrollView.bounces = false } else{ scrollView.bounces = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refresh(){ animateRefresh() postNotificationToReloadScreens() } func animateRefresh(){ /*let color1 = UIColor(red: 58/255.0, green: 1/255.0, blue: 65/255.0, alpha: 1.0) let color2 = UIColor(red: 125/255.0, green: 1/255.0, blue: 65/255.0, alpha: 1.0) let color3 = UIColor(red: 125/255.0, green: 130/255.0, blue: 65/255.0, alpha: 1.0) let color4 = UIColor(red: 125/255.0, green: 130/255.0, blue: 137/255.0, alpha: 1.0) let color5 = UIColor(red: 125/255.0, green: 130/255.0, blue: 230/255.0, alpha: 1.0) let color6 = UIColor(red: 125/255.0, green: 220/255.0, blue: 230/255.0, alpha: 1.0) var colorArray = [color1, color2, color3, color4, color5, color6] struct ColorIndex{ static var colorIndex = 0 } UIView.animate(withDuration: 1, animations: { refreshControl.backgroundColor = colorArray[ColorIndex.colorIndex] self.view.backgroundColor = colorArray[ColorIndex.colorIndex] ColorIndex.colorIndex = (ColorIndex.colorIndex + 1) % colorArray.count }) { finished in if (refreshControl.isRefreshing){ self.animateRefresh() } else{ refreshControl.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "Header1")) self.view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "Header1")) } }*/ } func postNotificationToReloadScreens() { if let screen = getLastScreen(){ print("\nthe screen is .. \(screen)") switch screen { case .UserProfileScreen: NotificationCenter.default.post(name: .reloadProfile, object: nil) case .NotificationsScreen: NotificationCenter.default.post(name: .reloadNotifications, object: nil) case .SearchedUserProfileScreen: //NotificationCenter.default.post(name: .reloadSearchedUserProfile, object: nil) // Will add notification later, pull to refresh isn't enabled on SeaarchedUserProfile yet refreshControl.endRefreshing() case .SwappedScreen: NotificationCenter.default.post(name: .reloadSwapped, object: nil) case .SwapsScreen: NotificationCenter.default.post(name: .reloadSwaps, object: nil) default: break } } else{ refreshControl.endRefreshing() } } func disableReloading(){ scrollView.alwaysBounceVertical = false scrollView.bounces = false } func enableReloading(){ scrollView.alwaysBounceVertical = true } } <file_sep>// // SavingDataInApp.swift // Swap // // Created by <NAME> on 11/27/16. // // Use this to save any type of data in the app –– never pass information through view controllers import Foundation /// Call this function to save the user's entered username in a field. This should be used whenever you want to save the usrename entered in order to pass it to a new view controller. For example, call saveUsername to save the username while the user is signing up and then getSavedUsername() to pass it to the sign in view controller text field so the user will not have to enter it again. /// /// - Parameter username: Username to save. func saveUsername(username: String?) { UserDefaults.standard.set((username ?? "").lowercased(), forKey: "username") UserDefaults.standard.synchronize() } /// Call this function to get the saved username when saveUsername(:_) was called. /// /// - Returns: Username string optional. func getSavedUsername() -> String? { return UserDefaults.standard.string(forKey: "username") } /// Save the password passed in the fuction to NSUserDefaults. /// /// - Parameter password: Password to save. func savePassword(password: String?) { UserDefaults.standard.set(password, forKey: "password") UserDefaults.standard.synchronize() } /// Return the password saved. /// /// - Returns: Password string optional. func getSavedPassword() -> String? { return UserDefaults.standard.string(forKey: "password") } /// Saves the firstname in user defaults. func saveFirstname(name: String?) { UserDefaults.standard.set(name, forKey: "firstname") UserDefaults.standard.synchronize() } /// Gets the saved firstname from user defaults. func getSavedFirstname() -> String? { return UserDefaults.standard.string(forKey: "firstname") } /// Saves the middlename in user defaults. func saveMiddlename(name: String?) { UserDefaults.standard.set(name, forKey: "middlename") UserDefaults.standard.synchronize() } /// Gets the saved middlename from user defaults. func getSavedMiddlename() -> String? { return UserDefaults.standard.string(forKey: "middlename") } /// Saves the lastname in user defaults. func saveLastname(name: String?) { UserDefaults.standard.set(name, forKey: "lastname") UserDefaults.standard.synchronize() } /// Gets the saved lastname from user defaults. func getSavedLastname() -> String? { return UserDefaults.standard.string(forKey: "lastname") } /// Saves the website in user defaults. func saveWebsite(name: String?) { UserDefaults.standard.set(name, forKey: "website") UserDefaults.standard.synchronize() } /// Gets the saved website from user defaults. func getSavedWebsite() -> String? { return UserDefaults.standard.string(forKey: "website") } /// Saves the company name in user defaults. func saveCompany(name: String?) { UserDefaults.standard.set(name, forKey: "company") UserDefaults.standard.synchronize() } /// Gets company name from user defaults func getSavedCompany() -> String? { return UserDefaults.standard.string(forKey: "company") } /// Save the link to the instagram profile picture in Userdefaults /// /// - Parameter withLink: String representing link to Instagram Profile Picture func saveInstagramPhoto(withLink: String?) { if let stringToImage = withLink{ UserDefaults.standard.set(URL(string: stringToImage), forKey: "instagramProfilePic") UserDefaults.standard.synchronize() } } /// Gets the Instagram Profile Picture URL saved in NSUserDefaults /// /// - Returns: URL to Profile Picture; otherwise, is nil func getInstagramProfilePictureLink() -> URL? { return UserDefaults.standard.url(forKey: "instagramProfilePic") } /// Save the link to the Twitter profile picture in Userdefaults /// /// - Parameter withLink: String representing link to Twitter Profile Picture func saveTwitterPhoto(withLink: String?) { UserDefaults.standard.set(URL(string: withLink!), forKey: "twitterProfilePic") UserDefaults.standard.synchronize() } /// Gets the Twitter Profile Picture URL saved in NSUserDefaults /// /// - Returns: URL to Profile Picture; otherwise, is nil func getTwitterProfilePictureLink() -> URL? { return UserDefaults.standard.url(forKey: "twitterProfilePic") } /// Save the link to the YouTube profile picture in Userdefaults /// /// - Parameter withLink: String representing link to YouTube Profile Picture func saveYouTubeProfilePicture(withLink: String?) { UserDefaults.standard.set(URL(string: withLink!), forKey: "youtubeProfilePicture") UserDefaults.standard.synchronize() } /// Gets the YouTube Profile Picture URL saved in NSUserDefaults /// /// - Returns: URL to Profile Picture; otherwise, is nil func getYouTubeProfilePictureLink() -> URL? { return UserDefaults.standard.url(forKey: "youtubeProfilePicture") } /// Saves the contact image from address book in user defaults. func saveContactImage(imageData: Data?) { UserDefaults.standard.set(imageData, forKey: "contactImage") UserDefaults.standard.synchronize() } /// Gets the contact image from user defaults as a UIImage func getContactImage() -> UIImage? { let imageData = UserDefaults.standard.object(forKey: "contactImage") as? Data if imageData != nil { return UIImage(data: imageData!) } else { return nil} } /// Saves the current UIViewController. Pass 'self' in this function in 'viewDidAppear' or 'viewWillAppear'. This will save the restoration ID of the view controller in order to instantiate that same view controller in app delegate. Call this function whenever you want the user to see this view controller again after they open the app after exiting or quiting. Set this to nil when user is on Profile View Controller. You ONLY want to save the last view controller when the user is on a sign up type screen. /// /// - Parameter viewController: View Controller with a restorationID func saveViewController(viewController: UIViewController?) { if let vc = viewController{ UserDefaults.standard.set(vc.restorationIdentifier, forKey: "lastViewController") UserDefaults.standard.synchronize() } else{ UserDefaults.standard.removeObject(forKey: "lastViewController") UserDefaults.standard.synchronize() } } /// Use this function to get the restoration ID of the last (saved) view controller the user was on before exiting app. /// /// - Returns: String indicating restoration ID of view controller func getLastViewControllerID() -> String? { let lastVC = UserDefaults.standard.object(forKey: "lastViewController") as? String return lastVC } /// Use this function to save the email of the user in order to pass it to a different view controller func saveEmail(email: String?) { UserDefaults.standard.set(email, forKey: "email") UserDefaults.standard.synchronize() } /// Get the saved phonenumber from User Defaults func getSavedEmail() -> String? { return UserDefaults.standard.object(forKey: "email") as? String } /// Use this function to save the phonenumber of the user in order to pass it to a different view controller func savePhonenumber(phone: String?) { UserDefaults.standard.set(phone, forKey: "phonenumber") UserDefaults.standard.synchronize() } /// Get the saved phone number from User Defaults func getSavedPhonenumber() -> String? { return UserDefaults.standard.object(forKey: "phonenumber") as? String } /// Saves the Twitter Consumer Key and Secret in User Defaults in order to later authenticate it in order to make API Requests /// /// - Parameters: /// - withToken: The Token Key of the Twitter Account /// - andSecret: The Secret of the Twitter Account /// - Todo: Make sure that this is stored in Keychain Rather than User Defaults func saveTwitterAccount(withToken: String, andSecret: String) { UserDefaults.standard.set(withToken, forKey: "TwitterToken") UserDefaults.standard.set(andSecret, forKey: "TwitterSecret") UserDefaults.standard.synchronize() } func getTwitterToken() -> String? { return UserDefaults.standard.string(forKey: "TwitterToken") } func getTwitterSecret() -> String? { return UserDefaults.standard.string(forKey: "TwitterSecret") } func saveVine(username: String, andPassword: String) { UserDefaults.standard.set(username, forKey: "VineUsername") UserDefaults.standard.set(andPassword, forKey: "VinePassword") UserDefaults.standard.synchronize() } func getVineUsername() -> String? { return UserDefaults.standard.string(forKey: "VineUsername") } func getVinePassword() -> String? { return UserDefaults.standard.string(forKey: "VinePassword") } func save(birthday: Double?) { UserDefaults.standard.set(birthday, forKey: "birthday") UserDefaults.standard.synchronize() } func getBirthday() -> Double { return UserDefaults.standard.double(forKey: "birthday") } func save(password: String?) { UserDefaults.standard.set(password, forKey: "password") UserDefaults.standard.synchronize() } func getPassword() -> String? { return UserDefaults.standard.string(forKey: "password") } func save(phoneNumber: String?) { UserDefaults.standard.set(phoneNumber, forKey: "phonenumber") UserDefaults.standard.synchronize() } func getPhoneNumber() -> String? { return UserDefaults.standard.string(forKey: "phonenumber") } func save(verificationCode: String?) { UserDefaults.standard.set(verificationCode, forKey: "verificationCodeForForgotPassword") UserDefaults.standard.synchronize() } func getVerificationCodeForForgotPassword() -> String? { return UserDefaults.standard.string(forKey: "verificationCodeForForgotPassword") } /// Saves Swap Code Image Locally func save(swapCodeImageData: Data?) { if let image = swapCodeImageData { let key = "\(getUsernameOfSignedInUser())-SwapCodeImageData" UserDefaults.standard.set(image, forKey: key) UserDefaults.standard.synchronize() } } /// Gets the Swap Code UIImage func getSwapCodeImage() -> UIImage?{ var image: UIImage? let key = "\(getUsernameOfSignedInUser())-SwapCodeImageData" let data = UserDefaults.standard.data(forKey: key) if let data = data { image = UIImage(data: data) } return image } /// Use this on viewdidappear in order to make note of the last active screen the user was on. (Used in order to determine what screen the user is on when they are pulling to refresh) /// /// - Parameter screen: Screen the user is on func save(screen: Screen){ var screenString = "" switch screen{ case .UserProfileScreen: screenString = "UserProfileScreen" break case .SearchedUserProfileScreen: screenString = "SearchedUserProfileScreen" break case .NotificationsScreen: screenString = "NotificationsScreen" break case .SwapsScreen: screenString = "SwapsScreen" break case .SwappedScreen: screenString = "SwappedScreen" break } UserDefaults.standard.set(screenString, forKey: "LastScreen") UserDefaults.standard.synchronize() } /// Use this in order to determine what screen the user is currently on in order to determine what screen to refresh when the user pulls to refresh func getLastScreen() -> Screen?{ if let screenString = UserDefaults.standard.string(forKey: "LastScreen"){ switch screenString { case "UserProfileScreen": return .UserProfileScreen case "SearchedUserProfileScreen": return .SearchedUserProfileScreen case "NotificationsScreen": return .NotificationsScreen case "SwapsScreen": return .SwapsScreen case "SwappedScreen": return .SwappedScreen default: return nil } } else { return nil } } /// Cache that contains profile picture cache for Swap Map let SwapMapProfilePictureCache = NSCache<NSString, NSString>() ///New annotations are created whenever you scroll in the map so use this function to locally cache the profile picture image url and map it to the username to prevent loading data too much. * Note, clear images from cache/user defaults as needed. (Maybe on viewDidLoad of the loading profile screen) /// <#Description#> /// /// - Parameters: /// - username: Username of the user /// - pictureURL: Picture URL of the user func saveMapProfilePictureToUser(username: String, pictureURL: String) { SwapMapProfilePictureCache.setObject(pictureURL as NSString, forKey: username as NSString) } // Call this on loadProfile of profile and whenever the 'swap' is reloaded. This should be called whenever it's required to reload the count of the user's 'swaps' so that the map can be reloaded. func clearSwapMapUserPhotos() { SwapMapProfilePictureCache.removeAllObjects() } /// Gets the saved profile picture from the user with specified username to be used in Swap Map func getSwapMapProfilePictureFromUser(with username: String ) -> String? { if let image = SwapMapProfilePictureCache.object(forKey: username as NSString) { return image as String } else{ return nil } } /// Enum containing the type of screens the user was last active on enum Screen{ case UserProfileScreen case SearchedUserProfileScreen case NotificationsScreen case SwapsScreen case SwappedScreen } <file_sep>// // Twitter.swift // Swap // // Created by <NAME> on 12/23/16. // // import Foundation import Social import Accounts import Swifter import SafariServices import TwitterKit /// - TODO: Document func authorizeTwitter(onViewController: UIViewController, completion: @escaping (_ loginError: AuthorizationError?) -> () ) { logoutTwitter() Twitter.sharedInstance().logIn(completion: { (session, error) in guard error == nil else{ completion(AuthorizationError.Unknown) return } if let session = session{ let token = session.authToken let secret = session.authTokenSecret saveTwitterAccount(withToken: token, andSecret: secret) if error != nil{ completion(AuthorizationError.Unknown) } else{ guard let token = getTwitterToken(), let secret = getTwitterSecret() else { completion(AuthorizationError.Unknown) return } let twitterAccount = Swifter(consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, oauthToken: token, oauthTokenSecret: secret) twitterAccount.getTimeline(for: session.userName, success: { (json) in print("\n\n\n\n\n\n\n\n the twitter json is ... \(json)") let image = json.array?[0]["user"]["profile_image_url_https"].string ?? defaultImage saveTwitterPhoto(withLink: image) SwapUser(username: getUsernameOfSignedInUser()).set(TwitterID: session.userID, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }) }) } } }) } <file_sep>// // ProfilePicturePageController.swift // Swap // // Created by <NAME> on 3/24/17. // // File holds all the classes neccessay for the user to select a profile picture from the available logged in social medias. import Foundation import Kingfisher var currentIndex = 0 //view that holds all the available profile pictures in a PageViewController class ProfilePicPageController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var instagramPicView = getSignupStoryboard().instantiateViewController(withIdentifier: "profilePicView") as! ProfilePicView var twitterPicView = getSignupStoryboard().instantiateViewController(withIdentifier: "profilePicView") as! ProfilePicView var youtubePicView = getSignupStoryboard().instantiateViewController(withIdentifier: "profilePicView") as! ProfilePicView var contactPicView = getSignupStoryboard().instantiateViewController(withIdentifier: "profilePicView") as! ProfilePicView var pictureViews = [UIViewController]() override func viewDidLoad() { super.viewDidLoad() instagramPicView.imageURL = getInstagramProfilePictureLink() ?? URL(string: defaultImage)! twitterPicView.imageURL = getTwitterProfilePictureLink() ?? URL(string: defaultImage)! youtubePicView.imageURL = getYouTubeProfilePictureLink() ?? URL(string: defaultImage)! contactPicView.imageURL = (getContactImage() != nil) ? nil : URL(string: defaultImage)! pictureViews = [instagramPicView, twitterPicView, youtubePicView, contactPicView] dataSource = self delegate = self //set the first controller in the pageViewController if let firstViewController = pictureViews.first { setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } } /*Delegate function*/ func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { //only execute if the transition from one page to the next is completed if completed{ //update the current index and the page Control currentIndex = pictureViews.index(of: (viewControllers?.first)!)! NotificationCenter.default.post(name: .updatePageControl, object: nil) } } /*Data Source Function*/ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = pictureViews.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return pictureViews.last } guard pictureViews.count > previousIndex else { return nil } return pictureViews[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = pictureViews.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 let pictureViewsCount = pictureViews.count guard pictureViewsCount != nextIndex else{ return pictureViews.first } guard pictureViewsCount > nextIndex else{ return nil } return pictureViews[nextIndex] } } class ProfilePicView: UIViewController { @IBOutlet var picture: UIImageView! var imageURL: URL? override func viewDidLoad() { super.viewDidLoad() if imageURL == nil{ picture.image = getContactImage() ?? #imageLiteral(resourceName: "DefaultProfileImage") } else{ picture.kf.indicatorType = .activity picture.kf.setImage(with: imageURL) } circularImage(photoImageView: picture) } } //View that holds the pageViewController class SelectProfilePicViewController: UIViewController { @IBOutlet var containerView: UIView! @IBOutlet var pageControl: UIPageControl! var numberOfPics: Int? var currentImage: UIImage? var link: URL? override func viewDidLoad() { currentIndex = 0 NotificationCenter.default.addObserver(self, selector: #selector(self.updatePageControl), name: .updatePageControl, object: nil) } func updatePageControl(){ pageControl.currentPage = currentIndex } @IBAction func didSelectPicture(_ sender: Any) { switch currentIndex { case 0: link = getInstagramProfilePictureLink() break case 1: link = getTwitterProfilePictureLink() break case 2: link = getYouTubeProfilePictureLink() break case 3: currentImage = getContactImage() ?? #imageLiteral(resourceName: "DefaultProfileImage") break default: currentImage = #imageLiteral(resourceName: "DefaultProfileImage") } if let selectedLink = link{ ImageDownloader.default.downloadImage(with: link ?? URL(string: "")!, options: [], completionHandler: { (image, error, url, data) in let imageData = UIImageJPEGRepresentation(image ?? #imageLiteral(resourceName: "DefaultProfileImage"), 1.0) SwapUser().uploadProfilePicture(withData: imageData!, completion: {_ in DispatchQueue.main.async { self.performSegue(withIdentifier: "showHome", sender: nil) } }) }) } else { let imageData = UIImageJPEGRepresentation(currentImage ?? #imageLiteral(resourceName: "DefaultProfileImage"), 1.0) SwapUser().uploadProfilePicture(withData: imageData!, completion: {_ in DispatchQueue.main.async { self.performSegue(withIdentifier: "showHome", sender: nil) } }) } } } <file_sep>// // ConnectingSocialMediasViewController.swift // Swap // // Created by <NAME> on 12/8/16. // // import UIKit import p2_OAuth2 import SafariServices class ConnectingSocialMediasViewController: UIViewController, SFSafariViewControllerDelegate { @IBOutlet var Github: UIButton! @IBOutlet weak var Twitter: UIButton! @IBOutlet weak var Spotify: UIButton! @IBOutlet weak var YouTube: UIButton! @IBOutlet var Reddit: UIButton! @IBOutlet weak var Instagram: UIButton! @IBOutlet weak var Vimeo: UIButton! @IBOutlet weak var Pinterest: UIButton! @IBOutlet weak var SoundCloud: UIButton! @IBOutlet var nextButton: UIButton! @IBAction func didTapConnectSocialMedia(_ sender: UIButton) { guard !sender.isSelected else{ // Log out social media if it's logged in switch sender { case Spotify: logoutSpotify() SwapUser().set(WillShareSpotify: false) break case Pinterest: logoutPinterest() SwapUser().set(WillSharePinterest: false) break case Vimeo: logoutVimeo() SwapUser().set(WillShareVimeo: false) break case YouTube: logoutYouTube() SwapUser().set(WillShareYouTube: false) break case Instagram: logoutInstagram() SwapUser().set(WillShareInstagram: false) break case Reddit: logoutReddit() SwapUser().set(WillShareReddit: false) break case SoundCloud: logoutSoundCloud() SwapUser().set(WillShareSoundCloud: false) break case Github: logoutGitHub() SwapUser().set(WillShareGitHub: false) break case Twitter: logoutTwitter() SwapUser().set(WillShareTwitter: false) break default: break } // Disbale icon sender.isSelected = false return } // Log in switch sender { case Spotify: authorizeSpotify(onViewController: self, completion: { (error) in if let error = error { // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ //There was no error authorizing // Highlights social media icon SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Twitter: // Authorize twitter print("did tap authorize twitter") authorizeTwitter(onViewController: self, completion: { (error) in if let error = error { // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ //There was no error authorizing // Highlights social media icon SwapUser().incrementPoints(byValue: 5) { error in } sender.isSelected = true } }) break case YouTube: // Authorize YouTube authorizeYouTube(onViewController: self, completion: { (error) in if let error = error { print("there is an error ... \(error)") // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ // It worked SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Reddit: // Authorize Reddit authorizeReddit(onViewController: self, completion: { (error) in if let error = error{ // There is an error } else{ // It worked SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Instagram: // Authorize Instagram authorizeInstagram(onViewController: self, completion: { (error) in if let error = error { // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ // It worked SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Vimeo: // Authorize Vimeo authorizeVimeo(onViewController: self, completion: { (error) in if let error = error { // There is an error } else{ // It worked SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Pinterest: // Authorize Pinterest authorizePinterest(onViewController: self, completion: { (error) in if let error = error { // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ // It worked SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case SoundCloud: // Authorize Sound Cloud authorizeSoundCloud(onViewController: self, completion: { (error) in if let error = error { print("there is an error ... \(error)") // There is an error // Determining Error Authorizing User for This Social Media switch error{ case .Cancelled: // Do nothing because the user cancelled break case .Unknown: // Tell the user there was an error logging in break case .IDNotFound: // Not sure of the error here, the ID was not found in the request so maybe it failed break } } else{ // It worked print("it worked") SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break case Github: //Authorize Github authorizeGitHub(onViewController: self, completion: { (error) in if let error = error { print("there is an error ... \(error)") // There is an error } else{ // It worked print("it worked") SwapUser().incrementPoints(byValue: 5){ error in } sender.isSelected = true } }) break default: break } } @IBAction func didTapNext(_ sender: UIButton) { let atLeastOneSocialMediaIsConnected: Bool = (Twitter.isSelected || SoundCloud.isSelected || Pinterest.isSelected || Vimeo.isSelected || Instagram.isSelected || Reddit.isSelected || YouTube.isSelected || Spotify.isSelected || Github.isSelected) if atLeastOneSocialMediaIsConnected{ // The user connected at least one social media // Now take them to select profile picture self.performSegue(withIdentifier: "toSelectProfilePicture", sender: self) } else{ // Warn the user that no social medias are connected //Proceed self.performSegue(withIdentifier: "toSelectProfilePicture", sender: self) } } override func viewWillAppear(_ animated: Bool) { // Sets the default images for social media icons if they are selected Spotify.setImage(#imageLiteral(resourceName: "SpotifyEnabled"), for: UIControlState.selected) Vimeo.setImage(#imageLiteral(resourceName: "VimeoEnabled"), for: UIControlState.selected) Twitter.setImage(#imageLiteral(resourceName: "TwitterEnabled"), for: UIControlState.selected) YouTube.setImage(#imageLiteral(resourceName: "YouTubeEnabled"), for: UIControlState.selected) SoundCloud.setImage(#imageLiteral(resourceName: "SoundCloudEnabled"), for: UIControlState.selected) Pinterest.setImage(#imageLiteral(resourceName: "PinterestEnabled"), for: UIControlState.selected) Reddit.setImage(#imageLiteral(resourceName: "RedditEnabled"), for: UIControlState.selected) Instagram.setImage(#imageLiteral(resourceName: "InstagramEnabled"), for: UIControlState.selected) Github.setImage(#imageLiteral(resourceName: "GithubEnabled"), for: UIControlState.selected) // Selects the social media icons if they are connected Spotify.isSelected = spotifyIsConnected() Instagram.isSelected = instagramIsConnected() SoundCloud.isSelected = soundcloudIsConnected() Pinterest.isSelected = pinterestIsConnected() Twitter.isSelected = twitterIsConnected() YouTube.isSelected = youtubeIsConnected() Reddit.isSelected = redditIsConnected() Github.isSelected = githubIsConnected() Vimeo.isSelected = vimeoIsConnected() } override func viewDidAppear(_ animated: Bool) { saveViewController(viewController: self) } override func viewDidLoad() { super.viewDidLoad() // Selects the social media icons if they are connected Spotify.isSelected = spotifyIsConnected() Instagram.isSelected = instagramIsConnected() SoundCloud.isSelected = soundcloudIsConnected() Pinterest.isSelected = pinterestIsConnected() Twitter.isSelected = twitterIsConnected() YouTube.isSelected = youtubeIsConnected() Reddit.isSelected = redditIsConnected() Github.isSelected = githubIsConnected() Vimeo.isSelected = vimeoIsConnected() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } func vimeoIsConnected() -> Bool { return ( (vimeo_oauth2.accessToken != nil) || (github_oauth2.refreshToken != nil) ) } func githubIsConnected() -> Bool { return ( (github_oauth2.accessToken != nil) || (github_oauth2.refreshToken != nil) ) } func redditIsConnected() -> Bool { return ( (reddit_oauth2.accessToken != nil) || (reddit_oauth2.refreshToken != nil) ) } func youtubeIsConnected() -> Bool { return ( (youtube_oauth2.accessToken != nil) || (youtube_oauth2.refreshToken != nil) ) } func twitterIsConnected() -> Bool { return (getTwitterSecret() != nil && getTwitterToken() != nil) } func pinterestIsConnected() -> Bool { return ( (pinterest_oauth2.accessToken != nil) || (pinterest_oauth2.refreshToken != nil) ) } func soundcloudIsConnected() -> Bool { return ((soundcloud_oauth2.accessToken != nil) || (soundcloud_oauth2.refreshToken != nil)) } func instagramIsConnected() -> Bool { return ((instagram_oauth2.accessToken != nil) || (instagram_oauth2.refreshToken != nil)) } func spotifyIsConnected() -> Bool { return ((spotify_oauth2.accessToken != nil) || (spotify_oauth2.refreshToken != nil)) } <file_sep>// // Setttings.swift // Swap // // Created by <NAME> on 12/20/16. // // import Foundation class SettingsView: UITableViewController { @IBOutlet var privateAccountSwitch: UISwitch! @IBOutlet var SwapCodeColorIndicator: UIImageView! var SwapCodeColorBlue: Bool? override func viewDidLoad() { SwapUser().getInformation { (error, user) in DispatchQueue.main.async { if let user = user{ let isPrivate = user._isPrivate as? Bool ?? false self.privateAccountSwitch.isOn = isPrivate } } } SwapCodeColorBlue = UserDefaults.standard.bool(forKey: "SwapCodeColorBlue") ?? false if SwapCodeColorBlue!{ SwapCodeColorIndicator.image = #imageLiteral(resourceName: "SwapCodeColor2") } } override func viewWillAppear(_ animated: Bool) { // Moved this code to ViewDidLoad - <NAME> } override func viewDidAppear(_ animated: Bool) { for indexpath in self.tableView.indexPathsForVisibleRows!{ self.tableView.deselectRow(at: indexpath, animated: true) } } @IBAction func closeSettings(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func didTogglePrivateAccount(_ sender: UISwitch) { SwapUser().set(isPrivate: sender.isOn) } //code that runs when a certain row is tapped override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //change swap code row pressed if (indexPath.section == 0 && indexPath.row == 1){ SwapCodeColorBlue = !SwapCodeColorBlue! if (SwapCodeColorBlue == false){ SwapCodeColorIndicator.image = #imageLiteral(resourceName: "SwapCodeColor1") UserDefaults.standard.set(false, forKey: "SwapCodeColorBlue") UserDefaults.standard.synchronize() // Send Notification That Swap Color Changed NotificationCenter.default.post(name: .changeSwapCodeToDark, object: nil) } else{ SwapCodeColorIndicator.image = #imageLiteral(resourceName: "SwapCodeColor2") UserDefaults.standard.set(true, forKey: "SwapCodeColorBlue") UserDefaults.standard.synchronize() // Send Notification That Swap Color Changed NotificationCenter.default.post(name: .changeSwapCodeToBlue, object: nil) } } //log out row pressed if (indexPath.section == 1 && indexPath.row == 3){ let alert = UIAlertController(title: "Are You Sure?", message: "Your swap points will reset and you will have to reconnect your social medias if you sign out", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Yes", style: .default){ (action) in let loadingOverlay = ShowLoadingOverlay() self.view.addSubview(loadingOverlay.showBlackOverlay()) self.view.addSubview(loadingOverlay.showLoadingSymbol(view: self.view)) signOut{ DispatchQueue.main.async { // Successfully Sign out logoutSocialMediasAndClearCookies() self.performSegue(withIdentifier: "signOut", sender: nil) } } }) self.present(alert, animated: true, completion: nil) } } } <file_sep>// // TwitterViewController.swift // // // Created by <NAME> on 2/14/17. // // import Foundation <file_sep>// // Contacts.swift // Swap // // Created by Dr. Stephen, Ph.D on 11/28/16. // // import Foundation import Contacts @available(iOS 9.0, *) /// Function that tried to find a contact in addressbook with specified phone number in background. Saves phonenumber, name, website, contact photo, and company in User Defaults. Country code can be included or omitted. Doesn't make a difference. /// /// - Parameter withPhonenumber: Phonenumber of the user /// - bug: /// Because it uses the custom ~ operator , it only tests if phonenumber A is a subset of phonenumber B and vice versa. Therefore, '34' will match 4043453234 because '34' is in 404345324. This may not be a problem because only real phone numbers will be in the database but I should probably keep this in mind. func getContact(withPhonenumber: String) { DispatchQueue.global(qos: .background).async { var contactFound: CNContact? var contactIsFound: Bool = false { didSet { if contactIsFound{ // contact is found // Run code here after the contact is found print("Contact is found!") // Get the information of the contact let firstname = contactFound?.givenName let middlename = contactFound?.middleName let lastname = contactFound?.familyName let website = contactFound?.urlAddresses.first?.value as String? let company = contactFound?.organizationName let imageData = contactFound?.imageData // Save it , don't save firstname and lastname anymore because it'll cause problems signing up // saveFirstname(name: firstname) saveMiddlename(name: middlename) // saveLastname(name: lastname) saveWebsite(name: website) saveCompany(name: company) saveContactImage(imageData: imageData) } } } // Background Thread let contactStore = CNContactStore() let predicate = CNContact.predicateForContactsInContainer(withIdentifier: contactStore.defaultContainerIdentifier()) var contacts: [CNContact]! = [] let keysToFetch = [ CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactOrganizationNameKey, CNContactUrlAddressesKey, CNContactNoteKey, CNContactJobTitleKey, CNContactBirthdayKey, CNContactNonGregorianBirthdayKey, CNContactFamilyNameKey, CNContactNicknameKey, CNContactPostalAddressesKey, CNContactSocialProfilesKey, CNContactDatesKey] as [Any] do { // Adds all contacts to contracts array print("Trying to get contacts") contacts = try contactStore.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])// [CNContact] }catch { print("cannot get contacts for some reason") // failed } // iterates through all contacts for contact in contacts{ print("Looping through contacts") // If a contact has more than one phone number if contact.phoneNumbers.count > 1 { print("more than one phone number") // Loop through all phone numbers for number in contact.phoneNumbers { print("looping") if number.value.stringValue ~ withPhonenumber{ // phone number is similar to withPhoneNumber print("contact is found") contactFound = contact contactIsFound = true } } } else{ // There is only ONE Phone number print("only one phone number") // Tests that phone number let num = contact.phoneNumbers.first?.value.stringValue print("The number is ...\(num)") if num ~ withPhonenumber { //Phone number is found print("contact is found") contactFound = contact contactIsFound = true } else{ print("Contact is not found yet") } } } } } func lookForContact(with phoneNumber: String, or email: String?) -> CNContact? { var contactFound: CNContact? let contactStore = CNContactStore() let predicate = CNContact.predicateForContactsInContainer(withIdentifier: contactStore.defaultContainerIdentifier()) var contacts: [CNContact]! = [] let keysToFetch = [ CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactOrganizationNameKey, CNContactUrlAddressesKey, CNContactNoteKey, CNContactJobTitleKey, CNContactBirthdayKey, CNContactNonGregorianBirthdayKey, CNContactFamilyNameKey, CNContactNicknameKey, CNContactPostalAddressesKey, CNContactSocialProfilesKey, CNContactDatesKey] as [Any] do { // Adds all contacts to contracts array print("Trying to get contacts") contacts = try contactStore.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])// [CNContact] }catch { print("cannot get contacts for some reason") // failed return nil } // iterates through all contacts for contact in contacts{ print("Looping through contacts") // If a contact has more than one phone number if contact.phoneNumbers.count > 1 { print("more than one phone number") // Loop through all phone numbers for number in contact.phoneNumbers { print("looping") if number.value.stringValue ~ phoneNumber{ // phone number is similar to withPhoneNumber contactFound = contact } } } else if contact.phoneNumbers.count == 1{ // There is only ONE Phone number print("only one phone number") // Tests that phone number let num = contact.phoneNumbers.first?.value.stringValue print("The number is ...\(num)") if num ~ phoneNumber { //Phone number is found print("contact is found") contactFound = contact } else{ // nothing print("\n\n\n\n nothing in this contact \(contact)") } } if contact.emailAddresses.count > 1 && email != nil{ for Email in contact.emailAddresses{ print("the email is ... \(Email.value)") print("looping throuhg emails") if Email.value as String == email!{ print("contact is found ") contactFound = contact } } } else if contact.emailAddresses.count == 1 && email != nil{ print("only one email which is \(contact.emailAddresses.first?.value)") if contact.emailAddresses.first?.value as! String == email!{ contactFound = contact } } } return contactFound } <file_sep>// // SearchUsersView.swift // Swap // // Created by <NAME> on 1/9/17. // // import Foundation import Kingfisher class SearchUsers: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UIGestureRecognizerDelegate, UIScrollViewDelegate { let featuredCellID = "FCell" var collectionView: UICollectionView? = nil @IBOutlet var searchedUsersTable: UITableView! // @IBOutlet var collectionView: UICollectionView! @IBOutlet var searchBar: UISearchBar! @IBOutlet var tableView: UITableView! @IBOutlet var searchLabel: UILabel! @IBOutlet var loadingSymbol: UIActivityIndicatorView! var returnedUsers: [SwapUser] = [] override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadingSymbol.stopAnimating() searchBar.backgroundImage = UIImage() searchBar.barTintColor = UIColor.white searchBar.layer.borderWidth = 10 searchBar.layer.borderColor = UIColor.white.cgColor /* for indexpath in self.tableView.indexPathsForVisibleRows!{ self.tableView.deselectRow(at: indexpath, animated: true) }*/ } override func viewDidLoad() { searchBar.delegate = self self.setupSwipeGestureRecognizers(allowCyclingThoughTabs: true) //recognizes a tap on the screen let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapScreen)) tapGestureRecognizer.numberOfTapsRequired = 1 tapGestureRecognizer.cancelsTouchesInView = false self.view.addGestureRecognizer(tapGestureRecognizer) //set up collection view and add it to the view let collectionViewRect = CGRect(x: 0, y: 140, width: self.view.frame.width, height: self.view.frame.height*0.75) let layout = UICollectionViewFlowLayout() collectionView = UICollectionView(frame: collectionViewRect, collectionViewLayout: layout) collectionView?.delegate = self collectionView?.dataSource = self collectionView?.backgroundColor = UIColor.white collectionView?.register(FeaturedProfilesCell.self, forCellWithReuseIdentifier: featuredCellID) self.view.addSubview(collectionView!) collectionView?.isHidden = true } func didTapScreen(){ searchBar.resignFirstResponder() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { collectionView?.isHidden = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { // collectionView?.isHidden = false } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { loadingSymbol.isHidden = false tableView.isHidden = true loadingSymbol.startAnimating() // Make sure that the input is not empty; otherwise, all usesrs will be returned guard !(searchBar.text?.isEmpty)! else { print("search is empty") self.loadingSymbol.isHidden = true self.tableView.isHidden = false return } searchLabel.text = searchText searchUsers(withUsername: searchBar.text!) { (error, users) in if error != nil{ print(error?.localizedDescription ?? "error searching usernames") } else{ DispatchQueue.main.async { self.returnedUsers = users ?? [] self.searchedUsersTable.reloadData() self.loadingSymbol.isHidden = true self.tableView.isHidden = false } } } } func scrollViewDidScroll(_ scrollView: UIScrollView) { searchBar.resignFirstResponder() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let username = returnedUsers[indexPath.item].username searchedUser = username performSegue(withIdentifier: "showUserProfile", sender: nil) } //setup table view func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return returnedUsers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! searchUsernamesCell; cell.selectionStyle = .none cell.username.text = returnedUsers[indexPath.item].username cell.profileImage.kf.indicatorType = .activity cell.profileImage.kf.setImage(with: returnedUsers[indexPath.item].profilePictureURL) circularImage(photoImageView: cell.profileImage) if (returnedUsers[indexPath.item].isVerified){ cell.verifiedIcon.isHidden = false } else{ cell.verifiedIcon.isHidden = true } return cell } //setup collection view func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: featuredCellID, for: indexPath) as! FeaturedProfilesCell cell.contentView.frame = cell.bounds return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //number of featured profiles return 3 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ return CGSize(width: view.frame.width, height: 130) } } class searchUsernamesCell: UITableViewCell { @IBOutlet weak var carrot: UIImageView! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var username: UILabel! @IBOutlet var verifiedIcon: UIImageView! } <file_sep>// // ConfirmAccountViewController.swift // Swap // // Created by Dr. Stephen, Ph.D on 12/8/16. // // import UIKit class ConfirmAccountViewController: UIViewController, UITextFieldDelegate { @IBOutlet var field1: UITextField! @IBOutlet var field2: UITextField! @IBOutlet var field3: UITextField! @IBOutlet var field4: UITextField! @IBOutlet var field5: UITextField! @IBOutlet var field6: UITextField! @IBOutlet var resendButton: UIButton! @IBOutlet var confirmButton: UIButton! /// This variable should be located in whatever view controller is used to sign in var passwordAuthenticationCompletion: AWSTaskCompletionSource<AnyObject>? override func viewDidAppear(_ animated: Bool) { saveViewController(viewController: self) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. field1.delegate = self field2.delegate = self field3.delegate = self field4.delegate = self field5.delegate = self field6.delegate = self field1.becomeFirstResponder() } @IBAction func didTapResendConfirmationCode(_ sender: UIButton) { resendConfirmationCode(toUserWithUsername: getUsernameOfSignedInUser()) } @IBAction func didConfirmCode(_ sender: UIButton) { guard let number1 = field1.text, let number2 = field2.text, let number3 = field3.text, let number4 = field4.text, let number5 = field5.text, let number6 = field6.text else{ return } let code = number1+number2+number3+number4+number5+number6 confirmUser(withCode: code, username: getSavedUsername()!, failed:{ UIAlertView(title: "Error", message: "Invalid Confirmation Code", delegate: nil, cancelButtonTitle: "Ok").show() }, succeded: { DispatchQueue.main.async { // Sign in the user self.signIn() } }) } @IBAction func didTapBack(_ sender: Any) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } @IBAction func enteredFirst(_ sender: Any) { field2.becomeFirstResponder() } @IBAction func enteredSecond(_ sender: Any) { field3.becomeFirstResponder() } @IBAction func enteredThird(_ sender: Any) { field4.becomeFirstResponder() } @IBAction func enteredFourth(_ sender: Any) { field5.becomeFirstResponder() } @IBAction func enteredFifth(_ sender: Any) { field6.becomeFirstResponder() } @IBAction func enteredSixth(_ sender: Any) { view.endEditing(true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // Constants.swift // Swap // // Created by <NAME> on 11/29/16. // // import Foundation import p2_OAuth2 // =================== Spotify Authorization Information ============================================ let SPOTIFY_CLIENT_ID = "28bd419f843a494faaafeef48a0962e0" let SPOTIFY_CLIENT_SECRET = "668e037a38b34d038686f40c85ed302e" let spotify_scope = "user-follow-modify user-read-email user-read-birthdate" let SPOTIFY_CALLBACK = "myapp://oauth/callback" let SPOTIFY_URL = "https://accounts.spotify.com/authorize" let SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token" let SPOTIFY_USER_URL = "https://api.spotify.com/v1/me" let SPOTIFY_FOLLOW_USER_URL = "https://api.spotify.com/v1/me/following" let spotify_settings = [ "client_id": SPOTIFY_CLIENT_ID, "client_secret": SPOTIFY_CLIENT_SECRET, "authorize_uri": SPOTIFY_URL, "token_uri": SPOTIFY_TOKEN_URL, // code grant only "scope": spotify_scope, "redirect_uris": [SPOTIFY_CALLBACK], // register the "myapp" scheme in Info.plist ["toapp://oauth/callback"] "keychain": true, // if you DON'T want keychain integration ] as OAuth2JSON let spotify_oauth2 = OAuth2CodeGrant(settings: spotify_settings) // =================== Spotify Authorization Information ============================================ // ===================== Instagram Authorization Information ======================================== let INSTAGRAM_CLIENT_ID = "22f7d645b33440399bfd78702c70276c" let INSTAGRAM_CLIENT_SECRET = "dd9df538eb77479eb523dd25eb276a93" let INSTAGRAM_CALLBACK = "https://localhost" let INSTAGRAM_AUTH_URL = "https://api.instagram.com/oauth/authorize" let INSTAGRAM_SCOPES = "basic relationships" //let INSTAGRAM_ACCESS_TOKEN_URI = "https://api.instagram.com/oauth/access_token" let instagram_settings = [ "client_id": INSTAGRAM_CLIENT_ID, "client_secret": INSTAGRAM_CLIENT_SECRET, "authorize_uri": INSTAGRAM_AUTH_URL, "token_uri": "https://api.instagram.com/oauth/access_token", "response_type": "code", "scope": INSTAGRAM_SCOPES, "redirect_uris": [INSTAGRAM_CALLBACK], // register the "myapp" scheme in Info.plist "secret_in_body": true, "keychain": true, // Keychain Integration "token_assume_unexpired": true, "verbose": true ] as OAuth2JSON let instagram_oauth2 = OAuth2CodeGrantNoTokenType(settings: instagram_settings) // ===================== Instagram Authorization Information ======================================== // =================== SoundCloud Authorization Information ========================================= let SoundCloud_ClientID = "5af081a8146cdd68e26c8fb1d1e1695a" let SoundCloud_ClientSecret = "fd12ea0959b076e51336aa9d5ac0d8d8" let SoundCloud_RedirectURI = "myapp://oauth/callback" let SOUNDCLOUD_AUTH_URL = "https://soundcloud.com/connect" let SOUNDCLOUD_TOKEN_URL = "https://API.soundcloud.com/oauth2/token" let soundcloud_settings = [ "client_id": SoundCloud_ClientID, "client_secret": SoundCloud_ClientSecret, "authorize_uri": SOUNDCLOUD_AUTH_URL, "token_uri": SOUNDCLOUD_TOKEN_URL, "response_type": "code", "scope": "non-expiring", "redirect_uris": [SoundCloud_RedirectURI], // register the "myapp" scheme in Info.plist "secret_in_body": true, "keychain": true, // Keychain Integration // "token_assume_unexpired": false, "verbose": true ] as OAuth2JSON let soundcloud_oauth2 = OAuth2CodeGrantNoTokenType(settings: soundcloud_settings) // =================== SoundCloud Authorization Information ========================================= // =================== Twitter Authorization Information ============================================ let TWITTER_CONSUMER_KEY = "vFuhhTMwYAZFEKJTOvLR0TbTU" let TWITTER_CONSUMER_SECRET = "<KEY>" let TWITTER_REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token" let TWITTER_AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize" let TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token" let twitter_settings = [ "client_id": TWITTER_CONSUMER_KEY, "client_secret": TWITTER_CONSUMER_SECRET, "authorize_uri": TWITTER_AUTHORIZE_URL, "token_uri": TWITTER_ACCESS_TOKEN_URL, // code grant only // "scope": , "redirect_uris": ["swap://"], // register the "myapp" scheme in Info.plist ["toapp://oauth/callback"] "keychain": true, // if you DON'T want keychain integration ] as OAuth2JSON let twitter_oauth2 = OAuth2CodeGrant(settings: twitter_settings) // =================== Twitter Authorization Information ============================================ //=================== Pinterest Authorization Information ==========================================// let token = "https://api.pinterest.com/v1/oauth/token" let PINTEREST_BASE = "https://api.pinterest.com/v1/" let APP_ID = "4853178264895635722" let APP_SECRET = "<KEY>" let PIN_REDIRECT = "https://localhost" let PINTEREST_URL = "https://api.pinterest.com/oauth" let scopes = "read_relationships,write_relationships,read_public" let response_type = "code" let pinterest_oauth2 = OAuth2CodeGrantNoTokenType(settings: [ "client_id": APP_ID, "client_secret": APP_SECRET, "authorize_uri": PINTEREST_URL, "token_uri": token, "redirect_uris": [PIN_REDIRECT], "scope": scopes, "keychain": true, "verbose": true, "secret_in_body": true ] as OAuth2JSON) // ==================================== YouTube Authoriation Info ================================== let GOOGLE_CLIENT_ID = "727584155719-j6d8on9k9h2vcb6ctggofg7ggp7reuhm.apps.googleusercontent.com" let googleURLScheme = "com.googleusercontent.apps.727584155719-j6d8on9k9h2vcb6ctggofg7ggp7reuhm:/oauth" var youtube_oauth2 = OAuth2CodeGrant(settings: [ "client_id": GOOGLE_CLIENT_ID, "authorize_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://www.googleapis.com/oauth2/v3/token", "scope": "https://www.googleapis.com/auth/plus.circles.read https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/youtube", // depends on the API you use "redirect_uris": [googleURLScheme], "keychain": true ]) // ==================================== YouTube Authoriation Info ================================== //=================== Reddit Authorization Information ==========================================// var reddit_oauth2: OAuth2CodeGrant = OAuth2CodeGrant(settings: [ "client_id": "s06QBYeHGLK8yg", "client_secret": "", "authorize_uri": "https://www.reddit.com/api/v1/authorize", "token_uri": "https://www.reddit.com/api/v1/access_token", "scope": "identity,edit,flair,history,mysubreddits,privatemessages,read,report,save,submit,subscribe,vote", // comma-separated, not space-separated scopes! "redirect_uris": ["http://swapapp.co"], // register scheme in Info.plist "parameters": ["duration": "permanent"], ]) //=================== Reddit Authorization Information ==========================================// //=================== GitHub Authorization Information ==========================================// let GITHUB_CLIENT_ID = "52e9a1b1e8f32e392c39" let GITHUB_CLIENT_SECRET = "1efa10c25aac49ed9527cb6385da8134365687af" let GITHUB_CALLBACK = "http://swapapp.co" var github_oauth2: OAuth2CodeGrant = OAuth2CodeGrant(settings: [ "client_id": GITHUB_CLIENT_ID, "client_secret": GITHUB_CLIENT_SECRET, "authorize_uri": "https://github.com/login/oauth/authorize", "token_uri": "https://github.com/login/oauth/access_token", "scope": "user user:follow", "redirect_uris": [GITHUB_CALLBACK], "secret_in_body": true, ]) //=================== GitHub Authorization Information ==========================================// //=================== Vimeo Authorization Information ==========================================// let VIMEO_CLIENT_ID = "134256550d9bb3189ff00892d18196b12cf858af" let VIMEO_CLIENT_SECRET = <KEY>" let VIMEO_AUTH_URL = "https://api.vimeo.com/oauth/authorize" let VIMEO_ACCESS_TOKEN_URL = "https://api.vimeo.com/oauth/access_token" let VIMEO_CALLBACK = "https://swapapp.co" var vimeo_oauth2: OAuth2CodeGrant = OAuth2CodeGrant(settings: [ "client_id": VIMEO_CLIENT_ID, "client_secret": VIMEO_CLIENT_SECRET, "authorize_uri": VIMEO_AUTH_URL, "token_uri": VIMEO_ACCESS_TOKEN_URL, "scope": "private interact create edit delete public video_files", "redirect_uris": [VIMEO_CALLBACK], // register scheme in Info.plist "secret_in_body": true, ]) //=================== Vimeo Authorization Information ==========================================// /** Simple class handling authorization and data requests with Reddit. */ class RedditLoader: OAuth2DataLoader { let baseURL = URL(string: "https://oauth.reddit.com")! public init() { let oauth = OAuth2CodeGrant(settings: [ "client_id": "s06QBYeHGLK8yg", // yes, this client-id will work! "client_secret": "", "authorize_uri": "https://www.reddit.com/api/v1/authorize", "token_uri": "https://www.reddit.com/api/v1/access_token", "scope": "identity,edit,flair,history,mysubreddits,privatemessages,read,report,save,submit,subscribe,vote", // note that reddit uses comma-separated, not space-separated scopes! "redirect_uris": ["http://swapapp.co"], // app has registered this scheme "parameters": ["duration": "permanent"], ]) oauth.authConfig.authorizeEmbedded = true oauth.logger = OAuth2DebugLogger(.trace) super.init(oauth2: oauth) alsoIntercept403 = true } /** Perform a request against the API and return decoded JSON or an Error. */ func request(path: String, callback: @escaping ((OAuth2JSON?, Error?) -> Void)) { let url = baseURL.appendingPathComponent(path) let req = oauth2.request(forURL: url) perform(request: req) { response in do { let dict = try response.responseJSON() if response.response.statusCode < 400 { DispatchQueue.main.async() { callback(dict, nil) } } else { DispatchQueue.main.async() { callback(nil, OAuth2Error.generic("\(response.response.statusCode)")) } } } catch let error { DispatchQueue.main.async() { callback(nil, error) } } } } func requestUserdata(callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { request(path: "api/v1/me", callback: callback) } func addFriend(withUsername: String, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { putRequest(path: "api/v1/me/friends/\(withUsername)", callback: callback) } /** Perform a request against the API and return decoded JSON or an Error. */ func putRequest(path: String, callback: @escaping ((OAuth2JSON?, Error?) -> Void)) { let url = baseURL.appendingPathComponent(path) var req = oauth2.request(forURL: url) req.httpMethod = "PUT" req.httpBody = "{}".data(using: .utf8) perform(request: req) { response in do { let dict = try response.responseJSON() if response.response.statusCode < 400 { DispatchQueue.main.async() { callback(dict, nil) } } else { DispatchQueue.main.async() { callback(nil, OAuth2Error.generic("\(response.response.statusCode)")) } } } catch let error { DispatchQueue.main.async() { callback(nil, error) } } } } } <file_sep>// // SettingUI.swift // Swap // // Created by <NAME> on 1/17/17. // // import Foundation func circularImage(photoImageView: UIImageView?) { photoImageView!.layer.frame = photoImageView!.layer.frame.insetBy(dx: 0, dy: 0) photoImageView!.layer.borderColor = (UIColor.black).cgColor//UIColor.init(red: 36, green: 174, blue: 199, alpha: 1).cgColor photoImageView!.layer.cornerRadius = photoImageView!.frame.height/2 photoImageView!.layer.masksToBounds = false photoImageView!.clipsToBounds = true photoImageView!.layer.borderWidth = 0.5 photoImageView!.contentMode = UIViewContentMode.scaleAspectFill } func circularImageNoBorder(photoImageView: UIImageView?){ photoImageView!.layer.frame = photoImageView!.layer.frame.insetBy(dx: 0, dy: 0) photoImageView!.layer.borderColor = (UIColor.clear).cgColor photoImageView!.layer.cornerRadius = photoImageView!.frame.height/2 photoImageView!.layer.masksToBounds = false photoImageView!.clipsToBounds = true photoImageView!.layer.borderWidth = 1.0 photoImageView!.contentMode = UIViewContentMode.scaleAspectFill } <file_sep>// // SwapUserHistory.swift // Swap // // Created by <NAME> on 12/21/16. // // import Foundation import AWSDynamoDB class SwapUserHistory{ /// The user who commits the Swap action var swap: String /// THe user who gets swapped var swapped: String /// Object refers to NoSQL database of users var NoSQL = AWSDynamoDBObjectMapper.default() /// Variable used to modify how data is stored in database var updateMapperConfig = AWSDynamoDBObjectMapperConfiguration() var currentTime = NSDate().timeIntervalSince1970 as NSNumber /// Creates a Swap User History Object with the swap and swapped usernames as partition and sort keys and automatically sets the time swapped in the Database init(swap: String = getUsernameOfSignedInUser(), swapped: String) { self.swap = swap self.swapped = swapped } func didShare(BirthdayIs: Bool? = nil, EmailIs: Bool? = nil, VineIs: Bool? = nil, PhonenumberIs: Bool? = nil, SpotifyIs: Bool? = nil, RedditIs: Bool? = nil, TwitterIs: Bool? = nil, YouTubeIs: Bool? = nil, SoundCloudIs: Bool? = nil, PinterestIs: Bool? = nil, InstagramIs: Bool? = nil, GitHubIs: Bool? = nil, VimeoIs: Bool? = nil, didGivePoints: Bool? = nil, latitude: String? = nil, longitude: String? = nil, completion: @escaping (_ error: Error?) -> Void = {noError in return}) { // Ensures that if a value is not passed in the function, it is ignored when saved into database updateMapperConfig.saveBehavior = .updateSkipNullAttributes /// Swap History Object for database let swapHistory = SwapHistory() // Each Swap History Row/Object in Database is identified by the person who swapped, 'swap' and the person that is swapped 'swapped' swapHistory?._swap = self.swap swapHistory?._swapped = self.swapped swapHistory?._time = currentTime swapHistory?._didShareBirthday = (BirthdayIs != nil) ? (BirthdayIs! as NSNumber) : nil swapHistory?._didShareEmail = (EmailIs != nil) ? (EmailIs! as NSNumber) : nil swapHistory?._didShareVine = (VineIs != nil) ? (VineIs! as NSNumber) : nil swapHistory?._didSharePhonenumber = (PhonenumberIs != nil) ? (PhonenumberIs! as NSNumber) : nil swapHistory?._didShareSpotify = (SpotifyIs != nil) ? (SpotifyIs! as NSNumber) : nil swapHistory?._didShareReddit = (RedditIs != nil) ? (RedditIs! as NSNumber) : nil swapHistory?._didShareTwitter = (TwitterIs != nil) ? (TwitterIs! as NSNumber) : nil swapHistory?._didShareYouTube = (YouTubeIs != nil) ? (YouTubeIs! as NSNumber) : nil swapHistory?._didShareSoundCloud = (SoundCloudIs != nil) ? (SoundCloudIs! as NSNumber) : nil swapHistory?._didSharePinterest = (PinterestIs != nil) ? (PinterestIs! as NSNumber) : nil swapHistory?._didShareInstagram = (InstagramIs != nil) ? (InstagramIs! as NSNumber) : nil swapHistory?._didShareGitHub = (GitHubIs != nil) ? (GitHubIs! as NSNumber) : nil swapHistory?._didShareVimeo = (VimeoIs != nil) ? (VimeoIs! as NSNumber) : nil swapHistory?._didGiveSwapPointsFromSwap = (didGivePoints != nil) ? (didGivePoints! as NSNumber) : nil swapHistory?._latitude = (latitude != nil) ? latitude! : nil swapHistory?._longitude = (longitude != nil) ? longitude! : nil NoSQL.save(swapHistory!, configuration: updateMapperConfig, completionHandler: { error in completion(error) }) } } <file_sep>// // SwapsViewController.swift // Swap // // Created by <NAME> on 1/14/17. // // import Foundation var swapHistoryUsers: [SwapHistory] = [] class SwapsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! @IBOutlet var activityView: UIActivityIndicatorView! var sharedSocialMedias: [UIImage] = [] override func viewDidLoad() { save(screen: .SwapsScreen) // loadSwaps() activityView.isHidden = true // Listens for reloadSwaps notification NotificationCenter.default.addObserver(self, selector: #selector(self.loadSwaps), name: .reloadSwaps, object: nil) } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return swapHistoryUsers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "swapsCell", for: indexPath) as! swapsTableCell; cell.selectionStyle = .none cell.profilePicture.kf.indicatorType = .activity let user = swapHistoryUsers[indexPath.item] sharedSocialMedias = getSharedSocialMedias(currentUser: user) if sharedSocialMedias.indices.contains(0){ cell.socialMedia1.image = sharedSocialMedias[0] } else{ cell.socialMedia1.image = nil } if sharedSocialMedias.indices.contains(1){ cell.socialMedia2.image = sharedSocialMedias[1] } else{ cell.socialMedia2.image = nil } if sharedSocialMedias.indices.contains(2){ cell.socialMedia3.image = sharedSocialMedias[2] } else{ cell.socialMedia3.image = nil } if sharedSocialMedias.indices.contains(3){ cell.socialMedia4.image = sharedSocialMedias[3] } else{ cell.socialMedia4.image = nil } if sharedSocialMedias.indices.contains(4){ cell.socialMedia5.image = sharedSocialMedias[4] } else{ cell.socialMedia5.image = nil } if sharedSocialMedias.indices.contains(5){ cell.socialMedia6.image = sharedSocialMedias[5] } else{ cell.socialMedia6.image = nil } if sharedSocialMedias.indices.contains(6){ cell.socialMedia7.image = sharedSocialMedias[6] } else{ cell.socialMedia7.image = nil } if sharedSocialMedias.indices.contains(7) { cell.socialMedia8.image = sharedSocialMedias[7] } else{ cell.socialMedia8.image = nil } if sharedSocialMedias.indices.contains(8) { cell.socialMedia9.image = sharedSocialMedias[8] } else{ cell.socialMedia9.image = nil } if sharedSocialMedias.indices.contains(9){ cell.socialMedia10.image = sharedSocialMedias[9] } else{ cell.socialMedia10.image = nil } cell.swapDate.text = user._time?.timeAgo() if let userInfo = user.user{ print("Already saved profile picture and name and do not need to load from database") // Set profile pic and name so that we do not have to fetch from database cell.profilePicture.kf.setImage(with: URL(string: userInfo._profilePictureUrl ?? "")) circularImage(photoImageView: cell.profilePicture) cell.username.text = "\(userInfo._firstname ?? "") \(userInfo._lastname ?? "")" } else{ // Go fetch profile pic and name from database print("fetching swap history attributes from database") SwapUser(username: user._swapped!).getInformation(completion: {(error, fetchedUser) in cell.profilePicture.kf.setImage(with: URL(string: (fetchedUser?._profilePictureUrl)!)) circularImage(photoImageView: cell.profilePicture) // Save the object in the cell to reduce loading user.user = fetchedUser DispatchQueue.main.async { cell.username.text = (fetchedUser?._firstname)! + " " + (fetchedUser?._lastname)! } }) } /* // Check if we already set the profile url in the object if let profilePicURL = swapHistoryUsers[indexPath.item].profileImageURL, let firstname = swapHistoryUsers[indexPath.item].firstname, let lastname = swapHistoryUsers[indexPath.item].lastname { print("Already saved profile picture and name and do not need to load from database") // Set profile pic and name so that we do not have to fetch from database cell.profilePicture.kf.setImage(with: profilePicURL) circularImage(photoImageView: cell.profilePicture) cell.username.text = "\(firstname) \(lastname)" } else{ // Go fetch profile pic and name from database print("fetching swap history attributes from database") SwapUser(username: user._swapped!).getInformation(completion: {(error, user) in cell.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) circularImage(photoImageView: cell.profilePicture) // set the image in the object swapHistoryUsers[indexPath.item].profileImageURL = URL(string: (user?._profilePictureUrl)!) DispatchQueue.main.async { cell.username.text = (user?._firstname)! + " " + (user?._lastname)! // set the name in the object swapHistoryUsers[indexPath.item].firstname = user?._firstname! swapHistoryUsers[indexPath.item].lastname = user?._lastname! } }) } */ return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { searchedUser = swapHistoryUsers[indexPath.item]._swapped! self.performSegue(withIdentifier: "ShowSwapsUserProfile", sender: nil) } func getSharedSocialMedias(currentUser: SwapHistory) -> [UIImage]{ var images: [UIImage] = [] if (currentUser._didShareInstagram as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "InstagramBlackIcon")) } if (currentUser._didShareTwitter as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "TwitterBlackIcon")) } if (currentUser._didShareSpotify as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "SpotifyBlackIcon")) } if (currentUser._didShareEmail as? Bool) ?? false || (currentUser._didSharePhonenumber as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "ProfileBlackIcon")) } if (currentUser._didShareSoundCloud as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "SoundCloudBlackIcon")) } if (currentUser._didSharePinterest as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "PinterestBlackIcon")) } if (currentUser._didShareGitHub as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "GithubBlackIcon")) } if (currentUser._didShareReddit as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "RedditBlackIcon")) } if (currentUser._didShareYouTube as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "YouTubeBlackIcon")) } if (currentUser._didShareVimeo as? Bool) ?? false{ images.append(#imageLiteral(resourceName: "VimeoBlackIcon")) } return images } func loadSwaps() { clearSwapMapUserPhotos() swapHistoryUsers.removeAll() SwapUser().getSwapHistory { (error, swapHistory) in if error != nil{ print("error retriving swap history") refreshControl.endRefreshing() } else{ DispatchQueue.main.async { self.activityView.isHidden = true swapHistoryUsers = swapHistory! refreshControl.endRefreshing() self.tableView.reloadData() } } } } } class swapsTableCell: UITableViewCell { @IBOutlet var socialMedia1: UIImageView! @IBOutlet var socialMedia2: UIImageView! @IBOutlet var socialMedia3: UIImageView! @IBOutlet var socialMedia4: UIImageView! @IBOutlet var socialMedia5: UIImageView! @IBOutlet var socialMedia6: UIImageView! @IBOutlet var socialMedia7: UIImageView! @IBOutlet var socialMedia8: UIImageView! @IBOutlet var socialMedia9: UIImageView! @IBOutlet var socialMedia10: UIImageView! @IBOutlet var profilePicture: UIImageView! @IBOutlet var swapDate: UILabel! @IBOutlet var username: UILabel! var user: Users? } <file_sep>// // Tweet.swift // Swap // // Created by <NAME> on 1/15/17. // // import Foundation //import RealmSwift import Swifter /* class Tweet: Object { dynamic var dateCreated : Date = "Fri Sep 9 6:38:00 +0000 2016".toDate() // Format: Wed Aug 29 17:12:58 +0000 2012 dynamic var isFavorite: Bool = false dynamic var id: String = "" dynamic var text: String = "" dynamic var retweetCount: Double = 0 dynamic var containsSensitiveContent: Bool = false dynamic var nameOfCreator: String = "" dynamic var profileImageLinkOfCreator: String = "" dynamic var creatorIsVerified: Bool = false dynamic var usernameOfCreator: String = "" dynamic var favoritesCount: Double = 0 dynamic var isARetweet: Bool = false dynamic var isAReply: Bool = false } func returnTweet(fromJSON: SwifteriOS.JSON) -> Tweet { let tweet = Tweet() // Check if it's a Retweet if fromJSON["retweeted"].bool! { // It's a retweet tweet.isARetweet = true tweet.isAReply = false // Get the Retweeted JSON let retweetJSON = fromJSON["retweeted_status"] tweet.isFavorite = retweetJSON["favorited"].bool! tweet.retweetCount = retweetJSON["retweet_count"].double! tweet.dateCreated = retweetJSON["created_at"].string!.toDate() tweet.text = retweetJSON["text"].string! tweet.id = retweetJSON["id_str"].string! tweet.favoritesCount = retweetJSON["favorite_count"].double! // Creator Information let userJSON = retweetJSON["user"] tweet.profileImageLinkOfCreator = userJSON["profile_image_url_https"].string! tweet.creatorIsVerified = userJSON["verified"].bool! tweet.nameOfCreator = userJSON["name"].string! tweet.usernameOfCreator = userJSON["screen_name"].string! } else{ // It is not a retweet tweet.isARetweet = false tweet.isAReply = false tweet.isFavorite = fromJSON["favorited"].bool! tweet.retweetCount = fromJSON["retweet_count"].double! tweet.dateCreated = fromJSON["created_at"].string!.toDate() tweet.text = fromJSON["text"].string! tweet.id = fromJSON["id_str"].string! tweet.favoritesCount = fromJSON["favorite_count"].double! // Creator Information let userJSON = fromJSON["user"] tweet.profileImageLinkOfCreator = userJSON["profile_image_url_https"].string! tweet.creatorIsVerified = userJSON["verified"].bool! tweet.nameOfCreator = userJSON["name"].string! tweet.usernameOfCreator = userJSON["screen_name"].string! } return tweet } func returnTweets(fromJSON: SwifteriOS.JSON) -> List<Tweet>? { if let tweetJsons = fromJSON.array{ let allTweets: List<Tweet> = List<Tweet>() for json in tweetJsons { allTweets.append(returnTweet(fromJSON: json)) } return allTweets } else{ return nil } } */ <file_sep>// // SearchUsers.swift // Swap // // Created by <NAME> on 12/28/16. // // import Foundation import AWSCognitoIdentityProvider /// Function to search for users by username /// /// - Parameters: /// - withUsername: Pass a partial username string to search for /// - completion: Returns an error and an array of SwapUser objects. Ensure that you unwrap the SwapUser array before iterating, also, be certain that there is no error (error == nil) before unwraping users array because it will be 'nil' if there is an error. Each SwapUser object contains the username and profile link url. See SwapUser class for more information. See exmaple in the function body. func searchUsers(withUsername: String, completion: @escaping (_ error: Error?, _ users: [SwapUser]? ) -> Void ) { /*: - Example: searchUsers(withUsername: "mic", completion:{ (error, users) in if error != nil{ // There is an error. No not attempt to unwrap users array } else { // There is no error. Now you can unwrap users array for user in users!{ print("the user is .. \(user.username) and the verification status is ... \(user.isVerified) and the profile picture is ... \(user.profilePictureURL)") } } }) */ let getUsersRequest = AWSCognitoIdentityProviderListUsersRequest() getUsersRequest?.userPoolId = AWSCognitoUserPoolId getUsersRequest?.filter = "username ^= \"\(withUsername.lowercased())\"" getUsersRequest?.attributesToGet = ["profile", "picture"] getUsersRequest?.limit = 10 idManager.listUsers(getUsersRequest!, completionHandler: { (response, error) in if error != nil{ print("Could not search with error ... \(error)") completion(error, nil) } else{ if response != nil{ if let users = response?.users{ completion(nil, convertCognitoUsersArrayToSwapUsersArray(users: users)) } else{ completion(UserError.Unknown, nil) } } else{ completion(UserError.Unknown, nil) } } }) } func convertCognitoUserToSwapUser(user: AWSCognitoIdentityProviderUserType ) -> SwapUser { var isVerified: Bool = false var link: URL = URL(string: defaultImage)! let Username = user.username! var swap_user = SwapUser(username: Username) let attributes = user.attributes! for attribute in attributes{ if attribute.name == "profile" && attribute.value == "IS_VERIFIED"{ // USER IS VERIFIED isVerified = true } if attribute.name == "picture"{ link = URL(string: attribute.value!)! } } swap_user.isVerified = isVerified swap_user.profilePictureURL = link return swap_user } func convertCognitoUsersArrayToSwapUsersArray(users: [AWSCognitoIdentityProviderUserType]) -> [SwapUser] { var SwapUsers: [SwapUser] = [] for user in users{ if user.userStatus.rawValue == 2{ SwapUsers.append(convertCognitoUserToSwapUser(user: user)) } } return SwapUsers } <file_sep>// // ProfileViewController.swift // Swap // // Created by Dr. Stephen, Ph.D on 12/8/16. // Editors: <NAME> // import UIKit import Kingfisher import Spring import Alamofire import Firebase import GeoFire class ProfileViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate { //labels @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var pointsLabel: UILabel! @IBOutlet weak var swapsLabel: UILabel! @IBOutlet weak var swappedLabel: UILabel! @IBOutlet var pointsNumberLabel: UILabel! @IBOutlet var swapsNumberLabel: UILabel! @IBOutlet var swappedNumberLabel: UILabel! //image views @IBOutlet weak var profilePicImageView: UIImageView! @IBOutlet weak var swapCodeImageView: UIImageView! @IBOutlet var GradientBottomLine: UIImageView! @IBOutlet var verifiedIcon: UIImageView! @IBOutlet var Topper: UIImageView! //buttons @IBOutlet weak var Spotify: UIButton! @IBOutlet weak var Phone: UIButton! @IBOutlet weak var Email: UIButton! @IBOutlet var Vimeo: UIButton! @IBOutlet var Twitter: UIButton! @IBOutlet var YouTube: UIButton! @IBOutlet var SoundCloud: UIButton! @IBOutlet var Pinterest: UIButton! @IBOutlet var Reddit: UIButton! @IBOutlet var Github: UIButton! @IBOutlet var Instagram: UIButton! @IBOutlet var infoIcon: UIButton! @IBOutlet var bioTextField: UITextField! @IBOutlet var loadingIndicator: UIActivityIndicatorView! @IBAction func didToggleSocialMediaPermission(_ sender: UIButton) { toogleSocialMedia(sender: sender) } @IBAction func didTapShareButton(_ sender: Any) { DispatchQueue.main.async { self.performSegue(withIdentifier: "showSwapLink", sender: nil) } } @IBAction func didTapProfilePic(_ sender: Any) { let actionSheeet = UIAlertController(title: "Change Picture", message: nil, preferredStyle: .actionSheet) actionSheeet.addAction(UIAlertAction(title: "Upload Picture", style: .default, handler: { (action) in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) { var imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary; imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } })) actionSheeet.addAction(UIAlertAction(title: "Take Picture", style: .default, handler: { (alert) in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { var imagePicker = UIImagePickerController() imagePicker.delegate = self as! UIImagePickerControllerDelegate & UINavigationControllerDelegate imagePicker.sourceType = UIImagePickerControllerSourceType.camera; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } })) actionSheeet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheeet, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.setupViewController() self.loadProfile() self.setupSwapCodeGestureRecognizer() // Listens for reloadProfile notification NotificationCenter.default.addObserver(self, selector: #selector(self.loadProfile), name: .reloadProfile, object: nil) // Listens for a change in swap code color NotificationCenter.default.addObserver(self, selector: #selector(self.changeSwapCodeToBlue), name: .changeSwapCodeToBlue, object: nil) // Listens for a change in swap code color NotificationCenter.default.addObserver(self, selector: #selector(self.changeSwapCodeToDark), name: .changeSwapCodeToDark, object: nil) if !UserDefaults.standard.bool(forKey: "didShowTutorial"){ self.performSegue(withIdentifier: "showTutorial", sender: nil) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) save(screen: .UserProfileScreen) } func textFieldDidEndEditing(_ textField: UITextField) { //upload the updated user bio let Userbio = bioTextField.text SwapUser().set(Bio: Userbio) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { bioTextField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { self.dismiss(animated: true, completion: nil) if let image = info[UIImagePickerControllerEditedImage] as? UIImage { let imageData = UIImageJPEGRepresentation(image, 1.0) DispatchQueue.main.async { SwapUser().uploadProfilePicture(withData: imageData!, completion: { (error) in }) } NotificationCenter.default.post(name: .reloadProfile, object: nil) } else{ let image = info[UIImagePickerControllerOriginalImage] as? UIImage let imageData = UIImageJPEGRepresentation(image!, 1.0) DispatchQueue.main.async { SwapUser().uploadProfilePicture(withData: imageData!, completion: { (error) in }) } NotificationCenter.default.post(name: .reloadProfile, object: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ /// Shows the loading symbol and reloads the profile data. func loadProfile() { loadSwapAndSwapHistoryInBackground() clearSwapMapUserPhotos() // Hide UI or do whatever to show that the profile is loading self.loadingIndicator.startAnimating() self.nameLabel.isHidden = true self.pointsLabel.isHidden = true self.swapsLabel.isHidden = true self.swappedLabel.isHidden = true self.pointsNumberLabel.isHidden = true self.swappedNumberLabel.isHidden = true self.swapsNumberLabel.isHidden = true self.GradientBottomLine.isHidden = true self.profilePicImageView.isHidden = true self.swapCodeImageView.isHidden = true self.Spotify.isHidden = true self.Phone.isHidden = true self.Email.isHidden = true self.Vimeo.isHidden = true self.Twitter.isHidden = true self.YouTube.isHidden = true self.SoundCloud.isHidden = true self.Pinterest.isHidden = true self.Reddit.isHidden = true self.Github.isHidden = true self.Instagram.isHidden = true self.bioTextField.isHidden = true self.infoIcon.isHidden = true self.verifiedIcon.isHidden = true //Gets info of signed in user // SwapUser(username: getUsernameOfSignedInUser()).getInformation(completion: { (error, user) in if error != nil{ // There is an error // Note -- <NAME> -- Should Handle this in the future refreshControl.endRefreshing() } else{ // Data is now loaded so stop any loading UI self.loadingIndicator.isHidden = true self.nameLabel.isHidden = false self.pointsLabel.isHidden = false self.swapsLabel.isHidden = false self.swappedLabel.isHidden = false self.pointsNumberLabel.isHidden = false self.swapsNumberLabel.isHidden = false self.swappedNumberLabel.isHidden = false self.GradientBottomLine.isHidden = false self.profilePicImageView.isHidden = false self.swapCodeImageView.isHidden = false self.Spotify.isHidden = false self.Phone.isHidden = false self.Email.isHidden = false self.Vimeo.isHidden = false // Change this to Reddit self.Twitter.isHidden = false self.YouTube.isHidden = false self.SoundCloud.isHidden = false self.Pinterest.isHidden = false self.Reddit.isHidden = false self.Github.isHidden = false self.Instagram.isHidden = false self.bioTextField.isHidden = false self.infoIcon.isHidden = false if (user?._isVerified?.boolValue ?? false){ self.verifiedIcon.isHidden = false } //Gets the Profile Information from User Object let firstname = user?._firstname ?? "" let lastname = user?._lastname ?? "" let points = user?._points ?? 0 let swaps = user?._swaps ?? 0 let swapped = user?._swapped ?? 0 let bio = user?._bio ?? "" let willShareSpotify = (user?._willShareSpotify as? Bool) ?? false let willShareEmail = (user?._willShareEmail as? Bool) ?? false let willSharePhone = (user?._willSharePhone as? Bool) ?? false let profileImageUrl = user?._profilePictureUrl ?? "http://www.american.edu/uploads/profiles/large/chris_palmer_profile_11.jpg" let swapCodeImageUrl = "https://unitag-qr-code-generation.p.mashape.com/api?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22transparent%22%2C%22COLOR1%22%3A%22262626%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2F38436a5c234f2c0817f2e83903d33287.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http%3A%2F%2Fgetswap.me%2F\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" // Updates UI self.nameLabel.text = "\(firstname) \(lastname)" self.bioTextField.text = "\(bio)" self.pointsNumberLabel.text = "\(abbreviateNumber(num: points ?? 0 ))" self.swapsNumberLabel.text = "\(abbreviateNumber(num: swaps ?? 0))" self.swappedNumberLabel.text = "\(abbreviateNumber(num: swapped ?? 0 ))" // Disable Permissions if they are not connected self.Spotify.isEnabled = spotifyIsConnected() self.Email.isEnabled = !(user?._email?.isEmpty ?? false) self.Phone.isEnabled = !(user?._phonenumber?.isEmpty ?? false) self.Reddit.isEnabled = redditIsConnected() self.Instagram.isEnabled = instagramIsConnected() self.Twitter.isEnabled = twitterIsConnected() self.YouTube.isEnabled = youtubeIsConnected() self.SoundCloud.isEnabled = soundcloudIsConnected() self.Pinterest.isEnabled = pinterestIsConnected() self.Vimeo.isEnabled = vimeoIsConnected() self.Github.isEnabled = githubIsConnected() self.Spotify.isSelected = willShareSpotify self.Email.isSelected = willShareEmail self.Phone.isSelected = willSharePhone self.Reddit.isSelected = (user?._willShareReddit as? Bool) ?? false self.Instagram.isSelected = (user?._willShareInstagram as? Bool) ?? false self.Twitter.isSelected = (user?._willShareTwitter as? Bool) ?? false self.YouTube.isSelected = (user?._willShareYouTube as? Bool) ?? false self.SoundCloud.isSelected = (user?._willShareSoundCloud as? Bool) ?? false self.Pinterest.isSelected = (user?._willSharePinterest as? Bool) ?? false self.Vimeo.isSelected = (user?._willShareVimeo as? Bool) ?? false self.Github.isSelected = (user?._willShareGitHub as? Bool) ?? false self.profilePicImageView.kf.indicatorType = .activity self.profilePicImageView.kf.setImage(with: URL(string: profileImageUrl)) circularImageNoBorder(photoImageView: self.profilePicImageView) self.setupSwapCodeImage() //Stop pull refresh here . refreshControl.endRefreshing() if let notificationID = user?._notification_id_one_signal { if notificationID == "0"{ SwapUser().setUpPushNotifications() } } } }) } /// Will also send a notification to update Map func loadSwapAndSwapHistoryInBackground() { swapHistoryUsers.removeAll() swappedHistoryUsers.removeAll() DispatchQueue.global(qos: .background).async { SwapUser().getSwapHistory(result: { (error, history) in DispatchQueue.main.async { let swaps = history?.count swapHistoryUsers = history ?? [] print("\n\n\n\n The Swap History is : \(swapHistoryUsers) and the count is \(swapHistoryUsers.count)") NotificationCenter.default.post(name: .reloadMap, object: nil) } }) SwapUser().getSwappedHistory(result: { (error, history) in DispatchQueue.main.async { let swapped = history?.count swappedHistoryUsers = history ?? [] print("\n\n\n\n The Swapped History is : \(swapHistoryUsers)") } }) } } func setupViewController() { removePlaceHoldersAndAdjustFontsByLabelWidth() DispatchQueue.main.async { slideLeft(label: self.nameLabel) slideRight(image: self.profilePicImageView) } saveViewController(viewController: nil) //set delegates bioTextField.delegate = self // CONFIGURING THE MAIN TAB BAR CONTROLLER tabBarController?.tabBar.backgroundImage = UIImage(named: "TabBarBackground") tabBarController?.tabBar.isTranslucent = false tabBarController?.tabBar.tintColor = UIColor.init(red: 0, green: 144, blue: 255, alpha: 1.0) let tabBarItem1 = tabBarController?.tabBar.items![0] let tabBarItem2 = tabBarController?.tabBar.items![1] let tabBarItem3 = tabBarController?.tabBar.items![2] let tabBarItem4 = tabBarController?.tabBar.items![3] tabBarItem1?.selectedImage = #imageLiteral(resourceName: "HomeIconSelected") tabBarItem2?.selectedImage = #imageLiteral(resourceName: "SearchIconSelected") tabBarItem3?.selectedImage = #imageLiteral(resourceName: "NotificationIconSelected") tabBarItem4?.selectedImage = #imageLiteral(resourceName: "ExploreIconSelected") if #available(iOS 10.0, *) { tabBarController?.tabBar.unselectedItemTintColor = UIColor.white } self.setupSwipeGestureRecognizers(allowCyclingThoughTabs: true) //set up nav controller let navBar = self.navigationController?.navigationBar self.navigationController?.interactivePopGestureRecognizer?.delegate = self navBar?.setBackgroundImage(#imageLiteral(resourceName: "Header1"), for: .default) navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont(name: "Avenir Next Ultra Light", size: 21)!] navBar?.tintColor = UIColor.white //navBar?.isTranslucent = false let topper = UIImageView(image: #imageLiteral(resourceName: "RoundWhiteTopper")) topper.frame = Topper.frame self.navigationController?.view.addSubview(topper) // Set the selected photos for when the social media icons are toggled Spotify.setImage(#imageLiteral(resourceName: "SpotifyEnabled"), for: .selected) Email.setImage(#imageLiteral(resourceName: "EmailEnabled"), for: .selected) Phone.setImage(#imageLiteral(resourceName: "PhoneEnabled"), for: .selected) Reddit.setImage(#imageLiteral(resourceName: "RedditEnabled"), for: .selected) Instagram.setImage(#imageLiteral(resourceName: "InstagramEnabled"), for: .selected) Github.setImage(#imageLiteral(resourceName: "GithubEnabled"), for: .selected) Vimeo.setImage(#imageLiteral(resourceName: "VimeoEnabled"), for: .selected) Twitter.setImage(#imageLiteral(resourceName: "TwitterEnabled"), for: .selected) YouTube.setImage(#imageLiteral(resourceName: "YouTubeEnabled"), for: .selected) SoundCloud.setImage(#imageLiteral(resourceName: "SoundCloudEnabled"), for: .selected) Pinterest.setImage(#imageLiteral(resourceName: "PinterestEnabled"), for: .selected) } func toogleSocialMedia(sender: UIButton) { let status: Bool = !sender.isSelected sender.isSelected = !sender.isSelected switch sender { case Spotify: SwapUser(username: getUsernameOfSignedInUser() ).set(WillShareSpotify: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Phone: SwapUser(username: getUsernameOfSignedInUser()).set(WillSharePhonenumber: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Email: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareEmail: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Reddit: SwapUser(username: getUsernameOfSignedInUser() ).set(WillShareReddit: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Instagram: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareInstagram: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Twitter: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareTwitter: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case YouTube: SwapUser(username: getUsernameOfSignedInUser() ).set(WillShareYouTube: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case SoundCloud: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareSoundCloud: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Pinterest: SwapUser(username: getUsernameOfSignedInUser()).set(WillSharePinterest: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Vimeo: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareVimeo: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break case Github: SwapUser(username: getUsernameOfSignedInUser()).set(WillShareGitHub: status, DidSetInformation: { return nil }, CannotSetInformation: { sender.isSelected = !sender.isSelected }) break default: break } } /// Sets up the gesture recognizer for the Swap Code func setupSwapCodeGestureRecognizer() { swapCodeImageView.isUserInteractionEnabled = true //now you need a tap gesture recognizer //note that target and action point to what happens when the action is recognized. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ProfileViewController.doubleTappedSwapCode(_:))) tapRecognizer.numberOfTapsRequired = 2 //Add the recognizer to your view. swapCodeImageView.addGestureRecognizer(tapRecognizer) } /// Called when the Swap Code is Double Tapped. Should turn on/off all permissions. func doubleTappedSwapCode(_ gestureRecognizer: UITapGestureRecognizer) { var countOfTrue = 0 let buttons: [UIButton] = [Reddit, Spotify, Phone, Email, Instagram, Github, Vimeo, Twitter, YouTube, SoundCloud, Pinterest] for button in buttons{ if button.isSelected { countOfTrue += 1 } } if countOfTrue >= 6 { // More enabled buttons than disabled so turn off all // Toggle Permissions toggleAllPermissions(as: false) } else{ // turn on // Toggle Permissions toggleAllPermissions(as: true) } } /// Turns on/off all permissions in database and in UI. func toggleAllPermissions(as state: Bool) { SwapUser().set( WillShareSpotify: state, WillShareYouTube: state, WillSharePhonenumber: state, WillShareVine: state, WillShareInstagram: state, WillShareTwitter: state, WillShareEmail: state, WillShareReddit: state, WillSharePinterest: state, WillShareSoundCloud: state, WillShareGitHub: state, WillShareVimeo: state, DidSetInformation:{ // Turn on all buttons self.toggleAllButtons(as: state) }) } /// Toggles buttons on or off given the state. Does NOT alter information in database! func toggleAllButtons(as state: Bool) { Reddit.isSelected = state Spotify.isSelected = state Phone.isSelected = state Email.isSelected = state Instagram.isSelected = state Github.isSelected = state Vimeo.isSelected = state Twitter.isSelected = state YouTube.isSelected = state SoundCloud.isSelected = state Pinterest.isSelected = state } func removePlaceHoldersAndAdjustFontsByLabelWidth() { nameLabel.shouldHidePlaceholderText = true nameLabel.adjustsFontSizeToFitWidth = true pointsNumberLabel.adjustsFontSizeToFitWidth = true swapsNumberLabel.adjustsFontSizeToFitWidth = true swappedNumberLabel.adjustsFontSizeToFitWidth = true } func setupSwapCodeImage() { print("the username of the signed in user is ... \(getUsernameOfSignedInUser())") self.swapCodeImageView.kf.indicatorType = .activity //determines the color of the swap codese let swapCodeColorShouldBeBlue = UserDefaults.standard.bool(forKey: "SwapCodeColorBlue") // Ternary Statement determines the value of defaultSwapCodeImageURL based on the user's settings let defaultSwapCodeImageURL = swapCodeColorShouldBeBlue ? blueSwapCodeURL : darkSwapCodeURL // Try to use old url first swapCodeImageView.kf.setImage(with: URL(string:defaultSwapCodeImageURL), placeholder: nil, options: nil, progressBlock: nil) { (image, error, type, url) in if let error = error{ print("Can't use old url") // Could not set it up with old url so try the paid version if let swapCodeImage = getSwapCodeImage(){ print("there is a swap code image saved") self.swapCodeImageView.image = swapCodeImage } else{ print("there is no swap code image saved") // Download Swap Code Image, Set it in Database let newSwapCodeImageURL = "https://unitag-qr-code-generation.p.mashape.com/api?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22transparent%22%2C%22COLOR1%22%3A%22262626%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2F38436a5c234f2c0817f2e83903d33287.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http%3A%2F%2Fgetswap.me%2F\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" // Set the image by calling HTTP Request let header: HTTPHeaders = ["X-Mashape-Key": "<KEY>"] Alamofire.request(newSwapCodeImageURL, method: .get, parameters: nil, headers: header).responseData(completionHandler: { (data) in if let data = data.data{ // Save Data save(swapCodeImageData: data) self.swapCodeImageView.image = UIImage(data: data) } }) } } else{ print("can use old url") } } } func changeSwapCodeToBlue() { self.swapCodeImageView.kf.setImage(with: URL(string: blueSwapCodeURL)) } func changeSwapCodeToDark() { self.swapCodeImageView.kf.setImage(with: URL(string: darkSwapCodeURL)) } } func slideLeft(label: UILabel){ let layer = label as! SpringLabel layer.animation = "squeezeLeft" layer.curve = "easeIn" layer.duration = 1.0 layer.animate() } func slideRight(image: UIImageView){ let layer = image as! SpringImageView layer.animation = "squeezRight" layer.curve = "easeIn" layer.duration = 1.0 layer.animate() } /// The 'free version' of the Swap Code URL Image via API let darkSwapCodeURL = "https://dashboard.unitag.io/qreator/generate?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22transparent%22%2C%22COLOR1%22%3A%22262626%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2F38436a5c234f2c0817f2e83903d33287.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http%3A%2F%2Fgetswap.me%2F\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" let blueSwapCodeURL = "https://dashboard.unitag.io/qreator/generate?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22transparent%22%2C%22COLOR1%22%3A%2203E4F3%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2Fe70b5ccd3ca5554615433abeae699420.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http%3A%2F%2Fgetswap.me%2F\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" /// The Paid version of the Swap Code URL Image via API let version2SwapCodeURL = "https://unitag-qr-code-generation.p.mashape.com/api?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22ffffff%22%2C%22COLOR1%22%3A%2203E4F3%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2Fe70b5ccd3ca5554615433abeae699420.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http://getswap.me/\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" func abbreviateNumber(num: NSNumber) -> String { // less than 1000, no abbreviation let num = num as Int if num < 1000 { return "\(num)" } // less than 1 million, abbreviate to thousands if num < 1000000 { var n = Double(num); n = Double( floor(n/100)/10 ) return "\(n.description)k" } // more than 1 million, abbreviate to millions var n = Double(num) n = Double( floor(n/100000)/10 ) return "\(n.description)m" } <file_sep>// // FeaturedProfilesCell.swift // Swap // // Created by <NAME> on 3/5/17. // // import UIKit class FeaturedProfilesCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{ private let cellId = "profilesCellId" override init(frame: CGRect){ super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let profilesCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor.clear collectionView.translatesAutoresizingMaskIntoConstraints = false return collectionView }() func setupView(){ backgroundColor = UIColor.clear addSubview(profilesCollectionView) profilesCollectionView.dataSource = self profilesCollectionView.delegate = self profilesCollectionView.register(ProfileCell.self, forCellWithReuseIdentifier: cellId) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[v0]-12-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profilesCollectionView])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-15-[v0]-15-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profilesCollectionView])) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 120, height: frame.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14) } class ProfileCell: UICollectionViewCell { override init(frame: CGRect){ super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let imageView: UIImageView = { let iv = UIImageView() iv.image = #imageLiteral(resourceName: "DefaultProfileImage") iv.contentMode = .scaleAspectFill iv.layer.masksToBounds = true return iv }() let nameLabel: UILabel = { let label = UILabel() label.text = "Featured" label.font = UIFont.systemFont(ofSize: 12) label.textAlignment = .center return label }() func setupView(){ addSubview(imageView) addSubview(nameLabel) imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width) nameLabel.frame = CGRect(x: 0, y: (frame.height/2) + 20, width: frame.width, height: 40) } } } <file_sep>// // YoutubeView.swift // Swap // // Created by <NAME> on 4/27/17. // // import Foundation var YouTubeUserID: String? = nil var YouTubePreviewUser: Users? = nil class YoutubeView: UIViewController, UITableViewDelegate, UITableViewDataSource { var youtubeVideos: [YouTubeMedia] = [] @IBOutlet var tableView: UITableView! override func viewDidLoad() { loadYouTubePreview() } func loadYouTubePreview() { let user = YouTubeUser(id: YouTubeUserID ?? "") tableView.separatorStyle = .none user.getMedia { (YoutubeMedias) in print(YoutubeMedias?.count ?? 0) for media in YoutubeMedias!{ self.youtubeVideos.append(media) } if self.youtubeVideos.count == 0 || (self.youtubeVideos.count - 1) == 0{ let blankTableMessage = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) blankTableMessage.text = "No Youtube Videos" blankTableMessage.textColor = .black blankTableMessage.textAlignment = NSTextAlignment.center blankTableMessage.font = UIFont(name: "Avenir-Next", size: 20) blankTableMessage.sizeToFit() self.tableView.backgroundView = blankTableMessage self.view.backgroundColor = UIColor.white } else{ self.view.backgroundColor = UIColor(hex: "#272931") } self.tableView.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return youtubeVideos.count - 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currentVideo = youtubeVideos[indexPath.row] let videoURL = "https://www.youtube.com/embed/\(currentVideo.videoID)" let cell = tableView.dequeueReusableCell(withIdentifier: "videoCell", for: indexPath) as! YouTubeVideoCell; cell.selectionStyle = .none // Set the video view cell.videoView.scrollView.contentInset = UIEdgeInsets.zero let url = URL(string: videoURL) let request = URLRequest(url: url!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 15.0) cell.videoView.loadRequest(request) cell.videoView.allowsInlineMediaPlayback = false cell.videoView.scrollView.isScrollEnabled = false cell.channelName.text = currentVideo.channelTitle cell.datePosted.text = currentVideo.datePublished.stringValueShort cell.setProfilePicture(imageURL: URL(string: (YouTubePreviewUser?._profilePictureUrl)!)!) return cell } } class YouTubeVideoCell: UITableViewCell { @IBOutlet var videoView: UIWebView! @IBOutlet var profilePicture: UIImageView! @IBOutlet var channelName: UILabel! @IBOutlet var datePosted: UILabel! var webview: UIWebView? func setVideo(videoURL: String){ if self.webview == nil { // Set the video view videoView.scrollView.contentInset = UIEdgeInsets.zero videoView.loadHTMLString("<iframe width=\"\(videoView.frame.width)\" height=\"\(videoView.frame.height)\" src=\"\(videoURL)?&playsinline=0\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil) videoView.allowsInlineMediaPlayback = false videoView.scrollView.isScrollEnabled = false // Save the video view in the cell self.webview = videoView } else { // Retreive the video view self.videoView = self.webview } } func setProfilePicture(imageURL: URL){ profilePicture.contentMode = .scaleAspectFit profilePicture.kf.setImage(with: imageURL) } } <file_sep>// notificationView.swift // Swap // // Created by <NAME> on 1/21/17. // // import Foundation var swapRequests: [SwapRequest] = [] var acceptedRequests: [SwapRequest] = [] class NotificationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var blankTableMessage: UILabel? @IBOutlet var tableView: UITableView! @IBOutlet var activityView: UIActivityIndicatorView! override func viewDidAppear(_ animated: Bool) { save(screen: .NotificationsScreen) } override func viewDidLoad() { super.viewDidLoad() setupViewController() loadNotifications() // Listens for reload notifications notification NotificationCenter.default.addObserver(self, selector: #selector(self.loadNotifications), name: .reloadNotifications, object: nil) } //table view func numberOfSections(in tableView: UITableView) -> Int { if swapRequests.count == 0 && acceptedRequests.count == 0{ self.tableView.backgroundView = blankTableMessage self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none return 0 } else{ self.tableView.backgroundView = nil self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine return 2 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var sectionName: String switch section { case 0: sectionName = "Swap Requests" break; case 1: sectionName = "Sent Requests" break; default: sectionName = "" } return sectionName } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0{ if swapRequests.count == 0{ return 0 } } return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0{ return swapRequests.count } else if section == 1{ return acceptedRequests.count } else{ return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: notificationCell if (indexPath.section == 0){ cell = tableView.dequeueReusableCell(withIdentifier: "privateSwapRequest", for: indexPath) as! notificationCell; cell.acceptButton.tag = indexPath.row circularImageNoBorder(photoImageView: cell.profilePicture) cell.profilePicture.kf.indicatorType = .activity if let user = swapRequests[safe: indexPath.item]?.user{ cell.profilePicture.kf.setImage(with: URL(string: (user._profilePictureUrl)!)) cell.usernameLabel.text = (user._firstname)! + " " + (user._lastname)! cell.timeLabel.text = (swapRequests[safe: indexPath.item]?._sent_at)?.timeAgo() } else { SwapUser(username: swapRequests[safe: indexPath.item]?._sender ?? "" ).getInformation { (error, user) in DispatchQueue.main.async { cell.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) cell.usernameLabel.text = (user?._firstname)! + " " + (user?._lastname)! cell.timeLabel.text = (swapRequests[safe: indexPath.item]?._sent_at)?.timeAgo() swapRequests[safe: indexPath.item]?.user = user } } } } else { cell = tableView.dequeueReusableCell(withIdentifier: "acceptedSwapRequest", for: indexPath) as! notificationCell; cell.swapButton.tag = indexPath.row circularImageNoBorder(photoImageView: cell.profilePicture) cell.profilePicture.kf.indicatorType = .activity if let user = acceptedRequests[safe: indexPath.item]?.user{ cell.profilePicture.kf.setImage(with: URL(string: (user._profilePictureUrl)!)) cell.usernameLabel.text = (user._firstname)! + " " + (user._lastname)! cell.timeLabel.text = (acceptedRequests[safe: indexPath.item]?._sent_at)?.timeAgo() cell.swapButton.isHidden = true if (acceptedRequests[safe: indexPath.item]?._status ?? 0).boolValue{ cell.swapButton.isHidden = false} } else { SwapUser(username: acceptedRequests[safe: indexPath.item]?._requested ?? "").getInformation { (error, user) in DispatchQueue.main.async { cell.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) cell.usernameLabel.text = (user?._firstname)! + " " + (user?._lastname)! cell.timeLabel.text = (acceptedRequests[safe: indexPath.item]?._sent_at)?.timeAgo() cell.swapButton.isHidden = true if (acceptedRequests[safe: indexPath.item]?._status ?? 0).boolValue{ cell.swapButton.isHidden = false} } } } } return cell } @IBAction func didAcceptRquest(_ sender: Any) { let usernameToSwapWith = swapRequests[safe: (sender as AnyObject).tag]?._sender ?? "" SwapUser().performActionOnSwapRequestFromUser(withUsername: usernameToSwapWith, doAccept: true, completion: {error in if error == nil{ // After Accepted or Rejected Swap Request // Should remove cell from table view DispatchQueue.main.async { swapRequests.remove(at: (sender as AnyObject).tag) self.tableView.reloadData() } } }) } @IBAction func didDeclineRequest(_ sender: Any) { let usernameToSwapWith = swapRequests[safe: (sender as AnyObject).tag]?._sender ?? "" SwapUser().performActionOnSwapRequestFromUser(withUsername: usernameToSwapWith, doAccept: false, completion: {error in if error == nil{ // After Accepted or Rejected Swap Request // Should remove cell from table view DispatchQueue.main.async { swapRequests.remove(at: (sender as AnyObject).tag) self.tableView.reloadData() } } }) } @IBAction func didPressSwap(_ sender: Any) { let usernameToSwapWith = acceptedRequests[(sender as AnyObject).tag]._requested! SwapUser().swap(with: usernameToSwapWith, authorizeOnViewController: self, overridePrivateAccount: true, method: .username, completion: { (error, user) in SwapUser().confirmSwapRequestToUser(withUsername: usernameToSwapWith) DispatchQueue.main.async { acceptedRequests.remove(at: (sender as AnyObject).tag) self.tableView.reloadData() // Add Swap Points let swap = SwapUser() let swapped = SwapUser(username: user?._username ?? "") SwapUser.giveSwapPointsToUsersWhoSwapped(swap: swap, swapped: swapped) } }) } func setupViewController() { tableView.delegate = self self.tableView.allowsSelection = false self.setupSwipeGestureRecognizers(allowCyclingThoughTabs: true) } func loadNotifications() { tableView.reloadData() activityView.startAnimating() blankTableMessage = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) blankTableMessage?.text = "No Swap Requests 😅" blankTableMessage?.textColor = .black blankTableMessage?.textAlignment = NSTextAlignment.center blankTableMessage?.font = UIFont(name: "Avenir-Medium", size: 17) blankTableMessage?.sizeToFit() blankTableMessage?.isHidden = true SwapUser(username: getUsernameOfSignedInUser()).getRequestedSwaps { (error, requests) in guard error == nil else { refreshControl.endRefreshing() return } if let requests = requests{ swapRequests = requests SwapUser().getPendingSentSwapRequests { (error, aRequests) in if let aRequests = aRequests{ DispatchQueue.main.async { acceptedRequests = aRequests self.activityView.stopAnimating() self.tableView.reloadData() refreshControl.endRefreshing() if swapRequests.count > 0 || acceptedRequests.count > 0 { self.blankTableMessage?.isHidden = true self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine } else { self.blankTableMessage?.isHidden = false self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none } } } } } } } } class notificationCell: UITableViewCell { @IBOutlet var usernameLabel: UILabel! @IBOutlet var profilePicture: UIImageView! @IBOutlet var acceptButton: UIButton! @IBOutlet var declineButton: UIButton! @IBOutlet var swapButton: UIButton! @IBOutlet var timeLabel: UILabel! } extension Collection where Indices.Iterator.Element == Index { /// Returns the element at the specified index iff it is within bounds, otherwise nil. subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } } <file_sep># Uncomment the next line to define a global platform for your project # platform :ios, '9.0' source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' target 'Swap' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for Swap pod 'p2.OAuth2’, :git => ‘https://github.com/p2/OAuth2.git', :branch => ‘master’, :submodules => true #, ‘3.0.2’ pod 'Alamofire' pod 'SwiftyJSON' pod 'Kingfisher’, :git => 'https://github.com/onevcat/Kingfisher.git’, :branch => 'swift3' pod 'IQKeyboardManagerSwift' pod 'Branch' pod 'OneSignal’ pod 'Fabric' pod 'Answers' pod 'TwitterKit' pod 'Crashlytics' pod 'CountryPickerSwift' pod 'PhoneNumberKit’, :git => ’https://github.com/marmelroy/PhoneNumberKit.git', :branch => ‘swift3’ pod 'Spring’, :git => 'https://github.com/MengTo/Spring.git', :branch => 'swift3' pod 'Swifter', :git => 'https://github.com/mattdonnelly/Swifter.git' pod 'Firebase/Core' pod 'Firebase' pod 'Firebase/Database' pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git' post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| xcconfig_path = config.base_configuration_reference.real_path xcconfig = File.read(xcconfig_path) new_xcconfig = xcconfig.sub('OTHER_LDFLAGS = $(inherited) -ObjC', 'OTHER_LDFLAGS = $(inherited)') File.open(xcconfig_path, "w") { |file| file << new_xcconfig } end end end end<file_sep>// // SwapHistory.swift // Swap // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // import Foundation import UIKit import AWSDynamoDB class SwapHistory: AWSDynamoDBObjectModel, AWSDynamoDBModeling { var _swap: String? var _swapped: String? var _didShareBirthday: NSNumber? var _didShareEmail: NSNumber? var _didShareInstagram: NSNumber? var _didSharePhonenumber: NSNumber? var _didSharePinterest: NSNumber? var _didShareReddit: NSNumber? var _didShareSoundCloud: NSNumber? var _didShareSpotify: NSNumber? var _didShareTwitter: NSNumber? var _didShareVine: NSNumber? var _didShareYouTube: NSNumber? var _didShareGitHub: NSNumber? var _didShareVimeo: NSNumber? var _location: Set<NSNumber>? var _method: String? var _time: NSNumber? var _didGiveSwapPointsFromSwap: NSNumber? var _longitude: String? var _latitude: String? var profileImageURL: URL? var firstname: String? var lastname: String? var user: Users? class func dynamoDBTableName() -> String { return "swap-mobilehub-1081613436-Swap_History" } class func hashKeyAttribute() -> String { return "_swap" } class func rangeKeyAttribute() -> String { return "_swapped" } override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] { return [ "_swap" : "swap", "_swapped" : "swapped", "_didShareBirthday" : "didShareBirthday", "_didShareEmail" : "didShareEmail", "_didShareInstagram" : "didShareInstagram", "_didSharePhonenumber" : "didSharePhonenumber", "_didSharePinterest" : "didSharePinterest", "_didShareReddit" : "didShareReddit", "_didShareSoundCloud" : "didShareSoundCloud", "_didShareSpotify" : "didShareSpotify", "_didShareTwitter" : "didShareTwitter", "_didShareVine" : "didShareVine", "_didShareYouTube" : "didShareYouTube", "_didShareGitHub" : "didShareGitHub", "_didShareVimeo" : "didShareVimeo", "_location" : "location", "_method" : "method", "_time" : "time", "_didGiveSwapPointsFromSwap": "didGiveSwapPointsFromSwap", "_latitude": "latitude", "_longitude": "longitude" ] } } <file_sep>// // Compilation.swift // Swap // // Created by <NAME> on 1/15/17. // // import Foundation //import RealmSwift /* class Compilation: Object { dynamic var id: String = "" dynamic var profilePicture: String = "" dynamic var name: String = "" dynamic var updatedAt: Date? dynamic var hasBeenViewed: Bool = false dynamic var isVerified: Bool = false var Tweets = List<Tweet>() override static func primaryKey() -> String? { return "id" } } */ <file_sep>// // EditProfile.swift // Swap // // Created by <NAME> on 1/10/17. // // import Foundation import Kingfisher var editProfileFirstName = "" var editProfileLastName = "" var editProfileEmail = "" var editProfileBirthday = 0.0 class EditProfile: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { let imagePicker = UIImagePickerController() @IBOutlet var doneButton: UIButton! @IBOutlet var profilePicture: UIImageView! @IBOutlet var activityView: UIActivityIndicatorView! @IBOutlet var doneActivityView: UIActivityIndicatorView! var didChangeProfilePicture: Bool = false override func viewDidLoad() { circularImageNoBorder(photoImageView: profilePicture) imagePicker.delegate = self doneActivityView.stopAnimating() activityView.startAnimating() SwapUser(username: getUsernameOfSignedInUser()).getInformation { (error, user) in DispatchQueue.main.async { self.activityView.isHidden = true self.activityView.stopAnimating() } self.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) } } @IBAction func didPressCancel(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func didPressDone(_ sender: Any) { self.view.endEditing(true) let firstName = editProfileFirstName let lastName = editProfileLastName let email = editProfileEmail let birthday = editProfileBirthday let imageData = UIImageJPEGRepresentation(profilePicture.image!, 1.0) doneActivityView.isHidden = false doneActivityView.startAnimating() doneButton.isHidden = true if didChangeProfilePicture{ SwapUser().uploadProfilePicture(withData: imageData!, completion: {_ in SwapUser().set(Firstname: firstName, Lastname: lastName, Email: email, Birthday: birthday, DidSetInformation: { DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) NotificationCenter.default.post(name: .reloadProfile, object: nil) } }, CannotSetInformation: { print("error setting basic profile info") }) }) } SwapUser().set(Firstname: firstName, Lastname: lastName, Email: email, Birthday: birthday, DidSetInformation: { DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) NotificationCenter.default.post(name: .reloadProfile, object: nil) } }, CannotSetInformation: { print("error setting basic profile info") }) } @IBAction func changePicture(_ sender: Any) { imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: nil) if let pickedimage = info[UIImagePickerControllerEditedImage] as? UIImage { didChangeProfilePicture = true profilePicture.image = pickedimage } else{ print("error selecting picture") } } func resizeImage(image: UIImage) -> UIImage { var newWidth: CGFloat let newHeight: CGFloat if image.size.width < 180{ newWidth = image.size.width newHeight = image.size.height } else{ newWidth = 180 newHeight = (newWidth * image.size.height)/image.size.width } let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContext(newSize) image.draw(in: CGRect(origin: CGPoint.zero, size: newSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } } class EditProfileTable: UITableViewController, UITextFieldDelegate { @IBOutlet public var firstNameField: UITextField! @IBOutlet public var lastNameField: UITextField! @IBOutlet public var emailField: UITextField! @IBOutlet public var birthdayField: UITextField! @IBOutlet public var birthdayPicker: UIDatePicker! override func viewWillAppear(_ animated: Bool) { SwapUser(username: getUsernameOfSignedInUser()).getInformation { (error, user) in DispatchQueue.main.async { self.firstNameField.text = user?._firstname self.lastNameField.text = user?._lastname self.emailField.text = user?._email self.birthdayPicker.date = NSDate(timeIntervalSince1970: user?._birthday as! TimeInterval) as Date editProfileFirstName = (user?._firstname)! editProfileLastName = (user?._lastname)! editProfileEmail = (user?._email)! editProfileBirthday = self.birthdayPicker.date.timeIntervalSince1970 as Double let dateFormatter = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.medium dateFormatter.timeStyle = DateFormatter.Style.none self.birthdayField.text = dateFormatter.string(from: self.birthdayPicker.date) } } } override func viewDidLoad() { tableView.allowsSelection = false emailField.delegate = self firstNameField.delegate = self lastNameField.delegate = self birthdayPicker.addTarget(self, action: #selector(datePickerValueChanged), for: UIControlEvents.valueChanged) } func datePickerValueChanged(sender:UIDatePicker) { editProfileBirthday = birthdayPicker.date.timeIntervalSince1970 as Double let dateFormatter = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.medium dateFormatter.timeStyle = DateFormatter.Style.none birthdayField.text = dateFormatter.string(from: sender.date) } func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == 2{ tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: tableView.contentOffset.y + 70), animated: true) } } func textFieldDidEndEditing(_ textField: UITextField) { //set global information editProfileFirstName = firstNameField.text! editProfileLastName = lastNameField.text! editProfileEmail = emailField.text! if textField.tag == 2{ tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: tableView.contentOffset.y - 70), animated: true) } } } <file_sep>// // SearchedUser.swift // Swap // // Created by <NAME> on 1/27/17. // // import Foundation import Kingfisher var searchedUser = "" class SearchedUser: UIViewController, UITabBarControllerDelegate { @IBOutlet var BlurView1: UIVisualEffectView! @IBOutlet var BlurView2: UIVisualEffectView! @IBOutlet var BlurView3: UIVisualEffectView! @IBOutlet var usernameLabel: UILabel! @IBOutlet var fullName: UILabel! @IBOutlet var profilePicture: UIImageView! @IBOutlet var verifiedIcon: UIImageView! @IBOutlet var swapButton: UIButton! @IBOutlet var bioLabel: UILabel! @IBOutlet var pointsNumberLabel: UILabel! @IBOutlet var swappedNumberLabel: UILabel! @IBOutlet var swapsNumberLabel: UILabel! @IBOutlet var media1: UIImageView! @IBOutlet var media2: UIImageView! @IBOutlet var media3: UIImageView! @IBOutlet var media4: UIImageView! @IBOutlet var media5: UIImageView! @IBOutlet var media6: UIImageView! @IBOutlet var media7: UIImageView! @IBOutlet var media8: UIImageView! @IBOutlet var media9: UIImageView! @IBOutlet var media10: UIImageView! @IBOutlet var popUp: UIView! @IBOutlet var loadingView: UIActivityIndicatorView! var activeMediaArray = [UIImage]() override func viewDidAppear(_ animated: Bool) { save(screen: .SearchedUserProfileScreen) } override func viewDidLoad() { setupViewController() loadProfile() // Listens for reloadSearchedUserProfile notification NotificationCenter.default.addObserver(self, selector: #selector(self.loadProfile), name: .reloadSearchedUserProfile, object: nil) } @IBAction func didTapBack(_ sender: Any) { exitProfile() } @IBAction func didTapSwap(_ sender: Any) { SwapUser().swap(with: searchedUser, authorizeOnViewController: self, method: .username) { (error, user) in if let error = error{ print("Error Trying to Swap"); } else { DispatchQueue.main.async{ if (user?._isPrivate as? Bool)!{ self.makeSwapButtonRequested() } else{ self.disableSwapButton() self.showPopUp() // Add Swap Points let swap = SwapUser() let swapped = SwapUser(username: user?._username ?? "") SwapUser.giveSwapPointsToUsersWhoSwapped(swap: swap, swapped: swapped) } } } } } func makeSwapButtonRequested(){ self.swapButton.isEnabled = false self.swapButton.titleLabel?.alpha = 0.4 self.swapButton.setBackgroundImage(#imageLiteral(resourceName: "RequestedSwapButton"), for: .normal) self.swapButton.setTitle("Requested", for: .normal) self.swapButton.frame = CGRect(x: self.swapButton.frame.origin.x - 12, y: self.swapButton.frame.origin.y, width: self.swapButton.frame.width + 26, height: self.swapButton.frame.height) } func disableSwapButton (){ self.swapButton.isEnabled = false self.swapButton.titleLabel?.alpha = 0.4 } func showPopUp(){ UIView.animate(withDuration: 0.4, animations: { self.popUp.transform = CGAffineTransform.init(translationX: 0, y: -400) }) { (completed) in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(500), execute: { () -> Void in UIView.animate(withDuration: 0.5, animations: { () -> Void in self.popUp.alpha = 0 }) }) } } func MakeBlurViewCircular(blurView: UIVisualEffectView) -> UIVisualEffectView{ blurView.layer.cornerRadius = blurView.frame.height/2 blurView.layer.masksToBounds = false blurView.clipsToBounds = true blurView.contentMode = .scaleAspectFill blurView.layer.frame = blurView.layer.frame.insetBy(dx: 0, dy: 0) return blurView } func setupViewController() { self.tabBarController?.tabBar.backgroundImage = #imageLiteral(resourceName: "Header1") if #available(iOS 10.0, *) { self.tabBarController?.tabBar.unselectedItemTintColor = UIColor.black } else { // Fallback on earlier versions } self.tabBarController?.tabBar.tintColor = UIColor.black self.tabBarController?.tabBar.isTranslucent = false UITabBar.appearance().layer.borderWidth = 0.0 UITabBar.appearance().clipsToBounds = true self.tabBarController?.delegate = self verifiedIcon.isHidden = true profilePicture.isHidden = true bioLabel.isHidden = true fullName.isHidden = true media1.isHidden = true media2.isHidden = true media3.isHidden = true media4.isHidden = true media5.isHidden = true media6.isHidden = true media7.isHidden = true media8.isHidden = true media9.isHidden = true media10.isHidden = true BlurView1.isHidden = true BlurView2.isHidden = true BlurView3.isHidden = true swapButton.isHidden = true MakeBlurViewCircular(blurView: BlurView1) MakeBlurViewCircular(blurView: BlurView2) MakeBlurViewCircular(blurView: BlurView3) self.view.addSubview(popUp) popUp.backgroundColor = UIColor.clear popUp.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 400) usernameLabel.text = searchedUser } func loadProfile() { self.loadingView.startAnimating() SwapUser(username: searchedUser).getInformation { (error, user) in guard error == nil else{ self.performSegue(withIdentifier: "fromSearchUsersToProfile", sender: nil) return } DispatchQueue.main.async { self.profilePicture.kf.indicatorType = .activity self.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) circularImage(photoImageView: self.profilePicture) // Set the Twitter ID to the Twitter Preview View Controller twitterUserID = user?._twitterID ?? "" // Set the Instagram ID instagramUserID = user?._instagramID ?? "" //set the youtube ID YouTubeUserID = user?._youtubeID ?? "" YouTubePreviewUser = user instagramPreviewUser = user self.fullName.text = ((user?._firstname)! + " " + (user?._lastname)!).uppercased() self.bioLabel.text = user?._bio self.swapsNumberLabel.text = "\(abbreviateNumber(num: user?._swaps ?? 0))" self.swappedNumberLabel.text = "\(abbreviateNumber(num: user?._swapped ?? 0))" self.pointsNumberLabel.text = "\(abbreviateNumber(num: user?._points ?? 0))" //check if the searched user is the signed in user if searchedUser == getUsernameOfSignedInUser() { self.disableSwapButton() } if (user?._isPrivate as? Bool)!{ //change to private swap button self.swapButton.setBackgroundImage(#imageLiteral(resourceName: "PrivateSwapButton"), for: .normal) self.swapButton.frame = CGRect(x: self.swapButton.frame.origin.x, y: self.swapButton.frame.origin.y, width: self.swapButton.frame.width + 13, height: self.swapButton.frame.height) self.swapButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 4, right: 10) //check if the searched user has a pending swap by the signed in user. SwapUser(username: getUsernameOfSignedInUser()).getPendingSentSwapRequests(result: { (error, requests) in if let error = error{ print(error.localizedDescription) } else{ for user in requests! { if (user._requested == searchedUser){ self.makeSwapButtonRequested() } } } }) } //show the hidden views self.profilePicture.isHidden = false self.bioLabel.isHidden = false self.fullName.isHidden = false self.BlurView1.isHidden = false self.BlurView2.isHidden = false self.BlurView3.isHidden = false self.swapButton.isHidden = false self.verifiedIcon.isHidden = !(user?._isVerified?.boolValue ?? false) if (user?._willShareTwitter?.boolValue ?? false) && !((user?._twitterID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "TwitterLight")) } if (user?._willShareInstagram?.boolValue ?? false) && !((user?._instagramID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "InstagramLight")) } if (user?._willShareSpotify?.boolValue ?? false) && !((user?._spotifyID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "SpotifyLight")) } if (user?._willShareEmail?.boolValue ?? false) || (user?._willSharePhone?.boolValue ?? false){ self.activeMediaArray.append(#imageLiteral(resourceName: "ContactLight")) } if (user?._willSharePinterest?.boolValue ?? false) && !((user?._pinterestID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "PinterestLight")) } if (user?._willShareYouTube?.boolValue ?? false) && !((user?._youtubeID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "YoutubeLight")) } if (user?._willShareSoundCloud?.boolValue ?? false) && !((user?._soundcloudID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "SoundCloudLight")) } if (user?._willShareVimeo?.boolValue ?? false) && !((user?._vimeoID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "VimeoLight")) } if (user?._willShareGitHub?.boolValue ?? false) && !((user?._githubID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "GithubLight")) } if (user?._willShareReddit?.boolValue ?? false) && !((user?._redditID ?? "") == ""){ self.activeMediaArray.append(#imageLiteral(resourceName: "RedditLight")) } if self.activeMediaArray.indices.contains(0){ self.media1.image = self.activeMediaArray[0] self.media1.isHidden = false } else{ self.disableSwapButton() } self.addMedia(media: self.media2, index: 1) self.addMedia(media: self.media3, index: 2) self.addMedia(media: self.media4, index: 3) self.addMedia(media: self.media5, index: 4) self.addMedia(media: self.media6, index: 5) self.addMedia(media: self.media7, index: 6) self.addMedia(media: self.media8, index: 7) self.addMedia(media: self.media9, index: 8) self.addMedia(media: self.media10, index: 9) if !(self.activeMediaArray.count % 2 == 0){ self.media1.frame.origin.x = self.media1.frame.origin.x + 10 self.media2.frame.origin.x = self.media2.frame.origin.x + 10 self.media3.frame.origin.x = self.media3.frame.origin.x + 10 self.media4.frame.origin.x = self.media4.frame.origin.x + 10 self.media5.frame.origin.x = self.media5.frame.origin.x + 10 self.media6.frame.origin.x = self.media6.frame.origin.x + 10 self.media7.frame.origin.x = self.media7.frame.origin.x + 10 self.media8.frame.origin.x = self.media8.frame.origin.x + 10 self.media9.frame.origin.x = self.media9.frame.origin.x + 10 self.media10.frame.origin.x = self.media10.frame.origin.x + 10 } self.loadingView.stopAnimating() } } } func addMedia(media: UIImageView, index: Int){ if self.activeMediaArray.indices.contains(index){ media.image = self.activeMediaArray[index] media.isHidden = false } } func exitProfile() { UITabBar.appearance().layer.borderWidth = 1.0 UITabBar.appearance().clipsToBounds = false if self.presentingViewController == nil{ self.performSegue(withIdentifier: "fromSearchUsersToProfile", sender: nil) } else{ dismiss(animated: true, completion: nil) } } func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { if tabBarController.viewControllers?.index(of: viewController) == 0{ tabBarController.tabBar.backgroundImage = #imageLiteral(resourceName: "Header1") } else{ tabBarController.tabBar.backgroundImage = #imageLiteral(resourceName: "TextfieldBottom") } } } <file_sep>// // SwapRequest.swift // Swap // // Created by <NAME> on 1/14/17. // // import Foundation import UIKit import AWSDynamoDB class SwapRequest: AWSDynamoDBObjectModel, AWSDynamoDBModeling { var _sender: String? var _requested: String? var _sender_confirmed_acceptance: NSNumber? var _sent_at: NSNumber? var _status: NSNumber? var _requested_user_has_responded_to_request: NSNumber? var user: Users? class func dynamoDBTableName() -> String { return "swap-mobilehub-1081613436-SwapRequest" } class func hashKeyAttribute() -> String { return "_sender" } class func rangeKeyAttribute() -> String { return "_requested" } override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] { return [ "_sender" : "sender", "_requested" : "requested", "_sender_confirmed_acceptance" : "sender_confirmed_acceptance", "_sent_at" : "sent_at", "_status" : "status", "_requested_user_has_responded_to_request" :"requested_user_has_responded_to_request", ] } } <file_sep>// // setBirthdayViewController.swift // Swap // // Created by <NAME> on 12/17/16. // // Description: Contains a date picker and a UITextfield to allow the user to set their birthday and then // saves this information. // import Foundation class SetBirthdayViewController: UIViewController { @IBOutlet var dateField: UITextField! @IBOutlet var datePicker: UIDatePicker! @IBOutlet var continueButton: UIButton! override func viewDidLoad() { datePicker.setValue(UIColor.white, forKeyPath: "textColor") datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: UIControlEvents.valueChanged) } func datePickerValueChanged(sender:UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.medium dateFormatter.timeStyle = DateFormatter.Style.none dateField.text = dateFormatter.string(from: sender.date) } @IBAction func didPressContinue(_ sender: Any) { /*show loading overlay let loadingOverlay = ShowLoadingOverlay() let blackOverlay = loadingOverlay.showBlackOverlay() let loadingSymbol = loadingOverlay.showLoadingSymbol(view: self.view) view.addSubview(blackOverlay) view.addSubview(loadingSymbol) datePicker.isEnabled = false continueButton.isEnabled = false*/ guard datePicker.date.age >= 13 else{ UIAlertView(title: "Sorry", message: "You must be at least 13 years old to use Swap.", delegate: nil, cancelButtonTitle: "Ok").show() return } // save birthday save(birthday: datePicker.date.timeIntervalSince1970 as Double) self.performSegue(withIdentifier: "toEmailController", sender: nil) } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // TutorialViewController.swift // Swap // // Created by <NAME> on 4/29/17. // // import Foundation var tutorialCurrentIndex = 0 class TutorialViewController: UIViewController { @IBOutlet var pageControl: UIPageControl! override func viewDidLoad() { NotificationCenter.default.addObserver(self, selector: #selector(self.updatePageControl), name: .updatePageControl, object: nil) if UserDefaults.standard.bool(forKey: "didShowTutorial"){ } else{ // closeButton.isHidden = true UserDefaults.standard.set(true, forKey: "didShowTutorial") } } @IBAction func closeTutorial(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func updatePageControl(){ pageControl.currentPage = tutorialCurrentIndex } override var prefersStatusBarHidden: Bool { return true } } <file_sep>// // TutorialPageController.swift // Swap // // Created by <NAME> on 2/3/17. // // import Foundation class TutorialPageController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { var tutorialViews = [UIViewController]() override func viewDidLoad() { super.viewDidLoad() var Tstoryboard: UIStoryboard! = nil Tstoryboard = UIStoryboard(name: "Tutorial_Main", bundle: nil) let tpage1 = Tstoryboard.instantiateViewController(withIdentifier: "tpage1") let tpage2 = Tstoryboard.instantiateViewController(withIdentifier: "tpage2") let tpage3 = Tstoryboard.instantiateViewController(withIdentifier: "tpage3") let tpage4 = Tstoryboard.instantiateViewController(withIdentifier: "tpage4") let tpage5 = Tstoryboard.instantiateViewController(withIdentifier: "tpage5") let tpage6 = Tstoryboard.instantiateViewController(withIdentifier: "tpage6") let tpage7 = Tstoryboard.instantiateViewController(withIdentifier: "tpage7") let tpage8 = Tstoryboard.instantiateViewController(withIdentifier: "tpage8") let tpage9 = Tstoryboard.instantiateViewController(withIdentifier: "tpage9") let tpage10 = Tstoryboard.instantiateViewController(withIdentifier: "tpage10") tutorialViews = [tpage1, tpage2, tpage3, tpage4, tpage5, tpage6, tpage7, tpage8, tpage9, tpage10] dataSource = self delegate = self //set the first controller in the pageViewController if let firstViewController = tutorialViews.first { setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } } /*Delegate function*/ func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { //only execute if the transition from one page to the next is completed if completed{ //update the current index and the page Control tutorialCurrentIndex = tutorialViews.index(of: (viewControllers?.first)!)! NotificationCenter.default.post(name: .updatePageControl, object: nil) } } /*Data Source Function*/ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = tutorialViews.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return nil } guard tutorialViews.count > previousIndex else { return nil } return tutorialViews[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = tutorialViews.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 let pictureViewsCount = tutorialViews.count guard pictureViewsCount != nextIndex else{ return nil } guard pictureViewsCount > nextIndex else{ return nil } return tutorialViews[nextIndex] } override var prefersStatusBarHidden: Bool { return true } } <file_sep>// // UtilityFunctions.swift // MySampleApp // // Use this file to add Utility Functions shared by the App // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // import Foundation func prettyPrintJson(_ object: AnyObject?) -> String { var prettyResult: String = "" if object == nil { return "" } else if let resultArray = object as? [AnyObject] { var entries: String = "" for index in 0..<resultArray.count { if (index == 0) { entries = "\(resultArray[index])" } else { entries = "\(entries), \(prettyPrintJson(resultArray[index]))" } } prettyResult = "[\(entries)]" } else if object is NSDictionary { let objectAsDictionary: [String: AnyObject] = object as! [String: AnyObject] prettyResult = "{" var entries: String = "" for (key,_) in objectAsDictionary { entries = "\"\(entries), \"\(key)\":\(prettyPrintJson(objectAsDictionary[key]))" } prettyResult = "{\(entries)}" return prettyResult } else if let objectAsNumber = object as? NSNumber { prettyResult = "\(objectAsNumber.stringValue)" } else if let objectAsString = object as? NSString { prettyResult = "\"\(objectAsString)\"" } return prettyResult } extension Notification.Name { //reload notifications static let reloadProfile = Notification.Name("reloadProfile") static let reloadSearchedUserProfile = Notification.Name("reloadSearchedUserProfile") static let reloadNotifications = Notification.Name("reloadNotifications") static let reloadSwaps = Notification.Name("reloadSwaps") static let reloadSwapped = Notification.Name("reloadSwapped") static let disableReloading = Notification.Name("disableReloading") static let didShowScanner = Notification.Name("didShowScanner") static let changeSwapCodeToBlue = Notification.Name("changeSwapCodeToBlue") static let changeSwapCodeToDark = Notification.Name("changeSwapCodeToDark") static let reloadMap = Notification.Name("reloadMap") static let showPinInfo = Notification.Name("showPinInfo") static let dismissPinInfo = Notification.Name("dismissPinInfo") //page control notifications static let updatePageControl = Notification.Name("updatePageControl") } <file_sep>// // ConfirmNewPhoneNumber.swift // Swap // // Created by <NAME> on 7/22/17. // // import Foundation class ConfirmNewPhoneNumber: UIViewController, UITextFieldDelegate { @IBOutlet var Textfield1: UITextField! @IBOutlet var Textfield2: UITextField! @IBOutlet var Textfield3: UITextField! @IBOutlet var Textfield4: UITextField! @IBOutlet var Textfield5: UITextField! @IBOutlet var Textfield6: UITextField! override func viewDidLoad() { Textfield1.delegate = self Textfield2.delegate = self Textfield3.delegate = self Textfield4.delegate = self Textfield5.delegate = self Textfield6.delegate = self } @IBAction func enteredFirst(_ sender: Any) { Textfield2.becomeFirstResponder() } @IBAction func enteredSecond(_ sender: Any) { Textfield3.becomeFirstResponder() } @IBAction func enteredThird(_ sender: Any) { Textfield4.becomeFirstResponder() } @IBAction func enteredFourth(_ sender: Any) { Textfield5.becomeFirstResponder() } @IBAction func enteredFifth(_ sender: Any) { Textfield6.becomeFirstResponder() } @IBAction func enteredSixth(_ sender: Any) { view.endEditing(true) } func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } @IBAction func SendCodeAgain(_ sender: Any) { pool.getUser(getUsernameOfSignedInUser()).getAttributeVerificationCode("phone_number") } @IBAction func didTapNext(_ sender: Any) { guard let number1 = Textfield1.text, let number2 = Textfield2.text, let number3 = Textfield3.text, let number4 = Textfield4.text, let number5 = Textfield5.text, let number6 = Textfield6.text else{ return } let code = number1+number2+number3+number4+number5+number6 pool.getUser(getUsernameOfSignedInUser()).verifyAttribute("phone_number", code: "\(code)").continue(with: AWSExecutor.mainThread(), with: { (task) -> Any? in DispatchQueue.main.async { if task.error != nil { // There was an error // Possibly Wrong Code UIAlertView(title: "Error", message: "Invalid Confirmation Code", delegate: nil, cancelButtonTitle: "Ok").show() self.Textfield1.text = "" self.Textfield2.text = "" self.Textfield3.text = "" self.Textfield4.text = "" self.Textfield5.text = "" self.Textfield6.text = "" } else { // Correct Code UIAlertView(title: "Success", message: "Phone number successfully changed", delegate: nil, cancelButtonTitle: "Ok").show() self.dismiss(animated: true, completion: nil) } } }) } @IBAction func didTapCancel(_ sender: Any) { self.dismiss(animated: true, completion: nil) } } <file_sep>// // InstagramView.swift // Swap // // Created by <NAME> on 4/16/17. // // import Foundation var instagramUserID: String? = nil var instagramPreviewUser: Users? = nil class instagramView: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var activityView: UIActivityIndicatorView! @IBOutlet var tableView: UITableView! var instagramImages: [IGMedia] = [] var videoIndexes: [Int] = [] override func viewDidLoad() { loadInstagramPreview() } func loadInstagramPreview() { instagramImages = [] tableView.isHidden = true let user = IGUser(id: instagramUserID ?? "") tableView.separatorStyle = .none let tapRecognizer = UILongPressGestureRecognizer() tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.addTarget(self, action: #selector(instagramView.didTapPhoto(_:))) user.getMedia { (IGMedias) in print(IGMedias?.count ?? 0) var index = 0; for media in IGMedias!{ if media.type == .photo{ self.instagramImages.append(media) } else if media.type == .video{ self.instagramImages.append(media) self.videoIndexes.append(index) } index += 1; } if self.instagramImages.count == 0{ let blankTableMessage = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) blankTableMessage.text = "No Instagram Posts" blankTableMessage.textColor = .black blankTableMessage.textAlignment = NSTextAlignment.center blankTableMessage.font = UIFont(name: "Avenir-Next", size: 20) blankTableMessage.sizeToFit() self.tableView.backgroundView = blankTableMessage self.view.backgroundColor = UIColor.white } self.activityView.stopAnimating() self.tableView.isHidden = false self.tableView.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return instagramImages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "photoCell", for: indexPath) as! InstagramPhotoCell; cell.selectionStyle = .none let currentImage = instagramImages[indexPath.row] cell.likeButton.tag = indexPath.row if currentImage.isLiked { cell.likeButton.setImage(#imageLiteral(resourceName: "FilledHeart"), for: .normal) } else{ cell.likeButton.setImage(#imageLiteral(resourceName: "UnfilledHeart"), for: .normal) } circularImageNoBorder(photoImageView: cell.profilePic) cell.profilePic.kf.setImage(with: URL(string: (instagramPreviewUser?._profilePictureUrl)!)) cell.username.text = instagramPreviewUser?._username if isVideo(media: currentImage, mediaIndex: indexPath.row){ //set a thumbnail to represent the instagram video cell.setPhoto(imageURL: currentImage.content_url!) } else { cell.setPhoto(imageURL: currentImage.content_url!) } return cell } func isVideo(media: IGMedia, mediaIndex: Int) -> Bool{ for index in videoIndexes{ if index == mediaIndex{ return true } } return false } func didTapPhoto(_ recognizer: UILongPressGestureRecognizer){ } @IBAction func didTapLike(_ sender: Any) { let likedImage = instagramImages[(sender as AnyObject).tag] likedImage.like { (error) in if error != nil { print("error liking picture") } else{ (sender as! UIButton).setImage(#imageLiteral(resourceName: "FilledHeart"), for: .normal) } } } } class InstagramPhotoCell: UITableViewCell { @IBOutlet var username: UILabel! @IBOutlet var profilePic: UIImageView! @IBOutlet var IGImageView: UIImageView! @IBOutlet var likeButton: UIButton! func setPhoto(imageURL: URL){ IGImageView.kf.setImage(with: imageURL) } } <file_sep># Swap Swap Is an application built by two High School Students - <NAME> and <NAME> We created this app in order to make it easier for people to connect on the fly across any social media account. Our vision for swap was to be a 'personal passport' into the social media world. After connecting their social medias, a user would be equiped with a custom QR code that can be scanned by other swap users. Social Media sharing for a certain profile could be switched on and off by tapping the icons below the QR code. ## [Demo Video](https://www.youtube.com/watch?v=F2_h2hxHzSw) <file_sep>// // AccountErrors.swft // Swap // // Created by <NAME> on 11/19/16. // Copyright © 2016 Swap Inc. All rights reserved. // import Foundation /// Enum Representing the type of errors that can happen during the Account Sign Up Process /// - Author: <NAME> /// /// - UsernameTaken: Username already exists /// - PasswordTooShort: Password must be at least 6 characters /// - InvalidEmail: User did not enter a valid email address /// - InvalidPhonenumber: User did not enter a valud phone number /// - EmptyFields: One or more fields were not entered while the user was signing up /// - InvalidUsername: Entered username is not a valid format. Maybe user entered spaces enum SignUpError: Error { case UsernameTaken case PasswordTooShort case InvalidEmail case InvalidPhonenumber case EmptyFields case InvalidUsername case UnknownSignUpError } <file_sep>// // verificationViewController.swift // Swap // // Created by <NAME> on 4/13/17. // // import Foundation class verificationViewController: UIViewController, UITextFieldDelegate { @IBOutlet var firstNumberField: UITextField! @IBOutlet var secondNumberField: UITextField! @IBOutlet var thirdNumberField: UITextField! @IBOutlet var forthNumberField: UITextField! @IBOutlet var fifthNumberField: UITextField! @IBOutlet var sixthNumberField: UITextField! override func viewDidLoad() { firstNumberField.delegate = self secondNumberField.delegate = self thirdNumberField.delegate = self forthNumberField.delegate = self fifthNumberField.delegate = self sixthNumberField.delegate = self firstNumberField.becomeFirstResponder() } func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } @IBAction func enteredFirst(_ sender: Any) { secondNumberField.becomeFirstResponder() } @IBAction func enteredSecond(_ sender: Any) { thirdNumberField.becomeFirstResponder() } @IBAction func enteredThird(_ sender: Any) { forthNumberField.becomeFirstResponder() } @IBAction func enteredForth(_ sender: Any) { fifthNumberField.becomeFirstResponder() } @IBAction func enteredFifth(_ sender: Any) { sixthNumberField.becomeFirstResponder() } @IBAction func enteredSixth(_ sender: Any) { view.endEditing(true) } @IBAction func didTapNext(_ sender: Any) { guard let number1 = firstNumberField.text, let number2 = secondNumberField.text, let number3 = thirdNumberField.text, let number4 = forthNumberField.text, let number5 = fifthNumberField.text, let number6 = sixthNumberField.text else{ return } let code = number1+number2+number3+number4+number5+number6 guard code.characters.count == 6 else { return } save(verificationCode: code) self.performSegue(withIdentifier: "showEnterNewPassword", sender: nil) } @IBAction func didTapSendCode(_ sender: Any) { guard getSavedUsername() != nil else { return } forgotPassword(username: getSavedUsername() ?? "" ) { (isSuccess, destination) in guard isSuccess && destination != nil else { // Tell the user that the username/phone number account could not be found UIAlertView(title: "Invalid Username or Phone Number", message: "Sorry, could not find that account.", delegate:nil, cancelButtonTitle: "Ok").show() return } if isSuccess{ print("is a success ! ") // Will send verification code // The string 'destination' is the email address or phone number the code was sent to let message = UIAlertController(title: "Reset Passord", message: "We sent a verification code to \(destination!)", preferredStyle: .alert) message.addAction(UIAlertAction(title: "Ok", style: .default){ (action) in // Now go to the verification page DispatchQueue.main.async { } }) self.present(message, animated: true, completion: nil) } } } } <file_sep>// // EnterUserViewController.swift // Swap // // Created by <NAME> on 4/13/17. // // import Foundation class EnterUserViewController: UIViewController { @IBOutlet var usernameField: UITextField! @IBAction func didTapNext(_ sender: Any) { guard !(usernameField.text?.isEmpty)! else { return } forgotPassword(username: usernameField.text ?? "" ) { (isSuccess, destination) in print("is success : \(isSuccess) \n destination: \(destination)") guard isSuccess && destination != nil else { // Tell the user that the username/phone number account could not be found UIAlertView(title: "Invalid Username or Phone Number", message: "Sorry, could not find that account.", delegate:nil, cancelButtonTitle: "Ok").show() return } if isSuccess{ print("is a success ! ") // Will send verification code // The string 'destination' is the email address or phone number the code was sent to let message = UIAlertController(title: "Reset Password", message: "We sent a verification code to \(destination!)", preferredStyle: .alert) message.addAction(UIAlertAction(title: "Ok", style: .default){ (action) in // Now go to the verification page DispatchQueue.main.async { self.performSegue(withIdentifier: "showVerification", sender: nil) } }) self.present(message, animated: true, completion: nil) } } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // YouTubeUser.swift // Swap // // Created by <NAME> on 2/7/17. // // import Foundation import Alamofire import SwiftyJSON class YouTubeUser { var id: String = "" init(id: String) { self.id = id } func getMedia(completion: @escaping ([YouTubeMedia]?) -> Void) { let url = "https://www.googleapis.com/youtube/v3/search?key=<KEY>&channelId=\(self.id)&part=snippet,id&order=date&maxResults=50" Alamofire.request(url, method: .get, parameters: nil, headers: nil).responseJSON { (response) in if let data = response.data{ let mediaObjects = JSON(data: data) let medias: [YouTubeMedia] = mediaObjects.toYouTubeMedias() completion(medias) } } } } <file_sep>// // SwapUser.swift // Swap // // Created by <NAME> on 11/19/16. // Copyright © 2016 Swap Inc. All rights reserved. // import Foundation import AWSDynamoDB import AWSCognitoIdentityProvider import AWSCore import AWSMobileHubHelper import OneSignal //import Realm //import RealmSwift import Swifter import AudioToolbox /// Class for a SwapUser object class SwapUser { /// Username identifies users in database var username: String /// Object refers to NoSQL database of users var NoSQL = AWSDynamoDBObjectMapper.default() /// Variable used to modify how data is stored in database var updateMapperConfig = AWSDynamoDBObjectMapperConfiguration() /// Variable to determine if user is verified var isVerified = false // Variable containing profile picture URL var profilePictureURL: URL = URL(string: defaultImage)! var dynamoDB = AWSDynamoDB(forKey: "USEast1DynamoDBProvider") /// Whenever a SwapUser object is created, unless otherwise specified in given username in the parameter, the object assumes it is referring to the current swap user init(username: String = getUsernameOfSignedInUser()) { self.username = username } /** Sets information of a Swap User. Will only set the information of data that is passed, if a parameter is not used, that attribute will not be altered in the database. For example, if you only want to set the first and last name, call SwapUserObject.set(Firstname: "Micheal", Lastname: "Bingham"). - Attention: Do not set values using this function if you want to remove an attribute or set an empty string as a value for an attribute; this does not delete attributes nor does it save empty values for attributes. - Author: <NAME> - Copyright: 2017 Swap Inc. - Version: 2.1 - Todo: Change email in Cognito - Parameter DidSetInformation: Completion block executed when information is set. - Parameter CannotSetInformation: Completion block executed when information cannot be set. - Parameter Firstname: The first name of the user. `String` - Parameter Middlename: The middle name of the user. `String` - Parameter Lastname: The last name of the user. `String`. - Parameter Phonenumber: The phone number of the user. `String`. - Parameter Email: The email of the user. `String`. - Parameter Website: The webste of the user. `String`. - Parameter Company: Company name of the user. `String` - Parameter Bio: Biographical information of user. `String` - Parameter Birthday: The birthday of the user as seconds since 1970. `Double` - Parameter Gender: M if male. F if female. `String` - Parameter Date_Created: The date of account creation. `Double` - Parameter isVerified: If the user is a `high class/verified` account. `Bool` - Parameter isPrivate: Set the user's account to private. `Bool` - Parameter Points: Sets the amount of swap points. Does not increment or decrement but sets the points to given amount. `Int` - Parameter Swapped: Sets the amount of `Swapped` . Does not increment or decrement but sets the points to given amount. `Int` - Parameter Swaps: Sets the amount of `swaps`. Does not increment or decrement but sets the points to given amount. `Int` - Parameter ProfileImage: Sets the profile picture with the given image URL. `String` - Parameter QRImage: Sets the swap code image with the given image URL. `String` - Parameter SpotifyID: The Spotify User ID. `String` - Parameter YouTubeID: The YouTube User ID. `String` - Parameter VineID: The Vine User ID. `String` - Parameter InstagramID: The Instagram User ID. `String` - Parameter TwitterID: The Twitter User ID for the user. `String` - Parameter RedditID: The Reddit User ID for the user. `String` - Parameter PinterestID: The Pinterest User ID for the user. `String` - Parameter SoundCloudID: The SoundCloud User ID for the user. `String` - Parameter GitHubID: The GitHub User ID for the user. `String` - Parameter VimeoID: The Vimeo User ID for the user. `String` - Parameter WillShareSpotify: Whether or not the usre will share Spotify. `Bool` - Parameter WillShareYouTube: Whether or not the usre will share YouTube. `Bool` - Parameter WillSharePhonenumber: Whether or not the usre will share Phone Number. `Bool` - Parameter WillShareVine: Whether or not the usre will share Vine. `Bool` - Parameter WillShareInstagram: Whether or not the usre will share Instagram. `Bool` - Parameter WillShareTwitter: Whether or not the usre will share Twitter. `Bool` - Parameter WillShareEmail: Whether or not the usre will share Email. `Bool` - Parameter WillShareReddit: Whether or not the usre will share Reddit. `Bool` - Parameter WillSharePinterest: Whether or not the usre will share Pinterest. `Bool` - Parameter WillShareSoundCloud: Whether or not the usre will share SoundCloud. `Bool` - Parameter WillShareGitHub: Whether or not the usre will share GitHub. `Bool` - Parameter WillShareVimeo: Whether or not the usre will share Vimeo. `Bool` - Parameter ShouldChangePhoneNumberAssociation: By default this is true. If this is true, a verification code will be sent to the phone number and it will change the phone number associated in Amazon Cognito. Otherwise, the phone number will only be changed in the database which is used for 'swapping'. If this is false, the phone number already verified in the account won't be changed. Otherwise, it will change the phone number used to verify the account for resetting passwords. `Bool` */ func set( Firstname: String? = nil, Middlename: String? = nil, Lastname: String? = nil, Phonenumber: String? = nil, Email: String? = nil, Website: String? = nil, Company: String? = nil, Bio: String? = nil, Birthday: Double? = nil, Gender: String? = nil, Date_Created: Double? = nil, isVerified: Bool? = nil, isPrivate: Bool? = nil, Points: Int? = nil, Swapped: Int? = nil, Swaps: Int? = nil, ProfileImage: String? = nil, QRImage: String? = nil, SpotifyID: String? = nil, YouTubeID: String? = nil, VineID: String? = nil, InstagramID: String? = nil, TwitterID: String? = nil, RedditID: String? = nil, PinterestID: String? = nil, SoundCloudID: String? = nil, GitHubID: String? = nil, VimeoID: String? = nil, WillShareSpotify: Bool? = nil, WillShareYouTube: Bool? = nil, WillSharePhonenumber: Bool? = nil, WillShareVine: Bool? = nil, WillShareInstagram: Bool? = nil, WillShareTwitter: Bool? = nil, WillShareEmail: Bool? = nil, WillShareReddit: Bool? = nil, WillSharePinterest: Bool? = nil, WillShareSoundCloud: Bool? = nil, WillShareGitHub: Bool? = nil, WillShareVimeo: Bool? = nil, ShouldChangePhoneNumberAssociation: Bool = true, DidSetInformation: @escaping () -> Void? = { return nil }, CannotSetInformation: @escaping () -> Void? = { return }) { // Ensures that if a value is not passed in the function, it is ignored when saved into database updateMapperConfig.saveBehavior = .updateSkipNullAttributes // Creates an 'Users' object in order to store to database let user = Users() user?._username = self.username user?._firstname = (Firstname != nil && !((Firstname?.isEmpty)!)) ? Firstname?.trim(): nil user?._middlename = (Middlename != nil && !((Middlename?.isEmpty)!)) ? Middlename?.trim(): nil user?._lastname = (Lastname != nil && !((Lastname?.isEmpty)!)) ? Lastname?.trim(): nil user?._phonenumber = (Phonenumber != nil && !((Phonenumber?.isEmpty)!)) ? Phonenumber?.trim(): nil user?._email = (Email != nil && !((Email?.isEmpty)!)) ? Email?.trim(): nil user?._website = (Website != nil && !((Website?.isEmpty)!)) ? Website?.trim(): nil user?._birthday = (Birthday != nil) ? (Birthday! as NSNumber) : nil user?._company = (Company != nil && !((Company?.isEmpty)!)) ? Company?.trim(): nil user?._bio = (Bio != nil && !((Bio?.isEmpty)!)) ? Bio?.trim(): nil user?._gender = (Gender != nil && !((Gender?.isEmpty)!)) ? Gender: nil user?._isVerified = (isVerified != nil) ? (isVerified! as NSNumber) : nil user?._dateCreated = (Date_Created != nil) ? (Date_Created! as NSNumber) : nil user?._isPrivate = (isPrivate != nil) ? (isPrivate! as NSNumber) : nil user?._points = (Points != nil) ? (Points! as NSNumber) : nil user?._swapped = (Swapped != nil) ? (Swapped! as NSNumber) : nil user?._swaps = (Swaps != nil) ? (Swaps! as NSNumber) : nil user?._profilePictureUrl = (ProfileImage != nil && !((ProfileImage?.isEmpty)!)) ? ProfileImage: nil user?._swapCodeUrl = (QRImage != nil && !((QRImage?.isEmpty)!)) ? QRImage: nil user?._spotifyID = (SpotifyID != nil && !((SpotifyID?.isEmpty)!)) ? SpotifyID: nil user?._youtubeID = (YouTubeID != nil && !((YouTubeID?.isEmpty)!)) ? YouTubeID: nil user?._vineID = (VineID != nil && !((VineID?.isEmpty)!)) ? VineID: nil user?._instagramID = (InstagramID != nil && !((InstagramID?.isEmpty)!)) ? InstagramID: nil user?._twitterID = (TwitterID != nil && !((TwitterID?.isEmpty)!)) ? TwitterID: nil user?._redditID = (RedditID != nil && !((RedditID?.isEmpty)!)) ? RedditID: nil user?._githubID = (GitHubID != nil && !((GitHubID?.isEmpty)!)) ? GitHubID: nil user?._pinterestID = (PinterestID != nil && !((PinterestID?.isEmpty)!)) ? PinterestID: nil user?._soundcloudID = (SoundCloudID != nil && !((SoundCloudID?.isEmpty)!)) ? SoundCloudID: nil user?._vimeoID = (VimeoID != nil && !((VimeoID?.isEmpty)!)) ? VimeoID: nil user?._willShareSpotify = (WillShareSpotify != nil) ? (WillShareSpotify! as NSNumber) : nil user?._willShareYouTube = (WillShareYouTube != nil) ? (WillShareYouTube! as NSNumber) : nil user?._willSharePhone = (WillSharePhonenumber != nil) ? (WillSharePhonenumber! as NSNumber) : nil user?._willShareVine = (WillShareVine != nil) ? (WillShareVine! as NSNumber) : nil user?._willShareInstagram = (WillShareInstagram != nil) ? (WillShareInstagram! as NSNumber) : nil user?._willShareTwitter = (WillShareTwitter != nil) ? (WillShareTwitter! as NSNumber) : nil user?._willShareEmail = (WillShareEmail != nil) ? (WillShareEmail! as NSNumber) : nil user?._willShareReddit = (WillShareReddit != nil) ? (WillShareReddit! as NSNumber) : nil user?._willSharePinterest = (WillSharePinterest != nil) ? (WillSharePinterest! as NSNumber) : nil user?._willShareSoundCloud = (WillShareSoundCloud != nil) ? (WillShareSoundCloud! as NSNumber) : nil user?._willShareGitHub = (WillShareGitHub != nil) ? (WillShareGitHub! as NSNumber) : nil user?._willShareVimeo = (WillShareVimeo != nil) ? (WillShareVimeo! as NSNumber) : nil if let linkToProfileImage = ProfileImage{ // User setted Profile Picture so we have to set it in amazon cognito let ProfilePictureURL = AWSCognitoIdentityUserAttributeType() ProfilePictureURL?.name = "picture" ProfilePictureURL?.value = linkToProfileImage pool.getUser(self.username).update([ProfilePictureURL!]) } if isVerified ?? false{ // Set verified in database let verified = AWSCognitoIdentityUserAttributeType() verified?.name = "profile" verified?.value = "IS_VERIFIED" pool.getUser(self.username).update([verified!]) } if let email = Email{ // Sets Email in Amazon Cognito let email_attribute = AWSCognitoIdentityUserAttributeType() email_attribute?.name = "email" email_attribute?.value = email pool.getUser(self.username).update([email_attribute!]) } if let number = Phonenumber{ // Sets Phone number in Amazon Cognito if ShouldChangePhoneNumberAssociation{ let n = AWSCognitoIdentityUserAttributeType() n?.name = "phone_number" n?.value = number pool.getUser(self.username).update([n!]) } } DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.save(user!, configuration: self.updateMapperConfig, completionHandler: { error in DispatchQueue.main.async { if error != nil{ print("Can set information") CannotSetInformation() } else{ DidSetInformation() } } }) } } func updateProfileInfoWith(Middlename: String? = nil, Company: String? = nil, Website: String? = nil, DidSetInformation: @escaping () -> Void? = { return nil }, CannotSetInformation: @escaping () -> Void? = { return }) { // Ensures that if a value is not passed in the function, it is deleted when saved into database updateMapperConfig.saveBehavior = .update self.getInformation { (error, user) in user?._middlename = (Middlename != nil && !((Middlename?.isEmpty)!)) ? Middlename?.trim(): nil user?._website = (Website != nil && !((Website?.isEmpty)!)) ? Website?.trim(): nil user?._company = (Company != nil && !((Company?.isEmpty)!)) ? Company?.trim(): nil DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.save(user!, configuration: self.updateMapperConfig, completionHandler: { error in DispatchQueue.main.async { if error != nil{ print("Can set information") CannotSetInformation() } else{ DidSetInformation() } } }) } } } func getInformation(completion: @escaping (_ error: UserError?, _ userData: Users? ) -> Void) { // Configures so that most recent data is obtained from NoSQL let config = AWSDynamoDBObjectMapperConfiguration() config.consistentRead = true DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.load(Users.self, hashKey: self.username, rangeKey: nil, configuration: config, completionHandler: { (user, error) in if error != nil { print("there was an error loading data..\nThe error is \(error.debugDescription)") let usererror: UserError = UserError.CouldNotGetUser completion(usererror, nil) } else{ // There is no error DispatchQueue.main.async { if user != nil{ let user = user as! Users completion(nil, user) } else{ let usererror: UserError = UserError.CouldNotGetUser completion(usererror, nil) } } } }) } } /// Function that returns an array of SwapHistory objects for the users that Swapped this user. /// /// - Parameter result: Returns and Error and an array of SwapHistory objects. Error will be nil if there is no error. Be sure to unwrap the swapHistory array. Iterate through swapHistories array to retrieve each individual SwapHistory object. See SwapHistory class for more information on a Swap History object. Each Swap History object has a property associated with the information it contains. For example: swapHistory._swapped is the person that was 'Swapped' and swapHistory.swap is the person that swapped. Each property also tells whether the specific social media were shared or not. It may be 'nil' or 'false' or 'true'. If swaphistory._didShareTwitter is nil or false , Twitter was not shared. It is more likely the value will be nil rather than false. If there are no records for Swap History, the array will be empty. func getSwappedHistory(result: @escaping (_ queryError: Error?, _ swappedHistories: [SwapHistory]? ) -> Void) { // Configures so that most recent data is obtained from NoSQL let config = AWSDynamoDBObjectMapperConfiguration() config.consistentRead = true let queryExpression = AWSDynamoDBQueryExpression() queryExpression.indexName = "swapped" queryExpression.keyConditionExpression = "#hashAttribute = :hashAttribute" queryExpression.expressionAttributeNames = ["#hashAttribute": "swapped"] queryExpression.expressionAttributeValues = [":hashAttribute": self.username] DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.query(SwapHistory.self, expression: queryExpression, configuration: nil, completionHandler: { (output, error) in DispatchQueue.main.async { if error != nil{ print("error querying ... \(error)") result(error, nil) } else{ // Converts the response to an array of Swap History objects let swapHistories = output?.items as! [SwapHistory] result(nil, swapHistories) } } }) } } /// Uploads a Profile Picture given the UIImage Data /// /// - Parameters: /// - withData: Data representation of the image /// - completion: If the error is nil, it has suceeded and the profile picture has been updated in Database func uploadProfilePicture(withData: Data, completion: @escaping (_ error: Error?) -> Void) { let randomNumber = Date().timeIntervalSince1970 as Double let manager = AWSUserFileManager.defaultUserFileManager() let localContent = manager.localContent(with: withData, key: "public/\(self.username)/profile_picture-\(randomNumber).jpg") localContent.uploadWithPin(onCompletion: true, progressBlock: { (content, progress) in // Shows Progress }, completionHandler: { (content, error) in // Finished uploading if error == nil { let LinkToProfilePicture = "https://s3.amazonaws.com/swap-userfiles-mobilehub-1081613436/public/\(self.username)/profile_picture-\(randomNumber).jpg" self.set(ProfileImage: LinkToProfilePicture,DidSetInformation: { completion(nil) return nil }) } else{ completion(error) } }) } /// Increments the 'swaps' value of a user. It increments by '1' by default if you do not pass anything as a parameter /// /// - Parameter byValue: 1 by default. It will decrement if you pass a negative number func incrementSwaps(byValue: NSNumber = 1, completion: @escaping (_ error: Error?) -> Void = {_ in return}) { let username = AWSDynamoDBAttributeValue() username?.s = self.username let value = AWSDynamoDBAttributeValue() value?.n = "\(byValue)" let updateItemInput = AWSDynamoDBUpdateItemInput() updateItemInput?.tableName = "swap-mobilehub-1081613436-Users" updateItemInput?.key = ["username": username!] updateItemInput?.updateExpression = "SET swaps = swaps + :val" updateItemInput?.expressionAttributeValues = [":val": value!] self.dynamoDB.updateItem(updateItemInput!, completionHandler: {(output, error) in DispatchQueue.main.async { completion(error) } }) } func incrementSwapped(byValue: NSNumber = 1, completion: @escaping (_ error: Error?) -> Void = { _ in return}) { let username = AWSDynamoDBAttributeValue() username?.s = self.username let value = AWSDynamoDBAttributeValue() value?.n = "\(byValue)" let updateItemInput = AWSDynamoDBUpdateItemInput() updateItemInput?.tableName = "swap-mobilehub-1081613436-Users" updateItemInput?.key = ["username": username!] updateItemInput?.updateExpression = "SET swapped = swapped + :val" updateItemInput?.expressionAttributeValues = [":val": value!] self.dynamoDB.updateItem(updateItemInput!, completionHandler: {(output, error) in DispatchQueue.main.async { completion(error) } }) } func incrementPoints(byValue: NSNumber = 1, completion: @escaping (_ error: Error?) -> Void = { _ in return }) { let username = AWSDynamoDBAttributeValue() username?.s = self.username let value = AWSDynamoDBAttributeValue() value?.n = "\(byValue)" let updateItemInput = AWSDynamoDBUpdateItemInput() updateItemInput?.tableName = "swap-mobilehub-1081613436-Users" updateItemInput?.key = ["username": username!] updateItemInput?.updateExpression = "SET points = points + :val" updateItemInput?.expressionAttributeValues = [":val": value!] self.dynamoDB.updateItem(updateItemInput!, completionHandler: {(output, error) in DispatchQueue.main.async { completion(error) } }) } /// Function that returns an array of SwapHistory objects /// /// - Parameter result: Returns and Error and an array of SwapHistory objects. Error will be nil if there is no error. Be sure to unwrap the swapHistory array. Iterate through swapHistories array to retrieve each individual SwapHistory object. See SwapHistory class for more information on a Swap History object. Each Swap History object has a property associated with the information it contains. For example: swapHistory._swapped is the person that was 'Swapped' and swapHistory.swap is the person that swapped. Each property also tells whether the specific social media were shared or not. It may be 'nil' or 'false' or 'true'. If swaphistory._didShareTwitter is nil or false , Twitter was not shared. It is more likely the value will be nil rather than false. If there are no records for Swap History, the array will be empty. func getSwapHistory(result: @escaping (_ queryError: Error?, _ swapHistories: [SwapHistory]?) -> Void) { // Configures so that most recent data is obtained from NoSQL let config = AWSDynamoDBObjectMapperConfiguration() config.consistentRead = true let queryExpression = AWSDynamoDBQueryExpression() queryExpression.keyConditionExpression = "#hashAttribute = :hashAttribute" queryExpression.expressionAttributeNames = ["#hashAttribute": "swap"] queryExpression.expressionAttributeValues = [":hashAttribute": self.username] DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.query(SwapHistory.self, expression: queryExpression, configuration: config, completionHandler: { (output, error) in DispatchQueue.main.async { if error != nil{ print("error querying ... \(error)") result(error, nil) } else{ // Converts the response to an array of Swap History objects let swapHistories = output?.items as! [SwapHistory] result(nil, swapHistories) } } }) } } /// Sets the user's One Signal User ID in database in order to send push notifications. Call this function when the user is signed in. func setUpPushNotifications() { // Ensures that if a value is not passed in the function, it is ignored when saved into database updateMapperConfig.saveBehavior = .updateSkipNullAttributes OneSignal.idsAvailable { (userID, pushToken) in print("THE NOTIFICATION ID IS .... \(userID)") if let notificationID = userID{ // Creates an 'Users' object in order to store to database let user = Users() user?._username = self.username user?._notification_id_one_signal = notificationID self.NoSQL.save(user!, configuration: self.updateMapperConfig, completionHandler: { (error) in }) } } } /// Removes the user's One Signal ID from the database. Call this function when the user attempts to sign out so that it no longer receives notifications on an account that has been signed out. It sets the User ID to '0' because a one signal user ID will not be 0. func removePushNotificationID() { // Ensures that if a value is not passed in the function, it is ignored when saved into database updateMapperConfig.saveBehavior = .updateSkipNullAttributes // Creates an 'Users' object in order to store to database let user = Users() user?._username = self.username user?._notification_id_one_signal = "0" self.NoSQL.save(user!, configuration: self.updateMapperConfig, completionHandler: { (error) in }) } /// Sends Notification user that they have been swapped /// -todo: Use OneSignal API so when the user clicks the notification, he is brought to the Swap History Screen func sendSwappedNotification(bySwapUser: SwapUser) { bySwapUser.getInformation { (error, byUser) in if let byUser = byUser { let nameOfUser = "\(byUser._firstname!) \(byUser._lastname!)" let usernameOfUser = byUser._username! self.getInformation { (error, user) in if error == nil{ if let id = user!._notification_id_one_signal{ OneSignal.postNotification(["contents": ["en": "\(nameOfUser) (@\(usernameOfUser)) has Swapped™ you."], "content_available": true, "ios_badgeType": "Increase", "ios_badgeCount": "1", "include_player_ids": [id]]) } } } } } } func sendSwapRequest(toSwapUser: SwapUser, completion: @escaping (_ error: Error?) -> Void = {_ in return}) { let request = SwapRequest() request?._sender = self.username request?._requested = toSwapUser.username request?._sent_at = NSDate().timeIntervalSince1970 as NSNumber // Current Time request?._status = false // Not accepted yet request?._sender_confirmed_acceptance = false // Sender has not confirmed yet request?._requested_user_has_responded_to_request = false updateMapperConfig.saveBehavior = .updateSkipNullAttributes NoSQL.save(request!, configuration : updateMapperConfig, completionHandler: { error in if error == nil{ self.getInformation(completion: { (error, me) in if let sender = me{ // Send Swap Request Notification To User toSwapUser.getInformation(completion: { (error, user) in if let user = user { // Did get information and there is no error let nameOfUser = "\(sender._firstname!) \(sender._lastname!)" let usernameOfUser = sender._username! if let id = user._notification_id_one_signal{ // Can send a notification to user // Sends notification to user OneSignal.postNotification([ "contents": ["en": "\(nameOfUser) (@\(usernameOfUser)) requested to Swap™ you."], "include_player_ids": [id], "content_available": true, "ios_badgeType": "Increase", "ios_badgeCount": "1", "buttons": [ ["id": "Accept", "text": "Accept"], ["id": "Decline", "text": "Decline"] ], "data": ["username": usernameOfUser] ]) } } }) } }) } // Error will be nil if everything worked completion(error) }) } func sendNotifcationOfSwapRequestAcceptanceToUser(withUsername: String) { self.getInformation { (error, thisUser) in if let thisUser = thisUser{ let nameOfUser = "\(thisUser._firstname!) \(thisUser._lastname!)" let username = thisUser._username! SwapUser(username: withUsername).getInformation { (error, user) in if let user = user { if let id = user._notification_id_one_signal{ // Send Notification to User withUsername that the Swap Request has been accepted // Sends notification to user OneSignal.postNotification([ "contents": ["en": "\(nameOfUser) (@\(username)) has accepted your Swap™ Request."], "content_available": true, "ios_badgeType": "Increase", "ios_badgeCount": "1", "include_player_ids": [id] ]) } } } } } } /// Function that returns an array of SwapRequest objects /// /// - Parameter result: Returns an array of SwapRequests that the user has sent out. When obtaining the swap requests array, ensure that the status (swapRequest.status) == true before allowing the user to press the swap button to confirm. The status property tells if the requested user has accepted a swap request. If the user has ignored the swap request, status will be false. If the user has denied a swap request, it will not be shown in the array. Here is an example: If David a private user and Micheal sends a swap request to David. Initially, the sender is Micheal, the requested is David, the status is false, and sender_confirmed_acceptance is also false. If David accepts the friend request, status = true when Micheal attempts to getPendingSentSwapRequests. If David has neither accepted or denied request, status = true. However, if David denies the request, the request is removed from getPendingSentSwapRequest and status = false AND sender_confirmed = true. func getPendingSentSwapRequests(result: @escaping (_ error: Error?, _ requests: [SwapRequest]?) -> Void) { // Configures so that most recent data is obtained from NoSQL let queryExpression = AWSDynamoDBQueryExpression() queryExpression.indexName = "sender" queryExpression.keyConditionExpression = "#hashAttribute = :hashAttribute" queryExpression.expressionAttributeNames = ["#hashAttribute": "sender", "#sender_confirmed_acceptance":"sender_confirmed_acceptance"] queryExpression.expressionAttributeValues = [":hashAttribute": self.username, ":val": false] queryExpression.filterExpression = "#sender_confirmed_acceptance = :val" DispatchQueue.global(qos: .userInteractive).async { self.NoSQL.query(SwapRequest.self, expression: queryExpression, completionHandler: { (output, error) in DispatchQueue.main.async { if error != nil{ result(error, nil) } else{ // Converts the response to an array of Swap History objects let swapRequests = output?.items as! [SwapRequest] result(nil, swapRequests) } } }) } } /// If Micheal sends David a Swap Request and David accepts it, this function should be called where withUsername = David so that sender_confirmed = true so that it is removed from the getPendingSentSwapRequests array. /// /// func confirmSwapRequestToUser(withUsername: String, completion: @escaping (_ error: Error?) -> Void = {_ in return }) { let swapRequest = SwapRequest() updateMapperConfig.saveBehavior = .updateSkipNullAttributes swapRequest?._sender = self.username swapRequest?._requested = withUsername swapRequest?._sender_confirmed_acceptance = true NoSQL.save(swapRequest!, configuration: updateMapperConfig, completionHandler: { error in completion(error) }) } func performActionOnSwapRequestFromUser(withUsername: String, doAccept: Bool, completion: @escaping (_ error: Error?) -> Void = {_ in return }) { let swapRequest = SwapRequest() updateMapperConfig.saveBehavior = .updateSkipNullAttributes swapRequest?._sender = withUsername swapRequest?._requested = self.username swapRequest?._status = doAccept as NSNumber swapRequest?._requested_user_has_responded_to_request = true as NSNumber if !doAccept{ // Sender rejected the Swap Request. So now, set senderConfirmed = true so that it no longer appears on their pending Swap Requests swapRequest?._sender_confirmed_acceptance = true } NoSQL.save(swapRequest!, configuration: updateMapperConfig, completionHandler: { error in if error == nil { if doAccept { self.sendNotifcationOfSwapRequestAcceptanceToUser(withUsername: withUsername) } } completion(error) }) } /// Gets the Swap Requests sent to the user func getRequestedSwaps(result: @escaping (_ error: Error?, _ requests: [SwapRequest]?) -> Void) { // Configures so that most recent data is obtained from NoSQL let queryExpression = AWSDynamoDBQueryExpression() queryExpression.indexName = "requested" queryExpression.keyConditionExpression = "#hashAttribute = :hashAttribute" // Attribute Names for Query queryExpression.expressionAttributeNames = ["#hashAttribute": "requested", "#requested_user_has_responded_to_request":"requested_user_has_responded_to_request"] // Values for Query queryExpression.expressionAttributeValues = [":hashAttribute": self.username, ":val": false] queryExpression.filterExpression = "#requested_user_has_responded_to_request = :val" self.NoSQL.query(SwapRequest.self, expression: queryExpression, completionHandler: { (output, error) in if error != nil{ result(error, nil) } else{ // Converts the response to an array of Swap History objects let swapRequests = output?.items as! [SwapRequest] result(nil, swapRequests) } }) } /// When two users have swapped, 'User A swaps user B', use this function to determine whether or not we should increment the swaps of user A and swapped of user B and give points to both. Do this AFTER the completion block of swapping is executed. It will return a boolean wheter or not points/swap/swapped SHOULD be given. class func shouldGivePointsSwapAndSwappedBetweenUsers(userWhoSwapped: SwapUser, userSwapped: SwapUser, result: @escaping (_ shouldGivePoints: Bool) -> Void ) { AWSDynamoDBObjectMapper.default().load(SwapHistory.self, hashKey: userWhoSwapped.username, rangeKey: userSwapped.username, completionHandler: { (request, error) in if let error = error{ // Should give points because a swap history record doesn't exist result(true) } else{ if let swaphistory = request as? SwapHistory{ // Swap History does exist so check if we've given points or not let didGivePoints = swaphistory._didGiveSwapPointsFromSwap?.boolValue ?? false result(!didGivePoints) } else{ // No record exists so give points result(true) } } }) } /// Use this function to check if user has swapped another user. func hasSwapped(withUser: SwapUser, result: @escaping (_ hasSwapped: Bool) -> Void) { // hashKey/swap = self // rangeKey/swapped = withUser self.NoSQL.load(SwapHistory.self, hashKey: self.username, rangeKey: withUser.username, completionHandler: { (request, error) in if let error = error{ result(false) } else{ if let _ = request as? SwapHistory{ result(true) } else{ result(false) } } }) } /* /// Downloads the social media compilation of the user func downloadCompilation() { let username = self.username // Get Compilation Object Or Create One if It doesn't exist let compilation = Compilation() compilation.id = username self.getInformation { (error, user) in if let user = user { // Update Compilation Object let realm1 = try! Realm() try! realm1.write { realm1.create(Compilation.self, value: ["id": username, "name": "\(user._firstname!) \(user._lastname!)", "isVerified": user._isVerified?.boolValue ?? false, "profilePicture": user._profilePictureUrl!], update: true) } // Download Tweets if let token = getTwitterToken(), let secret = getTwitterSecret(){ let swifter = Swifter(consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, oauthToken: token, oauthTokenSecret: secret) if let twitterID = user._twitterID{ swifter.getTimeline(for: twitterID, success: { (twitterJSON) in let realm2 = try! Realm() realm2.refresh() if let ownerCompilation = realm2.object(ofType: Compilation.self, forPrimaryKey: username){ // Can get compilation object from database var dateUpdated = ownerCompilation.updatedAt var hasSeen = ownerCompilation.hasBeenViewed if let tweets = returnTweets(fromJSON: twitterJSON){ if tweets.count != ownerCompilation.Tweets.count{ // New Tweets have been added since before // Update the dateUpdated dateUpdated = Date() hasSeen = false } try! realm2.write { realm2.create(Compilation.self, value: ["id": username, "Tweets": tweets, "updatedAt": dateUpdated as Date?, "hasBeenViewed": hasSeen], update: true) } } } }) } } } } } */ func swap(with userWithUsername: String, authorizeOnViewController: UIViewController, overridePrivateAccount: Bool = false, method: SwapMethod = .scan, completion: @escaping (_ error: Error?, _ user: Users?) -> Void){ guard self.username != userWithUsername else{ completion(UserError.CannotFollowSelf, nil) return } SwapUser(username: userWithUsername).getInformation(completion: { (error, user) in if error != nil { // There was an error trying to get the user from the swap code print("Could not get user.. Not a valid Swap Code... User does not exist...or bad internet connection") DispatchQueue.main.async { completion(error, nil) } } if let user = user{ // Could get user let userIsPrivate = user._isPrivate as! Bool let shouldSendSwapRequest = overridePrivateAccount ? false : userIsPrivate if shouldSendSwapRequest{ SwapUser(username: getUsernameOfSignedInUser()).sendSwapRequest(toSwapUser: SwapUser(username: user._username!), completion: { error in if error != nil { completion(error, nil) } else { // Request Sent // Log analytics Analytics.didSwap(byMethod: method, isPrivate: true) DispatchQueue.main.async { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) completion(nil, user) } } }) } else{ //configure confirm swap screen DispatchQueue.global(qos: .userInitiated).async { let currentUser = self let otherUser = SwapUser(username: userWithUsername) let history = SwapUserHistory(swap: self.username, swapped: userWithUsername) history.didShare() // Share social medias shareVine(withUser: user) shareSpotify(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) createContactInPhone(withContactDataOfUser: user, completion: {_ in return }) shareInstagram(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) shareTwitter(withUser: user) shareYouTube(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) shareSoundCloud(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) sharePinterest(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) shareReddit(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) shareGitHub(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) shareVimeo(withUser: user, andIfNeededAuthorizeOnViewController: authorizeOnViewController) otherUser.sendSwappedNotification(bySwapUser: SwapUser(username: getUsernameOfSignedInUser())) // Log Analytics // If current user has social media connected and the other has the social media 'on' then essentially the user has shared that social media. +- ~3% margin error perhaps // ========= Begin Loggin Analytics ==================================== let sharedSpotify = (spotify_oauth2.accessToken != nil || spotify_oauth2.refreshToken != nil) && (user._willShareSpotify?.boolValue ?? false) && (user._spotifyID != nil) let sharedPhone = (user._willSharePhone?.boolValue ?? false) let sharedEmail = (user._willShareEmail?.boolValue ?? false) let sharedInstagram = (instagram_oauth2.accessToken != nil || instagram_oauth2.refreshToken != nil) && (user._willShareInstagram?.boolValue ?? false) && user._instagramID != nil let sharedReddit = (reddit_oauth2.accessToken != nil || spotify_oauth2.refreshToken != nil) && (user._willShareSpotify?.boolValue ?? false) && user._redditID != nil let sharedTwitter = (getTwitterToken() != nil && getTwitterSecret() != nil ) && (user._willShareTwitter?.boolValue ?? false) && user._twitterID != nil let sharedYouTube = (youtube_oauth2.accessToken != nil || youtube_oauth2.refreshToken != nil) && (user._willShareYouTube?.boolValue ?? false) && user._youtubeID != nil let sharedSoundCloud = (soundcloud_oauth2.accessToken != nil || soundcloud_oauth2.refreshToken != nil) && (user._willShareSoundCloud?.boolValue ?? false) && user._soundcloudID != nil let sharedPinterest = (pinterest_oauth2.accessToken != nil || pinterest_oauth2.refreshToken != nil) && (user._willSharePinterest?.boolValue ?? false) && user._pinterestID != nil let sharedGitHub = (github_oauth2.accessToken != nil || github_oauth2.refreshToken != nil) && (user._willShareGitHub?.boolValue ?? false) && user._githubID != nil let sharedVimeo = (vimeo_oauth2.accessToken != nil || vimeo_oauth2.refreshToken != nil) && (user._willShareVimeo?.boolValue ?? false) && user._vimeoID != nil Analytics.didSwap(byMethod: method, didShareSpotify: sharedSpotify, didSharePhone: sharedPhone, didShareEmail: sharedEmail, didShareInstagram: sharedInstagram, didShareReddit: sharedReddit, didShareTwitter: sharedTwitter, didShareYouTube: sharedYouTube, didShareSoundCloud: sharedSoundCloud, didSharePinterest: sharedPinterest, didShareGitHub: sharedGitHub, didShareVimeo: sharedVimeo) // ========= End Logging Analytics ==================================== DispatchQueue.main.async { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) completion(nil, user) } } } } }) } /// Call this function after the completion block of a swap action is called in order to increment the swaps of the user 'swap' and the swapped points of the user 'swapped'. If user A swaps user B, this function will add the appropiate swap points to each user. User A is swap, User B is swapped class func giveSwapPointsToUsersWhoSwapped(swap: SwapUser, swapped: SwapUser) { SwapUser.shouldGivePointsSwapAndSwappedBetweenUsers(userWhoSwapped: swap, userSwapped: swapped) { (shouldGivePoints) in if shouldGivePoints { swap.incrementSwaps() swapped.incrementSwapped() swap.incrementPoints(byValue: 5, completion: {_ in return }) swapped.incrementPoints(byValue: 5, completion: {_ in return }) // Add to swap history that points were given let history = SwapUserHistory(swap: swap.username, swapped: swapped.username) history.didShare(didGivePoints: true) } else{ // Points are already given so forget it } } } } <file_sep>// // ShareSwapLinkView.swift // Swap // // Created by <NAME> on 1/26/17. // // import Foundation import Answers class ShareSwapLinkView: UIViewController{ @IBOutlet var swapLink: UILabel! var loadingView: UIImageView? = nil override func viewDidLoad() { loadingView = ShowLoadingOverlay().showLoadingSymbol(view: self.view) self.view.addSubview(loadingView!) swapLink.text = "getswap.me/\(getUsernameOfSignedInUser())" let shareVC = UIActivityViewController(activityItems: ["Swap with me! " + swapLink.text!], applicationActivities: nil) present(shareVC, animated: true, completion: { self.loadingView?.isHidden = true }) } override func viewWillAppear(_ animated: Bool) { //configure nav bar let shareButton = UIBarButtonItem(image: #imageLiteral(resourceName: "ShareIcon"), style: .plain, target: self, action: #selector(didTapShare)) shareButton.tintColor = UIColor.white self.navigationItem.rightBarButtonItem = shareButton } @IBAction func copyLink(_ sender: Any) { UIPasteboard.general.string = swapLink.text } @IBAction func didTapBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) } func didTapShare() { self.loadingView?.isHidden = false let shareVC = UIActivityViewController(activityItems: [swapLink.text!], applicationActivities: nil) present(shareVC, animated: true, completion: { self.loadingView?.isHidden = true // Answers.logInvite(withMethod: "Swap Link", customAttributes: nil) }) } } <file_sep>// // ConnectSocialMedias.swift // Swap // // Created by <NAME> on 12/16/16. // // import Foundation import p2_OAuth2 import Alamofire import SwiftyJSON import Swifter import Contacts import Kingfisher /// Function that follows the given user on Twitter. Authorizes the Twitter Account based on the stored Twitter Access Token and Twitter Secret Token /// /// func shareTwitter(withUser: Users?, completion: (_ error: Error?) -> Void = {noError in return}) { // Ensures a Twitter Account is Connected Before Proceeding guard ( getTwitterToken() != nil && getTwitterSecret() != nil ) else{ completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Pinterest with completion(UserError.CouldNotGetUser) return } let UserWillShareTwitter = user._willShareTwitter as? Bool ?? false guard UserWillShareTwitter else{ completion(UserError.WillNotShareSocialMedia) return } guard let TwitterID = user._twitterID else { // User does not have a Twitter ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) let twitterAccount = Swifter(consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, oauthToken: getTwitterToken()!, oauthTokenSecret: getTwitterSecret()!) twitterAccount.followUser(for: UserTag.id(TwitterID), follow: false, success: { json in // success history.didShare(TwitterIs: true) }, failure: { error in // it failed }) } func shareReddit(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return}) { guard (reddit_oauth2.accessToken != nil || reddit_oauth2.refreshToken != nil) else { // User does not have a Reddit account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Pinterest with completion(UserError.CouldNotGetUser) return } let UserWillShareReddit = user._willShareReddit as? Bool ?? false guard UserWillShareReddit else{ completion(UserError.WillNotShareSocialMedia) return } guard let RedditID = user._redditID else { // User does not have a reddit ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize Reddit reddit_oauth2.authConfig.authorizeEmbedded = true reddit_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController reddit_oauth2.authConfig.ui.useSafariView = false reddit_oauth2.authorize(params: ["duration": "permanent"], callback: { (json, error) in if error != nil { // There was some error trying to authorize it completion(AuthorizationError.Unknown) } else{ let loader = RedditLoader() loader.addFriend(withUsername: RedditID, callback: { (json, error) in if let error = error{ completion(error) } if let response = json{ // Check if "id" is in the JSON to determine if it is a success if let id = response["id"] as? String{ // FOLLOWING WORKED history.didShare(RedditIs: true) completion(nil) } else{ // Did not work completion(AuthorizationError.Unknown) } } }) } }) } /// Function that follows given user on Pinterest. Function will first check if a Pinterest account is configured, if not, an error will be returned in completion block. Function will also check if the user has set permission to follow on Pinterest. If there is no valid (expired) access token and refresh token, the function will attempt to authorize the user with an embedded web view controller on view controller specified. /// /// - Parameters: /// - withUser: Users object of user you want to follow /// - andIfNeededAuthorizeOnViewController: usually self /// - completion: Completion block executed. Error is nil if it succeeds in following on Pinterest. /// - error: The error is nil if the user is successfully followed. Error = UserError.NotConnected if the current user does not have Pinterest connected. Error = UserError.CouldNotGetUser if withUser is nil. Error = UserError.WillNotShareSocialMedia if 'withUser' has Pinterest off or if 'withUser' does not have a Pinterest Account Configured. func sharePinterest(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return} ) { guard (pinterest_oauth2.accessToken != nil || pinterest_oauth2.refreshToken != nil) else { // User does not have a Pinterest account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Pinterest with completion(UserError.CouldNotGetUser) return } let UserWillSharePinterest = user._willSharePinterest as? Bool ?? false guard UserWillSharePinterest else{ completion(UserError.WillNotShareSocialMedia) return } guard let PinterestID = user._pinterestID else { // User does not have a pinterest ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize Pinterest pinterest_oauth2.authConfig.authorizeEmbedded = true pinterest_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController pinterest_oauth2.authConfig.ui.useSafariView = false // Will show login screen if cannot refresh access token with refresh token pinterest_oauth2.authorize { (json, error) in if error != nil { // There was some error trying to authorize it completion(AuthorizationError.Unknown) } else{ var req = pinterest_oauth2.request(forURL: URL(string: "https://api.pinterest.com/v1/me/following/users/?user=\(PinterestID)")!) req.httpMethod = "POST" let task = pinterest_oauth2.session.dataTask(with: req) { data, response, error in if let error = error { // There was an error making the request completion(error) } else { if let data = data { // There is data in the request let jsonResponse = JSON(data: data) // the json response for "data" is nil if it succeeded in following let followedAccount = jsonResponse["data"].string == nil if followedAccount{ // SUCCESS // Set in Swap History print("did follow pinterest") history.didShare(PinterestIs: true) completion(nil) } else{ completion(UserError.Unknown) } } else{ // No data in request completion(AuthorizationError.Unknown) } } } task.resume() } } } /// Function that follows given user on Spotify. Function will first check if a Spotify account is configured, if not, an error will be returned in completion block. Function will also check if the user has set permission to follow on Spotify. If there is no valid (expired) access token and refresh token, the function will attempt to authorize the user with an embedded web view controller on view controller specified. /// - Author: <NAME> /// - Parameters: /// - withUser: Users object of user you want to follow /// - andIfNeededAuthorizeOnViewController: usually self /// - completion: Completion block executed. Error is nil if it succeeds in following on Pinterest. /// - error: The error is nil if the user is successfully followed. Error = UserError.NotConnected if the current user does not have Spotify connected. Error = UserError.CouldNotGetUser if withUser is nil. Error = UserError.WillNotShareSocialMedia if 'withUser' has Spotify off or if 'withUser' does not have a Spotify Account Configured. func shareSpotify(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return}) { guard (spotify_oauth2.accessToken != nil || spotify_oauth2.refreshToken != nil )else { // User does not have a Spotify account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Spotify with completion(UserError.CouldNotGetUser) return } let UserWillShareSpotify = user._willShareSpotify as? Bool ?? false guard UserWillShareSpotify else{ completion(UserError.WillNotShareSocialMedia) return } guard let SpotifyID = user._spotifyID else { // User does not have a Spotify ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize Spotify spotify_oauth2.authConfig.authorizeEmbedded = true spotify_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController spotify_oauth2.authConfig.ui.useSafariView = false // Will show login screen if cannot refresh access token with refresh token spotify_oauth2.authorize { (json, error) in if error != nil { // There was some error trying to authorize it completion(AuthorizationError.Unknown) } else{ var req = spotify_oauth2.request(forURL: URL(string: "https://api.spotify.com/v1/me/following?type=user&ids=\(SpotifyID)")!) req.httpMethod = "PUT" let task = spotify_oauth2.session.dataTask(with: req) { data, response, error in if let error = error { // There was an error making the request completion(error) } else { if let data = data { // There is data in the request let jsonResponse = JSON(data: data) // Parse JSON response for errors or success**** print("the json response for spotify follow is ....\(jsonResponse)") let didFollow = jsonResponse.string == nil if didFollow{ print("DID FOLLOW SPOTIFY") history.didShare(SpotifyIs: true) completion(nil) } else{ // Did not follow user completion(UserError.Unknown) } } else{ // No data in request completion(AuthorizationError.Unknown) } } } task.resume() } } } /// Function that follows given user on Instagram. Function will first check if an Instagram account is configured, if not, an error will be returned in completion block. Function will also check if the user has set permission to follow on Instagram. If there is no valid (expired) access token and refresh token, the function will attempt to authorize the user with an embedded web view controller on view controller specified. /// - Author: <NAME> /// - Parameters: /// - withUser: Users object of user you want to follow /// - andIfNeededAuthorizeOnViewController: usually self /// - completion: Completion block executed. Error is nil if it succeeds in following on Instagram. /// - error: The error is nil if the user is successfully followed. Error = UserError.NotConnected if the current user does not have Instagram connected. Error = UserError.CouldNotGetUser if withUser is nil. Error = UserError.WillNotShareSocialMedia if 'withUser' has Instagram off or if 'withUser' does not have a Instagram Account Configured. func shareInstagram(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return}) { guard (instagram_oauth2.accessToken != nil || instagram_oauth2.refreshToken != nil) else { // User does not have a Instagram account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Instagram with completion(UserError.CouldNotGetUser) return } let UserWillShareInstagram = user._willShareInstagram as? Bool ?? false guard UserWillShareInstagram else{ completion(UserError.WillNotShareSocialMedia) return } guard let InstagramID = user._instagramID else { // User does not have a Instagram ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize Instagram instagram_oauth2.authConfig.authorizeEmbedded = true instagram_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController instagram_oauth2.authConfig.ui.useSafariView = false // Will show login screen if cannot refresh access token with refresh token instagram_oauth2.authorize { (json, error) in if let error = error { // There was some error trying to authorize it print("error refreshing .. \(error)") completion(AuthorizationError.Unknown) } else{ Alamofire.request("https://api.instagram.com/v1/users/\(InstagramID)/relationship", method: .post, parameters: ["action": "follow", "access_token": instagram_oauth2.accessToken!]).responseJSON(completionHandler: { (response) in if let data = response.data{ let json = JSON(data: data) print("instagram follow response .. \(json)") if let code = json["meta"]["code"].int{ if code == 200{ // SUCCESS // Add to Swap History history.didShare(InstagramIs: true) completion(nil) } else{ // No success code completion(UserError.Unknown) } } else{ // No success completion(UserError.Unknown) } } else{ // No data in reponse completion(AuthorizationError.Unknown) } }) } } } /// Function that follows the user on YouTube. See other 'share' functions for additional details to the functionality. /// /// - Parameters: /// - withUser: User to follow on YouTube /// - completion: Error is nil if there is success func shareYouTube(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return}) { guard (youtube_oauth2.accessToken != nil || youtube_oauth2.refreshToken != nil) else { // User does not have a YouTube account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share YouTube with completion(UserError.CouldNotGetUser) return } let UserWillShareYouTube = user._willShareYouTube as? Bool ?? false guard UserWillShareYouTube else{ completion(UserError.WillNotShareSocialMedia) return } guard let YouTubeID = user._youtubeID else { // User does not have a YouTube ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Continue to Subscribe on YouTube let parameters: [String: Any]? = [ "snippet": [ "resourceId": [ "channelId": "\(YouTubeID)" ] ] ] youtube_oauth2.authorizeEmbedded(from: andIfNeededAuthorizeOnViewController) { (json, error) in if error != nil{ // Can't Authorize completion(AuthorizationError.Unknown) } else{ // Subscribe on YouTube let headers: HTTPHeaders = [ "Authorization": "Bearer \(youtube_oauth2.accessToken!)", "Accept": "application/json" ] let url = "https://www.googleapis.com/youtube/v3/subscriptions?part=snippet" Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: { (response) in if let data = response.data{ let jsonReply = JSON(data: data) if let id = jsonReply["id"].string{ // Follow Attempt Worked history.didShare(YouTubeIs: true) completion(nil) } else{ //Did not work completion(UserError.CouldNotGetUser) } } else{ completion(UserError.Unknown) } }) } } } func shareGitHub(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error? ) -> Void = {noError in return}) { guard (github_oauth2.accessToken != nil || github_oauth2.refreshToken != nil) else { // User does not have a GitHub account connected print("no git hub connected") completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share GitHub with completion(UserError.CouldNotGetUser) return } let UserWillShareGitHub = user._willShareGitHub as? Bool ?? false guard UserWillShareGitHub else{ completion(UserError.WillNotShareSocialMedia) return } guard let GitHubID = user._githubID else { // User does not have a GitHub ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize GitHub github_oauth2.authConfig.authorizeEmbedded = true github_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController github_oauth2.authConfig.ui.useSafariView = false // Will show login screen if there is no valid refresh token to refresh access token github_oauth2.authorize { (json, error) in if let _ = error { // Some error authorizing GitHub print("Some error authorizing github") completion(AuthorizationError.Unknown) } else{ // Try to follow on GitHub if let accessToken = github_oauth2.accessToken{ print("access token found") Alamofire.request("https://api.github.com/user/following/\(GitHubID)?access_token=\(accessToken)", method: .put).responseJSON(completionHandler: { (response) in if let response = response.response{ let code = response.statusCode if code == 204{ // most likely a success history.didShare(GitHubIs: true) DispatchQueue.main.async { completion(nil) } } else{ // most likely a fail completion(AuthorizationError.Unknown) } } else{ completion(AuthorizationError.Unknown) } }) } else{ // No Access Token print("no github access token") completion(UserError.Unknown) } } } } /// Function that follows the user on SoundCloud. See other 'share' functions for additional details to the functionality. /// /// - Parameters: /// - withUser: User to follow on SoundCloud /// - andIfNeededAuthorizeOnViewController: Usually self /// - completion: Error is nil if there is success func shareSoundCloud(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return }) { guard (soundcloud_oauth2.accessToken != nil || soundcloud_oauth2.refreshToken != nil) else { // User does not have a SoundCloud account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share SoundCloud with completion(UserError.CouldNotGetUser) return } let UserWillShareSoundCloud = user._willShareSoundCloud as? Bool ?? false guard UserWillShareSoundCloud else{ completion(UserError.WillNotShareSocialMedia) return } guard let SoundCloudID = user._soundcloudID else { // User does not have a SoundCloud ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Sets up Authorization Screen if you need to authorize SoundCloud soundcloud_oauth2.authConfig.authorizeEmbedded = true soundcloud_oauth2.authConfig.authorizeContext = andIfNeededAuthorizeOnViewController soundcloud_oauth2.authConfig.ui.useSafariView = false // Will show login screen if there is no valid refresh token to refresh access token soundcloud_oauth2.authorize { (json, error) in if let _ = error { // Some error authorizing SoundCloud completion(AuthorizationError.Unknown) } else{ // Try to follow on SoundCloud Alamofire.request("https://api.soundcloud.com/me/followings/\(SoundCloudID).json?oauth_token=\(soundcloud_oauth2.accessToken!)&client_id=\(soundcloud_oauth2.clientId!)", method: .put).responseJSON(completionHandler: { (response) in if let Data = response.data{ let soundcloudJSON = JSON(data: Data) // Reads JSON to check if it succeeded in following print("the soundcloud response is ... \(soundcloudJSON)") if let status = soundcloudJSON["status"].string{ if status.contains("OK"){ // SoundCloud Worked history.didShare(SoundCloudIs: true) completion(nil) } } else if let id = soundcloudJSON["id"].int{ if "\(id)" == "\(SoundCloudID)"{ // Soundcloud Worked history.didShare(SoundCloudIs: true) completion(nil) } else{ // Did not work completion(UserError.Unknown) } } } else{ // No data in response completion(UserError.Unknown) } }) } } } func shareVine(withUser: Users?, completion: @escaping (_ error: Error?) -> Void = {noError in return }) { guard getVinePassword() != nil && getVineUsername() != nil else{ // No Vine Account Configured completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Vine with completion(UserError.CouldNotGetUser) return } let UserWillShareVine = user._willShareVine as? Bool ?? false guard UserWillShareVine else{ completion(UserError.WillNotShareSocialMedia) return } guard let VineID = user._vineID else { // User does not have a Vine ID connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Attempt to Authorize Vine authorizeVine(username: getVineUsername()!, password: <PASSWORD>()!, completion: { error, key, _ in if error != nil{ // Error Authorizing completion(AuthorizationError.Unknown) } else{ // Continue to follow Vine let headers = ["vine-session-id": key!] Alamofire.request("https://api.vineapp.com/users/\(VineID)/followers", method: .post, parameters: nil, headers: headers).responseJSON(completionHandler: { (response) in if let data = response.data{ let json = JSON(data: data) print("Vine json is ... \(json)") print(json) if json["success"].boolValue{ history.didShare(VineIs: true) completion(nil) } else{ // Could not follow completion(UserError.Unknown) } } else{ completion(UserError.Unknown) } }) } }) } func shareVimeo(withUser: Users?, andIfNeededAuthorizeOnViewController: UIViewController, completion: @escaping (_ error: Error?) -> Void = {noError in return} ) { guard (vimeo_oauth2.accessToken != nil || vimeo_oauth2.refreshToken != nil )else { // User does not have a Vimeo account connected completion(UserError.NotConnected) return } guard let user = withUser else{ // There is no user to share Vimeo with completion(UserError.CouldNotGetUser) return } let UserWillShareVimeo = user._willShareVimeo as? Bool ?? false guard UserWillShareVimeo else{ completion(UserError.WillNotShareSocialMedia) return } guard let VimeoID = user._vimeoID else { // User does not have a Vimeo ID Connected completion(UserError.WillNotShareSocialMedia) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) // Try to follow vimeo_oauth2.authorizeEmbedded(from: andIfNeededAuthorizeOnViewController, callback: { (response, error) in if let error = error{ completion(error) } else{ // No error authorizing now try to Follow let vimeoLoader = OAuth2DataLoader(oauth2: vimeo_oauth2) var vimeoFollowRequest = vimeo_oauth2.request(forURL: URL(string: "https://api.vimeo.com/me/following/\(VimeoID)")!) vimeoFollowRequest.httpMethod = "PUT" vimeoLoader.perform(request: vimeoFollowRequest, callback: { (response) in let responseCode = response.response.statusCode if responseCode == 204{ // success history.didShare(VimeoIs: true) completion(nil) } else{ // failure completion(AuthorizationError.Unknown) } }) } }) } /// /// -todo: Check if Contact already exists before adding (done March 2017 <NAME>) /// - Parameters /// - withContactDataOfUser: /// - completion: func createContactInPhone(withContactDataOfUser: Users?, completion: @escaping (_ error: Error?) -> Void) { var DidSharePhone: Bool? = nil var DidShareEmail: Bool? = nil guard let user = withContactDataOfUser else{ // There is no user to obtain contact completion(UserError.CouldNotGetUser) return } // Creates a SwapUserHistory Object in order to save in Swap History if the Follow Attempt was a success let history = SwapUserHistory(swap: getUsernameOfSignedInUser(), swapped: user._username!) let UserWillSharePhone = user._willSharePhone as? Bool ?? false let UserWillShareEmail = user._willShareEmail as? Bool ?? false guard UserWillSharePhone || UserWillShareEmail else{ completion(UserError.WillNotShareSocialMedia) return } var store = CNContactStore() let contactMatchingNumberThatAlreadyExists = lookForContact(with: user._phonenumber!, or: user._email) let contact = (contactMatchingNumberThatAlreadyExists != nil) ? contactMatchingNumberThatAlreadyExists?.mutableCopy() as! CNMutableContact : CNMutableContact() let url = URL(string: user._profilePictureUrl!)! // Set Contact Image ImageDownloader.default.downloadImage(with: url , options: [], progressBlock: nil, completionHandler: { (image, error, url, data) in if error != nil{ print("can't download image") completion(error) } else{ // Image has finished downloading contact.imageData = data! if let firstname = user._firstname { contact.givenName = firstname } if let middlename = user._middlename { contact.middleName = middlename } if let lastname = user._lastname { contact.familyName = lastname } if let company = user._company { contact.organizationName = company } if let website = user._website{ // let websiteURL = CNLabeledValue(label:CNLabelURLAddressHomePage., value: website) let websiteURL = CNLabeledValue(label: "homepage", value: website as NSString) contact.urlAddresses = [websiteURL] } if UserWillShareEmail{ DidShareEmail = true if let email = user._email{ let Email = CNLabeledValue(label: "email", value: email as NSString) contact.emailAddresses = [Email] } } if UserWillSharePhone{ DidSharePhone = true if let phone = user._phonenumber{ let Phone = CNPhoneNumber(stringValue: phone) let phonenumber = CNLabeledValue(label: "iPhone", value: Phone) contact.phoneNumbers = [phonenumber ] } } // Save the date the user exchanged information let date = NSDate() let calendar = NSCalendar.current let components = calendar.dateComponents([.day, .month, .year, .hour, .minute], from: date as Date) let year = components.year! let month = components.month! let day = components.day! let hour = components.hour! let minute = components.minute! if (minute < 10){ contact.note = "Met on \(month).\(day).\(year) at \(hour):0\(minute)" } else{ contact.note = "Met on \(month).\(day).\(year) at \(hour):\(minute)" } print("going to try to save contact") let request = CNSaveRequest() if contactMatchingNumberThatAlreadyExists == nil{ // There was no contact that was already in the address book so we have to make a new contact request.add(contact, toContainerWithIdentifier: nil) } else{ // Update existing contact instead request.update(contact) } do{ try store.execute(request) print("Should have saved contact") history.didShare( EmailIs: DidShareEmail, PhonenumberIs: DidSharePhone,completion: { (error) in if let error = error{ completion(error) } else{ completion(nil) } }) } catch let err{ // Failed trying to save contact print("Can't save contact with error \(err)") completion(err) } } }) } <file_sep>// // Custom Operators.swift // Swap // // Created by <NAME> on 11/28/16. // // import Foundation import PhoneNumberKit // declaring custom operator infix operator ~ { associativity left precedence 160 } /// Operator that tests if two phone numbers are the same. Handles the case that one phone number has country code and one does not. /// /// - Parameters: /// - left: First string (phone number) to compare /// - right: Second string (phone number) to compare /// - Returns: True if one string is a string subset of the other, false if not func ~(left: String?, right: String?) -> Bool { guard let Left = left, let Right = right else{ // ensures the strings have a value return false } return (Left.digits.contains(Right.digits) || Right.digits.contains(Left.digits)) } // MARK: - Extension to convert phone number strings to numbers only: +1 (555)-555-5555 = 15555555555 extension String { var digits: String { return components(separatedBy: CharacterSet.decimalDigits.inverted) .joined(separator: "") } } // Mark: - Extension to trim whitespace extension String { /// Converts the input to a username or a phone number. Since a user can sign in with a username or password, this returns the usenrame they entered or phone number that they entered so that it is properly passed into sign in functions. func toUsernameSignInAlias() -> String { let username = "" let phoneNumberKit = PhoneNumberKit() var formattedPhoneNumber = "" do { let phoneNumber = try phoneNumberKit.parse(self) return phoneNumberKit.format(phoneNumber, toType: .e164) } catch { return self } } func trim() -> String { return self.trimmingCharacters(in: NSCharacterSet.whitespaces) } /// Do not use this to validate a username. Use 'validate' instead func isAValidUsername() -> Bool { let RegEx = "\\A\\w{1,18}\\z" let Test = NSPredicate(format:"SELF MATCHES %@", RegEx) return Test.evaluate(with: self) } /// Property that tests if a string contains all numbers var isNumber : Bool { get{ return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } } /// Returns a boolean that determines if the username is valid and available. Also returns a string for the reason why the username was not valid func validate(completion: @escaping (_ isAValidUsername: Bool, _ errorMessage: String?) -> Void) { if self.characters.count < 1{ let message = "Usernames must be at least one character." completion(false, message) } else if self.characters.count > 18{ let message = "Usernames must be less than 18 characters." completion(false, message) } else if !self.lowercased().isAValidUsername(){ let message = "Usernames cannot contain special characters." completion(false, message) } else if self.isNumber{ let message = "Usernames cannot contain all numbers." completion(false, message) } else { pool.getUser(self.lowercased()).confirmSignUp("0").continue({ (task) in DispatchQueue.main.async { if let error = task.error as? NSError{ if error.debugDescription.contains("Invalid code provided"){ // User Exists print("user exists") let message = "Username is taken, try another." completion(false, message) } else{ // User Does Not Exist completion(true, nil) } } } }) } } /// Converts a string to a Date if the date is in the form: Wed Aug 29 17:12:58 +0000 2012 /// /// - Returns: The converted Date func toDate() -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "E MM dd HH:mm:ss Z yyyy" let date = dateFormatter.date(from: self) return date! } func isValidEmail() -> Bool { let types: NSTextCheckingResult.CheckingType = [.link] let linkDetector = try? NSDataDetector(types: types.rawValue) let range = NSRange(location: 0, length: self.characters.count) let result = linkDetector?.firstMatch(in: self, options: .reportCompletion, range: range) let scheme = result?.url?.scheme ?? "" return scheme == "mailto" && result?.range.length == self.characters.count } } extension NSNumber{ func timeAgo() -> String { let date = Date(timeIntervalSince1970: TimeInterval(self)) return timeAgoSinceDate(date: date as NSDate, numericDates: false) } } extension Date{ /// Returns string representing time passed since, example: '2h ago' etc func timeAgo() -> String { return timeAgoSinceDate(date: self as NSDate, numericDates: false) } /// Gets the number of years since the date. var age: Int { return Calendar.current.dateComponents([.year], from: self, to: Date()).year! } } extension Bool { static func random() -> Bool { return arc4random_uniform(2) == 0 } } func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String { let calendar = NSCalendar.current let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second] let now = NSDate() let earliest = now.earlierDate(date as Date) let latest = (earliest == now as Date) ? date : now let components = calendar.dateComponents(unitFlags, from: earliest as Date, to: latest as Date) if (components.year! >= 2) { return "\(components.year!) years ago" } else if (components.year! >= 1){ if (numericDates){ return "1 year ago" } else { return "Last year" } } else if (components.month! >= 2) { return "\(components.month!) months ago" } else if (components.month! >= 1){ if (numericDates){ return "1 month ago" } else { return "Last month" } } else if (components.weekOfYear! >= 2) { return "\(components.weekOfYear!) weeks ago" } else if (components.weekOfYear! >= 1){ if (numericDates){ return "1 week ago" } else { return "Last week" } } else if (components.day! >= 2) { return "\(components.day!) days ago" } else if (components.day! >= 1){ if (numericDates){ return "1 day ago" } else { return "Yesterday" } } else if (components.hour! >= 2) { return "\(components.hour!) hours ago" } else if (components.hour! >= 1){ if (numericDates){ return "1 hour ago" } else { return "An hour ago" } } else if (components.minute! >= 2) { return "\(components.minute!) minutes ago" } else if (components.minute! >= 1){ if (numericDates){ return "1 minute ago" } else { return "A minute ago" } } else if (components.second! >= 3) { return "\(components.second!) seconds ago" } else { return "Just now" } } <file_sep>// // ShowLoadingOverlay.swift // Swap // // Created by <NAME> on 12/25/16. // // import Foundation class ShowLoadingOverlay { var imageView: UIImageView! func showBlackOverlay() -> UIImageView { let image = UIImage(named: "GrayOverlay") let blackOverlay = UIImageView(image: image!) blackOverlay.alpha = 0.5 blackOverlay.frame = CGRect(x: -300, y: -100, width: 1000, height: 1000) return blackOverlay } func showLoadingSymbol(view: UIView, shouldCenter: Bool = false) -> UIImageView { let image = UIImage(named: "LoadingSymbol") let loadingSymbol = UIImageView(image: image!) // loadingSymbol.frame = CGRect(x: 171, y: 318, width: 35, height: 35) if shouldCenter{ loadingSymbol.center = (view.superview?.center)! } else { loadingSymbol.frame = CGRect(x: view.frame.size.width/2-20, y: view.frame.size.height/2, width: 35, height: 35) } let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = 2 * M_PI rotationAnimation.repeatCount = 180 rotationAnimation.duration = 1.0 loadingSymbol.layer.add(rotationAnimation, forKey: nil) return loadingSymbol } } <file_sep>// // SignUpViewController.swift // Swap // // Created by <NAME> on 12/8/16. // // import UIKit import PhoneNumberKit class SignUpViewController: UIViewController { //Text Fields @IBOutlet weak var emailField: UITextField! @IBOutlet var usernameField: UITextField! @IBOutlet var phonenumberField: UITextField! @IBOutlet var passwordField: PhoneNumberTextField! //Buttons @IBOutlet var backButton: UIButton! @IBOutlet var nextButton: UIButton! @IBAction func didTapNextToCreateAccount(_ sender: UIButton) { //show loading overlay let loadingOverlay = ShowLoadingOverlay() let blackOverlay = loadingOverlay.showBlackOverlay() let loadingSymbol = loadingOverlay.showLoadingSymbol(view: self.view) self.view.addSubview(blackOverlay) self.view.addSubview(loadingSymbol) let phoneNumberKit = PhoneNumberKit() var formattedPhoneNumber = "" do { let phoneNumber = try phoneNumberKit.parse(phonenumberField.text!) formattedPhoneNumber = PhoneNumberKit().format(phoneNumber, toType: .e164) } catch { UIAlertView(title: "Could Not Create Account", message: "Please enter a valid phone number.", delegate: nil, cancelButtonTitle: "Ok").show() } createAccount(username: usernameField.text, password: <PASSWORD>, email: emailField.text, phonenumber: formattedPhoneNumber, failedToCreateAccount:{ signUpError in blackOverlay.isHidden = true loadingSymbol.isHidden = true switch signUpError{ case .EmptyFields: // Tell the user to enter required fields UIAlertView(title: "Could Not Create Account", message: "Please ensure you completed the sign up process and try again.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidEmail: // Tell the user to enter a valid email address UIAlertView(title: "Invalid Email Address", message: "Please enter a valid email address.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidPhonenumber: // Tell the user to enter a valid phone number UIAlertView(title: "Invalid Phone Number", message: "Please enter a valid phone number.", delegate: nil, cancelButtonTitle: "Ok").show() break case .InvalidUsername: // Tell the user to enter a valid username format UIAlertView(title: "Invalid Username", message: "Usernames can be no longer than 18 characters and cannot contain special characters.", delegate: nil, cancelButtonTitle: "Ok").show() break case .PasswordTooShort: // Tell the user that his/her password is too short - Must be at least 6 characters UIAlertView(title: "Invalid Password", message: "Password must be at least 6 characters.", delegate: nil, cancelButtonTitle: "Ok").show() break case .UsernameTaken: // Tell the user to enter a different username UIAlertView(title: "Username Taken", message: "Please enter a different username.", delegate: nil, cancelButtonTitle: "Ok").show() break case .UnknownSignUpError: // Some unknown error has occured ... Tell the user to try again UIAlertView(title: "Try Again", message: "Check internet connection and try again.", delegate: nil, cancelButtonTitle: "Ok").show() break } }, didCreateAccount: { DispatchQueue.main.async { self.performSegue(withIdentifier: "toConfirmAccount", sender: nil) } }) } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } override func viewDidAppear(_ animated: Bool) { } override func viewDidLoad() { super.viewDidLoad() emailField.becomeFirstResponder() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // SetEmailViewController.swift // Swap // // Created by <NAME> on 3/12/17. // // import Foundation class setEmailViewController: UIViewController { //text field @IBOutlet var emailField: UITextField! override func viewDidLoad() { emailField.becomeFirstResponder() } @IBAction func didTapNext(_ sender: Any) { if (emailField.text?.isValidEmail())!{ saveEmail(email: emailField.text!) self.performSegue(withIdentifier: "toUsernameController", sender: nil) } else{ UIAlertView(title: "Invalid Email", message: "Please Enter A Valid Email Address", delegate: nil, cancelButtonTitle: "Ok").show() } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // Authorizing.swift // Swap // // Created by <NAME> on 11/29/16. // // import Foundation import p2_OAuth2 import Alamofire import SwiftyJSON import Accounts import TwitterKit /// Clears the Tokens from User Defaults in Twitter /// - Todo: Switch to using Keychain instead func logoutTwitter() { let store = Twitter.sharedInstance().sessionStore if let userID = store.session()?.userID{ store.logOutUserID(userID) } UserDefaults.standard.removeObject(forKey: "TwitterToken") UserDefaults.standard.removeObject(forKey: "TwitterSecret") UserDefaults.standard.synchronize() } /// Clears the access tokens from keychain in each social media and clears social media login cookies. func logoutSocialMediasAndClearCookies() { // Clears cookies let storage = HTTPCookieStorage.shared storage.cookies?.forEach() { storage.deleteCookie($0)} logoutPinterest() logoutSpotify() logoutInstagram() logoutSoundCloud() logoutTwitter() logoutVine() logoutYouTube() logoutGitHub() logoutVimeo() logoutReddit() // Delete everything out of User Defaults UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!) UserDefaults.standard.synchronize() } /// Forgets the access tokens for Spotify in keychain. However, if this function is called, calling authorizeSpotify() will not show the login screen for Spotify again. The login screen will appear disapper shortly after because the login information is still stored in web cookies. Cookies have to be cleared in order to do this. See logoutSocialMediasAndClearCookies(). func logoutSpotify() { // Forgets the access tokens in keychain spotify_oauth2.forgetTokens() } /// Function to authorize spotify with an embedded view controller. Function will forget access tokens first and then show the embedded view controller which instantly disappears if the user is logged in, or pops up and prompts the user to log in if the user is not logged in. Do not call this function to authorize Spotify before making a request, call spotify_oauth2.authorize() instead. Authorize() will only show the view controller if the user is logged out. Function will store the Spotify UID in the database for the user currently signed in. /// /// - Parameters: /// - onViewController: View Controller to show Embedded View Controller for Web on (usually self) /// - completion: Called when completed, error is nil if there is no error. /// - Attention: Access tokens for Spotify DO expire; therefore, ensure that spotify_oauth2.authorize() is called whenever a request is being made. However, as of December 11, there has not being any problems reamining logged into Spotify for the purpose of making API requests. func authorizeSpotify(onViewController: UIViewController, completion: @escaping (_ logInError: AuthorizationError?) -> Void) { logoutSpotify() // Stuff For AlamoFire /* let sessionManager = SessionManager() let retrier = OAuth2RetryHandler(oauth2: spotify_oauth2) sessionManager.adapter = retrier sessionManager.retrier = retrier */ // Makes the authorization in embedded view controller spotify_oauth2.authConfig.authorizeEmbedded = true spotify_oauth2.authConfig.authorizeContext = onViewController spotify_oauth2.authConfig.ui.useSafariView = false // Authorizes Spotify spotify_oauth2.authorizeEmbedded(from: onViewController, callback: { (response, error) in if let error = error{ if error == nil{ // User cancelled authorizing completion(AuthorizationError.Cancelled) } else{ // Not sure of specific Error completion(AuthorizationError.Unknown) } } else{ // Block is called whenever .authorize() is called and there is success // The DataLoader class ensures that a request will be made. It will authorize if needed var spotifyReq = spotify_oauth2.request(forURL: URL(string: SPOTIFY_USER_URL)!) try! spotifyReq.sign(with: spotify_oauth2) let loader = OAuth2DataLoader(oauth2: spotify_oauth2) loader.perform(request: spotifyReq, callback: { (response) in do{ let spotifyJSON = try response.responseJSON() if let id = spotifyJSON["id"] as? String{ // Sets the SpotifyID in the Database SwapUser(username: getUsernameOfSignedInUser()).set(SpotifyID: id, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else{ // ID Not Found in Spotify Response JSON completion(AuthorizationError.IDNotFound) } } catch let _ { // Could not get a response for some reason. completion(AuthorizationError.Unknown) } }) } }) } func logoutVimeo() { vimeo_oauth2.forgetTokens() } func authorizeVimeo(onViewController: UIViewController, completion: @escaping (_ loginError: Error?) -> ()) { logoutVimeo() vimeo_oauth2.authConfig.authorizeEmbedded = true vimeo_oauth2.authConfig.authorizeContext = onViewController vimeo_oauth2.authConfig.ui.useSafariView = false vimeo_oauth2.authorizeEmbedded(from: onViewController, callback:{ (json, error) in if let error = error { completion(error) } else{ // No error //Request User Data let vimeoLoader = OAuth2DataLoader(oauth2: vimeo_oauth2) let vimReq = vimeo_oauth2.request(forURL: URL(string: "https://api.vimeo.com/me")!) vimeoLoader.perform(request: vimReq, callback: { (response) in do{ let vimeoJSON = try response.responseJSON() if let idURL = vimeoJSON["uri"] as? String{ let vimeoID = (idURL as NSString).lastPathComponent // Save to database SwapUser(username: getUsernameOfSignedInUser()).set(VimeoID: vimeoID, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else { completion(AuthorizationError.Unknown) } } catch let _ { // Could not get a response for some reason. completion(AuthorizationError.Unknown) } }) } }) } ///Forgets the access tokens for Instagram in keychain. However, if this function is called, calling authorizeInstagram() will not show the login screen for Spotify again. The login screen will appear disapper shortly after because the login information is still stored in web cookies. Cookies have to be cleared in order to do this. See logoutSocialMediasAndClearCookies(). func logoutInstagram() { instagram_oauth2.forgetTokens() let cookieStorage: HTTPCookieStorage = HTTPCookieStorage.shared for cookie in cookieStorage.cookies! { if cookie.domain.contains("instagram") { cookieStorage.deleteCookie(cookie) } } } /// Function to authorize Instagram with an embedded view controller. Function will forget access tokens first and then show the embedded view controller which instantly disappears if the user is logged in, or pops up and prompts the user to log in if the user is not logged in. Do not call this function to authorize Instagram before making a request, call instagram_oauth2.authorize() instead. Authorize() will only show the view controller if the user is logged out. Function will store the Instagram UID in the database for the user currently signed in. Function also stores the Instagram profile picture URL in Userdefaults. /// /// - Parameters: /// - onViewController: View Controller to show Embedded View Controller for Web on (usually self) /// - completion: Called when completed, error is nil if there is no error. /// - Attention: As of December 2016, Access Tokens for Instagram do not expire; however, instagram has explicitly stated that to never assume that access tokens will remain forever; therefore, always call instagram_oauth2.authorize() before making requests func authorizeInstagram(onViewController: UIViewController, completion: @escaping (_ logInError: AuthorizationError?) -> () ) { logoutInstagram() instagram_oauth2.authConfig.authorizeEmbedded = true instagram_oauth2.authConfig.authorizeContext = onViewController instagram_oauth2.authConfig.ui.useSafariView = false instagram_oauth2.authorizeEmbedded(from: onViewController, callback: { (parameters, error) in if let error = error{ // ERROR Failed Authorizing if error == nil{ // User cancelled authorizing completion(AuthorizationError.Cancelled) } else{ // Not sure of specific Error completion(AuthorizationError.Unknown) } } else { let json = JSON(parameters) let instagramID = json["user"]["id"].string let imageURL = json["user"]["profile_picture"].string _ = json["user"]["username"].string saveInstagramPhoto(withLink: imageURL) SwapUser(username: getUsernameOfSignedInUser()).set(InstagramID: instagramID, DidSetInformation: { error in // It worked.. .setting instagram ID Now DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { error in completion(AuthorizationError.Unknown) }) } }) } /// See logoutSpotify() for more informaton. Forgets Tokens for SoundCloud func logoutSoundCloud() { soundcloud_oauth2.forgetTokens() } /// Function to authorize SoundCloud with an embedded view controller. Function will forget access tokens first and then show the embedded view controller which instantly disappears if the user is logged in, or pops up and prompts the user to log in if the user is not logged in. Do not call this function to authorize Instagram before making a request, call soundcloud_oauth2.authorize() instead. Authorize() will only show the view controller if the user is logged out. Function will store the SoundCloud UID in the database for the user currently signed in. /// /// - Parameters: /// - onViewController: View Controller to show Embedded View Controller for Web on (usually self) /// - completion: Called when completed, error is nil if there is no error. /// - Attention: SoundCloud access tokens do not expire; however, they do change when the user changes their pasword. Should test app for when users change passwords. func authorizeSoundCloud(onViewController: UIViewController, completion: @escaping (_ loginError: AuthorizationError?) -> () ) { logoutSoundCloud() soundcloud_oauth2.authConfig.authorizeEmbedded = true soundcloud_oauth2.authConfig.authorizeContext = onViewController soundcloud_oauth2.authConfig.ui.useSafariView = false soundcloud_oauth2.authorizeEmbedded(from: onViewController, callback:{ (parameters, error) in if let error = error{ // ERROR Failed Authorizing if error == nil{ // User cancelled authorizing completion(AuthorizationError.Cancelled) } else{ // Not sure of specific Error completion(AuthorizationError.Unknown) } } else{ // The DataLoader class ensures that a request will be made. It will authorize if needed var soundcloudReq = soundcloud_oauth2.request(forURL: URL(string: "https://api.soundcloud.com/me?oauth_token=\(soundcloud_oauth2.accessToken!)")!) try! soundcloudReq.sign(with: soundcloud_oauth2) let loader = OAuth2DataLoader(oauth2: soundcloud_oauth2) loader.perform(request: soundcloudReq, callback: { (response) in do { let soundcloudJSON = try response.responseJSON() if let SoundCloudID = soundcloudJSON["id"] as? NSNumber{ SwapUser(username: getUsernameOfSignedInUser()).set( SoundCloudID: "\(SoundCloudID)", DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else{ completion(AuthorizationError.IDNotFound) } } catch _ { // Could not get a response completion(AuthorizationError.Unknown) } }) } }) } /// See logoutSpotify() for more explanation func logoutPinterest() { pinterest_oauth2.forgetTokens() } /// Function to authorize Pinterest with an embedded view controller. Function will forget access tokens first and then show the embedded view controller which instantly disappears if the user is logged in, or pops up and prompts the user to log in if the user is not logged in. Do not call this function to authorize Instagram before making a request, call pinterest_oauth2.authorize() instead. Authorize() will only show the view controller if the user is logged out. Function will store the Pinterest UID in the database for the user currently signed in. /// /// - Parameters: /// - onViewController: View Controller to show Embedded View Controller for Web on (usually self) /// - completion: Called when completed, error is nil if there is no error. /// - Attention: Call pinterest.authorize() before making requests because Pinterest tokens expire. func authorizePinterest(onViewController: UIViewController, completion: @escaping (_ loginError: AuthorizationError?) -> () ) { logoutPinterest() pinterest_oauth2.authConfig.authorizeEmbedded = true pinterest_oauth2.authConfig.authorizeContext = onViewController pinterest_oauth2.authConfig.ui.useSafariView = false pinterest_oauth2.authorizeEmbedded(from: onViewController, callback: { (parameters, error) in if let error = error{ // ERROR Failed Authorizing if error == nil{ // User cancelled authorizing completion(AuthorizationError.Cancelled) } else{ // Not sure of specific Error completion(AuthorizationError.Unknown) } } else{ Alamofire.request("https://api.pinterest.com/v1/me/?access_token=\(pinterest_oauth2.accessToken!)", method: .get).validate().responseJSON(completionHandler: { (response) in print("the response is ... \(response)") if let data = response.data{ let json = JSON(data: data) print("the pinterest json is ... \(json)") if !(json["data"]["id"].null != nil){ let PinterestID = json["data"]["id"].stringValue SwapUser(username: getUsernameOfSignedInUser()).set(PinterestID: PinterestID,DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else{ completion(AuthorizationError.IDNotFound) } } else{ completion(AuthorizationError.Unknown) } }) } }) } /** Function to authorize Vine account and store username and password into keychain. Method will log into Vine and return session key and userID in `completion` code block. - Author: <NAME> - Copyright: (c) 2016 <NAME> - Version: 2.0 - Attention: Use this function before making HTTP Requests to vine to ensure that the user is logged into vine; however, pass the parameter false to atSetUp before making HTTP Reuqests. - Parameters: - username: The username of the Vine user. - password: The password of the Vine user. - atSetUp: Boolean value of whether the user is setting up Vine or not, set to false if making HTTP request. - completion: Code block with Session Key and vine Id passed in. Executed when authorization succeeds. Error is nil if succeded */ func authorizeVine(username: String?, password: String?, atSetUp: Bool = true, completion: @escaping (_ error: AuthorizationError?, _ key: String? , _ id: String? ) -> Void) { guard let username = username, let password = <PASSWORD> else{ print("Not let username and password") completion(AuthorizationError.Cancelled, nil, nil) return } let parameters = ["username": username, "password": <PASSWORD>] let vineAuthUrl = "https://api.vineapp.com/users/authenticate" Alamofire.request(vineAuthUrl, method: .post, parameters: parameters) .responseJSON { (response) in if let data = response.data { let vineResponse = JSON(data: data) print("vine response is ... \(vineResponse)") if let vineKey = vineResponse["data"]["key"].string{ // There is Session Key for Vine so Auth did Work let vineID = vineResponse["data"]["userId"].stringValue if atSetUp{ // Set Vine Auth Info in Keychain/UserDefaults saveVine(username: username, andPassword: <PASSWORD>) SwapUser(username: getUsernameOfSignedInUser()).set(VineID: vineID, DidSetInformation: { DispatchQueue.main.async { completion(nil, vineKey, vineID) } }, CannotSetInformation: { completion(AuthorizationError.Unknown, nil, nil) }) } else{ completion(nil, vineKey, vineID) } } else{ // No session key in vine response completion(AuthorizationError.Cancelled, nil, nil) } } else{ // No Data in Response completion(AuthorizationError.Unknown, nil, nil) } } } func logoutVine() { UserDefaults.standard.removeObject(forKey: "VineUsername") UserDefaults.standard.removeObject(forKey: "VinePassword") UserDefaults.standard.synchronize() } func logoutYouTube() { youtube_oauth2.forgetTokens() } func authorizeYouTube(onViewController: UIViewController, completion: @escaping (_ loginError: AuthorizationError?) -> () ) { logoutYouTube() youtube_oauth2.authorizeEmbedded(from: onViewController) { (json, error) in if let error = error { // ERROR Failed Authorizing if error == nil{ // User cancelled authorizing completion(AuthorizationError.Cancelled) } else{ // Not sure of specific Error completion(AuthorizationError.Unknown) } } else{ // The DataLoader class ensures that a request will be made. It will authorize if needed var youtubeReq = youtube_oauth2.request(forURL: URL(string: "https://www.googleapis.com/youtube/v3/channels?part=id&mine=true")!) try! youtubeReq.sign(with: youtube_oauth2) let loader = OAuth2DataLoader(oauth2: youtube_oauth2) loader.perform(request: youtubeReq, callback: { (response) in do{ if let data = response.data{ let json = JSON(data: data) let items = json["items"] if let channelID = items[0]["id"].string{ var plusReq = youtube_oauth2.request(forURL: URL(string: "https://www.googleapis.com/plus/v1/people/me")!) try! plusReq.sign(with: youtube_oauth2 ) let loader = OAuth2DataLoader(oauth2: youtube_oauth2) loader.perform(request: plusReq, callback: { (response ) in if let data = response.data{ let json = JSON(data: data) let imageUrl = json["image"]["url"].stringValue saveYouTubeProfilePicture(withLink: imageUrl) // Sets the YouTube in the Database SwapUser(username: getUsernameOfSignedInUser()).set(YouTubeID: channelID, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else{ completion(AuthorizationError.Unknown) } }) } else{ // No ID completion(AuthorizationError.IDNotFound) } } else{ // No data in response completion(AuthorizationError.Unknown) } } catch let _ { // Could not get a response for some reason. completion(AuthorizationError.Unknown) } }) } } } func logoutReddit() { reddit_oauth2.forgetTokens() } func authorizeReddit(onViewController: UIViewController, completion: @escaping (_ loginError: Error?) -> Void) { logoutReddit() reddit_oauth2.authConfig.authorizeEmbedded = true reddit_oauth2.authConfig.authorizeContext = onViewController reddit_oauth2.authConfig.ui.useSafariView = false reddit_oauth2.authorizeEmbedded(from: onViewController, params: ["duration": "permanent"] , callback:{ json, error in if let error = error { // Did not work completion(error) } else{ if let _ = json{ print("if let json = json") // Get Reddit ID // Block is called whenever .authorize() is called and there is success let loader = RedditLoader() loader.requestUserdata(callback: { (json, error) in if let json = json { print("\n\n\n\n\n\n\n\n\n\n\n\n\n\nHERE IS REDDIT ... \(json)") if let username = json["name"] as? String { // Sets the YouTube in the Database SwapUser(username: getUsernameOfSignedInUser()).set(RedditID: username, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }, CannotSetInformation: { completion(AuthorizationError.Unknown) }) } else{ completion(AuthorizationError.IDNotFound) } } else{ completion(error) } }) } } }) } func logoutGitHub() { github_oauth2.forgetTokens() } func authorizeGitHub(onViewController: UIViewController, completion: @escaping (_ loginError: Error?) -> Void) { logoutGitHub() github_oauth2.authConfig.authorizeEmbedded = true github_oauth2.authConfig.authorizeContext = onViewController github_oauth2.authConfig.ui.useSafariView = false github_oauth2.authorizeEmbedded(from: onViewController, callback: { (response, error) in if let error = error { completion(error) } else{ if let response = response{ if let accessToken = github_oauth2.accessToken{ Alamofire.request("https://api.github.com/user", method: .get, parameters: ["access_token": accessToken]).responseJSON(completionHandler: { (response) in if let data = response.data{ let json = JSON(data: data) print("\n\n\n\n\n\n\n the github response is ... \(json)") if let GitHubID = json["login"].string{ // can get an id SwapUser().set(GitHubID: GitHubID, DidSetInformation: { DispatchQueue.main.async { completion(nil) } }) } else{ completion(AuthorizationError.IDNotFound) } } else{ completion(AuthorizationError.IDNotFound) } }) } else { completion(AuthorizationError.Unknown) } } else{ completion(AuthorizationError.Unknown) } } }) } /// Class to use Oauth with Alamofire class OAuth2RetryHandler: RequestRetrier, RequestAdapter { let loader: OAuth2DataLoader init(oauth2: OAuth2) { loader = OAuth2DataLoader(oauth2: oauth2) } /// Intercept 401 and do an OAuth2 authorization. public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { if let response = request.task?.response as? HTTPURLResponse, 401 == response.statusCode, let req = request.request { var dataRequest = OAuth2DataRequest(request: req, callback: { _ in }) dataRequest.context = completion loader.enqueue(request: dataRequest) loader.attemptToAuthorize() { authParams, error in self.loader.dequeueAndApply() { req in if let comp = req.context as? RequestRetryCompletion { comp(nil != authParams, 0.0) } } } } else { completion(false, 0.0) // not a 401, not our problem } } /// Sign the request with the access token. public func adapt(_ urlRequest: URLRequest) throws -> URLRequest { guard nil != loader.oauth2.accessToken else { return urlRequest } return try! urlRequest.signed(with: loader.oauth2) } } <file_sep>// // Users.swift // MySampleApp // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // import Foundation import UIKit import AWSDynamoDB class Users: AWSDynamoDBObjectModel, AWSDynamoDBModeling { var _username: String? var _bio: String? var _birthday: NSNumber? var _company: String? var _dateCreated: NSNumber? var _email: String? var _firstname: String? var _gender: String? var _instagramID: String? var _isPrivate: NSNumber? var _isVerified: NSNumber? var _lastname: String? var _location: Set<NSNumber>? var _middlename: String? var _phonenumber: String? var _pinterestID: String? var _points: NSNumber? var _profilePictureUrl: String? var _redditID: String? var _soundcloudID: String? var _spotifyID: String? var _githubID: String? var _swapCodeUrl: String? var _swapped: NSNumber? var _swaps: NSNumber? var _twitterID: String? var _vineID: String? var _vimeoID: String? var _website: String? var _willShareEmail: NSNumber? var _willShareInstagram: NSNumber? var _willSharePhone: NSNumber? var _willSharePinterest: NSNumber? var _willShareReddit: NSNumber? var _willShareSoundCloud: NSNumber? var _willShareSpotify: NSNumber? var _willShareTwitter: NSNumber? var _willShareVine: NSNumber? var _willShareYouTube: NSNumber? var _willShareGitHub: NSNumber? var _willShareVimeo: NSNumber? var _youtubeID: String? var _notification_id_one_signal: String? var _VPCode: String? class func dynamoDBTableName() -> String { return "swap-mobilehub-1081613436-Users" } class func hashKeyAttribute() -> String { return "_username" } override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] { return [ "_username" : "username", "_bio" : "bio", "_birthday" : "birthday", "_company" : "company", "_dateCreated" : "date_created", "_email" : "email", "_firstname" : "firstname", "_gender" : "gender", "_instagramID" : "instagram_ID", "_isPrivate" : "isPrivate", "_isVerified" : "isVerified", "_lastname" : "lastname", "_location" : "location", "_middlename" : "middlename", "_phonenumber" : "phonenumber", "_pinterestID" : "pinterest_ID", "_points" : "points", "_profilePictureUrl" : "profile_picture_url", "_redditID" : "redditID", "_githubID": "githubID", "_soundcloudID" : "soundcloud_ID", "_spotifyID" : "spotify_ID", "_swapCodeUrl" : "swap_code_url", "_swapped" : "swapped", "_swaps" : "swaps", "_twitterID" : "twitter_ID", "_vineID" : "vine_ID", "_vimeoID": "vimeoID", "_website" : "website", "_willShareEmail" : "willShareEmail", "_willShareInstagram" : "willShareInstagram", "_willSharePhone" : "willSharePhone", "_willSharePinterest" : "willSharePinterest", "_willShareReddit" : "willShareReddit", "_willShareSoundCloud" : "willShareSoundCloud", "_willShareSpotify" : "willShareSpotify", "_willShareTwitter" : "willShareTwitter", "_willShareVine" : "willShareVine", "_willShareYouTube" : "willShareYouTube", "_willShareGitHub": "willShareGitHub", "_willShareVimeo": "willShareVimeo", "_youtubeID" : "youtube_ID", "_notification_id_one_signal": "notification_id_one_signal", "_VPCode": "VPCode", ] } } <file_sep>// // User Errors.swift // Swap // // Created by <NAME> on 12/8/16. // // import Foundation /// UserError /// - CouldNotGetUser: Could not loader user from database /// - WillNotShareSocialMedia: User has denied access to social media /// - NotConnected: User does not have social media connected /// - Unknown: Unknown Error enum UserError: Error { case CouldNotGetUser case WillNotShareSocialMedia case NotConnected case Unknown case CannotFollowSelf } <file_sep>// // IGUser.swift // Swap // // Created by <NAME> on 2/2/17. // // import Foundation import Alamofire import SwiftyJSON class IGUser { var id: String = "" init(id: String) { self.id = id } func getMedia(completion: @escaping (_ medias: [IGMedia]?) -> Void) { Alamofire.request("https://api.instagram.com/v1/users/\(self.id)/media/recent/", method: .get, parameters: ["access_token": instagram_oauth2.accessToken ?? ""]).responseJSON { (response) in if let Data = response.data{ let mediaObjects = JSON(data: Data) let medias: [IGMedia] = mediaObjects.toIGMedias() completion(medias) } } } } extension Notification.Name{ static let updatedInstagramMedia = Notification.Name("updatedInstagramMedia") } extension JSON{ func toIGMedias() -> [IGMedia] { var medias: [IGMedia] = [] let jsonResponse = self guard jsonResponse["data"].array != nil else { return [] } let arrayOfJSONs = jsonResponse["data"].array! for json in arrayOfJSONs{ let media = IGMedia(media: json) medias.append(media) } return medias } } <file_sep>// // SetNameViewController.swift // Swap // // Created by Dr. Stephen, Ph.D on 12/8/16. // // import UIKit /// Default Profile Picture Image URL String let defaultImage: String = "https://s3.amazonaws.com/swap-userfiles-mobilehub-1081613436/default/DefaultProfilePicSwap.png" class SetNameViewController: UIViewController { @IBOutlet var firstnameField: UITextField! @IBOutlet var lastnameField: UITextField! // let swapCodeImage = "https://dashboard.unitag.io/qreator/generate?setting=%7B%22LAYOUT%22%3A%7B%22COLORBG%22%3A%22ffffff%22%2C%22COLOR1%22%3A%2203E4F3%22%7D%2C%22EYES%22%3A%7B%22EYE_TYPE%22%3A%22Grid%22%7D%2C%22BODY_TYPE%22%3A5%2C%22E%22%3A%22H%22%2C%22LOGO%22%3A%7B%22L_NAME%22%3A%22https%3A%2F%2Fstatic-unitag.com%2Ffile%2Ffreeqr%2Fe70b5ccd3ca5554615433abeae699420.png%22%2C%22EXCAVATE%22%3Atrue%7D%7D&data=%7B%22TYPE%22%3A%22text%22%2C%22DATA%22%3A%7B%22TEXT%22%3A%22http://getswap.me/\(getUsernameOfSignedInUser())%22%2C%22URL%22%3A%22%22%7D%7D" @IBAction func continueToSetProfileInfo(_ sender: UIButton) { // Sets the Swap User's initial data in the database // By default, the user is NOT searchable if (firstnameField.text != "" && lastnameField.text != ""){ saveFirstname(name: firstnameField.text!.capitalized) saveLastname(name: lastnameField.text!.capitalized) self.performSegue(withIdentifier: "toBirthdayController", sender: nil) print("the saved firstname is \(getSavedFirstname()) ") } else{ UIAlertView(title: "Cannot Continue", message: "Please Enter Your First And Last Names", delegate: nil, cancelButtonTitle: "Ok").show() } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } override func viewWillAppear(_ animated: Bool) { // Autofills the fields based on if the information is in the user's addressbook already firstnameField.text = getSavedFirstname() ?? "" lastnameField.text = getSavedLastname() ?? "" } override func viewDidAppear(_ animated: Bool) { firstnameField.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() firstnameField.becomeFirstResponder() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // AuthorizationErrors.swift // Swap // // Created by <NAME> on 11/30/16. // // import Foundation enum AuthorizationError: Error { case Cancelled case Unknown case IDNotFound } <file_sep>// // AppDelegate.swift // Swap // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // import UIKit import IQKeyboardManagerSwift import Swifter import AWSCognitoIdentityProvider import OneSignal import Branch import Fabric import Answers import TwitterKit import Crashlytics import SafariServices import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate, UIScrollViewDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //make UI changes UIApplication.shared.statusBarStyle = .lightContent var storyboard: UIStoryboard = grabStoryboard() Fabric.with([Crashlytics.self(), Answers.self()]) Fabric.sharedSDK().debug = true Twitter.sharedInstance().start(withConsumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET) // Override point for customization after application launch. AWSMobileClient.sharedInstance.didFinishLaunching(application, withOptions: launchOptions) //enable keyboard manager IQKeyboardManager.sharedManager().enable = true configureRemoteNotificationsSettings(with: launchOptions) configureUniversalLinksAndSwapLinks(with: launchOptions, and: storyboard) determineWhatScreenToShow(on: storyboard) FirebaseApp.configure() return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return AWSMobileClient.sharedInstance.withApplication(application, withURL: url, withSourceApplication: sourceApplication, withAnnotation: annotation as AnyObject) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. AWSMobileClient.sharedInstance.applicationDidBecomeActive(application) } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { AWSMobileClient.sharedInstance.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { AWSMobileClient.sharedInstance.application(application, didFailToRegisterForRemoteNotificationsWithError: error as NSError) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { AWSMobileClient.sharedInstance.application(application, didReceiveRemoteNotification: userInfo) } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if Twitter.sharedInstance().application(app, open:url, options: options) { return true } Swifter.handleOpenURL(url) youtube_oauth2.handleRedirectURL(url) return true } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { Branch.getInstance().continue(userActivity) return true } func configureRemoteNotificationsSettings(with launchOptions: [UIApplicationLaunchOptionsKey: Any]?) { OneSignal.initWithLaunchOptions(launchOptions, appId: ONE_SIGNAL_APP_ID, handleNotificationAction: { (result) in // Completion Block Called when the user presses an action button from a Swap Request let payload = result?.notification.payload // Obtain the Action Selected From Notification if let additionalData = payload?.additionalData, let actionSelected = additionalData["actionSelected"] as? String { let username = additionalData["username"] as? String ?? "" switch actionSelected{ case "Accept": // User Accepted SwapUser(username: getUsernameOfSignedInUser()).performActionOnSwapRequestFromUser(withUsername: username, doAccept: true) break case "Decline": SwapUser(username: getUsernameOfSignedInUser()).performActionOnSwapRequestFromUser(withUsername: username, doAccept: false) break default: break } } }, settings: [kOSSettingsKeyInFocusDisplayOption:OSNotificationDisplayType.notification.rawValue]) OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification } func configureUniversalLinksAndSwapLinks(with launchOptions: [UIApplicationLaunchOptionsKey: Any]?, and storyboard: UIStoryboard) { let branch = Branch.getInstance() branch?.initSession(launchOptions: launchOptions, andRegisterDeepLinkHandler: { (param, error) in if error == nil{ // opened by swap link if let swapLink = param?["+non_branch_link"] as? String{ if isSignedIn(){ if swapLink.contains("/VP"){ // VP verification links should be in the form http://getswap.me/VP/###### where ###### is the VP code let code = getUsernameFromSwapLink(swapLink: swapLink) SwapUser().getInformation(completion: { (error, user) in DispatchQueue.main.async { if user != nil { // Valid Swap Link or VP Code if let VPcode = user?._VPCode{ if VPcode == code{ // Verify account SwapUser().set(isVerified: true) } } } } }) } else { let username = getUsernameFromSwapLink(swapLink: swapLink) guard username != "getswap.me" && username != "swapapp.co" else { self.determineWhatScreenToShow(on: storyboard) return } searchedUser = username // Pass the username to the searched user view controller let TabBarVC = storyboard.instantiateViewController(withIdentifier: "SearchUsersTabBarController") var SearchedProfileVC = storyboard.instantiateViewController(withIdentifier: "SearchedUserProfileViewController") TabBarVC.present(SearchedProfileVC, animated: false) self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.rootViewController = TabBarVC self.window!.backgroundColor = UIColor.white self.window!.makeKeyAndVisible() } } } } }) } func determineWhatScreenToShow(on storyboard: UIStoryboard) { self.window = UIWindow(frame: UIScreen.main.bounds) // Reference to Profile View Controller let profileViewControllerID: String = "ProfileViewController" let profileVC = storyboard.instantiateViewController(withIdentifier: profileViewControllerID) let signInVCID: String = "SignInViewController" let signInVC = storyboard.instantiateViewController(withIdentifier: signInVCID) // if signed in -> profile view controller else -> login view controller let defaultVC: UIViewController = isSignedIn() ? profileVC : signInVC // If there is no saved view controller ID in UserDefaults, it instantiates the default view controller as the initial view controller. However, if there is, it instantiates the last view controller it can remember being on self.window?.rootViewController = (getLastViewControllerID() != nil ) ? getSignupStoryboard().instantiateViewController(withIdentifier: getLastViewControllerID()! ) : defaultVC self.window?.makeKeyAndVisible() } } func grabStoryboard() -> UIStoryboard { // determine screen size let screenHeight = UIScreen.main.bounds.size.height var storyboard: UIStoryboard! = nil switch (screenHeight) { // iPhone SE case 568: storyboard = UIStoryboard(name: "IPhoneSE", bundle: nil) // iPhone 8 case 667: storyboard = UIStoryboard(name: "Main", bundle: nil) // iPhone 8 Plus case 736: storyboard = UIStoryboard(name: "IPhone7Plus", bundle: nil) //iPhone X case 812: storyboard = UIStoryboard(name: "IPhoneX", bundle: nil) //Ipad or 4s default: storyboard = UIStoryboard(name: "IPad", bundle: nil) break } return storyboard } func getSignupStoryboard() -> UIStoryboard{ let screenHeight = UIScreen.main.bounds.size.height var storyboard: UIStoryboard! = nil switch (screenHeight) { // iPhone SE case 568: storyboard = UIStoryboard(name: "Signup_SE", bundle: nil) // iPhone 8 case 667: storyboard = UIStoryboard(name: "Signup_Main", bundle: nil) // iPhone 8 Plus case 736: storyboard = UIStoryboard(name: "Signup_Plus", bundle: nil) //iPhone X case 812: storyboard = UIStoryboard(name: "Signup_X", bundle: nil) //Ipad or 4s default: storyboard = UIStoryboard(name: "Signup_IPad", bundle: nil) break } return storyboard } <file_sep>// // SignInViewController.swift // Swap // // Created by <NAME> on 12/8/16. // // import UIKit import Alamofire import SwiftyJSON //import FacebookLogin class SignInViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet var SignInButton: UIButton! @IBOutlet var SignUpButton: UIButton! @IBOutlet var passwordBottom: UIImageView! var blackOverlay: UIImageView? var loadingSymbol: UIImageView? @IBOutlet var orLabel: UILabel! /// This variable should be located in whatever view controller is used to sign in var passwordAuthenticationCompletion: AWSTaskCompletionSource<AnyObject>? // let FBLoginButton = LoginButton(readPermissions: [ .publicProfile, .email ]) @IBAction func didTapSignIn(_ sender: UIButton) { //loading let loadingOverlay = ShowLoadingOverlay() blackOverlay = loadingOverlay.showBlackOverlay() loadingSymbol = loadingOverlay.showLoadingSymbol(view: self.view) self.view.addSubview(blackOverlay!) self.view.addSubview(loadingSymbol!) //disable UI Components SignInButton.isEnabled = false SignUpButton.isEnabled = false usernameField.isEnabled = false passwordField.isEnabled = false //drop keyboard usernameField.resignFirstResponder() passwordField.resignFirstResponder() signIn() } override func viewDidLoad() { super.viewDidLoad() usernameField.delegate = self passwordField.delegate = self usernameField.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.white]) passwordField.attributedPlaceholder = NSAttributedString(string: "<PASSWORD>", attributes: [NSForegroundColorAttributeName: UIColor.white]) // Do any additional setup after loading the view. /* FBLoginButton.center = CGPoint(x: view.center.x, y: view.center.y + 200) FBLoginButton.frame.size = CGSize(width: 250, height: 40) view.addSubview(FBLoginButton) */ } func textFieldDidBeginEditing(_ textField: UITextField) { orLabel.isHidden = true textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.gray]) SignInButton.frame = CGRect(x: SignInButton.frame.origin.x, y: SignInButton.frame.origin.y - 60, width: SignInButton.frame.width, height: SignInButton.frame.height) SignUpButton.frame = CGRect(x: SignUpButton.frame.origin.x, y: SignUpButton.frame.origin.y - 85, width: SignUpButton.frame.width, height: SignUpButton.frame.height) passwordField.frame = CGRect(x: passwordField.frame.origin.x, y: passwordField.frame.origin.y - 25, width: passwordField.frame.width, height: passwordField.frame.height) passwordBottom.frame = CGRect(x: passwordBottom.frame.origin.x, y: passwordBottom.frame.origin.y - 25, width: passwordBottom.frame.width, height: passwordBottom.frame.height) } @available(iOS 10.0, *) func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { orLabel.isHidden = false textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.white]) SignInButton.frame = CGRect(x: SignInButton.frame.origin.x, y: SignInButton.frame.origin.y + 60, width: SignInButton.frame.width, height: SignInButton.frame.height) SignUpButton.frame = CGRect(x: SignUpButton.frame.origin.x, y: SignUpButton.frame.origin.y + 85, width: SignUpButton.frame.width, height: SignUpButton.frame.height) passwordField.frame = CGRect(x: passwordField.frame.origin.x, y: passwordField.frame.origin.y + 25, width: passwordField.frame.width, height: passwordField.frame.height) passwordBottom.frame = CGRect(x: passwordBottom.frame.origin.x, y: passwordBottom.frame.origin.y + 25, width: passwordBottom.frame.width, height: passwordBottom.frame.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // IGMedia.swift // Swap // // Created by <NAME> on 2/2/17. // // import Foundation import SwiftyJSON class IGMedia { var id: String = "" var isLiked: Bool = false var content_url: URL? var type: IGMediaType = .photo // Assume a photo by default var date_created: Date = Date() var likes: NSNumber = 0 var caption: String = "" var full_name_of_creator: String = "" var username_of_creator: String = "" var id_of_creator: String = "" var thumbnail_url: URL? var creator_profile_picture_URL: URL? // Read JSON response to create media object init(media: JSON) { let user_has_liked = media["user_has_liked"].bool ?? false let username = media["user"]["username"].string ?? "" let full_name = media["user"]["full_name"].string ?? "" let profile_picture = media["user"]["profile_picture"].string ?? "" let user_id = media["user"]["id"].string ?? "" let Likes = media["likes"]["count"].number ?? 0 let time_created = media["caption"]["created_time"].string ?? "0" let media_type = media["type"].string ?? "" let ID = media["id"].string ?? "" let contentURL = media["images"]["standard_resolution"]["url"].string ?? "" let thumbnailURL = media["images"]["thumbnail"]["url"].string ?? "" let text = media["caption"]["text"].string ?? "" self.id = ID self.isLiked = user_has_liked self.content_url = URL(string: contentURL) if media_type == "image"{ self.type = .photo } else{ self.type = .video } self.date_created = Date(timeIntervalSince1970: Double(time_created)!) self.likes = Likes self.caption = text self.full_name_of_creator = full_name self.username_of_creator = username self.id_of_creator = user_id self.thumbnail_url = URL(string: thumbnailURL) self.creator_profile_picture_URL = URL(string: profile_picture) } func like(completion: (_ error: Error?) -> Void = {_ in return}) { } func unlike(completion: (_ error: Error?) -> Void = {_ in return}) { } func comment(withText: String?, completion: (_ error: Error?) -> Void = {_ in return}) { } func getComments(completion: (_ error: Error?, _ comments: [IGComment]?) -> Void = {_ in return}) { } } enum IGMediaType{ case video case photo } <file_sep>// // SetPasswordViewController.swift // Swap // // Created by <NAME> on 3/12/17. // // import Foundation class setPasswordViewController: UIViewController{ @IBOutlet var passwordField: UITextField! @IBOutlet var showPasswordButton: UIButton! var passwordSecure = true override func viewDidLoad() { passwordField.becomeFirstResponder() } @IBAction func showPassword(_ sender: Any) { passwordSecure = !passwordField.isSecureTextEntry passwordField.isSecureTextEntry = passwordSecure if (passwordSecure){ showPasswordButton.setTitle("Show Password", for: .normal) } else{ showPasswordButton.setTitle("Hide Password", for: .normal) } } @IBAction func didTapNext(_ sender: Any) { if (passwordField.text?.length)! >= 6{ savePassword(password: <PASSWORD>Field.text) self.performSegue(withIdentifier: "toPhoneNumberController", sender: nil) } else{ UIAlertView(title: "Invalid Password", message: "Password Must Be At Least 6 Characters", delegate: nil, cancelButtonTitle: "Ok").show() } } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } } <file_sep>// // Account.swift // Swap // This file handles creating, resetting, etc a Swap Account // Created by <NAME> on 11/19/16. // Copyright © 2016 Swap Inc. All rights reserved. // import Foundation import AWSCore import AWSCognitoIdentityProvider import AWSMobileHubHelper import Alamofire import SwiftyJSON /// Function to create an account for a Swap User. /// - author: <NAME> /// - todo: Find more errors that can result in signing up /// - version: 2.0 /// - Parameters: /// - username: Entered username /// - password: <PASSWORD> /// - email: Entered email address /// - phonenumber: Entered phone number /// - toPool: AWSCognitioIdenity Pool Object to add this user to, by default it is the pool declared in constants /// - failedToCreateAccount: Completion block executed with 'SignUpError' passed in it if there is an error creating an account /// - signUpError: .EmptyFields .PasswordTooShort .UsernameTaken .InvalidUsername .InvalidPhonenumber .InvalidEmail .UnknownSignUpError /// - didCreateAccount: Code block executed if succeded creating an account /// - todo: Find more errors that can result in signing up func createAccount(username: String?, password: String?, email: String?, phonenumber: String?, toPool: AWSCognitoIdentityUserPool = pool, failedToCreateAccount: @escaping (_ signUpError: SignUpError) -> Void, didCreateAccount: @escaping () -> Void) { // Ensures that the entered parameters are not empty guard !(username?.isEmpty)! && !(password?.isEmpty)! && !(email?.isEmpty)! && !(phonenumber?.isEmpty)! else{ let signUpError = SignUpError.EmptyFields // Error is passed in completion block 'failedToCreateAccount' failedToCreateAccount(signUpError) return } guard (username?.isAValidUsername())! else { failedToCreateAccount(SignUpError.InvalidUsername) return } // Ensures Password is long enough guard (password?.characters.count)! >= 6 else{ failedToCreateAccount(SignUpError.PasswordTooShort) return } let Phone = AWSCognitoIdentityUserAttributeType() let Email = AWSCognitoIdentityUserAttributeType() let ProfilePictureURL = AWSCognitoIdentityUserAttributeType() let IsVerified = AWSCognitoIdentityUserAttributeType() Phone?.name = "phone_number" Email?.name = "email" Email?.value = email!.lowercased().trim() Phone?.value = phonenumber! ProfilePictureURL?.name = "picture" ProfilePictureURL?.value = defaultImage IsVerified?.name = "profile" IsVerified?.value = "IS_NOT_VERIFIED" // Adds user to user pool in backend toPool.signUp(username!.lowercased().trim(), password: <PASSWORD>!, userAttributes: [Phone!, Email!, ProfilePictureURL!, IsVerified!], validationData: nil).continue(with: AWSExecutor.mainThread(), with: { (task) in print("inside sign up") if let error = task.error as? NSError{ // There was an error signing up print("The sign up error is \(error.debugDescription)") let errorString = error.debugDescription if errorString.contains("UsernameExistsException"){ failedToCreateAccount(SignUpError.UsernameTaken) } else if errorString.contains("Invalid phone number format"){ failedToCreateAccount(SignUpError.InvalidPhonenumber) } else if errorString.contains("Invalid email address format"){ failedToCreateAccount(SignUpError.InvalidEmail) } else if errorString.contains("Invalid email address format"){ failedToCreateAccount(SignUpError.InvalidEmail) } else if errorString.contains("Value at 'username' failed to satisfy constraint"){ failedToCreateAccount(SignUpError.InvalidUsername) } else{ //Unknown Error that hasn't been handled failedToCreateAccount(SignUpError.UnknownSignUpError) } } if task.result != nil{ getContact(withPhonenumber: phonenumber!) // Succeeded in signing up user print("Succeeded in Signing Up User") // Saves the username and password in nsuserdefaults so you can retreive it in another view controller saveUsername(username: username?.trim().lowercased()) savePassword(password: <PASSWORD>!) saveEmail(email: email?.lowercased().trim()) savePhonenumber(phone: phonenumber?.trim()) Analytics.didSignUp() didCreateAccount() } return nil }) } /// /// Function that resends confirmation code to user with specified username /// - Author: <NAME> /// - Parameter toUserWithUsername: Username that belongs to the user to send code to func resendConfirmationCode(toUserWithUsername: String, inPool: AWSCognitoIdentityUserPool? = pool){ inPool?.getUser(toUserWithUsername.lowercased()).resendConfirmationCode() } /// Function to confirm user with the verification number sent to their phonenumber /// - Author: <NAME> /// - Parameters: /// - inPool: AWSCognitioIdentityUserPool object that the user is located in, by default it is the pool declared in constants /// - withCode: Optional String that the user entered in as the confirmation code /// - username: Username of the user that needs to be confirmed /// - failed: Code block executed if failed (invalid code or empty string - user did not enter confirmation code) /// - succeded: Code block executed if succeeded func confirmUser(inPool: AWSCognitoIdentityUserPool? = pool, withCode: String?, username: String, failed: @escaping () -> Void, succeded: @escaping ()-> Void) { guard withCode != nil else{ // String is nil failed() return } guard !(withCode?.isEmpty)! else{ // Empty String failed() return } // Confirms User Account inPool?.getUser(username.lowercased()).confirmSignUp(withCode!, forceAliasCreation: true).continue(with: AWSExecutor.mainThread(), with: { (task) -> Any? in DispatchQueue.main.async { if task.error != nil { // There was an error // Possibly Wrong Code failed() } else { // Correct Code succeded() } } }) } /// Function that returns whether user is signed in or not /// /// - Returns: If user is signed in func isSignedIn() -> Bool { return AWSIdentityManager.defaultIdentityManager().isLoggedIn } /// Function to sign out of Swap. /// /// - Parameter didSignOut: This optional completion block is executed whenever there is a successful sign out func signOut(didSignOut: @escaping () -> Void? = {return} ) { SwapUser(username: getUsernameOfSignedInUser()).removePushNotificationID() SwapUser(username: getUsernameOfSignedInUser()).set(Points: 0, WillShareSpotify: false, WillShareYouTube: false, WillSharePhonenumber: false, WillShareVine: false, WillShareInstagram: false, WillShareTwitter: false, WillShareEmail: false, WillShareReddit: false, WillSharePinterest: false, WillShareSoundCloud: false, WillShareGitHub: false, WillShareVimeo: false) AWSIdentityManager.defaultIdentityManager().logout { (result, error) in // successful sign in print("Sign out") Analytics.didSignOut() didSignOut() } } /// Gets the username of the Swap User that is currently signed in /// /// - Returns: Username of signed in user func getUsernameOfSignedInUser() -> String { if let username = AWSIdentityManager.defaultIdentityManager().userName{ return username } else{ return getSavedUsername() ?? "" } } /// Sends a verification code in order to reset the password of the user to 'destination' in completion block (String). The booleans test shows if it succeeded in sending a verificaiton, if it's false, the user could not be found. The SwapUser object should contain the username, email address, or phone number as the 'username' attribute. func forgotPassword(username: String, completion: @escaping (_ didSendCode: Bool, _ destination: String?) -> Void) { pool.getUser(username.lowercased().trim().toUsernameSignInAlias()).forgotPassword().continue({ (task) in DispatchQueue.main.async { if let response = task.result?.codeDeliveryDetails{ let destination = response.destination! saveUsername(username: username.lowercased().trim().toUsernameSignInAlias()) completion(true, destination) } else{ // User Not Found completion(false, nil) } } }) } func confirmForgotPassword(username: String, confirmation code: String, new password: String, completion: @escaping (_: Bool) -> Void) { pool.getUser(username.lowercased().trim().toUsernameSignInAlias()).confirmForgotPassword(code, password: <PASSWORD>).continue({ (task) in DispatchQueue.main.async { guard task.error == nil else { completion(false) return } completion(true) } }) } /// Change password of a signed in user func change(username: String, oldPassword old: String, newPassword new: String, completion: @escaping (_ success: Bool) -> Void) { pool.getUser(username.lowercased().trim().toUsernameSignInAlias()).changePassword(old, proposedPassword: new).continue({ (task) in DispatchQueue.main.async { guard task.error == nil else { completion(false) return } completion(true) } }) } /// Predicts user's gender based on first name and stores their gender in database on a background thread /// /// - Parameter withFirstname: Firstname of the user func guessAndSetSex(withFirstname: String) { DispatchQueue.global(qos: .default).async { Alamofire.request(URL(string: "https://api.genderize.io/")!, method: .get, parameters: ["name": "\(withFirstname)"]).responseJSON { (response) in if let data = response.data{ let json = JSON(data: data) print("the json is ..... \(json)") if let gender = json["gender"].string{ SwapUser(username: getUsernameOfSignedInUser()).set(Gender: gender) } } } } } <file_sep>// // AWSConfiguration.swift // MySampleApp // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // // import AWSCore import AWSMobileHubHelper import AWSCognitoIdentityProvider /// Cognito User Pools Identity Id let AWSCognitoUserPoolId: String = "us-east-1_YWiyB9cSt" /// Cognito User ID let AWSCognitoID: String = "us-east-1:d0d2cc0d-a727-4228-91b7-f1e7aba06e5c" /// Cognito User Pools App Client Id let AWSCognitoUserPoolAppClientId: String = "4aosg5oj8fcqiv20uf1mic1sds" /// Cognito User Pools Region let AWSCognitoUserPoolRegion: AWSRegionType = .usEast1 /// Cognito User Pools Client Secret let AWSCognitoUserPoolClientSecret: String = "<KEY>" /// Identifier for Cloud Logic API invocation clients let AWSCloudLogicDefaultConfigurationKey: String = "CloudLogicAPIKey" let AWSCloudLogicDefaultRegion: AWSRegionType = .usEast1 /// Pool that contains users for authentification let pool = AWSCognitoIdentityUserPool(forKey: AWSCognitoUserPoolsSignInProviderKey) let idManager = AWSCognitoIdentityProvider(forKey: "USEast1CognitoIdentityProvider") let ONE_SIGNAL_APP_ID = "60f1a2ad-082f-4ff0-9d51-dbf991bc23f3" <file_sep>// // ScannerView.swift // Swap // // Created by <NAME> on 1/7/17. // // import Foundation import AVFoundation import Spring import MapKit let scanner = QRCode(autoRemoveSubLayers: false, lineWidth: CGFloat(nan: 0,signaling: true) , strokeColor: UIColor.clear, maxDetectedCount: 1) class ScannerViewController: UIViewController, UIImagePickerControllerDelegate, UIGestureRecognizerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate{ let imagePicker = UIImagePickerController() @IBOutlet var enableCameraLabel: UILabel! @IBOutlet var enableCameraButton: UIButton! @IBOutlet var blurView: UIVisualEffectView! @IBOutlet var confirmSwapView: UIView! @IBOutlet var nameLabel: UILabel! @IBOutlet var bioLabel: UILabel! @IBOutlet var profilePic: UIImageView! @IBOutlet var verifiedIcon: UIImageView! // @IBOutlet var blurView: UIVisualEffectView! var effect: UIVisualEffect! var loadingSymbol: UIImageView? let locationManager = CLLocationManager() var latitude: String? = nil var longitude: String? = nil override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self setupViewController() handleCaseOfDisabledCamera() NotificationCenter.default.addObserver(self, selector: #selector(self.scannerDidShow), name: .didShowScanner, object: nil) } func scannerDidShow(){ setupSwapScanner() } @IBAction func showProfile(_ sender: Any) { self.performSegue(withIdentifier: "showProfile", sender: nil) } @IBAction func enableCamera(_ sender: Any) { UIApplication.shared.openURL(NSURL(string:UIApplicationOpenSettingsURLString)! as URL) } @IBAction func uploadSwapCode(_ sender: Any) { imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } func setupViewController() { //sets up swap confirm view self.view.addSubview(confirmSwapView) confirmSwapView.backgroundColor = UIColor.clear confirmSwapView.alpha = 0 confirmSwapView.center = CGPoint(x: self.view.center.x, y: self.view.center.y+200) //recognizes a tap anywhere on the screen let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapScreen)) tapGestureRecognizer.numberOfTapsRequired = 1 self.view.addGestureRecognizer(tapGestureRecognizer) circularImageNoBorder(photoImageView: profilePic) blurView.isHidden = true enableCameraLabel.isHidden = true enableCameraButton.isHidden = true } func didTapScreen(){ blurView.isHidden = true // User has tapped the screen UIView.animate(withDuration: 0.2, animations: { self.confirmSwapView.alpha = 0 self.confirmSwapView.transform = CGAffineTransform.init(translationX: 0, y: 200) }) scanner.startScan() } func animateInSwapView(){ blurView.isHidden = false UIView.animate(withDuration: 0.25){ self.confirmSwapView.alpha = 1 self.confirmSwapView.transform = CGAffineTransform.init(translationX: 0, y: -200) self.nameLabel.adjustsFontSizeToFitWidth = true self.bioLabel.adjustsFontSizeToFitWidth = true } } func handleCaseOfDisabledCamera() { let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch authStatus { case .authorized: break case .denied: enableCameraLabel.isHidden = false enableCameraButton.isHidden = false break default: break } } func setupSwapScanner() { let loadingOverlay = ShowLoadingOverlay() scanner.prepareScan(self.view){ (swapLink) in self.nameLabel.isHidden = true self.bioLabel.isHidden = true self.verifiedIcon.isHidden = true self.profilePic.isHidden = true self.animateInSwapView() self.loadingSymbol = loadingOverlay.showLoadingSymbol(view: self.view, shouldCenter: true) self.view.addSubview(self.loadingSymbol!) let username = getUsernameFromSwapLink(swapLink: swapLink) SwapUser().swap(with: username, authorizeOnViewController: self, completion: { (error, user) in DispatchQueue.main.async { // Ask for location Authorization from the User. //** Ask for Location Always // self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest//kCLLocationAccuracyNearestTenMeters self.locationManager.startUpdatingLocation() } self.nameLabel.isHidden = false self.bioLabel.isHidden = false self.profilePic.isHidden = false self.loadingSymbol?.isHidden = true if error != nil { // There was an error trying to get the user from the swap code self.animateInSwapView() self.nameLabel.text = "User Not Found" self.bioLabel.text = "" self.verifiedIcon.isHidden = true self.profilePic.image = #imageLiteral(resourceName: "DefaultProfileImage") } if let user = user { searchedUser = user._username! if user._isPrivate?.boolValue ?? false{ //the user is private; notify the user that a request was sent. self.animateInSwapView() let fullString = NSMutableAttributedString(string: "") let lockedImageAttachment = NSTextAttachment() lockedImageAttachment.image = #imageLiteral(resourceName: "LockIcon") let lockedImageString = NSAttributedString(attachment: lockedImageAttachment) let nameString = NSMutableAttributedString(string: " \(user._firstname ?? "") \(user._lastname ?? "")") fullString.append(lockedImageString) fullString.append(nameString) self.profilePic.kf.indicatorType = .activity self.profilePic.kf.setImage(with: URL(string: user._profilePictureUrl ?? defaultImage)) self.nameLabel.attributedText = fullString self.bioLabel.text = user._bio ?? "" if !(user._isVerified as? Bool ?? false){ self.verifiedIcon.isHidden = true } else{ self.verifiedIcon.isHidden = false } } else{ //notify the user that swap was sucessful self.animateInSwapView() self.profilePic.kf.indicatorType = .activity self.profilePic.kf.setImage(with: URL(string: user._profilePictureUrl ?? defaultImage)) self.nameLabel.text = "\(user._firstname ?? "") \(user._lastname ?? "")" self.bioLabel.text = user._bio ?? "" if !(user._isVerified as? Bool ?? false){ self.verifiedIcon.isHidden = true } else{ self.verifiedIcon.isHidden = false } // Add Swap Points let swap = SwapUser() let swapped = SwapUser(username: user._username ?? "") SwapUser.giveSwapPointsToUsersWhoSwapped(swap: swap, swapped: swapped) // Add location to swap history let history = SwapUserHistory(swap: swap.username, swapped: swapped.username) history.didShare( latitude: self.latitude, longitude: self.longitude) // Reload Profile to refresh swap points and swap maps NotificationCenter.default.post(name: .reloadProfile, object: nil) } } } }) } scanner.scanFrame = view.bounds } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: nil) if let pickedimage = info[UIImagePickerControllerEditedImage] as? UIImage { let swapLink = swapCodeLinkFrom(Image: pickedimage) let usernameFromSwapCode = getUsernameFromSwapLink(swapLink: swapLink) SwapUser().swap(with: usernameFromSwapCode, authorizeOnViewController: self, method: .upload, completion: { (error, user) in guard error == nil, let user = user else { // User Not Found // There was an error trying to get the user from the swap code self.animateInSwapView() self.nameLabel.text = "User Not Found" self.bioLabel.text = "" self.verifiedIcon.isHidden = true self.profilePic.image = #imageLiteral(resourceName: "DefaultProfileImage") return } DispatchQueue.main.async { if user._isPrivate?.boolValue ?? false{ //the user is private; notify the user that a request was sent. self.animateInSwapView() let fullString = NSMutableAttributedString(string: "") let lockedImageAttachment = NSTextAttachment() lockedImageAttachment.image = #imageLiteral(resourceName: "LockIcon") let lockedImageString = NSAttributedString(attachment: lockedImageAttachment) let nameString = NSMutableAttributedString(string: " \(user._firstname ?? "") \(user._lastname ?? "")") fullString.append(lockedImageString) fullString.append(nameString) self.profilePic.kf.indicatorType = .activity self.profilePic.kf.setImage(with: URL(string: user._profilePictureUrl ?? defaultImage)) self.nameLabel.attributedText = fullString self.bioLabel.text = user._bio ?? "" if !(user._isVerified as? Bool ?? false){ self.verifiedIcon.isHidden = true } else{ self.verifiedIcon.isHidden = false } } else{ //notify the user that swap was sucessful self.animateInSwapView() self.profilePic.kf.indicatorType = .activity self.profilePic.kf.setImage(with: URL(string: user._profilePictureUrl ?? defaultImage)) self.nameLabel.text = "\(user._firstname ?? "") \(user._lastname ?? "")" self.bioLabel.text = user._bio ?? "" if !(user._isVerified as? Bool ?? false){ self.verifiedIcon.isHidden = true } else{ self.verifiedIcon.isHidden = false } // Add Swap Points let swap = SwapUser() let swapped = SwapUser(username: user._username ?? "") SwapUser.giveSwapPointsToUsersWhoSwapped(swap: swap, swapped: swapped) } } }) } else{ print("error selecting picture") } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = manager.location { let x_location = location.coordinate.latitude let y_location = location.coordinate.longitude latitude = "\(x_location)" longitude = "\(y_location)" } } } func getUsernameFromSwapLink(swapLink: String) -> String { return (swapLink as NSString).lastPathComponent.lowercased() } /// Returns the swap link from a Swap Code read from an UIImage. Will return "" if none is found. func swapCodeLinkFrom(Image image: UIImage) -> String { var swapLink = "" var detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) if let detector = detector{ if let ciimage = CIImage(image: image){ var features = detector.features(in: ciimage) for feature in features{ let decodedCode = (feature as! CIQRCodeFeature).messageString swapLink = decodedCode ?? "" } } } return swapLink } <file_sep>// // MoreInfo.swift // Swap // // Created by <NAME> on 1/20/17. // // import Foundation var moreInfoMiddleName = "" var moreInfoCompany = "" var moreInfoWebsite = "" class MoreInfoTable: UITableViewController, UITextFieldDelegate { @IBOutlet public var middleNameField: UITextField! @IBOutlet var companyField: UITextField! @IBOutlet var websiteField: UITextField! override func viewWillAppear(_ animated: Bool) { SwapUser(username: getUsernameOfSignedInUser()).getInformation { (error, user) in DispatchQueue.main.async { let middlename = (user?._middlename == nil && getSavedMiddlename() != nil) ?getSavedMiddlename()! : ( user?._middlename ?? "") let company = (user?._company == nil && getSavedCompany() != nil) ? getSavedCompany()! : ( user?._company ?? "") let website = (user?._website == nil && getSavedWebsite() != nil) ?getSavedWebsite()! : ( user?._website ?? "") self.middleNameField.text = middlename self.companyField.text = company self.websiteField.text = website var moreInfoMiddleName = middlename var moreInfoCompany = company var moreInfoWebsite = website } } } override func viewDidLoad() { tableView.allowsSelection = false middleNameField.delegate = self companyField.delegate = self websiteField.delegate = self } func textFieldDidEndEditing(_ textField: UITextField) { moreInfoMiddleName = middleNameField.text! moreInfoCompany = companyField.text! moreInfoWebsite = websiteField.text! } } class MoreInfo: UIViewController{ @IBOutlet var activityView: UIActivityIndicatorView! @IBAction func didTapBack(_ sender: Any) { self.view.endEditing(true) activityView.isHidden = false activityView.startAnimating() SwapUser().updateProfileInfoWith(Middlename: moreInfoMiddleName, Company: moreInfoCompany,Website: moreInfoWebsite, DidSetInformation: { DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) } }, CannotSetInformation: { print("error setting basic profile info") }) } override func viewDidLoad() { activityView.isHidden = true activityView.stopAnimating() } } <file_sep>// // SetNewPhoneNumber.swift // Swap // // Created by <NAME> on 7/22/17. // // import Foundation import PhoneNumberKit import CountryPicker class SetNewPhoneNumber: UIViewController, UITextFieldDelegate, CountryPickerDelegate { @IBOutlet var phoneNumberTextField: PhoneNumberTextField! @IBOutlet var CountryCodeButton: UIButton! @IBOutlet var ConfirmationView: UIView! @IBOutlet var CountryCodePicker: CountryPicker! @IBOutlet var blurView: UIVisualEffectView! @IBOutlet var confirmationLabel: UILabel! @IBOutlet var SendSMSButton: UIButton! var phoneNumber: String! var PhoneCode: String! var COUNTRYCODE: String! override func viewDidLoad() { phoneNumberTextField.delegate = self phoneNumberTextField.becomeFirstResponder() //get current country let locale = Locale.current let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String? //init Picker CountryCodePicker.countryPickerDelegate = self CountryCodePicker.showPhoneNumbers = true CountryCodePicker.setCountry(code!) blurView.isHidden = true } @IBAction func didTapCountryCode(_ sender: Any) { self.resignFirstResponder() view.endEditing(false) } @IBAction func didTapNext(_ sender: Any) { phoneNumber = "\(PhoneCode ?? "") \(phoneNumberTextField.text ?? "")" guard phoneNumber.isPhoneNumber else { UIAlertView(title: "Invalid Phone Number", message: "Please enter a valid phone number.", delegate: self, cancelButtonTitle: "Ok").show() return } savePhonenumber(phone: "+\(phoneNumber.digits)") let alert = UIAlertController(title: "Change phone number associated with this Swap account?", message:"You have successfully changed the number used to swap contacts. Is this a new number you will be able to recieve text messages at?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action) in // Set New Phone Number in DynamoDB Without Changing in Amazon Cognito SwapUser().set(Phonenumber: "+\(self.phoneNumber.digits)", ShouldChangePhoneNumberAssociation: false, DidSetInformation: { _ in self.dismiss(animated: true, completion: nil) return nil }) })) alert.addAction(UIAlertAction(title: "Verify", style: .default, handler: { (action) in // Show popup view self.view.endEditing(true) self.view.addSubview(self.ConfirmationView) self.ConfirmationView.backgroundColor = UIColor.clear self.ConfirmationView.center = self.view.center self.ConfirmationView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3) self.ConfirmationView.alpha = 0 // Set the confirmation view text here self.confirmationLabel.text = "Send Confirmation Code to \(self.phoneNumber ?? "")?" UIView.animate(withDuration: 0.4){ self.blurView.isHidden = false self.blurView.alpha = 0.5 self.ConfirmationView.alpha = 1 self.ConfirmationView.transform = CGAffineTransform.identity } })) self.present(alert, animated: true, completion: nil) } func countryPhoneCodePicker(_ picker: CountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage) { PhoneCode = phoneCode CountryCodeButton.setTitle(countryCode + " " + phoneCode, for: .normal) COUNTRYCODE = phoneCode } @IBAction func didTapBack(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func didTapSendSMS(_ sender: Any) { SendSMSButton.isEnabled = false SwapUser().set(Phonenumber: "+\(self.phoneNumber.digits)", DidSetInformation: { _ in DispatchQueue.main.async { self.performSegue(withIdentifier: "confirmNumber", sender: nil) } }) } @IBAction func didTapCloseConfirmation(_ sender: Any) { SendSMSButton.isEnabled = true UIView.animate(withDuration: 0.2){ self.ConfirmationView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3) self.ConfirmationView.alpha = 0 self.blurView.isHidden = true } } } <file_sep>// // twitterView.swift // Swap // // Created by <NAME> & <NAME> on 1/31/17. // // import Foundation import TwitterKit var twitterUserID: String? = nil class TwitterView: TWTRTimelineViewController { override func viewDidLoad() { super.viewDidLoad() //declare UI variables let overlayImage = UIImageView() overlayImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 1000) overlayImage.backgroundColor = UIColor.white self.view.addSubview(overlayImage) overlayImage.isHidden = true let noTwitterLabel = UILabel(frame: CGRect(x: self.view.center.x-65, y: self.view.center.y, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) noTwitterLabel.text = "No Twitter Feed" noTwitterLabel.textColor = .black noTwitterLabel.textAlignment = NSTextAlignment.center noTwitterLabel.font = UIFont(name: "Avenir-Next", size: 20) noTwitterLabel.sizeToFit() self.view.addSubview(noTwitterLabel) noTwitterLabel.isHidden = true let client = TWTRAPIClient() client.loadUser(withID: twitterUserID ?? "") { (user, error) in guard error == nil else{ print("Error... Could not obtain Twitter. Invalid twitter ID or user does not have twitter connected") overlayImage.isHidden = false noTwitterLabel.isHidden = false return } guard !(user?.isProtected ?? true) else { print("Cannot view Tweets of a protected/private user. Twitter is private") overlayImage.isHidden = false noTwitterLabel.isHidden = false return } self.dataSource = TWTRUserTimelineDataSource(screenName: nil, userID: twitterUserID, apiClient: client, maxTweetsPerRequest: 500, includeReplies: true, includeRetweets: true) TWTRTweetView.appearance().backgroundColor = UIColor(colorLiteralRed: 0.110, green: 0.161, blue: 0.212, alpha: 1.00) TWTRTweetView.appearance().primaryTextColor = UIColor.white self.showTweetActions = true } } } <file_sep>// // StoriesView.swift // Swap // // Created by <NAME> on 1/31/17. // // import Foundation import MapKit class StoriesView: UIViewController { @IBOutlet var mapView: MKMapView! override func viewDidLoad() { self.setupSwipeGestureRecognizers(allowCyclingThoughTabs: true) setupMap() addPins() } /// Adds pins on map that show locations of where you swapped users func addPins() { for history in swapHistoryUsers{ /* let rand = drand48() / 100 history._latitude = (mapView.userLocation.coordinate.latitude != 0) ? "\(mapView.userLocation.coordinate.latitude)" : "40.7128" history._longitude = (mapView.userLocation.coordinate.longitude != 0) ? "\(mapView.userLocation.coordinate.longitude)" : "-74.0059" */ if let x_cordinate_string = history._latitude, let y_cordinate_string = history._longitude{ let x_cordinate = Double(x_cordinate_string) let y_cordinate = Double(y_cordinate_string) // Ensure there are cordinates presents if let x = x_cordinate, let y = y_cordinate{ // Add Annotations var annotation = MKPointAnnotation() // ***DELETE RAND IN PRODUCTION annotation.coordinate = CLLocationCoordinate2DMake(x, y) annotation.title = history._swapped ?? "" mapView.addAnnotation(annotation) } } } } /// Center's Map on User's Location. If there's no location, it defaults to New York City func setupMap() { // Gets the user's location and centers map var currentLocation = mapView.userLocation.coordinate if currentLocation.latitude == 0 && currentLocation.longitude == 0 { // Set Location to default location let NewYorkCity = CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0059) currentLocation = NewYorkCity } let region = MKCoordinateRegion(center: currentLocation, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) mapView.setRegion(region, animated: true) } } <file_sep>// // StoriesView.swift // Swap // // Created by <NAME> on 1/31/17. // // import Foundation import MapKit import Firebase import GeoFire // Reference to location database with live user locations let geofireRef = Database.database().reference() // Location Database let locationDatabase = GeoFire(firebaseRef: geofireRef) class PopularNearbyMapView: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet var mapView: MKMapView! @IBOutlet var moreInfoView: UIView! @IBOutlet var nameLabel: UILabel! @IBOutlet var bioLabel: UILabel! @IBOutlet var locationLabel: UILabel! @IBOutlet var profilePicture: UIImageView! @IBOutlet var blurView: UIVisualEffectView! var swapPin: SwapsAnnotation! var NewYorkCity = CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0059)//defaults to New York City let locationManager = CLLocationManager() override func viewDidLoad() { // Checks if Location Services Are Enabled if CLLocationManager.locationServicesEnabled() { switch(CLLocationManager.authorizationStatus()) { case .notDetermined, .restricted, .denied: // Tell the user that location services is disabled and take them to settings let alertView = UIAlertController(title: "Location Services Disabled", message: "Enable location to see popular profiles around you", preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (_) -> Void in guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { if #available(iOS 10.0, *) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } })) alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertView, animated: true, completion: nil) //locationManager.requestAlwaysAuthorization() case .authorizedAlways: print("Can always access location (this is what we need)") case .authorizedWhenInUse: print("Only when in use. We need access always") } } else { print("Location services are not enabled") } blurView.isHidden = true circularImageNoBorder(photoImageView: profilePicture) // Listens for reloadProfile notification NotificationCenter.default.addObserver(self, selector: #selector(self.reloadMap), name: .reloadMap, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.pinSelected), name: .showPinInfo, object: nil) mapView.delegate = self locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() if #available(iOS 11.0, *) { locationManager.showsBackgroundLocationIndicator = false } else { // Fallback on earlier versions } //addPins() locationManager.startUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = true locationManager.distanceFilter = 10 let region = MKCoordinateRegionForMapRect(MKMapRectWorld) mapView.setRegion(region, animated: true) } ///This will remove all pins on the map and reload the pins func reloadMap() { //Remove all added annotations mapView.removeAnnotations(mapView.annotations) // addPins() } //Center the map on the user's location when the view appears func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var currentLocation = manager.location!.coordinate let region = MKCoordinateRegion(center: currentLocation, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) mapView.setRegion(region, animated: true) // Update User Location in Database if let location = locations.first{ locationDatabase?.setLocation(location, forKey: getUsernameOfSignedInUser()) ///******* TESTING POPULAR NEARBY ******* var nearbyUsers: [String: Double] = [:] // Query Users Based on Location Radius //Key Entered: The location of a key now matches the query criteria. let radius = 0.2 // In Kilometers let query = locationDatabase?.query(at: location, withRadius: radius) query?.observe(.keyEntered, with: { (username, user_location) in guard username != getUsernameOfSignedInUser() else{ return } // Called whenever another user moves within a nearby location. print("Key Entered Event\n\n") var meters = user_location?.distance(from: location) nearbyUsers[username!] = meters // This is ran everytime a new user is found nearby // Add code to update swap map here }) query?.observeReady({ guard nearbyUsers.count > 0 else { return } // Called when query is complete // This is called after ALL nearby users have been found }) } mapView.showsUserLocation = true } func addNearbyUserPins() { } /// Adds pins on map that show locations of where you swapped users func addPins() { for history in swapHistoryUsers{ if let x_cordinate_string = history._latitude, let y_cordinate_string = history._longitude{ print("I have cordinates") let x_cordinate = Double(x_cordinate_string) let y_cordinate = Double(y_cordinate_string) print("X_Cordinate: \(x_cordinate)\nY_Cordinate: \(y_cordinate)") // Ensure there are cordinates presents if let x = x_cordinate, let y = y_cordinate{ // Add Annotations print("creating pin") swapPin = SwapsAnnotation() swapPin.coordinate = CLLocationCoordinate2D(latitude: x , longitude: y ) swapPin.title = history._swapped ?? "" mapView.addAnnotation(swapPin) } } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if !(annotation is MKPointAnnotation) { return nil } var identifier = "pinID" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if annotationView == nil { annotationView = SwapsAnnotationView(annotation: annotation, reuseIdentifier: identifier) print("ANNOTATION TITILE: \(annotation.title!!)") let swapPinView = self.createAnnotationView(from: (annotation.title ?? "")!) annotationView! = swapPinView annotationView!.canShowCallout = false } else { annotationView?.annotation = annotation } return annotationView } /// Creates an annotation view from a username func createAnnotationView(from username: String) -> MKAnnotationView{ var AnnotationView = SwapsAnnotationView() var pinImageView = UIImageView(image: #imageLiteral(resourceName: "SwapAnnotationIcon")) var profilePicImageView = UIImageView() AnnotationView.title = username profilePicImageView.kf.indicatorType = .activity // Check if there's an image saved in user defaults for the user if let profilePicture = getSwapMapProfilePictureFromUser(with: username){ print("Profile Picture Saved in User Defaults") profilePicImageView.kf.setImage(with: URL(string: profilePicture)) } else{ print("No Profile Picture Saved in User Defaults") // No Image Saved... download it SwapUser(username: username).getInformation { (error, user) in if let user = user { profilePicImageView.kf.setImage(with: URL(string: user._profilePictureUrl ?? "")) // Save the image if let picture = user._profilePictureUrl{ saveMapProfilePictureToUser(username: username, pictureURL: picture) } } else{ profilePicImageView.image = #imageLiteral(resourceName: "DefaultProfileImage") } } } DispatchQueue.main.async { circularImageNoBorder(photoImageView: profilePicImageView) } if (self.storyboard?.value(forKey: "name") as! String == "IPhone7Plus"){ profilePicImageView.frame = CGRect(x: profilePicImageView.center.x + 15, y: profilePicImageView.center.y - 24, width: profilePicImageView.frame.width - 41, height: profilePicImageView.frame.height - 41) } else{ profilePicImageView.frame = CGRect(x: profilePicImageView.center.x + 22, y: profilePicImageView.center.y - 20, width: profilePicImageView.frame.width - 44, height: profilePicImageView.frame.height - 44) } pinImageView.frame = CGRect(x: pinImageView.center.x - 62, y: pinImageView.center.y - 110, width: pinImageView.frame.width, height: pinImageView.frame.height) AnnotationView.addSubview(pinImageView) AnnotationView.addSubview(profilePicImageView) return AnnotationView } func pinSelected() { let dismissTap = UITapGestureRecognizer(target: self, action: #selector(self.dismissMorePinInfo)) blurView.isHidden = false blurView.addGestureRecognizer(dismissTap) moreInfoView.frame = CGRect(x: view.center.x - moreInfoView.frame.width/2, y: view.center.y - moreInfoView.frame.height/2, width: moreInfoView.frame.width, height: moreInfoView.frame.height) moreInfoView.backgroundColor = .clear view.addSubview(moreInfoView) for annotation in mapView.selectedAnnotations{ SwapUser(username: annotation.title!!).getInformation(completion: { (error, user) in if error == nil{ DispatchQueue.main.async { self.nameLabel.text = "\(user?._firstname ?? "") \(user?._lastname ?? "")" self.profilePicture.kf.setImage(with: URL(string: (user?._profilePictureUrl)!)) self.bioLabel.text = user?._bio ?? "" var metAt = "" let geoCoder = CLGeocoder() let location = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude) geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in // Place details var placeMark: CLPlacemark! placeMark = placemarks?[0] // Address dictionary print(placeMark.addressDictionary as Any) // Location name if let locationName = placeMark.addressDictionary!["Name"] as? NSString { metAt.append(locationName as String) } // City if let city = placeMark.addressDictionary!["City"] as? NSString { metAt.append(", \(city)") } self.locationLabel.text = metAt }) } } }) } } func dismissMorePinInfo(){ moreInfoView.removeFromSuperview() blurView.isHidden = true profilePicture.image = #imageLiteral(resourceName: "DefaultProfileImage") nameLabel.text = "Loading..." bioLabel.text = "" locationLabel.text = "" } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { // Executed when there is an error in updating location } }
045aa7242414f503e977adb45caeb3c87f0f16f3
[ "Swift", "Ruby", "Markdown" ]
71
Swift
eliu2016/Swap
8439250611d007ab9b2c4bab5e206228988ad647
321c65c6b977fe589f2f009a1072ba6de4332d4b
refs/heads/master
<repo_name>Pankraty/StringBenchmark<file_sep>/Program.cs using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using System; using System.Text; namespace StringBenchmark { class Program { static void Main(string[] args) { BenchmarkRunner.Run<CellBenchmark>(); BenchmarkRunner.Run<RangeBenchmark>(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } public class CellBenchmark { public class Cell { static Random rnd = new Random(); readonly string[] columns = { "A", "B", "C", "D", "E", "F", "AB", "CD", "EF", "GH", "IJ", "KL", "ABC", "DEF", "GHI", "JKL", "MNO", "PRQ" }; public string Col { get; set; } public int Row { get; set; } public Cell() { Col = columns[rnd.Next(columns.Length)]; Row = rnd.Next(1_000_000); } } [Benchmark(Description = "Create cell", Baseline = true)] public string CreateCells() { var cell = new Cell(); return ""; } [Benchmark(Description = "String.Format(...)")] public string TestFormat() { var cell = new Cell(); return Format(cell.Col, cell.Row); } [Benchmark(Description = "String.Concat(...)")] public string TestConcat() { var cell = new Cell(); return Concat(cell.Col, cell.Row); } [Benchmark(Description = "StringBuilder.ToString()")] public string TestStringBuilder() { var cell = new Cell(); return Builder(cell.Col, cell.Row); } [Benchmark(Description = "\"$\"+col+\"$\"+row.ToString()")] public string TestPlus() { var cell = new Cell(); return Plus(cell.Col, cell.Row); } private string Plus(string col, int row) { return "$" + col + "$" + row.ToString(); } private string Format(string col, int row) { return string.Format("${0}${1}", col, row); } private string Concat(string col, int row) { return String.Concat("$", col, "$", row); } private string Builder(string col, int row) { return new StringBuilder("$").Append(col).Append("$").Append(row).ToString(); } } public class RangeBenchmark { public class Cell { static Random rnd = new Random(); readonly string[] columns = { "A", "B", "C", "D", "E", "F", "AB", "CD", "EF", "GH", "IJ", "KL", "ABC", "DEF", "GHI", "JKL", "MNO", "PRQ" }; public string Col { get; set; } public int Row { get; set; } public Cell() { Col = columns[rnd.Next(columns.Length)]; Row = rnd.Next(1_000_000); } } [Benchmark(Description = "Create cells", Baseline = true)] public string CreateCells() { var cell1 = new Cell(); var cell2 = new Cell(); return ""; } [Benchmark(Description = "String.Format(...)")] public string TestFormat() { var cell1 = new Cell(); var cell2 = new Cell(); return Format(cell1.Col, cell1.Row, cell2.Col, cell2.Row); } [Benchmark(Description = "String.Concat(...)")] public string TestConcat() { var cell1 = new Cell(); var cell2 = new Cell(); return Concat(cell1.Col, cell1.Row, cell2.Col, cell2.Row); } [Benchmark(Description = "StringBuilder.ToString()")] public string TestStringBuilder() { var cell1 = new Cell(); var cell2 = new Cell(); return Builder(cell1.Col, cell1.Row, cell2.Col, cell2.Row); } [Benchmark(Description = "String.Plus")] public string TestPlus() { var cell1 = new Cell(); var cell2 = new Cell(); return Plus(cell1.Col, cell1.Row, cell2.Col, cell2.Row); } private string Plus(string col1, int row1, string col2, int row2) { return "$" + col1 + "$" + row1.ToString() + ":" + "$" + col2 + "$" + row2; } private string Format(string col1, int row1, string col2, int row2) { return string.Format("${0}${1}:${2}${3}", col1, row1, col2, row2); } private string Concat(string col1, int row1, string col2, int row2) { return String.Concat("$", col1, "$", row1, ":", "$", col2, "$", row2); } private string Builder(string col1, int row1, string col2, int row2) { return new StringBuilder("$").Append(col1).Append("$").Append(row1).Append(":") .Append("$").Append(col2).Append("$").Append(row2) .ToString(); } } } <file_sep>/README.md # StringBenchmark _Everybody knows_ that string concatenation with a plus sign is a very inefficient way of doing. Using a StringBuilder is much more preferable. But it turned out that it is not always true. If we are looking for the way of building a cell address in an "Excel-way", the most primitive way shows the best performance. ``` Method | Mean | Error | StdDev | Scaled | ScaledSD | --------------------------- |---------:|---------:|----------:|-------:|---------:| 'Create cell' | 156.9 ns | 1.167 ns | 1.0912 ns | 1.00 | 0.00 | -- background value String.Format(...) | 509.8 ns | 2.292 ns | 2.1442 ns | 3.25 | 0.03 | -- 100% String.Concat(...) | 483.8 ns | 2.087 ns | 1.9523 ns | 3.08 | 0.02 | -- 92% StringBuilder.ToString() | 400.3 ns | 1.099 ns | 0.8580 ns | 2.55 | 0.02 | -- 69% "$"+col+"$"+row.ToString() | 356.7 ns | 1.615 ns | 1.5107 ns | 2.27 | 0.02 | -- 56% ``` Building cell range addresses ("$AB$100:$DE$200"), however, shows a different result. StringBuilder wins: ``` Method | Mean | Error | StdDev | Scaled | ScaledSD | ------------------------- |---------:|---------:|---------:|-------:|---------:| 'Create cells' | 314.0 ns | 2.647 ns | 2.476 ns | 1.00 | 0.00 | -- background value String.Format(...) | 958.4 ns | 3.317 ns | 3.103 ns | 3.05 | 0.03 | -- 100% String.Concat(...) | 968.8 ns | 2.740 ns | 2.288 ns | 3.08 | 0.02 | -- 101% StringBuilder.ToString() | 855.4 ns | 2.593 ns | 2.425 ns | 2.72 | 0.02 | -- 84% String.Plus | 893.8 ns | 1.883 ns | 1.761 ns | 2.85 | 0.02 | -- 90% ```
8281b7c671c5939b7b156f3ff43e20a6a604ed4c
[ "Markdown", "C#" ]
2
C#
Pankraty/StringBenchmark
03c77e0597e8a1eee57a3d95712800b670297dc0
1477a3915b366a11de9c8e40a470459a46737021
refs/heads/master
<file_sep>import React, { Fragment, useRef } from "react"; import Button from "../UI/Button"; import classes from "./AddMovie.module.css"; const AddMovie = (props) => { const title = useRef(); const message = useRef(); const releaseDate = useRef(); const submitHandler = (event) => { event.preventDefault(); console.log("you come here"); const movie = { titleValue: title.current.value, messageValue: message.current.value, releaseDateValue: releaseDate.current.value, }; props.addMovie(movie); }; return ( <Fragment> <form onSubmit={submitHandler}> <label htmlFor="title" className={classes.label}> Title </label> <input name="title" ref={title} /> <label htmlFor="message">Opening Text</label> <textarea rows="5" name="message" ref={message}></textarea> <label htmlFor="releaseDate">Release Date</label> <input name="releaseDate" ref={releaseDate}></input> <Button type="submit" title="Add Movie"> Add Movie </Button> </form> </Fragment> ); }; export default AddMovie; <file_sep>import Card from "./Component/UI/Card"; import Button from "./Component/UI/Button"; import { Fragment, useState } from "react"; import MovieList from "./Component/Movie/MovieList"; import classes from "./App.module.css"; import AddMovie from "./Component/Movie/AddMovie"; function App() { const [movies, setMovies] = useState([]); async function fetchMoviesHandler() { const response = await fetch( "https://react-movie-e18ec-default-rtdb.firebaseio.com/movies.json" ); const data = await response.json(); console.log(data); const loadedMovies = []; for (const key in data) { loadedMovies.push({ id: key, title: data[key].titleValue, description: data[key].messageValue, releaseDate: data[key].releaseDateValue, }); } setMovies(loadedMovies); /* const transformedMovies = data.results.map((movieData) => { return { id: movieData.episode_id, title: movieData.title, description: movieData.opening_crawl, releaseDate: movieData.release_date, }; }); setMovies(transformedMovies); */ } async function addMovieHandler(movie) { console.log("this is your movie", movie); const response = await fetch( "https://react-movie-e18ec-default-rtdb.firebaseio.com/movies.json", { method: "POST", body: JSON.stringify(movie), header: { "Content-Type": "application/json" }, } ); const data = await response.json(); console.log(data); } return ( <Fragment> <Card> <AddMovie addMovie={addMovieHandler} /> </Card> <Card> <Button onClick={fetchMoviesHandler} title={"Fecth Movie"} /> </Card> <MovieList movies={movies} /> </Fragment> ); } export default App; <file_sep>export const data = [ { title: "movie1", description: "movie blelenen", releaseDate: "2015/05/21", }, { title: "movie2", description: "movie blelenen", releaseDate: "2015/05/21", }, { title: "movie3", description: "movie blelenen", releaseDate: "2015/05/21", }, ];
fd197e493f940bd8d253a74b5dd8fe1be6b893b3
[ "JavaScript" ]
3
JavaScript
RihabBerry/React-Movies
cc7eed2a786bc9e923de0e9f0ede9d19fc22407c
f798cd27e03407bcdfb56687a8539cf065a6078b
refs/heads/master
<file_sep>import React, { Component } from "react"; import ChatBox from "../components/ChatBox/ChatBox"; import {getFriendProfile} from "../actions/friendAction"; import {roomService} from "../services/roomService"; import {setRoomId, fetchMessageHistory} from "../actions/chatAction"; import "../styles/chatRoom.css"; import Navbar from "../components/Navbar/Navbar"; class ChatRoom extends Component { constructor(props){ super(props); let {token} = JSON.parse(localStorage.getItem("credentials")); let friendId = this.props.match.params.id; getFriendProfile(friendId); roomService.getRoomId({relatedUserId: friendId, accessToken: token }) .then(response => { let roomId = response.data._id; setRoomId(roomId); fetchMessageHistory(roomId); }) .catch(err=>{ console.log(err); }) } // componentWillUnmount(){ // setRoomId(""); // } render() { return ( <div> <Navbar history={this.props.history}/> <div className="chat-room"> <ChatBox {...this.props} /> </div> </div> ); } } export default ChatRoom;<file_sep>import {config} from "../constants/config"; const getRoomId = async ({relatedUserId, accessToken}) => { try { const response = await fetch(`${config.SERVER_API}/rooms/${relatedUserId}`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `${accessToken}` }, }); const json = await response.json(); return json; } catch(err){ console.log(err); } } export const roomService = { getRoomId };<file_sep> export const config = { // SERVER_API: "http://172.16.1.204:5000/api", // SERVER_CHAT: "http://172.16.1.204:5000", // SERVER_API: "http://192.168.1.14:5000/api", // SERVER_CHAT: "http://192.168.1.14:5000", // SERVER_API: "http://localhost:5000/api", // SERVER_CHAT: "http://localhost:5000", SERVER_API: "https://doyoulovemenodejs.herokuapp.com/api", SERVER_CHAT: "https://doyoulovemenodejs.herokuapp.com", GRAPH_API: "https://graph.facebook.com", LIMIT_REQUEST_USER: 8, LIMIT_REQUEST_MESSAGE: 20, }<file_sep>import React, { Component } from "react"; import "./navbarStyle.css"; import {connect} from "react-redux"; import {logout} from "../../actions/authenticationAction"; import FormSearch from "../FormSearch/FormSearch"; import {Link} from "react-router-dom"; class Navbar extends Component { constructor(props){ super(props); this.handleLogout = this.handleLogout.bind(this); } handleLogout(){ logout(); } render() { let {name, picture, status} = this.props.user; return ( <nav className="navbar navbar-expand-lg navbar-light bg-light"> <Link className="navbar-brand" to="/">Let's find friends...</Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse bg-light" id="navbarSupportedContent"> <FormSearch {...this.props} /> <ul className="navbar-nav ml-auto"> <li className="nav-item my-auto nav-item-profile"> <div className="nav-link wrap-name-status"> <Link className="nav-item-name" to="/profile/me" >{name}</Link> <span className="nav-item-status" >{status || "..."}</span> </div> </li> <li className="nav-item my-auto nav-item-profile"> <Link className="nav-link" to="/profile/me" > <img style={{ objectFit: "cover", height: "40px", width: "40px", borderRadius: "32rem"}} alt="" src={picture}/> </Link> </li> <li className="nav-item dropdown nav-item-dropdown"> <button className="nav-link dropdown-toggle btn btn-link btn-lg" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button> <div className="dropdown-menu" aria-labelledby="navbarDropdown"> <button onClick={this.handleLogout} className="dropdown-item">Logout</button> </div> </li> </ul> </div> </nav> ); } } Navbar.defaultProps = { user: {} } const mapStateToProps = state =>{ return { user: state.userReducer.user } } export default connect(mapStateToProps)(Navbar);<file_sep>import "./SearchList.css"; import React, { Component } from "react"; import PersonView from "../PersonView/PersonView"; import {connect} from "react-redux"; import LoadingIcon from "../LoadingIcon/LoadingIcon"; import ShowMore from "../ShowMore/ShowMore"; import {loadMore} from "../../actions/searchAction"; class SearchList extends Component { constructor(props){ super(props) this.handleLoadMore = this.handleLoadMore.bind(this); } handleLoadMore(){ loadMore(this.props.match.params.name, this.props.nextPage); } render() { let {data, searching, nextPage} = this.props; return ( <div className="search-list"> <div className="search-list-title"> <p>Search Result</p> </div> <div className="search-list-show"> { (!!data.length) ? data.map((element, key)=>{ return <PersonView history={this.props.history} key={key} {...element}/> }) : <p className="search-no-user">No user found out!</p> } { searching ? <LoadingIcon size="50px" /> : null } { (nextPage !== 0 && !searching) ? <ShowMore onClick={this.handleLoadMore} /> : null } </div> </div> ); } } SearchList.defaultProps = { data: [] } const mapStateToProps = state =>{ return { data: state.searchReducer.users, searching: state.searchReducer.searching, showMore: state.searchReducer.showMore, nextPage: state.searchReducer.nextPage } } export default connect(mapStateToProps)(SearchList);<file_sep>import React, {Component} from "react"; import PersonViewFull from "../components/PersonViewFull/PersonViewFull"; import Navbar from "../components/Navbar/Navbar"; class UserProfile extends Component { render(){ return ( <div> <Navbar history={this.props.history}/> <div className="container" style={{marginTop: "10px"}}> <PersonViewFull {...this.props}/> </div> </div> ); } } export default UserProfile;<file_sep>import "./viewPage.css"; import React, { Component } from "react"; import ViewList from "../ViewList/ViewList"; class ViewPage extends Component { render() { return ( <div className="container"> <ViewList {...this.props} listTitle="You may know" /> </div> ); } } export default ViewPage;<file_sep>/*global FB*/ import React, {Component} from "react"; import {loginSuccess} from "../../actions/authenticationAction"; import {userService} from "../../services/userService"; import "./facebookButtonStyle.css"; class FacebookButton extends Component { constructor(props){ super(props); this.state = { label: "Loading..." } this.redirectLoginSuccess = this.redirectLoginSuccess.bind(this); this.statusChangeCallback = this.statusChangeCallback.bind(this); this.handleLogin = this.handleLogin.bind(this); } redirectLoginSuccess(){ this.props.history.push(`/`); } statusChangeCallback(response) { if (response.status === "connected"){ let {userID, accessToken} = response.authResponse; loginSuccess({userID, accessToken}); this.redirectLoginSuccess(); } else { FB.login(async (responseInLogin) =>{ if (responseInLogin.status === "connected"){ let {userID, accessToken} = responseInLogin.authResponse; // let getUserResponse = await userService.getUserByFacebookId(responseInLogin.userID); // if (getUserResponse.error && getUserResponse.message === "user_not_exist") { // FB.api("/me", {fields: "name, about, email"}, (userApiCall)=>{ // userApiCall.facebookId = userApiCall.id; // delete userApiCall.id; // userService.createNewUser(userApiCall); // }) // } else { // console.log("Error when login facebook"); // } loginSuccess({userID, accessToken}); this.redirectLoginSuccess(); } }, {scope: 'email'}); } } componentDidMount(){ window.fbAsyncInit = function () { FB.init({ appId: '626713064376073', autoLogAppEvents: true, xfbml: true, version: 'v3.0' }); FB.getLoginStatus(response =>{ let label = ""; if (response.status === "connected"){ label = "Continue with facebook"; } else { label = "Login with facebook"; } this.setState({ label: label }); }) }.bind(this); (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.0&appId=626713064376073'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } handleLogin(){ FB.getLoginStatus(response =>{ this.statusChangeCallback(response); }) } render(){ return ( <button className="facebookButton" onClick={this.handleLogin}>{this.state.label}</button> ); } } export default FacebookButton;<file_sep> export const ACTION_TYPE_AUTH = { LOGIN_SUCCESS: "LOGIN_SUCCESS", LOGOUT_SUCCESS: "LOGOUT_SUCCESS", } export const ACTION_TYPE_USER = { GET_USER_PROFILE_SUCCESS: "GET_USER_PROFILE_SUCCESS", GET_USER_PROFILE_DOING: "GET_USER_PROFILE_DOING", GET_USER_PROFILE_FAILED: "GET_USER_PROFILE_FAILED", UPDATE_USER_PROFILE_SUCCESS: "UPDATE_USER_PROFILE_SUCCESS", UPDATE_USER_PROFILE_FAILED: "UPDATE_USER_PROFILE_FAILED", GET_ALL_USER_DOING: "GET_ALL_USER_DOING", GET_ALL_USER_SUCCESS: "GET_ALL_USER_SUCCESS", GET_ALL_USER_FAILED: "GET_ALL_USER_FAILED", LOAD_MORE_USER_SUCCESS: "LOAD_MORE_USER_SUCCESS" } export const ACTION_TYPE_CHAT = { ADD_MESSAGE_SUCCESS: "ADD_MESSAGE_SUCCESS", ADD_MESSAGE_FAILED: "ADD_MESSAGE_FAILED", SET_CURRENT_ROOMID: "SET_CURRENT_ROOMID", FETCH_MESSAGE_HISTORY_DOING: "FETCH_MESSAGE_HISTORY_DOING", FETCH_MESSAGE_HISTORY_SUCCESS: "FETCH_MESSAGE_HISTORY_SUCCESS", FETCH_MESSAGE_HISTORY_FAILED: "FETCH_MESSAGE_HISTORY_FAILED", FETCH_MESSAGE_HISTORY_MORE_SUCCESS: "FETCH_MESSAGE_HISTORY_MORE_SUCCESS" } export const ACTION_TYPE_FRIEND = { GET_FRIEND_PROFILE_DOING: "GET_FRIEND_PROFILE_DOING", GET_FRIEND_PROFILE_SUCCESS: "GET_FRIEND_PROFILE_SUCCESS" } export const ACTION_TYPE_SEARCH = { SEARCH_DOING: "SEARCH_DOING", SEARCH_SUCCESS: "SEARCH_SUCCESS", LOAD_MORE_SUCCESS: "LOAD_MORE_SUCCESS" } export const ACTION_TYPE_SOCKET = { MAP_SUCCESS: "MAP_SUCCESS" }<file_sep>import "./FormRegister.css"; import React, { PureComponent } from "react"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faExclamationTriangle } from "@fortawesome/free-solid-svg-icons"; import {authService} from "../../services/authService"; class FormRegister extends PureComponent { constructor(props) { super(props); this.state = { email: "", password: "", passwordConfirm: "", submiting: false, error: "" } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleValidate = this.handleValidate.bind(this); } handleChange(event) { let { name, value } = event.target; this.setState({ error: "", [name]: value }) } handleValidate(event){ event.preventDefault(); this.setState({ submiting: true }); let {email, password, passwordConfirm} = this.state; email = email.trim(); password = password.trim(); passwordConfirm = passwordConfirm.trim(); if (email && password){ if (password === passwordConfirm){ return true; } else { this.setState({ error: "Password and password confirm must be the same!", submiting: false }); event.target.passwordConfirm.focus(); } } else { if (!email) { this.setState({ error: "Username can't be space!", submiting: false }); event.target.email.focus(); } else if (!password) { this.setState({ error: "Password can't be space!", submiting: false }); event.target.password.focus(); } return false; } } async handleSubmit(event) { if (this.handleValidate(event)){ let {email, password} = this.state; const registerResponse = await authService.register({email, password}); if (!registerResponse.error){ this.props.history.push("/login"); } else { this.setState({ error: registerResponse.message, submiting: false }) } } } render() { return ( <div className="container wrap-form-register"> { this.state.error ? <div className="alert alert-danger" role="alert"> <FontAwesomeIcon icon={faExclamationTriangle} size="lg" style={{margin: "0px 10px"}} /> {this.state.error} </div> : <div className="alert alert-light"> ... </div> } <form className="form-register" onSubmit={this.handleSubmit}> <div className="form-register-title"> <span>Please provide username and password or <a href="/login">login</a></span> </div> <div className="form-group"> <label htmlFor="InputUsername">Email</label> <input type="email" className="form-control" id="InputUsername" maxLength="200" name="email" value={this.state.email} onChange={this.handleChange} placeholder="Enter email" required /> </div> <div className="form-group"> <label htmlFor="InputPassword">Password</label> <input type="password" className="form-control" id="InputPassword" maxLength="200" name="password" value={this.state.password} onChange={this.handleChange} placeholder="Enter password" required/> </div> <div className="form-group"> <label htmlFor="InputPasswordConfirm">Confirm Password</label> <input type="password" className="form-control" id="InputPasswordConfirm" maxLength="200" name="passwordConfirm" value={this.state.passwordConfirm} onChange={this.handleChange} placeholder="Enter password again" required/> </div> <button type="submit" disabled={this.state.submiting} className="btn btn-primary">Register</button> </form> </div> ); } } export default FormRegister;<file_sep>import {config} from "../constants/config"; const login = async ({email, password})=>{ const response = await fetch(`${config.SERVER_API}/login`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({email, password}) }); const json = await response.json(); return json; } const register = async ({email, password})=>{ const response = await fetch(`${config.SERVER_API}/register`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({email, password}) }); const json = await response.json(); return json; } export const authService = { login, register };<file_sep>import "./ShowUp.css"; import React from "react"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faArrowCircleUp } from "@fortawesome/free-solid-svg-icons"; const ShowUP = props =>{ return( <div className="show-up"> <button type="button" onClick={props.onClick}> <FontAwesomeIcon icon={faArrowCircleUp} size="lg" /> </button> </div> ); } export default ShowUP;<file_sep>import "./LoadingIcon.css"; import React from "react"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSpinner } from "@fortawesome/free-solid-svg-icons"; const LoadingIcon = (props)=>{ return( <div className="wrap-loading-icon"> <FontAwesomeIcon style={{fontSize: props.size}} className="spinner-icon" icon={faSpinner} size="lg" spin /> </div> ); } export default LoadingIcon; <file_sep>import {config} from "../constants/config"; const getMessagesByRoomId = async ({roomId, accessToken}) => { const response = await fetch(`${config.SERVER_API}/messages?roomId=${roomId}`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `${accessToken}` } }); const json = await response.json(); return json; } const addNewMessage = async ({roomId, sender, body}) => { const response = await fetch(`${config.SERVER_API}/messages`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({sender, roomId, body}) }); const json = await response.json(); return json; } export const messageService = { addNewMessage, getMessagesByRoomId };<file_sep>import {config} from "../constants/config"; const getUserById = async (userId) =>{ const response = await fetch(`${config.SERVER_API}/users/${userId}`, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }); const json = await response.json(); return json; } const getAllUser = async ({search="", page=0})=>{ let url = ""; if (!!search){ url = `${config.SERVER_API}/users?page=${page}&search=${search}`; } else { url = `${config.SERVER_API}/users?page=${page}`; } const response = await fetch(url, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }); const json = response.json(); return json; } const updateUser = async ({userId, user={}, accessToken})=>{ const response = await fetch(`${config.SERVER_API}/users/${userId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `${accessToken}` }, body: JSON.stringify(user) }); const json = await response.json(); return json; } export const userService = { getUserById, updateUser, getAllUser };<file_sep>import React, { Component } from 'react'; import Login from "./views/Login"; import {BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom'; import Home from './views/Home'; import PrivateRoute from "./helpers/PrivateRoute"; import UserProfile from "./views/UserProfile"; import {connect} from "react-redux"; import ChatRoom from "./views/ChatRoom"; import FriendProfile from './views/FriendProfile'; import Register from './views/Register'; import SearchPage from "./views/SearchPage"; class App extends Component { render() { const { loggedIn } = this.props; return ( <Router> <Switch> <Route exact path="/login" component={Login} /> <Route exact path="/register" component={Register} /> <PrivateRoute exact path="/profile/me" loggedIn={loggedIn} component={UserProfile} /> <PrivateRoute exact path="/profile/:id" loggedIn={loggedIn} component={FriendProfile} /> <PrivateRoute exact path="/chat/:id" loggedIn={loggedIn} component={ChatRoom} /> <PrivateRoute exact path="/search/:name" loggedIn={loggedIn} component={SearchPage} /> <PrivateRoute path="/" loggedIn={loggedIn} component={Home} /> <Redirect to="/" /> </Switch> </Router> ); } } const mapStateToProps = state => { return { loggedIn: state.userReducer.loggedIn } } export default connect(mapStateToProps)(App); <file_sep>import { store } from "../store/store"; import { ACTION_TYPE_FRIEND } from '../constants/actionType'; import { userService } from "../services/userService"; export const getFriendProfile = async (userId) => { store.dispatch({ type: ACTION_TYPE_FRIEND.GET_FRIEND_PROFILE_DOING }); const response = await userService.getUserById(userId); store.dispatch({ type: ACTION_TYPE_FRIEND.GET_FRIEND_PROFILE_SUCCESS, payload: response.data }); } <file_sep>import {store} from "../store/store"; import {ACTION_TYPE_AUTH} from '../constants/actionType'; export const logout = ()=> { localStorage.removeItem("credentials"); store.dispatch({ type: ACTION_TYPE_AUTH.LOGOUT_SUCCESS }); } export const loginSuccess = async (data)=> { localStorage.setItem("credentials", JSON.stringify(data)); store.dispatch({ type: ACTION_TYPE_AUTH.LOGIN_SUCCESS, payload: data.user }); }<file_sep>import React from "react"; import "./SendMessage.css"; import {Link} from "react-router-dom"; const SendMessage = (props) =>{ return ( <div className="container-send-message "> <Link to={`/profile/${props._id}`}><img className="send-picture" src={props.picture} alt="" /></Link> <p className="send-body">{props.body}</p> </div> ); } export default SendMessage;<file_sep>import {ACTION_TYPE_FRIEND} from '../constants/actionType'; const initialState = { friendProfile: {} } const friendReducer = (state = initialState, action = {}) => { switch (action.type) { case ACTION_TYPE_FRIEND.GET_FRIEND_PROFILE_DOING: return { ...state, friendProfile: { name: "...", about: "...", status: "...", birthday: "...", gender: "...", email: "...", picture: "https://scontent.fdad2-1.fna.fbcdn.net/v/t1.0-1/c47.0.160.160/p160x160/10354686_10150004552801856_220367501106153455_n.jpg?_nc_cat=0&oh=64e8f9fb1b3f0e70939b56f91adca78d&oe=5C0C2B49" } } case ACTION_TYPE_FRIEND.GET_FRIEND_PROFILE_SUCCESS: return { ...state, friendProfile: action.payload } default: return state; } } export default friendReducer;<file_sep>import React from "react"; import "./ReceiveMessage.css"; import {Link} from "react-router-dom"; const ReceiveMessage = (props) =>{ return ( <div className="container-receive-message"> <Link to={`/profile/${props._id}`}><img className="receive-picture" src={props.picture} alt="" /></Link> <p className="receive-body">{props.body}</p> </div> ); } export default ReceiveMessage;<file_sep>import React from "react"; import "./FriendInfo.css"; const FriendInfo = (props) => { let { name, status, gender, birthday, about, picture, _id } = props; let transferBirthday = ""; if (birthday) { let splitDate = birthday.split("T")[0].split("-"); transferBirthday = splitDate[2] + '/' + splitDate[1] + "/" + splitDate[0]; } return ( <div className="friendInfo"> <div className="friendInfo-wrap-info float-left"> <div className="friendInfo-heading"> <span className="">BASIC INFORMATION</span> <button onClick={()=>{props.history.push(`/chat/${_id}`)}} className="btn btn-outline-success btn-md btn-message" type="button">Message</button> </div> <div className="friendInfo-detail"> <span>Name</span><span className="detail-value">{name}</span> </div> <div className="friendInfo-detail"> <span>Status</span><span className="detail-value">{status}</span> </div> <div className="friendInfo-detail"> <span>Birthday</span><span className="detail-value">{transferBirthday}</span> </div> <div className="friendInfo-detail"> <span>Gender</span><span className="detail-value">{gender}</span> </div> <div className="friendInfo-detail"> <span>About</span><p className="detail-value">{about}</p> </div> </div> <div className="friendInfo-wrap-img"> <img className="img-thumbnail rounded float-right" src={picture} alt="" /> </div> </div> ) } export default FriendInfo;<file_sep>import { store } from "../store/store"; import { ACTION_TYPE_CHAT } from '../constants/actionType'; import { messageService } from "../services/messageService"; import {config} from "../constants/config"; // import io from 'socket.io-client'; // messageModel = { // body: "message", // sender: userId, // roomId: roomId // } // const createMySocketMiddleware = () => { // return store => { // let socket = io(`${config.SERVER_CHAT}`, { // path: "/api/chat", // query: `token=${JSON.parse(localStorage.getItem("credentials").token)}`, // transports: ['websocket'] // }); // socket.on("RECEIVE_MESSAGE", (messageModel) => { // store.dispatch({ // type : ACTION_TYPE_CHAT.ADD_MESSAGE_SUCCESS, // payload : messageModel // }); // }); // return next => action => { // if(action.type == "SEND_MESSAGE") { // socket.send(action.payload); // return; // } // if (action.type == "JOIN_ROOM"){ // socket.join(action.payload); // return; // } // return next(action); // } // } // } export const addMessage = async (messageModel) => { store.dispatch({ type: ACTION_TYPE_CHAT.ADD_MESSAGE_SUCCESS, payload: messageModel }); } export const setRoomId = async (roomId) => { store.dispatch({ type: ACTION_TYPE_CHAT.SET_CURRENT_ROOMID, payload: roomId }); } export const fetchMessageHistory = async (roomId) => { try { store.dispatch({ type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_DOING }); let {token} = JSON.parse(localStorage.getItem("credentials")); const response = await messageService.getMessagesByRoomId({roomId, accessToken: token}); if (!response.error){ store.dispatch({ type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_SUCCESS, nextPage: response.data.length >= config.LIMIT_REQUEST_MESSAGE ? 1 : 0, payload: response.data }); } else { store.dispatch({ type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_FAILED, error: response.message }); } }catch(err){ console.log(err); store.dispatch({ type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_FAILED }); } } // export const fetchMessageHistoryMore = async (roomId, page=0) => { // try { // store.dispatch({ // type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_DOING // }); // let {token} = JSON.parse(localStorage.getItem("credentials")); // const response = await messageService.getMessagesByRoomId({roomId, page, accessToken: token}); // if (!response.error){ // console.log("Fetch more success"); // console.log("nextPage: " + response.data.length >= config.LIMIT_REQUEST_MESSAGE ? ++page : 0); // store.dispatch({ // type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_MORE_SUCCESS, // nextPage: response.data.length >= config.LIMIT_REQUEST_MESSAGE ? ++page : 0, // payload: response.data // }); // } else { // console.log("Fetch more failed"); // store.dispatch({ // type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_FAILED, // error: response.message // }); // } // }catch(err){ // console.log(err); // store.dispatch({ // type: ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_FAILED // }); // } // } <file_sep>import {store} from "../store/store"; import {ACTION_TYPE_USER} from '../constants/actionType'; import {userService} from "../services/userService"; import {config} from "../constants/config"; export const getUserProfile = async ()=> { store.dispatch({ type: ACTION_TYPE_USER.GET_USER_PROFILE_DOING }); const credentials= JSON.parse((localStorage.getItem('credentials'))); try { let getResponse = await userService.getUserById(credentials.user._id); if (!getResponse.error) { store.dispatch({ type: ACTION_TYPE_USER.GET_USER_PROFILE_SUCCESS, payload: getResponse.data }); } store.dispatch({ type: ACTION_TYPE_USER.GET_USER_PROFILE_FAILED, }); } catch(err) { console.log(err); store.dispatch({ type: ACTION_TYPE_USER.GET_USER_PROFILE_FAILED }); } } export const updateProfile = async(newUser) =>{ try { let data = JSON.parse(localStorage.getItem("credentials")); const response = await userService.updateUser({userId: data.user._id, user: newUser, accessToken: data.token}); if (!response.error){ data.user = response.data; localStorage.setItem("credentials", JSON.stringify(data)); store.dispatch({ type: ACTION_TYPE_USER.UPDATE_USER_PROFILE_SUCCESS, payload: response.data }); }else if (response.message === "invalid_token"){ localStorage.setItem("credentials", JSON.stringify(data)); store.dispatch({ type: ACTION_TYPE_USER.TOKEN_EXPIRED }); }else { store.dispatch({ type: ACTION_TYPE_USER.UPDATE_USER_PROFILE_FAILED }); } } catch(err){ console.log(err); store.dispatch({ type: ACTION_TYPE_USER.UPDATE_USER_PROFILE_FAILED }); } } export const getAllUser = async(page=0) =>{ try { store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_DOING }); const response = await userService.getAllUser({page}); if (!response.error){ store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_SUCCESS, payload: response.data, nextPage: response.data.length >= config.LIMIT_REQUEST_USER ? ++page : 0 }); }else { store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_FAILED }); } } catch(err){ console.log(err); store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_FAILED }); } } export const loadMore = async(page=0) =>{ try { store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_DOING }); const response = await userService.getAllUser({page}); if (!response.error){ store.dispatch({ type: ACTION_TYPE_USER.LOAD_MORE_USER_SUCCESS, payload: response.data, nextPage: response.data.length >= config.LIMIT_REQUEST_USER ? ++page : 0 }); } else { store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_FAILED, payload: response.message }); } } catch(err){ console.log(err); store.dispatch({ type: ACTION_TYPE_USER.GET_ALL_USER_FAILED }); } }<file_sep>import {ACTION_TYPE_USER} from '../constants/actionType'; const initialState = { users: [], loading: false, nextPage: 0 } const allUserReducer = (state = initialState, action = {}) => { switch (action.type) { case ACTION_TYPE_USER.GET_ALL_USER_DOING: return { ...state, loading: true, nextPage: 0 } case ACTION_TYPE_USER.GET_ALL_USER_SUCCESS: // const userWithoutCurrentUser = action.payload.filter(user =>{ // return user._id !== credentials.user._id; // }); return { ...state, users: action.payload, nextPage: action.nextPage, loading: false } case ACTION_TYPE_USER.LOAD_MORE_USER_SUCCESS: // let currentUserId = JSON.parse(localStorage.getItem("credentials")).user._id; // const userWithoutCurrentUserLoadMore = action.payload.filter(user =>{ // return user._id !== currentUserId; // }); return { ...state, users: [...state.users, ...action.payload], nextPage: action.nextPage, loading: false } case ACTION_TYPE_USER.GET_ALL_USER_FAILED: return { ...state, loading: false } default: return state; } } export default allUserReducer;<file_sep>import {config} from "../constants/config"; const getUser = async ({userID, accessToken})=>{ const response = await fetch(`${config.GRAPH_API}/${userID}?fields=about,name, email,gender`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}` } }); const json = await response.json(); return json; } export const FacebookApi = { getUser };<file_sep>import "./personViewFull.css"; import React, {Component} from "react"; import FormEditUser from "../FormEditUser/FormEditUser"; import UserInfo from "../UserInfo/UserInfo"; import {connect} from "react-redux"; class PersonViewFull extends Component { constructor(props){ super(props); this.state = { editting: false } } render(){ if (this.props.error === "failed"){ alert("Fetching failed"); return null; } return ( <div className="person-view-full"> <div className="person-view-full-wrap-info float-left"> { this.state.editting ? <FormEditUser {...this.props.user} onClickSaveButton={()=> { this.setState({editting: false}); }} /> : <UserInfo {...this.props.user} onClickEditButton={() => this.setState({editting: true})}/> } </div> <div className="person-view-full-wrap-img"> <img className="img-thumbnail rounded float-right" src={this.props.user.picture} alt=""/> </div> </div> ); } } const mapStateToProps = state =>{ return { user: state.userReducer.user, error: state.userReducer.error } } export default connect(mapStateToProps)(PersonViewFull);<file_sep>import "./viewList.css"; import React, { Component } from "react"; import PersonView from "../PersonView/PersonView"; import {connect} from "react-redux"; import ShowMore from "../ShowMore/ShowMore"; import LoadingIcon from "../LoadingIcon/LoadingIcon"; import {loadMore} from "../../actions/userAction"; import {getAllUser} from "../../actions/userAction"; class ViewList extends Component { constructor(props){ super(props) this.handleLoadMore = this.handleLoadMore.bind(this); } componentDidMount(){ if (this.props.users.length < 1) { getAllUser(); } } handleLoadMore(){ loadMore(this.props.nextPage); } render() { let {users, listTitle, loading, nextPage} = this.props; const currentUserId = JSON.parse(localStorage.getItem("credentials")).user._id; return ( <div className="view-list"> <div className="view-list-title"> <p>{listTitle}</p> </div> <div className="view-list-show"> { (!!users.length) ? users.map((user, key)=>{ if (user._id !== currentUserId){ return <PersonView history={this.props.history} key={key} {...user}/> } return null; }) : (!loading ? <p className="view-list-no-user">No current users</p> : null) } { loading ? <LoadingIcon size="50px" /> : null } { (nextPage !== 0 && !loading) ? <ShowMore onClick={this.handleLoadMore} /> : null } </div> </div> ); } } ViewList.defaultProps = { users: [] } const mapStateToProps = state =>{ return { users: state.allUserReducer.users, loading: state.allUserReducer.loading, nextPage: state.allUserReducer.nextPage } } export default connect(mapStateToProps)(ViewList);<file_sep>import React, { Component } from "react"; import ViewPage from "../components/ViewPage/ViewPage"; import Navbar from "../components/Navbar/Navbar"; class Home extends Component { render() { return ( <div> <Navbar history={this.props.history}/> <ViewPage {...this.props} /> </div> ); } } export default Home;<file_sep>import "./FormSearch.css"; import React, {PureComponent} from "react"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import $ from 'jquery'; import { Link } from 'react-router-dom'; import LoadingIcon from "../LoadingIcon/LoadingIcon"; import {userService} from "../../services/userService"; import {search} from "../../actions/searchAction"; class FormSearch extends PureComponent{ constructor(props){ super(props); this.state = { search: "", searching: false, onClickSearchForm: false, searchedUsers: [] } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this.callSearch = search.bind(this); } componentDidMount () { $(window).on('click', this.handleBlur); } componentWillUnmount() { $(window).off('click', this.handleBlur); } handleChange = async (event)=>{ let search = event.target.value; this.setState({ search: search, searching: true }) if (!!search.trim()){ const response = await userService.getAllUser({search}); if (!response.error){ this.setState({ searchedUsers: response.data, searching: false }) } else { this.setState({ searchedUsers: [], searching: false }) } } else { this.setState({ searchedUsers: [], searching: false }) } } handleSubmit(event){ event.preventDefault(); this.setState({ onClickSearchForm: false }) let search = this.state.search; if (search.trim()){ this.callSearch(search); this.props.history.push(`/search/${search}`); } } handleFocus(e) { e.stopPropagation(); this.setState({ onClickSearchForm: true }) } handleBlur() { this.setState({ onClickSearchForm: false }) } render(){ let {searchedUsers, searching} = this.state; return ( <form className="form-inline position-relative my-2 my-lg-0" onSubmit={this.handleSubmit}> <div className="input-group" onClick={(e) => e.stopPropagation()}> <input className="form-control form-control-md my-2 my-sm-0 form-search-input" onFocus={this.handleFocus} autoComplete="off" aria-describedby="submit-button" name="search" value={this.state.search} onChange={this.handleChange} type="search" placeholder="Search" aria-label="Search" /> <div className="input-group-append"> <button className="btn btn-outline-secondary btn-md my-2 my-sm-0 form-search-button" id="submit-button" type="submit"> <FontAwesomeIcon icon={faSearch} size="lg" /> </button> </div> </div> { this.state.onClickSearchForm && <div className="list-search-item mt-5" onClick={(e) => {e.stopPropagation()}}> { searchedUsers.map((user) => { return <Link className="search-item" key={user._id} to={`/profile/${user._id}`} >{user.name}</Link> }) } { searching ? <LoadingIcon /> : null } </div> } </form> ); } } export default FormSearch;<file_sep>import {config} from "../constants/config"; const makeFriend = async ({relatingUserId, relatedUserId}) => { const response = await fetch(`${config.SERVER_API}/friends`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ relatingUserId, relatedUserId }) }); const json = await response.json(); return json; } const getFriendId = async ({relatingUserId, relatedUserId}) => { const response = await fetch(`${config.SERVER_API}/friends/getFriendId`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ relatingUserId, relatedUserId }) }); const json = await response.json(); return json; } export const friendService = { makeFriend };<file_sep>import {ACTION_TYPE_AUTH} from '../constants/actionType'; const user = JSON.parse(localStorage.getItem("user")); const initialState = user ? {loggedIn: true, user} : {} const authenticationReducer = (state = initialState, action = {}) => { switch (action.type) { case ACTION_TYPE_AUTH.LOGIN_SUCCESS: return { ...state, user: action.payload, loggedIn: true } case ACTION_TYPE_AUTH.LOGOUT_SUCCESS: return { ...state, user: {}, loggedIn: false } default: return state; } } export default authenticationReducer;<file_sep>import {ACTION_TYPE_CHAT} from "../constants/actionType"; const initialState = { roomId: '', messageModels: [], loading: false, error: "" } const chatReducer = (state = initialState, action = {})=>{ switch(action.type){ case ACTION_TYPE_CHAT.ADD_MESSAGE_SUCCESS: return { ...state, messageModels: [...state.messageModels, action.payload] } case ACTION_TYPE_CHAT.ADD_MESSAGE_FAILED: return { ...state } case ACTION_TYPE_CHAT.SET_CURRENT_ROOMID: return { ...state, roomId: action.payload } case ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_SUCCESS: return { ...state, loading: false, messageModels: action.payload.reverse() } case ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_DOING: return { ...state, loading: true, } // case ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_MORE_SUCCESS: // return { // ...state, // nextPage: action.nextPage, // loading: false, // messageModels: [...action.payload.reverse(), ...state.messageModels] // } case ACTION_TYPE_CHAT.FETCH_MESSAGE_HISTORY_FAILED: return { ...state, error: action.payload, loading: false } default: return state; } } export default chatReducer;<file_sep>import React, { Component } from "react"; import FriendInfo from "../components/FriendInfo/FriendInfo"; import {connect} from "react-redux"; import {getFriendProfile} from "../actions/friendAction"; import Navbar from "../components/Navbar/Navbar"; class FriendProfile extends Component { componentDidMount(){ getFriendProfile(this.props.match.params.id); } render() { return ( <div> <Navbar history={this.props.history}/> <div className="container" style={{ marginTop: "10px" }}> <FriendInfo {...this.props.friendProfile} history={this.props.history} /> </div> </div> ); } } const mapStateToProps = state =>{ return { friendProfile: state.friendReducer.friendProfile } } export default connect(mapStateToProps)(FriendProfile);
4214307ced65dbd4b1c275dafb03718fedd304f9
[ "JavaScript" ]
34
JavaScript
tranphuochiep1997/do-you-love-me
5ba370668f099e2db96e37d70fb98faf5fc1896e
d54321a3e90d71ceaa4726e543c2f20e05d17e4c
refs/heads/master
<repo_name>amitchhajer/shifu<file_sep>/src/Sequoia/HackBundle/Controller/ImagemenuController.php <?php namespace Sequoia\HackBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use FOS\RestBundle\View\View; use FOS\Rest\Util\Codes; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use TesseractOCR; use Buzz\Browser; class ImagemenuController extends Controller { public function getImagemenuAction() { $nAppId = '2de08922'; $nAppKey = '93a079beaedf21003f55b902a4724df0'; $request = $this->getRequest(); $mm = $request->get('mm'); $buzz = $this->get('buzz'); $kk = $request->get('kk'); $imageUrl = $request->get('image_url'); $ph = $request->get('ph'); $cache = $this->get('beryllium_cache'); if ($imageUrl) { $imageContents = file_get_contents($imageUrl); $path = '/tmp/'.time().'.jpg'; file_put_contents($path, $imageContents); } else { $path = 'moscow.jpg'; } $tesseract = new TesseractOCR($path); $tesseract->setTempDir('/tmp'); //$tesseract->setWhitelist(range('A','Z'), range('a','z')); $data = strtolower($tesseract->recognize()); $blackListedKeys = array( 'just', 'starts', 'starters', 'vegetarian' ); $breakKeys = array( ']', '[', '/', '\\' ); //str_replace($breakKeys, '' , $data); if ($mm == 1) { $data = $data . ' 200'. ' pork chops'. ' 234'; } $words = preg_split('/[\s]+/', $data, -1, PREG_SPLIT_NO_EMPTY); $items = array(); $combinedWord = null; //what all fields to get if ($ph == 1) { $words = array('Chilli Pork','425','Fish Chilli','200','Chicken Tikka','450','Buffalo Wings','100','Chicken Burger','100','French Fries','200' ); } $fields = 'nf_ingredient_statement,nf_calories,nf_total_fat,nf_serving_weight_grams'; if ($kk == 1) { $words = array('chatpate tandoor aloo', '200','pudhina paneer tikka','300','dal bukhara', '400','jhinga do pyaza', '600','paneer khurchan','200','subz pulao','300' );} $id = 0; foreach ($words as $word) { if (!in_array($word, $blackListedKeys)) { if (intval($word)) { $combinedWord = trim($combinedWord); $items[$id]['id'] = $id; $items[$id]['name'] = $combinedWord; $combinedWord = urlencode($combinedWord); $nutritionUrls[] = "https://api.nutritionix.com/v1_1/search/$combinedWord?results=0:1&fields=item_name,nf_ingredient_statement,nf_calories,nf_total_fat,nf_serving_weight_grams&appId=$nAppId&appKey=$nAppKey"; $googleUrls[] = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=$combinedWord&imgsz=large"; $combinedWord = null; $id = $id + 1; continue; } else { $combinedWord .= ' '.$word; } } } $data = 0; if ($mm == 1 && $data = $cache->get('googleData:mm')) { $googleData = $data; $nutritionData = $cache->get('nutritionData:mm'); } else if ($mm == 1) { $googleData = $this->multiCurl($googleUrls); $nutritionData = $this->multiCurl($nutritionUrls); $cache->set("googleData:mm", $googleData, 3600*5); //5hour ttl $cache->set("nutritionData:mm", $nutritionData, 3600*5); //5hour ttl } if ($kk == 1 && $data = $cache->get('googleData:kk')) { $googleData = $data; $nutritionData = $cache->get('nutritionData:kk'); } else if ($kk==1){ $googleData = $this->multiCurl($googleUrls); $nutritionData = $this->multiCurl($nutritionUrls); $cache->set("googleData:kk", $googleData, 3600*5); //5hour ttl $cache->set("nutritionData:kk", $nutritionData, 3600*5); //5hour ttl } if ($ph == 1 && $data = $cache->get('googleData:ph')) { $googleData = $data; $nutritionData = $cache->get('nutritionData:ph'); } else if ($ph == 1) { $googleData = $this->multiCurl($googleUrls); $nutritionData = $this->multiCurl($nutritionUrls); $cache->set("googleData:ph", $googleData, 3600*5); //5hour ttl $cache->set("nutritionData:ph", $nutritionData, 3600*5); //5hour ttl } if (!$mm and !$kk and !$ph) { $googleData = $this->multiCurl($googleUrls); $nutritionData = $this->multiCurl($nutritionUrls); } $id = 0; foreach ($googleData as $googleDatum) { if ($googleDatum) { $result = json_decode($googleDatum[0], true); $results = $result['responseData']['results']; $i = 0; foreach ($results as $result) { $items[$id]['image_urls'][] = $result['url']; $i = $i + 1; if ($i >= 4) { break; } } } $id = $id + 1; } $id = 0; foreach ($nutritionData as $nutritionDatum) { if ($nutritionDatum) { $result = json_decode($nutritionDatum[0],true); $fields = $result['hits'][0]['fields']; $items[$id]['item_name'] = $fields['item_name']; $items[$id]['ingredients'] = $fields['nf_ingredient_statement']; $items[$id]['calories'] = $fields['nf_calories']; $items[$id]['fat'] = $fields['nf_total_fat']; $items[$id]['serving_weight_grams'] = $fields['nf_serving_weight_grams']; } $id = $id + 1; } return View::create(array_values($items)); } /** * Takes array of URL's */ protected function multiCurl($urls) { $nodes = $urls; $nodeCount = count($nodes); $curlArr = array(); $master = curl_multi_init(); for($i = 0; $i < $nodeCount; $i++) { $url = $nodes[$i]; $curlArr[$i] = curl_init($url); curl_setopt($curlArr[$i], CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($master, $curlArr[$i]); } do { curl_multi_exec($master,$running); } while($running > 0); for($i = 0; $i < $nodeCount; $i++) { $results[$i][] = curl_multi_getcontent($curlArr[$i]); } return $results; } }
5961cf74a82e587954c4a73dcae42521da4fca0b
[ "PHP" ]
1
PHP
amitchhajer/shifu
fae400ec63c6c2639ae34bceca99e48a2a695bee
1e9050c5f74f1a35277ec70b0263afa4316f085b
refs/heads/master
<repo_name>zzs-web/proxy<file_sep>/README.md # ZhangZisu.CN Proxy Services ![Netlify](https://img.shields.io/netlify/4d380063-9f4b-4a33-8092-df8026fa7570?logo=netlify&style=flat-square)<file_sep>/src/shims-define.d.ts declare let GIT_HASH: string declare let GIT_BRANCH: string declare let BUILD_DATE: string declare let GA_ID: string
e6cc29aa821430584dc423c342a78ec3fbeb3eff
[ "Markdown", "TypeScript" ]
2
Markdown
zzs-web/proxy
68b7c39116564bad79b47361af84c9d94073c6d1
9cc213b511b3867252d4eda6c02a7595bb93db3d
refs/heads/master
<repo_name>Gaurav94506/SpringBoot<file_sep>/src/test/java/com/citiustech/contact/controller/ViewControllerTest.java package com.citiustech.contact.controller; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.citiustech.contact.repository.AddressRepository; import com.citiustech.contact.repository.EmployeeRepository; import com.citiustech.contact.service.EmployeeService; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; public class ViewControllerTest { @Autowired private MockMvc mockMvc; @InjectMocks private ViewController emc; @Before public void setup() { MockitoAnnotations.initMocks(this); mockMvc=MockMvcBuilders.standaloneSetup(emc).build(); } @Test public void welcome() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")); } } <file_sep>/src/main/java/com/citiustech/contact/model/Address.java package com.citiustech.contact.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; 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; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="Address") @EntityListeners(AuditingEntityListener.class) @XmlRootElement public class Address { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @NotNull private String state; public Address() { } public Address(Long id, String state, int pincode) { this.id = id; this.state = state; this.pincode = pincode; } private int pincode; @OneToOne(mappedBy="adr") private Employee employee; @JsonIgnore public Employee getEmp() { return employee; } public void setEmp(Employee emp) { this.employee = emp; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getPincode() { return pincode; } public void setPincode(int pincode) { this.pincode = pincode; } } /* commented on 19-9-2018 package com.citiustech.contact.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; 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; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="Address") @EntityListeners(AuditingEntityListener.class) public class Address { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @NotNull private String state; private int pincode; @OneToOne(mappedBy="adr") private Employee employee; public Address() { } public Address(Long id, String state, int pincode) { this.id = id; this.state = state; this.pincode = pincode; } public Address(Long id, String state, int pincode, Long empid) { super(); this.id = id; this.state = state; this.pincode = pincode; this.employee = new Employee(empid,"","",""); } @JsonIgnore public Employee getEmp() { return employee; } public void setEmp(Employee emp) { this.employee = emp; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getPincode() { return pincode; } public void setPincode(int pincode) { this.pincode = pincode; } } */ <file_sep>/src/main/java/com/citiustech/contact/model/Employee.java package com.citiustech.contact.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Entity @Table(name="Employees") @EntityListeners(AuditingEntityListener.class) @XmlRootElement public class Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; public Employee(Long id, String name, String designation, String expertise) { super(); this.id = id; this.name = name; this.designation = designation; this.expertise = expertise; this.adr=adr; } @OneToOne(cascade=CascadeType.ALL) private Address adr; public Address getAdr() { return adr; } public void setAdr(Address adr) { this.adr = adr; } @NotBlank private String name; @NotBlank private String designation; public Employee() { } public Employee(Long id, Address adr, String name, String designation, String expertise) { super(); this.id = id; this.adr = adr; this.name = name; this.designation = designation; this.expertise = expertise; } @NotBlank private String expertise; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getExpertise() { return expertise; } public void setExpertise(String expertise) { this.expertise = expertise; } } /* package com.citiustech.contact.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Entity @Table(name="Employees") @EntityListeners(AuditingEntityListener.class) public class Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; public Employee(Long id, String name, String designation, String expertise) { super(); this.id = id; this.name = name; this.designation = designation; this.expertise = expertise; } @OneToOne(cascade=CascadeType.ALL) private Address adr; public Address getAdr() { return adr; } public void setAdr(Address adr) { this.adr = adr; } @NotBlank private String name; @NotBlank private String designation; public Employee() { } public Employee(Long id, Address adr, String name, String designation, String expertise) { super(); this.id = id; this.adr = adr; this.name = name; this.designation = designation; this.expertise = expertise; } @NotBlank private String expertise; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getExpertise() { return expertise; } public void setExpertise(String expertise) { this.expertise = expertise; } } */ <file_sep>/src/main/java/com/citiustech/contact/repository/AddressRepository.java package com.citiustech.contact.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository.*; import com.citiustech.contact.model.Address; import com.citiustech.contact.model.Employee; @Repository public interface AddressRepository extends JpaRepository<Address, Long> { public Address findByEmployeeId(Long employeeID); /*PagingAndSortingRepository<Employee, Long> repository // … get access to a bean Page<Employee> users= repository.findAll(new PageRequest(1, 20));*/ } /* package com.citiustech.contact.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.citiustech.contact.model.Address; import com.citiustech.contact.model.Employee; @Repository public interface AddressRepository extends JpaRepository<Address, Long> { public List<Address> findByEmployeeId(Long employeeID); } */
800f07cb80f198da888ca12be7c95e8d005ea03e
[ "Java" ]
4
Java
Gaurav94506/SpringBoot
3eeabe1233855880cdf6254f4b7b80d5db41cb1b
ccd82a9d020c180a9b44ed90e08616360c2242bb
refs/heads/master
<repo_name>dragon6776/angular_mvc<file_sep>/angular_mvc/Controllers/API/CategoriesController.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.ModelBinding; using System.Web.Http.OData; using System.Web.Http.OData.Routing; using angular_mvc.Models; namespace angular_mvc.Controllers.API { /* The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive. using System.Web.Http.OData.Builder; using System.Web.Http.OData.Extensions; using angular_mvc.Models; ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Categories>("Categories"); builder.EntitySet<Products>("Products"); config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel()); */ public class CategoriesController : ODataController { private NorthWindContext db = new NorthWindContext(); // GET: odata/Categories [EnableQuery] public IQueryable<Categories> GetCategories() { return db.Categories; } // GET: odata/Categories(5) [EnableQuery] public SingleResult<Categories> GetCategories([FromODataUri] int key) { return SingleResult.Create(db.Categories.Where(categories => categories.CategoryID == key)); } // PUT: odata/Categories(5) public IHttpActionResult Put([FromODataUri] int key, Delta<Categories> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Categories categories = db.Categories.Find(key); if (categories == null) { return NotFound(); } patch.Put(categories); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CategoriesExists(key)) { return NotFound(); } else { throw; } } return Updated(categories); } // POST: odata/Categories public IHttpActionResult Post(Categories categories) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Categories.Add(categories); db.SaveChanges(); return Created(categories); } // PATCH: odata/Categories(5) [AcceptVerbs("PATCH", "MERGE")] public IHttpActionResult Patch([FromODataUri] int key, Delta<Categories> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Categories categories = db.Categories.Find(key); if (categories == null) { return NotFound(); } patch.Patch(categories); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CategoriesExists(key)) { return NotFound(); } else { throw; } } return Updated(categories); } // DELETE: odata/Categories(5) public IHttpActionResult Delete([FromODataUri] int key) { Categories categories = db.Categories.Find(key); if (categories == null) { return NotFound(); } db.Categories.Remove(categories); db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } // GET: odata/Categories(5)/Products [EnableQuery] public IQueryable<Products> GetProducts([FromODataUri] int key) { return db.Categories.Where(m => m.CategoryID == key).SelectMany(m => m.Products); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CategoriesExists(int key) { return db.Categories.Count(e => e.CategoryID == key) > 0; } } } <file_sep>/angular_mvc/Scripts/services.js myApp.factory('productService', ['$resource', function($resource){ // return $resource('/odata/Products/:', {}, { // query: { // method: 'GET', // //params:{ ProductId: '' }, // isArray: true // } // }); return $resource('/odata/Products', function(data){ debugger; }); }]);
fbe33e0ecfabb25d83a5924d7d8d566282a3848c
[ "JavaScript", "C#" ]
2
C#
dragon6776/angular_mvc
d57379fd8b987c747aa5ee50f9a04e71d49baaea
48986e45820cac4c610f9e77f4f7ddffd6eb7eb7
refs/heads/master
<file_sep>\name{addDays} \alias{addDays} \title{add days} \usage{ addDays(dt, days) } \arguments{ \item{dt}{a Date or timeDate object} \item{days}{to be added} } \value{ a Date or timeDate object } \description{ add days to timeDate or Date objects } \examples{ d1 <- myDate('23-10-2010') d2 <- addDays(d1, 1) } <file_sep>\name{SimpleSensitivity} \alias{SimpleSensitivity} \title{Bond sensitivity} \usage{ SimpleSensitivity(coupon, n, yield) } \arguments{ \item{coupon}{(real) coupon rate (.05: 5\%)} \item{n}{(integer) number of years to expiry} \item{yield}{(real) yield to maturity} } \value{ derivative of price with respect to yield } \description{ Simplified bond sensitivity calculation } \details{ Bond sensitivity with respect to yield, ie. \deqn{ s = -\frac{frac{\partial P}{\partial y}}{P} } } \examples{ s <- SimpleSensitivity(.05, 10, .05) } <file_sep>\name{SimpleDuration} \alias{SimpleDuration} \title{Bond duration} \usage{ SimpleDuration(coupon, n, yield) } \arguments{ \item{coupon}{(real) coupon rate (.05: 5\%)} \item{n}{(integer) number of years to expiry} \item{yield}{(real) yield to maturity} } \value{ derivative of price with respect to yield } \description{ Simplified bond duration calculation } \details{ Modified duration of a bond price. It is the weighted maturity, where the weights are the present value of the cash flow paid at each date. Let \eqn{F_i} be the cash flow paid at time \eqn{i}. Duration is defined as \deqn{ d = \sum_{i=1}^n \frac{F_i (1+y)^{-i}}{P}} } \examples{ d <- SimpleDuration(.05, 10, .05) } <file_sep>\name{print.xb} \alias{print.xb} \title{Table pretty printer} \usage{ print.xb(xtab, ...) } \arguments{ \item{xtab}{a table} } \description{ Table pretty printer } <file_sep>\name{BondYield2Price} \alias{BondYield2Price} \title{Bond price from yield} \usage{ BondYield2Price(bond, dtSettlement, yield) } \arguments{ \item{bond}{data structure generated by \code{Bond}} \item{dtSettlement}{settlement date} \item{yield}{bond yield} } \value{ dirty price } \description{ This function computes the bond (dirty) price, given its yield, by the formula \deqn{ P = \sum_{i=1}^n F_i (1+y)^{-\frac{d_i - d_0}{365}} } with: \describe{ \item{\eqn{F_i}}{Cash flow paid at date \eqn{d_i}} \item{\eqn{d_i}}{Cash flow date, measured in days} \item{\eqn{d_0}}{settlement date} } } \examples{ b374 <- Bond('374', myDate('01/01/2000'), myDate('04/01/2019'), .0375, 100, 'a') p <- BondYield2Price(b374, myDate('03/01/2012'), yield=.04) } <file_sep>\name{myDate} \alias{myDate} \title{Date constructor} \usage{ myDate(dt) } \arguments{ \item{dt}{(string) a date. Legal formats: \describe{ \item{\code{ddmmmYYYY}}{ex: 23jun2010} \item{\code{dd-mm-YYYY}}{ex: 23-12-2010} \item{\code{dd/mm/YYYY}}{ex: 23/12/2010} \item{\code{YYYY/mm/dd}}{ex: 2010/12/23} \item{\code{dd.mm.YYYY}}{ex: 23.12.2010} }} } \value{ a Date object } \description{ Date creation } \details{ A shortcut for date creation, locale independent validates day and month ranges } \examples{ d1 <- myDate('30-10-2010') d2 <- myDate('30/10/2010') d3 <- myDate('30.10.2010') d4 <- myDate('30oct2010') (d1 == d2) & (d1 == d3) & (d1 == d4) } <file_sep>\name{tDiff} \alias{tDiff} \title{time difference} \usage{ tDiff(dtFirst, dtLast) } \arguments{ \item{dtFirst}{a date or timeDate} \item{dtLast}{a date or timeDate} } \value{ the time difference in year fraction } \description{ time difference in fraction of years, given 2 timeDate or Date objects } <file_sep>\name{Bond} \alias{Bond} \title{Bond cash flow generator} \usage{ Bond(id, dtIssue, dtMaturity, couponRate, nominal, frequency) } \arguments{ \item{id}{(string) the identifier of the bond} \item{dtIssue}{(date) bond issue date} \item{dtMaturity}{(date) bond maturity date} \item{couponRate}{(real) coupon rate, in decimal form} \item{nominal}{(real) nominal amount} \item{frequency}{(string) 'A' for annual, 'S' for semi-annual.} } \value{ a list with the following elements: \describe{ \item{id}{the bond identifier} \item{cf}{vector of cash flows} \item{dt}{vector of payment dates for each cash flow} \item{freq}{frequency ("a" or "s")} \item{coupon}{coupon rate} \item{nominal}{nominal amount} } } \description{ Bond Definition } \details{ This function constructs a data structure that describes the cash flow schedule of a bond. } \examples{ b374 <- Bond('374', myDate('01/01/2000'), myDate('04/01/2019'), .0375, 100, 'a') } <file_sep>##' Trinomial model ##' ##' Trinomial model for pricing European or American vanilla options. ##' @title Trinomial tree model ##' @param TypeFlag the option type: ##' \describe{ ##' \item{\code{ce}}{European call} ##' \item{\code{pe}}{European put} ##' \item{\code{ca}}{American call} ##' \item{\code{pa}}{American put} ##' } ##' @param S price of underlying asset ##' @param X strike ##' @param Time time to expiry ##' @param r risk-free interest rate ##' @param b cost of carry ##' @param sigma annualized volatility ##' @param n number of steps in tree ##' @return a data structure with the following elements: ##' \describe{ ##' \item{\code{param}}{list of input parameters} ##' \item{\code{price}}{price} ##' \item{\code{delta}}{delta} ##' \item{\code{gamma}}{gamma} ##' } ##' @examples ##' res <- CRRTrinomial(TypeFlag="ce", S=100, X=100, Time=1, r=.03, ##' b=.03, sigma=.3, n=100) ##' @export CRRTrinomial <- function (TypeFlag = c("ce", "pe", "ca", "pa"), S, X, Time, r, b, sigma, n) { TypeFlag = TypeFlag[1] z = NA if (TypeFlag == "ce" || TypeFlag == "ca") z = +1 if (TypeFlag == "pe" || TypeFlag == "pa") z = -1 if (is.na(z)) stop("TypeFlag misspecified: ce|ca|pe|pa") dt = Time/n u = exp(sigma * sqrt(2*dt)) d = 1/u dd <- exp(-sigma*sqrt(dt/2)) pu = ((exp(b * dt/2) - dd)/(1/dd - dd))^2 pd = (1-sqrt(pu))^2 pm <- 1-pu-pd Df = exp(-r * dt) # add 1 steps to tree n <- n+1 # exponent iExp <- (1:(2*(n+1)-1))-(n+1) OptionValue = z * (S * u^iExp - X) OptionValue = (abs(OptionValue) + OptionValue)/2 if (TypeFlag == "ce" || TypeFlag == "pe") { for (j in seq(from = (n), to = 2, by = -1)) for (i in 1:(2*j-1)) OptionValue[i] = (pu*OptionValue[i+2] + pm*OptionValue[i+1] + pd*OptionValue[i]) * Df } if (TypeFlag == "ca" || TypeFlag == "pa") { for (j in seq(from = (n), to = 2, by = -1)) for (i in 1:(2*j-1)) { SS = S * d^(j-1) * u^(i-1) exVal = z * (SS - X) OptionValue[i] = (pu*OptionValue[i + 2] + pm*OptionValue[i+1] + pd*OptionValue[i]) * Df OptionValue[i] = max(exVal, OptionValue[i]) } } # the middle node is the price Sup <- S*u Sdown <- S*d # delta by central difference delta <- (OptionValue[3] - OptionValue[1])/(Sup-Sdown) du <- (OptionValue[3] - OptionValue[2])/(Sup-S) dd <- (OptionValue[2] - OptionValue[1])/(S-Sdown) gamma <- (du-dd)/((Sup-Sdown)/2) param = llist(TypeFlag, S, X, Time, r, b, sigma, n) llist(param, price=OptionValue[2], delta, gamma) } ##' Cox-Ross-Rubinstein binomial model with payoff function ##' ##' @title Cox-Ross-Rubinstein binomial model with payoff function ##' ##' @param TypeFlag e:European exercise, a: American ##' @param PayOff PayOff function: f(underlying value) ##' @param S Spot ##' @param Time Time to maturity ##' @param r interest rate ##' @param b cost of carry ##' @param sigma volatility ##' @param n number of time steps ##' @return PV of option ##' @export CRRWithPayOff <- function (TypeFlag = c("e", "a"), PayOff, S, Time, r, b, sigma, n) { TypeFlag = TypeFlag[1] dt = Time/n u = exp(sigma * sqrt(dt)) d = 1/u p = (exp(b * dt) - d)/(u - d) Df = exp(-r * dt) # underlying asset at step N-1 ST <- S*(d^(n-1))*cumprod(c(1, rep((u/d), n-1))) # at step (n-1), value an European option of maturity dt BSTypeFlag <- substr(TypeFlag,1,1) OptionValue <- PayOff(ST) if (TypeFlag == "e") { for (j in seq(from = n - 2, to = 0, by = -1)) OptionValue <- (p*OptionValue[2:(j+2)] + (1-p)*OptionValue[1:(j+1)])*Df } if (TypeFlag == "a") { for (j in seq(from = n - 2, to = 0, by = -1)) { ContValue <- (p*OptionValue[2:(j+2)] + (1-p)*OptionValue[1:(j+1)])*Df ST <- S*(d^j)*cumprod(c(1, rep((u/d), j))) OptionValue <- sapply(1:(j+1), function(i) max(PayOff(ST[i]), ContValue[i])) } } OptionValue[1] } ##' Trinomial tree plot ##' ##' @title Trinomial tree plot ##' ##' @param TrinomialTreeValues tree values grid ##' @param dx step ##' @param digits format ##' @export TrinomialTreePlot <- function (TrinomialTreeValues, dx = -0.025, dy = 0.4, cex = 1, digits = 2, ...) { # draw 3 branches originating at node (x,y) drawLines <- function(x,y,col=2) { xx = c(x,x+1) for(k in -1:1) { yy = c(y, y+k) lines(x=xx,y=yy,col=col) } } Tree = round(TrinomialTreeValues, digits = digits) depth = ncol(Tree) # frame and coordinates: plot(x = c(1, depth), y = c(-depth+1, depth-1), type = "n", col = 0, yaxt='n', xaxt='n', xlab='step', ylab='', ...) axis(1,at=1:depth) # tree root points(x = 1, y = 0) drawLines(1,0) text(1 + dx, 0 + dy, deparse(Tree[1, 1]), cex = cex) for (i in 1:(depth - 1)) { y = seq(from = i, by = -1, length = 2*i + 1) x = rep(i, times = length(y)) + 1 points(x, y, col = 1) # place text for (j in 1:length(x)) text(x[j] + dx, y[j] + dy, deparse(Tree[j, i + 1]), cex = cex) if(i<(depth-1)) { for (k in 1:length(x)) drawLines(x[k], y[k]) } } invisible() } <file_sep>\name{CRRTrinomial} \alias{CRRTrinomial} \title{Trinomial tree model} \usage{ CRRTrinomial(TypeFlag = c("ce", "pe", "ca", "pa"), S, X, Time, r, b, sigma, n) } \arguments{ \item{TypeFlag}{the option type: \describe{ \item{\code{ce}}{European call} \item{\code{pe}}{European put} \item{\code{ca}}{American call} \item{\code{pa}}{American put} }} \item{S}{price of underlying asset} \item{X}{strike} \item{Time}{time to expiry} \item{r}{risk-free interest rate} \item{b}{cost of carry} \item{sigma}{annualized volatility} \item{n}{number of steps in tree} } \value{ a data structure with the following elements: \describe{ \item{\code{param}}{list of input parameters} \item{\code{price}}{price} \item{\code{delta}}{delta} \item{\code{gamma}}{gamma} } } \description{ Trinomial model } \details{ Trinomial model for pricing European or American vanilla options. } \examples{ res <- CRRTrinomial(TypeFlag="ce", S=100, X=100, Time=1, r=.03, b=.03, sigma=.3, n=100) } <file_sep>\name{BondAC} \alias{BondAC} \title{Bond accrued interest} \usage{ BondAC(bond, dtSettlement) } \arguments{ \item{bond}{data structure generated by \code{Bond}} \item{dtSettlement}{settlement date} } \value{ the accrued interest } \description{ This function computes the accrued interest on a bond by the formula \deqn{ ac = c N \frac{m}{365} } } \details{ with \describe{ \item{\eqn{c}}{coupon rate} \item{\eqn{N}}{nominal amount} \item{\eqn{m}}{actual number of days since last coupon payment} } } \examples{ b374 <- Bond('374', myDate('01/01/2000'), myDate('04/01/2019'), .0375, 100, 'a') a <- BondAC(b374, myDate('03/01/2012')) } <file_sep>\name{SimpleVariation} \alias{SimpleVariation} \title{Bond variation} \usage{ SimpleVariation(coupon, n, yield) } \arguments{ \item{coupon}{(real) coupon rate (.05: 5\%)} \item{n}{(integer) number of years to expiry} \item{yield}{(real) yield to maturity} } \value{ derivative of price with respect to yield } \description{ Simplified bond variation calculation } \details{ Derivative of bond price with respect to yield \deqn{ v = \frac{\partial P}{\partial y}} } \examples{ p <- SimpleVariation(.05, 10, .05) } <file_sep>\name{mytDate} \alias{mytDate} \title{dateTime constructor} \usage{ mytDate(dt) } \arguments{ \item{dt}{(string) a date. Legal formats: \describe{ \item{ddmmmYYYY}{ex: 23jun2010} \item{dd-mm-YYYY}{ex: 23-12-2010} \item{dd/mm/YYYY}{ex: 23/12/2010} \item{dd.mm.YYYY}{ex: 23.12.2010} }} } \value{ a timeDate object } \description{ timeDate creation } \details{ A shortcut for date creation, locale independent validates day and month ranges } \examples{ d1 <- mytDate('30-10-2010') d2 <- mytDate('30/10/2010') d3 <- mytDate('30.10.2010') d4 <- mytDate('30oct2010') (d1 == d2) & (d1 == d3) & (d1 == d4) }
545ff826ea862c6881e83125af4d38f47db8d1c0
[ "R" ]
13
R
pdiazs/R-Package-empfin
4ce1ab370c07ea31ec86d197417507fc51916266
d5dd101035d58f1ced58990184ef9d59c795e8d1
refs/heads/master
<repo_name>linhcao1611/CPSC-223J---Java-Workshop<file_sep>/Sphere/sphereui.java // Programmer's name: <NAME> // Email address: <EMAIL> // Course: CPSC 223j // Assignment number: 1 // Due date: Sept 14, 2015 // Title: Sphere Computations // Purpose: Find the area and the volume of any sphere // This file name: sphereui.java import javax.swing.Timer; import java.awt.event.ActionListener; public class sphereui extends javax.swing.JFrame { /** * Creates new form sphereui */ public sphereui() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txt_radius = new javax.swing.JTextField(); btn_compute = new javax.swing.JButton(); btn_clear = new javax.swing.JButton(); btn_exit = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txt_area = new javax.swing.JTextField(); txt_volume = new javax.swing.JTextField(); lb_message = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("<html><p> Welcome to Spheres</p> <p>Programmed by Linh Cao</p> </html>"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Please enter the radius:"); txt_radius.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btn_compute.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btn_compute.setText("Compute"); btn_compute.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_computeActionPerformed(evt); } }); btn_clear.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btn_clear.setText("Clear"); btn_clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_clearActionPerformed(evt); } }); btn_exit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btn_exit.setText("Exit"); btn_exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_exitActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Surface area:"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Volume:"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Message: "); txt_area.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N txt_area.setDisabledTextColor(new java.awt.Color(0, 0, 0)); txt_area.setEnabled(false); txt_volume.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N txt_volume.setDisabledTextColor(new java.awt.Color(0, 0, 0)); txt_volume.setEnabled(false); lb_message.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N lb_message.setText(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(34, 34, 34) .addComponent(txt_radius, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lb_message) .addGroup(layout.createSequentialGroup() .addComponent(btn_compute, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(btn_clear, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_exit, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_volume, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_area, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(78, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_radius, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txt_area, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txt_volume, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(lb_message)) .addGroup(layout.createSequentialGroup() .addGap(64, 64, 64) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_compute, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_clear, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_exit, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(63, 63, 63)) ); pack(); }// </editor-fold> private void btn_clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_clearActionPerformed // TODO add your handling code here: txt_radius.setText(""); txt_area.setText(""); txt_volume.setText(""); lb_message.setText("all fields are now blank"); }//GEN-LAST:event_btn_clearActionPerformed // This function will check if input is a number or not public static boolean isNumber(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException nfe) {} return false; }// end isNumber private void btn_computeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_computeActionPerformed // TODO add your handling code here: inputradius = txt_radius.getText(); txt_area.setText(""); txt_volume.setText(""); if(inputradius.trim().isEmpty()){ lb_message.setText("Missing radius"); } else if (isNumber(inputradius)){ radius = Double.parseDouble(inputradius); if(radius<0){ lb_message.setText("radius cannot be a negative number"); } else{ area = sphereop.sphereArea(radius); volume = sphereop.sphereVol(radius); areastring = String.format("%1$,.10f",area); volstring = String.format("%1$,.10f",volume); txt_area.setText(areastring + " square inches"); txt_volume.setText(volstring + " cubic inches"); lb_message.setText("Computed success"); } } else{ // invalid input lb_message.setText("Invalid input"); } }//GEN-LAST:event_btn_computeActionPerformed private void btn_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_exitActionPerformed // TODO add your handling code here: lb_message.setText("this program will now close"); listentask = new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } }; delayclosing = new Timer(length_of_delay,listentask); delayclosing.start(); //System.exit(0); }//GEN-LAST:event_btn_exitActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_clear; private javax.swing.JButton btn_compute; private javax.swing.JButton btn_exit; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel lb_message; private javax.swing.JTextField txt_area; private javax.swing.JTextField txt_radius; private javax.swing.JTextField txt_volume; private operations sphereop; private double area; private double volume; private String inputradius; private double radius; private String areastring; private String volstring; private Timer delayclosing; private final int length_of_delay = 2000; private ActionListener listentask; // End of variables declaration//GEN-END:variables } <file_sep>/Payroll Program/operations.java // Programmer's name: <NAME> // Email address: <EMAIL> // Course: CPSC 223j // Assignment number: 2 // Due date: Sept 28, 2015 // Title: Payroll User Interface // Purpose: Performing the basic payroll calculations // This file name: operations.java public class operations { private static final int hour_per_week = 40; private static final double empl_insurance_price = 28.75; private static final double depend_insurance_price = 17.35; private static final double max_fica = 55.0; // calculate gross pay public static double grosspay(double rate, int hours){ if(hours > hour_per_week){ int extra = hours - hour_per_week; return hours * rate + 0.5*(extra*rate); } else{ return hours * rate; } } // calculate fed tax public static double fedtax(double grosspay){ if(grosspay > 300){ return 0.22*grosspay; } else{ return 0; } } // calculate insurance cost public static double healthinsurance(int depend){ if (depend == 0){ return empl_insurance_price; } else { return empl_insurance_price + depend*depend_insurance_price; } } // calculate fica public static double fica(double gross){ double pay; pay = 0.85 * gross; if(pay < max_fica){ return pay; } else{ return max_fica; } } // calculate net pay public static double netpay(double grosspay, double fedtax, double insurance, double fica){ return grosspay - fedtax - insurance - fica; } // This function will check if input is an integer or not public static boolean isInt(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException nfe) {} return false; }// end isInt // This function will check if input is a double or not public static boolean isDouble(String str) { char[] temp = str.toCharArray(); for(char c:temp){ if(!Character.isDigit(c) && c!='.'){ return false; } } try { Double.parseDouble(str); return true; } catch (NumberFormatException nfe) {} return false; }// end isDouble // This function will check if a string contain only letter public static boolean onlyLetter(String str){ char[] temp = str.toCharArray(); for(char c:temp){ if(!Character.isLetter(c) && c!=' '){ return false; } } return true; } }
d0a0134efd8a2c4c11b77e8433b7693a841c4f13
[ "Java" ]
2
Java
linhcao1611/CPSC-223J---Java-Workshop
aeee4d4ecd91fd72e91cb5899925d8872fdbb8bb
866fd59e93c10c90b85e0fe5146da82b5627710a
refs/heads/master
<file_sep>__version__ = '0.8.0.dev734' <file_sep>#include <string> #include <iostream> #include <specex_message.h> #include <specex_spot.h> #include <specex_pyio.h> #include <specex_pyimage.h> #include <specex_psf_proc.h> using namespace std; int specex::PyIO::load_psf(specex::PyOptions opts, specex::PyPSF& pypsf){ load_psf_work(pypsf.psf); return EXIT_SUCCESS; } int specex::PyIO::write_spots(specex::PyOptions opts, specex::PyPSF& pypsf){ vector <Spot_p> fitted_spots = pypsf.fitted_spots; // future location of spot writing return EXIT_SUCCESS; } int specex::PyIO::set_inputpsf(specex::PyOptions opts){ use_input_specex_psf = true; psf_change_req |= (! opts.half_size_x_def); psf_change_req |= (! opts.half_size_y_def); psf_change_req |= (! opts.gauss_hermite_deg_def); psf_change_req |= (! opts.gauss_hermite_deg2_def); psf_change_req |= (! opts.legendre_deg_wave_def); psf_change_req |= (! opts.legendre_deg_x_def); psf_change_req |= (! opts.trace_deg_wave_def); psf_change_req |= (! opts.trace_deg_x_def); if(psf_change_req && use_input_specex_psf) { SPECEX_WARNING("option(s) were given to specify the psf properties, so we cannot use the input PSF parameters as a starting point (except for the trace coordinates)"); use_input_specex_psf = false; } if(use_input_specex_psf) { SPECEX_INFO("will start from input psf parameters") } return EXIT_SUCCESS; }
07893a8c600e91a83001e41b1ae1e31adda1fafc
[ "Python", "C++" ]
2
Python
tskisner/specex
c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2
a05034437506009cb2455fceee25700868fd9759
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 25 19:25:02 2019 @author: <NAME> """ import os import pandas as pd import numpy as np import gc import matplotlib.pyplot as plt from scipy import stats gc.collect() os.chdir('C:/Users/YIFAN DANG/Desktop/Datathon') bikeshare=pd.read_csv('bikeshare.csv') DCTaxi=pd.read_csv('DCTaxi.csv',nrows=10000) bikeshare.info() summary_bike=bikeshare.describe() DCTaxi.info() summary_taxi=DCTaxi.describe() bikenumber_histogram=plt.hist(bikeshare['Duration'],bins=50 ,density=True) #check unique Bikenumber len(bikeshare['Duration'].unique()) #check End station number len(bikeshare['End station number'].unique()) #check Start station number len(bikeshare['Start station number'].unique()) #check Member type len(bikeshare['Member type'].unique()) #duration check maxduration=bikeshare[bikeshare['Duration']==86394] minduration=bikeshare[bikeshare['Duration']==60] len(minduration['Bike number'].unique()) len(minduration[minduration['Member type']=='Member']) len(minduration[minduration['Member type']=='Casual']) same1=bikeshare[(bikeshare['Start station number']==31266)&(bikeshare['End station number']==31281)] same2=bikeshare[(bikeshare['Start station number']==31281)&(bikeshare['End station number']==31266)] same=pd.concat([same1,same2],axis=0) same=same.groupby('Bike number').filter(lambda x: len(x)>1) same=same.sort_values(by=['Bike number']) same_describe=same.describe() same.to_csv('round_trip.csv') #taxi duration check max_row=DCTaxi['Duration'].idxmax() taxi_maxduration=DCTaxi.loc[[max_row]] ###remove outliers### mean_duration=np.mean(DCTaxi['Duration']) std_duration=np.std(DCTaxi['Duration']) mean_totalamount=np.mean(DCTaxi['TotalAmount']) std_totalamount=np.std(DCTaxi['TotalAmount']) mean_mileage=np.mean(DCTaxi['Mileage']) std_mileage=np.std(DCTaxi['Mileage']) #def outliers(data): # new_data=pd.DataFrame() # for i in (7,24,25): # mean=np.mean(data.iloc[:,i]) # std=np.std(data.iloc[:,i]) # for j in range(len(DCTaxi)): # if data.iat[j,i]<=(mean-3*std) or data.iat[j,i]>=(mean+3*std): # new_data.append(data.loc[[j]]) # return new_data #outliers(DCTaxi) DCTaxi=pd.read_csv('DCtaxi_selected.csv') #sample_DCTaxi=DCTaxi.iloc[:10000,:] #sample_DCTaxi.to_csv('sample_DCTaxi.csv') DCTaxi_stats=DCTaxi.describe() DCTaxi=DCTaxi[(DCTaxi['Duration']>0)&(DCTaxi['milage']>0)&(DCTaxi['TotalAMount']>0)] DCTaxi['milage']=DCTaxi['milage'][(np.abs(stats.zscore(DCTaxi['milage']))<3)] DCTaxi['Duration']=DCTaxi['Duration'][(np.abs(stats.zscore(DCTaxi['Duration']))<3)] DCTaxi['TotalAMount']=DCTaxi['TotalAMount'][(np.abs(stats.zscore(DCTaxi['TotalAMount']))<3)] for i in range(len(DCTaxi)): if DCTaxi['Duration'][i]>120: DCTaxi['Duration'][i]=DCTaxi['Duration'][i]/60 return DCTaxi DCTaxi['Duration']=DCTaxi[(DCTaxi['Duration'] DCTaxi['milage per minute']=DCTaxi['milage']/DCTaxi['Duration'] DCTaxi_stats=DCTaxi.describe() DCTaxi.to_csv('DCtaxi.csv') capitalbike=pd.read_csv('capitalbikeshare_selected.csv') capitalbike=capitalbike[capitalbike['Duration']>0] capitalbike['Duration']=capitalbike['Duration'][(np.abs(stats.zscore(capitalbike['Duration']))<3)] capitalbike['Duration in Minutes']=capitalbike['Duration']/60 capitalbike_stats=capitalbike.describe() capitalbike.to_csv('capitalbike.csv') ##reverse geocoding zip_code=pd.read_csv('US Zip Codes from 2013 Government Data') Startzipcode=[] for i in range(len(capitalbike)): for j in range(len(zip_code)): if (capitalbike.iloc[i,1]==zip_code.iloc[j,1])and(capitalbike.iloc[i,2]==zip_code.iloc[j,2]): Startzipcode.append(zip_code[j,0]) return Startzipcode capitalbike=pd.read_csv('capitalbikes.csv') capitalbike['Duration']=capitalbike['Duration'][(np.abs(stats.zscore(capitalbike['Duration']))<3)] capitalbike['Duration per minute']=capitalbike['Duration']/60 capitalbike_stats=capitalbike.describe() capitalbike.to_csv('capitalbike.csv') <file_sep># Project Descripton (sponsored by Smith Analytics Consortium members: Deloitte, KPMG, MERKLE) In 2019, city-goers have access to a range of transportation modes, whereas 20 years ago options were limited. Transportation companies that thrived when consumers were limited are now forced to rethink their approach to their current market share of city travelers. This is a 4-person team projects that uses problem sloving, analytics, and data visualization skills to analyze the impact of intermediate transportation trends within the DC Metro area as it relates to Capital Bikeshare and DC Taxis, and present recommendataions for impacted businesses(i.e, taxi companies) to consider in their effort to regain their market share, # DataSet 1. Capital BikeShare(2016 - 2017): Where do Capital Bikeshare riders go? When do they ride? How far do they go? Which stations are most popular? What days of the week are most rides taken on? All of this data and more has been collected since the company started in 2010. ![](presentation/bikeshare%20columns.png) 2. DC For- Hire(Taxi): The DC Office of the Chief Technology Officer has shared samples of DC Taxicab trip data by month and year. Pick up and drop off locations with times rounded to the nearest hour. Data such as fare total, payment type, miles trveled and pick up/drop off times are included. ![](presentation/taxi%20columns.png) # Prerequistes tools: - Tableau(Visualization): https://www.tableau.com/products/desktop/download - Python(Data Analysis): https://www.anaconda.com/distribution/ - Google Cloud Platform (GCP) Big Query(Data Analysis): https://console.cloud.google.com/bigquery?project=umd-sac-datathon - GCP Cloud Storage(Data Storage): https://console.cloud.google.com/storage/browser/umdsac-datathon-rawdata/?prefix=cleaned_datasets&project=umd-sac-datathon # Running the tests ## 1. Based on same zipcode area, used Big Query to select the key features for both Bikeshare and taxis data. Exploring the data and removed missing value and outliers. ``` # -*- coding: utf-8 -*- """ Created on Mon Mar 25 19:25:02 2019 @author: <NAME> """ import os import pandas as pd import numpy as np import gc import matplotlib.pyplot as plt from scipy import stats gc.collect() os.chdir('C:/Users/YIFAN DANG/Desktop/Datathon') bikeshare=pd.read_csv('bikeshare.csv') DCTaxi=pd.read_csv('DCTaxi.csv',nrows=10000) bikeshare.info() summary_bike=bikeshare.describe() DCTaxi.info() summary_taxi=DCTaxi.describe() bikenumber_histogram=plt.hist(bikeshare['Duration'],bins=50 ,density=True) #check unique Bikenumber len(bikeshare['Duration'].unique()) #check End station number len(bikeshare['End station number'].unique()) #check Start station number len(bikeshare['Start station number'].unique()) #check Member type len(bikeshare['Member type'].unique()) #duration check maxduration=bikeshare[bikeshare['Duration']==86394] minduration=bikeshare[bikeshare['Duration']==60] len(minduration['Bike number'].unique()) len(minduration[minduration['Member type']=='Member']) len(minduration[minduration['Member type']=='Casual']) same1=bikeshare[(bikeshare['Start station number']==31266)&(bikeshare['End station number']==31281)] same2=bikeshare[(bikeshare['Start station number']==31281)&(bikeshare['End station number']==31266)] same=pd.concat([same1,same2],axis=0) same=same.groupby('Bike number').filter(lambda x: len(x)>1) same=same.sort_values(by=['Bike number']) same_describe=same.describe() same.to_csv('round_trip.csv') #taxi duration check max_row=DCTaxi['Duration'].idxmax() taxi_maxduration=DCTaxi.loc[[max_row]] ###remove outliers### mean_duration=np.mean(DCTaxi['Duration']) std_duration=np.std(DCTaxi['Duration']) mean_totalamount=np.mean(DCTaxi['TotalAmount']) std_totalamount=np.std(DCTaxi['TotalAmount']) mean_mileage=np.mean(DCTaxi['Mileage']) std_mileage=np.std(DCTaxi['Mileage']) #def outliers(data): # new_data=pd.DataFrame() # for i in (7,24,25): # mean=np.mean(data.iloc[:,i]) # std=np.std(data.iloc[:,i]) # for j in range(len(DCTaxi)): # if data.iat[j,i]<=(mean-3*std) or data.iat[j,i]>=(mean+3*std): # new_data.append(data.loc[[j]]) # return new_data #outliers(DCTaxi) DCTaxi=pd.read_csv('DCtaxi_selected.csv') #sample_DCTaxi=DCTaxi.iloc[:10000,:] #sample_DCTaxi.to_csv('sample_DCTaxi.csv') DCTaxi_stats=DCTaxi.describe() DCTaxi=DCTaxi[(DCTaxi['Duration']>0)&(DCTaxi['milage']>0)&(DCTaxi['TotalAMount']>0)] DCTaxi['milage']=DCTaxi['milage'][(np.abs(stats.zscore(DCTaxi['milage']))<3)] DCTaxi['Duration']=DCTaxi['Duration'][(np.abs(stats.zscore(DCTaxi['Duration']))<3)] DCTaxi['TotalAMount']=DCTaxi['TotalAMount'][(np.abs(stats.zscore(DCTaxi['TotalAMount']))<3)] for i in range(len(DCTaxi)): if DCTaxi['Duration'][i]>120: DCTaxi['Duration'][i]=DCTaxi['Duration'][i]/60 return DCTaxi DCTaxi['Duration']=DCTaxi[(DCTaxi['Duration'] DCTaxi['milage per minute']=DCTaxi['milage']/DCTaxi['Duration'] DCTaxi_stats=DCTaxi.describe() DCTaxi.to_csv('DCtaxi.csv') capitalbike=pd.read_csv('capitalbikeshare_selected.csv') capitalbike=capitalbike[capitalbike['Duration']>0] capitalbike['Duration']=capitalbike['Duration'][(np.abs(stats.zscore(capitalbike['Duration']))<3)] capitalbike['Duration in Minutes']=capitalbike['Duration']/60 capitalbike_stats=capitalbike.describe() capitalbike.to_csv('capitalbike.csv') ##reverse geocoding zip_code=pd.read_csv('US Zip Codes from 2013 Government Data') Startzipcode=[] for i in range(len(capitalbike)): for j in range(len(zip_code)): if (capitalbike.iloc[i,1]==zip_code.iloc[j,1])and(capitalbike.iloc[i,2]==zip_code.iloc[j,2]): Startzipcode.append(zip_code[j,0]) return Startzipcode capitalbike=pd.read_csv('capitalbikes.csv') capitalbike['Duration']=capitalbike['Duration'][(np.abs(stats.zscore(capitalbike['Duration']))<3)] capitalbike['Duration per minute']=capitalbike['Duration']/60 capitalbike_stats=capitalbike.describe() capitalbike.to_csv('capitalbike.csv') ``` Bikeshare (Select the same zipcode for OriginZip and DestinationZip): |Bike_number |StartLatitude |StartLongitude |EndLatitude |EndLogitude |OriginZip |DestinationZip |Duration |Duration per minute| |------------|--------------|---------------|------------|------------|----------|---------------|---------|-------------------| |W20870| 38.9086| -77.0323| 38.9086| -77.0323| 20005| 20005| 904.0| 15.066666666666666| |W22962| 38.9176| -77.0321| 38.9176| -77.0321| 20010| 20010| 80.0| 1.3333333333333333| sample_DCTaxi: |externalID |OriginZip |DestinationZip |TotalAMount milage |Duration| |-----------|----------|---------------|-------------------|--------| |70300_26NQE2DC |20045 |20008 |15.38 |4.53 |906| |52753_26NFPSK9 | 20002 |20001 |8.9 |1.25 |546| ## 2. Data visualization (plot in Tableau) ![](data%20visualization/bike%20start%20station.png) ![](data%20visualization/bike%20end%20station.png) ![](data%20visualization/bike%20round%20trip%20stations.png) ![](data%20visualization/bike%20round%20trip%20stations%20neighborhood.png) taxi starts and ends station ![](data%20visualization/taxi%20station.png) DC bike Density ![](data%20visualization/DC%20bike%20density.png) DC taxi density ![](data%20visualization/DC%20taxi%20density.png) Daily bikeshare and taxis change ![](data%20visualization/Picture1.png) seasonal bikeshare and texis change ![](data%20visualization/Picture2.png) # Conclusion & interesting findings 1. Taxi Company should have potential growth by regaining the market in zipcode areas 20009 and 20003, whereas decrease the taxi distribution in downtown DC areas such as zipcode 20024 because it has a high density of bikeshares. 2. There are only two bikeshare stations which bike riders did round trip.(start from one and end on the other and vice versa). As we open the google map and find out the neighborhood around these two bikeshare station, we find there are a shopping mall, recreation center and school around this area. 3. The daily bikeshare numbers start increases from 5:00 A.M. and reach the peak point near 8 A.M., then suddenly decrease, And start increase again from 3:00 P.M. and reach the peak point near 5:00 P.M., then drop again. It could be that there a lot of people take advantage of using bikeshare right before the rush hour starts to avoid the traffics. 4. The seasonal graph shows that during the winter, people like both bikeshare and taxi, it could be biking in winter is a good outdoor exercises for most of the people. ## Future Imporvement - used multiple random subsets of data to do the distribution on the map to make comparison. It might save more time then plot the whole dataset all together in tableau. - Doulbe Check the data set, make sure there are no abnormal value apprears when ploting the grapg, some information like the duration within the same zipcode area could be too large to be trusted. - Consider more features, conduct a predictive model if necessary for future analysis. # Contribution - Assigned a new team and help team members understand the task and the work process from a high level. - Used big query to select data contained necessary informations. - used Tableau to visualze the bike and taxi spatial distributions on geographic map. - Used Python to explore and manipulate the data for team members to conduct daily and seasonal visualization - Lead the team to work on the presentation slides, voiceover and support team with any necessary documents.
a40319ad88502e28b8bc41bcc2376b0a0bfb0cb0
[ "Markdown", "Python" ]
2
Python
ydang1/Datathon-DC-bikeshare-and-Taxi
973ecba4fc9b1df0dd2a24a4a1e7f7a668dffc6b
2551acbf8b06b8b86a8d269de375caed8f16247e
refs/heads/master
<repo_name>zfxu/EigenPro2<file_sep>/eigenpro.py import numpy as np import scipy as sp import tensorflow as tf import time from keras import backend as K from keras.layers import Dense, Input, Lambda from keras.models import Model import utils from backend_extra import scatter_update from layers import KernelEmbedding from optimizers import PSGD def pre_eigenpro_f(feat, phi, k, n, mG, alpha=.9, seed=1): """Prepare gradient map f for EigenPro and calculate scale factor for step size such that the update rule, p <- p - eta * g becomes, p <- p - scale * eta * (g - f(g)) Arguments: feat: feature matrix. phi: feature map or kernel function. k: top-k eigensystem for constructing eigenpro iteration/kernel. n: number of training points. mG: maxinum batch size corresponding to GPU memory. alpha: exponential factor (<= 1) for eigenvalue ratio. Returns: f: tensor function. scale: factor that rescales step size. s1: largest eigenvalue. beta: largest k(x, x) for the EigenPro kernel. """ np.random.seed(seed) # set random seed for subsamples start = time.time() n_sample, d = feat.shape if k is None: svd_k = min(n_sample - 1, 1000) else: svd_k = k _s, _V = nystrom_kernel_svd(feat, phi, n, svd_k) # Choose k such that the batch size is bounded by # the subsample size and the memory size. # Keep the original k if it is pre-specified. if k is None: k = np.sum(n / _s < min(n_sample, mG)) - 1 _s, _sk, _V = _s[:k-1], _s[k-1], _V[:, :k-1] s = K.constant(_s) V = utils.loadvar_in_sess(_V.astype('float32')) sk = K.constant(_sk) scale = np.power(_s[0] / _sk, alpha, dtype='float32') D = (1 - K.pow(sk / s, np.float32(alpha))) / s pre_f = lambda g, kfeat: K.dot( V * D, K.transpose(K.dot(K.dot(K.transpose(g), kfeat), V))) s1 = _s[0] / n print("SVD time: %.2f, adjusted k: %d, s1: %.2f, new s1: %.2e" % (time.time() - start, k, _s[0] / n, s1 / scale)) kxx = 1 - np.sum(_V ** 2, axis=1) / n * feat.shape[0] beta = np.max(kxx) return pre_f, scale, s1, beta def asm_eigenpro_f(pre_f, kfeat, inx): """Assemble map for EigenPro iteration""" def eigenpro_f(p, g, eta): inx_t = K.constant(inx, dtype='int32') kinx = tf.gather(kfeat, inx_t, axis=1) pinx = K.gather(p, inx_t) update_p = pinx + eta * pre_f(g, kinx) new_p = scatter_update(p, inx, update_p) return new_p return eigenpro_f def nystrom_kernel_svd(X, kernel_f, n, k, bs=512): """Compute top eigensystem of kernel matrix using Nystrom method. Arguments: X: data matrix of shape (n_sample, n_feature). kernel_f: kernel tensor function k(X, Y). n: number of training points. k: top-k eigensystem. bs: batch size. Returns: s: top eigenvalues of shape (k). U: top eigenvectors of shape (n_sample, k). """ m, d = X.shape # Assemble kernel function evaluator. input_shape = (d, ) x = Input(shape=input_shape, dtype='float32', name='feat-for-nystrom') K_t = KernelEmbedding(kernel_f, X)(x) kernel_tf = Model(x, K_t) K = kernel_tf.predict(X, batch_size=bs) D = np.float32(np.ones((m, 1)) * np.sqrt(n) / np.sqrt(m)) W = D * K * D.T w, V = sp.linalg.eigh(W, eigvals=(m-k, m-1)) U1r, sr = V[:, ::-1], w[::-1] s = sr[:k] NU = np.float32(D * U1r[:, :k]) return s, NU class EigenPro(object): def __init__(self, kernel, centers, n_label, mem_gb, n_subsample=None, k=None, bs=None, metric='accuracy', scale=.5, seed=1): """Assemble learner using EigenPro iteration/kernel. Arguments: kernel: kernel tensor function k(X, Y). centers: kernel centers of shape (n_center, n_feature). n_label: number of labels. mem_gb: GPU memory in GB. n_subsample: number of subsamples for preconditioner. k: top-k eigensystem for preconditioner. bs: mini-batch size. metric: keras metric, e.g., 'accuracy'. seed: random seed. """ n, d = centers.shape if n_subsample is None: if n < 100000: n_subsample = 2000 else: n_subsample = 10000 mem_bytes = mem_gb * 1024**3 - 100 * 1024**2 # preserve 100MB # Has a factor 3 due to tensorflow implementation. mem_usages = (d + n_label + 3 * np.arange(n_subsample)) * n * 4 mG = np.sum(mem_usages < mem_bytes) # device-dependent batch size # Calculate batch/step size for improved EigenPro iteration. np.random.seed(seed) pinx = np.random.choice(n, n_subsample, replace=False).astype('int32') kf, gap, s1, beta = pre_eigenpro_f( centers[pinx], kernel, k, n, mG, alpha=.95, seed=seed) new_s1 = s1 / gap if bs is None: bs = min(np.int32(beta / new_s1 + 1), mG) if bs < beta / new_s1 + 1: eta = bs / beta elif bs < n: eta = 2 * bs / (beta + (bs - 1) * new_s1) else: eta = 0.95 * 2 / new_s1 eta = .5 * eta # .5 for constant related to mse loss. print("n_subsample=%d, mG=%d, eta=%.2f, bs=%d, s1=%.2e, beta=%.2f" % (n_subsample, mG, eta, bs, s1, beta)) eta = np.float32(eta * n_label) # Assemble kernel model. ix = Input(shape=(d+1,), dtype='float32', name='indexed-feat') x, index = utils.separate_index(ix) # features, sample_id kfeat = KernelEmbedding(kernel, centers, input_shape=(d,))(x) y = Dense(n_label, input_shape=(n,), activation='linear', kernel_initializer='zeros', use_bias=False)(kfeat) model = Model(ix, y) model.compile( loss='mse', optimizer=PSGD(pred_t=y, index_t=index, eta=eta, eigenpro_f=asm_eigenpro_f(kf, kfeat, pinx)), metrics=[metric]) self.n_label = n_label self.seed = seed self.bs = bs self.model = model def fit(self, x_train, y_train, x_val, y_val, epochs, seed=1, n_train_sample=10000): """Train the model. Arguments: x_train: feature matrix of shape (n_train, n_feature). y_train: label matrix of shape (n_train, n_label). x_val: feature matrix for validation. y_val: label matrix for validation. epochs: list of epochs when the error is calculated. Return: res: dictionary with key: epoch, value: (train_error, test_error). """ assert self.n_label == y_train.shape[1] np.random.seed(seed) x_train = utils.add_index(x_train) x_val = utils.add_index(x_val) bs = self.bs res = dict() initial_epoch=0 train_sec = 0 # training time in seconds n, _ = x_train.shape # Subsample training data for fast estimation of training loss. inx = np.random.choice(n, min(n, n_train_sample), replace=False) x_sample, y_sample = x_train[inx], y_train[inx] for epoch in epochs: start = time.time() for _ in range(epoch - initial_epoch): epoch_ids = np.random.choice(n, n / bs * bs, replace=False) for batch_ids in np.array_split(epoch_ids, n / bs): x_batch, y_batch = x_train[batch_ids], y_train[batch_ids] self.model.train_on_batch(x_batch, y_batch) train_sec += time.time() - start tr_score = self.model.evaluate(x_sample, y_sample, batch_size=bs, verbose=0) tv_score = self.model.evaluate(x_val, y_val, batch_size=bs, verbose=0) print("train error: %.2f%%\tval error: %.2f%% (%d epochs, %.2f seconds)\t" "train l2: %.2e\tval l2: %.2e" % ((1 - tr_score[1]) * 100, (1 - tv_score[1]) * 100, epoch, train_sec, tr_score[0], tv_score[0])) res[epoch] = (tr_score, tv_score) initial_epoch = epoch return res def predict(self, x_feat): """Predict regression scores. Argument: x_feat: feature matrix of shape (?, n_feature). Return: score matrix of shape (?, n_label). """ return self.model.predict(utils.add_index(x_feat), batch_size=self.bs)
dac89a479ab842d41178fe6c73067f7af44955a0
[ "Python" ]
1
Python
zfxu/EigenPro2
5286d0c6c30cce04e2bae095f8f8b82a315cae8f
49c42601b69873b73efb33ed97d9e541948094f6
refs/heads/master
<repo_name>purevanilla-es/Gemmy<file_sep>/src/ovh/quiquelhappy/mcplugins/gemmy/drops/blocks.java package ovh.quiquelhappy.mcplugins.gemmy.drops; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.scheduler.BukkitRunnable; import ovh.quiquelhappy.mcplugins.gemmy.main; public class blocks implements Listener { static drops gem = new drops(); ArrayList<Location> bannedLocations = new ArrayList(); public blocks() { } @EventHandler public void BlockBreakEvent(BlockBreakEvent event) { Location location = event.getBlock().getLocation(); Material block = event.getBlock().getType(); Player player = event.getPlayer(); if (!this.bannedLocations.contains(location) && this.blockList().contains(block)) { new BukkitRunnable() { @Override public void run() { if(event.getPlayer().getLocation().getWorld().getBlockAt(event.getBlock().getLocation()).getType() == Material.AIR){ gem.createDrop(player, location, main.plugin.getConfig().getInt("drops.blocks." + block.toString() + ".min"), main.plugin.getConfig().getInt("drops.blocks." + block.toString() + ".max")); } else { TextComponent msg = new TextComponent("§e§lGEMS §7You can only get gems from blocks in unprotected areas: "+(event.getPlayer().getLocation().getWorld().getBlockAt(event.getBlock().getLocation()).getType()).toString()); Objects.requireNonNull(player).spigot().sendMessage(msg); } } }.runTaskLater(main.plugin, 1); } } @EventHandler public void BlockPlaceEvent(BlockPlaceEvent e) { Location location = e.getBlock().getLocation(); Material block = e.getBlock().getType(); if (this.bannedLocations.size() >= main.plugin.getConfig().getInt("drops.blackListing.blocks")) { this.bannedLocations.clear(); this.bannedLocations.add(location); } if (this.blockList().contains(block)) { this.bannedLocations.add(location); } } public List<Material> blockList() { List<Material> blockList = new ArrayList(); blockList.clear(); ConfigurationSection sec = main.plugin.getConfig().getConfigurationSection("drops.blocks"); Iterator var3 = sec.getKeys(false).iterator(); while(var3.hasNext()) { String key = (String)var3.next(); blockList.add(Material.getMaterial(key)); } return blockList; } static { List<Material> blockList = new ArrayList(); ConfigurationSection sec = main.plugin.getConfig().getConfigurationSection("drops.blocks"); Iterator var2 = sec.getKeys(false).iterator(); while(var2.hasNext()) { String key = (String)var2.next(); blockList.add(Material.getMaterial(key)); } System.out.println("[Gemmy] Loading " + blockList.size() + " block drops"); } }<file_sep>/src/ovh/quiquelhappy/mcplugins/gemmy/economy/death.java package ovh.quiquelhappy.mcplugins.gemmy.economy; import io.github.theluca98.textapi.ActionBar; import net.milkbowl.vault.economy.Economy; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import ovh.quiquelhappy.mcplugins.gemmy.drops.drops; import ovh.quiquelhappy.mcplugins.gemmy.main; public class death implements Listener { drops gem = new drops(); Economy eco = ovh.quiquelhappy.mcplugins.gemmy.main.getEconomy(); @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { if(main.plugin.getConfig().getBoolean("economy.death.enable")){ Player player = event.getEntity(); Double player_money = eco.getBalance(player.getPlayer()); Integer percent = main.plugin.getConfig().getInt("economy.death.default"); Double money_raw = player_money*percent*0.01; Long money_rounded = Math.round(money_raw); Integer money_final = Math.toIntExact(money_rounded); if((money_raw-money_rounded)<0){ money_final = Math.toIntExact(money_rounded-1); } eco.withdrawPlayer(player, money_final); this.gem.createExactDrop(player, player.getLocation(), money_final); ActionBar bar = new ActionBar(ChatColor.translateAlternateColorCodes('&', "&4&l- "+main.plugin.getConfig().getString("economy.currency")+money_final)); bar.send(player); } } static { if(main.plugin.getConfig().getBoolean("economy.death.enable")){ System.out.println("[Gemmy] Default players will drop " + main.plugin.getConfig().getInt("economy.death.default") + "% of their balance when they die"); } else { System.out.println("[Gemmy] Players won't drop gems when they die"); } } } <file_sep>/src/ovh/quiquelhappy/mcplugins/gemmy/main.java package ovh.quiquelhappy.mcplugins.gemmy; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import ovh.quiquelhappy.mcplugins.gemmy.drops.blocks; import ovh.quiquelhappy.mcplugins.gemmy.drops.mobs; import ovh.quiquelhappy.mcplugins.gemmy.economy.death; import ovh.quiquelhappy.mcplugins.gemmy.economy.pickup; import java.io.File; public class main extends JavaPlugin { public static Plugin plugin = null; private static Economy econ = null; private static Permission perms = null; public void onEnable() { plugin = this; createHeader(" "); System.out.println(" ____ "); System.out.println(" / ___| ___ _ __ ___ _ __ ___ _ _ "); System.out.println(" | | _ / _ \\ '_ ` _ \\| '_ ` _ \\| | | |"); System.out.println(" | |_| | __/ | | | | | | | | | | |_| |"); System.out.println(" \\____|\\___|_| |_| |_|_| |_| |_|\\__, |"); System.out.println(" |___/"); createHeader("CONFIG"); if ((new File("plugins" + File.separator + "Gemmy" + File.separator + "config.yml")).isFile()) { System.out.println("[Gemmy] Loading config"); } else { System.out.println("[Gemmy] Creating config"); this.saveDefaultConfig(); this.getConfig().options().copyDefaults(true); } createHeader("DROPS"); FileConfiguration config = this.getConfig(); if (config.getBoolean("drops.enable")) { Bukkit.getServer().getPluginManager().registerEvents(new blocks(), this); Bukkit.getServer().getPluginManager().registerEvents(new mobs(), this); } else { System.out.println("[Gemmy] Drops are DISABLED"); } createHeader("ECONOMY"); if (config.getBoolean("economy.enable")) { System.out.println("[Gemmy] Enabling economy"); setupPermissions(); if (!setupEconomy() ) { System.out.println("[Gemmy] Vault is not installed or/and you don't have any economy plugin. Install these dependencies or disable Gemmy economy"); getServer().getPluginManager().disablePlugin(this); } else { System.out.println("[Gemmy] Hooked into Vault"); Bukkit.getServer().getPluginManager().registerEvents(new death(), this); Bukkit.getServer().getPluginManager().registerEvents(new pickup(), this); } } else { System.out.println("[Gemmy] Economy is DISABLED"); } createHeader("LOADING FINISHED"); } private boolean createHeader(String header){ System.out.println(" "); System.out.println(" "); System.out.println(header); System.out.println(" "); return true; } private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } econ = rsp.getProvider(); return econ != null; } private boolean setupPermissions() { RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class); perms = rsp.getProvider(); return perms != null; } public static Economy getEconomy() { return econ; } public static Permission getPermissions() { return perms; } public void onDisable() { System.out.println("[Gemmy] Terminating process"); } }
d798efe97d302c6c4cdf2bb48d85a08b14f40b82
[ "Java" ]
3
Java
purevanilla-es/Gemmy
00b8ef12130ffa28e2ecaf6a45ddb40eb9738909
1c808a409c0102c6aad8a1b3bfbff2b31dbbfe5f
refs/heads/master
<repo_name>haoxiao0107/SimpleApp<file_sep>/app/src/main/java/com/hx/simpleapp/ui/gan/fragment/ArticleFragment.java package com.hx.simpleapp.ui.gan.fragment; import android.support.annotation.NonNull; import android.view.View; import android.widget.AdapterView; import com.hx.simpleapp.AppContext; import com.hx.simpleapp.api.remote.ApiFactory; import com.hx.simpleapp.base.adapter.ListBaseAdapter; import com.hx.simpleapp.base.ui.BaseListFragment; import com.hx.simpleapp.db.RealmHelper; import com.hx.simpleapp.model.ReadRecordRealm; import com.hx.simpleapp.model.response.gan.GanItem; import com.hx.simpleapp.router.Router; import com.hx.simpleapp.ui.gan.adapter.GanAdapter; import com.trello.rxlifecycle.FragmentEvent; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ArticleFragment extends BaseListFragment<GanItem> { @Override protected void sendRequest() { String keyword = getSearchKeyword(); ApiFactory.getGanApi().getArticles(keyword, getPageSize(), mCurrentPage).compose(this.bindUntilEvent(FragmentEvent.STOP)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mSubscriber); } @NonNull private String getSearchKeyword() { String keyword = ""; switch (mCatalog) { case 0: keyword = "Android"; break; case 1: keyword = "iOS"; break; case 2: keyword = "前端"; break; } return keyword; } @Override protected ListBaseAdapter getListAdapter() { GanAdapter adapter = new GanAdapter(); return adapter; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GanItem item = mAdapter.getItem(position); if (item != null) Router.showDetail(getActivity(), item.getDesc(), item.getUrl(), "", "", ""); RealmHelper realmHelper = new RealmHelper(AppContext.context()); if (realmHelper.findReadRecord(item.getDesc()) != null) { return; } ReadRecordRealm recordRealm = new ReadRecordRealm(); recordRealm.setId(item.getUrl()); recordRealm.setTitle(item.getDesc()); recordRealm.setTime(System.currentTimeMillis()); realmHelper.addReadRecord(recordRealm); } } <file_sep>/app/src/main/java/com/hx/simpleapp/ui/setting/fragment/AboutFragment.java package com.hx.simpleapp.ui.setting.fragment; import com.hx.simpleapp.base.ui.BaseFragment; /** * Created by God * on 2016/10/11. */ public class AboutFragment extends BaseFragment { } <file_sep>/app/src/main/java/com/hx/simpleapp/base/ui/BaseTabFragment.java package com.hx.simpleapp.base.ui; public class BaseTabFragment extends BaseFragment { } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'realm-android' android { compileSdkVersion 24 buildToolsVersion '24.0.1' defaultConfig { applicationId "com.hx.simpleapp" minSdkVersion 14 targetSdkVersion 24 versionCode 2 versionName "1.1.0" multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } dexOptions { jumboMode = true } signingConfigs { releaseConfig { keyAlias 'hb' keyPassword '<PASSWORD>' storeFile file('../key/apk_key.jks') storePassword '<PASSWORD>' } } buildTypes { release { signingConfig signingConfigs.releaseConfig minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } productFlavors { } lintOptions { abortOnError false checkReleaseBuilds false // 防止在发布的时候出现因MissingTranslation导致Build Failed! disable 'MissingTranslation' } sourceSets { main { java.srcDirs = ['src/main/java', 'src/main/java-gen'] } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.1.1' compile 'com.android.support:design:24.1.1' compile 'com.android.support:support-v4:24.1.1' compile 'com.jakewharton:butterknife:7.0.1' //retrofit compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.okhttp3:logging-interceptor:3.1.2' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' //rxjava compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2' compile 'io.reactivex:rxjava:1.1.0' compile 'io.reactivex:rxandroid:1.1.0' //rxlifecycle compile 'com.trello:rxlifecycle:0.3.1' compile 'com.trello:rxlifecycle-components:0.3.1' //gson compile 'com.google.code.gson:gson:2.7' compile 'com.github.ksoichiro:android-observablescrollview:1.5.0' //Glide compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar' compile files('libs/tbs_sdk_thirdapp_v2.2.0.1096_36549_sharewithdownload_withoutGame_obfs_20160830_211645.jar') compile files('libs/joda-time-2.2.jar') compile files('libs/Bughd_android_sdk_v1.3.7.jar') compile 'com.android.support:cardview-v7:24.1.1' } apt { arguments { androidManifestFile variant.outputs[0]?.processResources?.manifestFile resourcePackageName 'com.hx.simpleapp' } }
7aec4146166c6970413acaca22ce98468993a82f
[ "Java", "Gradle" ]
4
Java
haoxiao0107/SimpleApp
98c0c00549436253161d692c8ec6e4a5e997556f
3eb8b277dd850b9719d1ae7fd08a86d3e61c680c
refs/heads/master
<repo_name>BartlomiejFrankow/First-compass<file_sep>/app/src/main/java/com/example/firstcompas/dialog/NewDirectionDialogVM.kt package com.example.firstcompas.dialog import android.content.Context import androidx.databinding.ObservableField import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.firstcompas.R import com.example.firstcompas.utils.toValidateDouble class NewDirectionDialogVM : ViewModel() { val hideKeyboard = MutableLiveData<Unit>() val closeDialog = MutableLiveData<Unit>() val saveData = MutableLiveData<LatLongData>() lateinit var context : Context val providedLatitude = ObservableField("") val providedLongitude = ObservableField("") val latitudeError = ObservableField("") val longitudeError = ObservableField("") private val latitude: Double get() = providedLatitude.get()?.toValidateDouble(latitudeError) ?: 0.0 private val longitude: Double get() = providedLongitude.get()?.toValidateDouble(longitudeError) ?: 0.0 fun onCloseClicked() { closeDialog.postValue(Unit) } fun onCheckClicked() { if (validateFields()) saveData.postValue(LatLongData(latitude, longitude)) } private fun validateFields() = validateLatitude() and validateLongitude() private fun validateLatitude(): Boolean { return when { providedLatitude.get().isNullOrEmpty() -> { setErrorMessage(context.getString(R.string.error_empty_value), latitudeError) false } latitude == 0.0 ->{ hideKeyboard.postValue(Unit) false //setting error message by toValidateDouble() } latitude > 90.00 -> { setErrorMessage(context.getString(R.string.error_to_big_value), latitudeError) false } else -> { latitudeError.set("") true } } } private fun validateLongitude(): Boolean { return when { providedLongitude.get().isNullOrEmpty() -> { setErrorMessage(context.getString(R.string.error_empty_value), longitudeError) false } longitude == 0.0 ->{ hideKeyboard.postValue(Unit) false //setting error message by toValidateDouble() } longitude > 180.00 -> { setErrorMessage(context.getString(R.string.error_to_big_value), longitudeError) false } else -> { longitudeError.set("") true } } } private fun setErrorMessage(errorMessage: String, observableField: ObservableField<String>) { observableField.set(errorMessage) hideKeyboard.postValue(Unit) } } data class LatLongData(val latitude: Double, val longitude: Double)<file_sep>/app/src/main/java/com/example/firstcompas/utils/extension.kt package com.example.firstcompas.utils import androidx.databinding.ObservableField fun String?.toValidateDouble(errorObservableField: ObservableField<String>? = null): Double? { try { return this!!.toDouble() } catch (e: NumberFormatException) { errorObservableField?.set("Invalid value") } catch (e: Exception) { errorObservableField?.set("Bad") } return null }<file_sep>/app/src/main/java/com/example/firstcompas/dialog/NewDirectionDialog.kt package com.example.firstcompas.dialog import android.app.Activity import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.firstcompas.BR import com.example.firstcompas.MainActivity import com.example.firstcompas.R import com.example.firstcompas.databinding.DialogNewDirectionBinding import com.google.android.material.bottomsheet.BottomSheetDialogFragment class NewDirectionDialog : BottomSheetDialogFragment() { private lateinit var viewModel: NewDirectionDialogVM var onSave: (LatLongData) -> Unit = { } companion object { fun newInstance(): NewDirectionDialog = NewDirectionDialog() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { viewModel = ViewModelProviders.of(this).get(NewDirectionDialogVM::class.java) return performDataBinding(inflater, container) } private fun performDataBinding(inflater: LayoutInflater, container: ViewGroup?): View { val viewDataBinding: DialogNewDirectionBinding = DataBindingUtil.inflate( inflater, R.layout.dialog_new_direction, container, false ) viewDataBinding.lifecycleOwner = this viewDataBinding.setVariable(BR.vm, ViewModelProviders.of(this).get(NewDirectionDialogVM::class.java)) viewDataBinding.executePendingBindings() return viewDataBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.context = this.context!! viewModel.closeDialog.observe(this, Observer { closeDialog() }) viewModel.saveData.observe(this, Observer { saveDataAncCloseDialog(it) }) viewModel.hideKeyboard.observe(this, Observer { hideKeyboard() }) } private fun saveDataAncCloseDialog(it: LatLongData) { onSave(it) closeDialog() } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) closeDialog() } private fun closeDialog() { hideKeyboard() dismiss() } private fun hideKeyboard() { val imm = (activity as MainActivity).applicationContext.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view?.windowToken, 0) } }<file_sep>/app/src/main/java/com/example/firstcompas/MainActivity.kt package com.example.firstcompas import android.content.Context import android.hardware.SensorManager import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.firstcompas.databinding.ActivityMainBinding import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var viewModel: MainActivityVM private lateinit var sensorManager: SensorManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) performDataBinding() sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager viewModel.rotateCompass.observe(this, Observer { rotateCompass(it!!) }) viewModel.rotateArrow.observe(this, Observer { rotateArrow(it!!) }) viewModel.checkGPSPermission.observe(this, Observer { checkPermission() }) checkPermission() } private fun checkPermission() { viewModel.checkLocationPermission(this, supportFragmentManager) } private fun performDataBinding() { val viewDataBinding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) viewDataBinding.lifecycleOwner = this viewModel = ViewModelProviders.of(this).get(MainActivityVM::class.java) viewDataBinding.setVariable(BR.vm, viewModel) viewDataBinding.executePendingBindings() } private fun rotateCompass(azimuth: Float) { ivCompass.rotation = azimuth } private fun rotateArrow(azimuth: Float) { ivArrow.rotation = azimuth } override fun onPause() { super.onPause() viewModel.stopSensors(sensorManager) } override fun onResume() { super.onResume() viewModel.startSensors(sensorManager) } }<file_sep>/app/src/main/java/com/example/firstcompas/MainActivityVM.kt package com.example.firstcompas import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.hardware.Sensor import android.hardware.Sensor.* import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.hardware.SensorManager.* import android.location.Location import android.location.LocationManager import androidx.databinding.ObservableField import androidx.fragment.app.FragmentManager import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.firstcompas.dialog.NewDirectionDialog import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.karumi.dexter.Dexter import com.karumi.dexter.PermissionToken import com.karumi.dexter.listener.PermissionDeniedResponse import com.karumi.dexter.listener.PermissionGrantedResponse import com.karumi.dexter.listener.PermissionRequest import com.karumi.dexter.listener.single.PermissionListener import java.lang.Math.round import java.lang.Math.toDegrees import java.lang.System.arraycopy class MainActivityVM : ViewModel(), SensorEventListener { private lateinit var fragmentManager: FragmentManager private lateinit var context: Context private var degreesToNewLocation: Float = 0f private var degrees: Int = 0 private var rotation: Sensor? = null private var accelerometer: Sensor? = null private var magnetometer: Sensor? = null private var rotationMatrix = FloatArray(9) private var orientation = FloatArray(9) private val actualAccelerometer = FloatArray(3) private val actualMagnetometer = FloatArray(3) private var haveAccelerometerSensor: Boolean = false private var haveMagnetometerSensor: Boolean = false private var isAccelerometer: Boolean = false private var isMagnetometer: Boolean = false private var isPermissionGranted: Boolean = false private var myLatitude = ObservableField(0.0) private var myLongitude = ObservableField(0.0) private var destinationLatitude = 0.0 private var destinationLongitude = 0.0 var degreesAndDirection = ObservableField("") val showArrow = ObservableField<Boolean>(false) val rotateCompass = MutableLiveData<Float>() val rotateArrow = MutableLiveData<Float>() val checkGPSPermission = MutableLiveData<Unit>() private lateinit var fusedLocationClient: FusedLocationProviderClient fun startSensors(manager: SensorManager) { if (manager.getDefaultSensor(TYPE_ROTATION_VECTOR) == null) { accelerometer = manager.getDefaultSensor(TYPE_ACCELEROMETER) magnetometer = manager.getDefaultSensor(TYPE_MAGNETIC_FIELD) haveAccelerometerSensor = manager.registerListener(this, accelerometer, SENSOR_DELAY_FASTEST) haveMagnetometerSensor = manager.registerListener(this, magnetometer, SENSOR_DELAY_FASTEST) } else { rotation = manager.getDefaultSensor(TYPE_ROTATION_VECTOR) haveAccelerometerSensor = manager.registerListener(this, rotation, SENSOR_DELAY_FASTEST) } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} override fun onSensorChanged(event: SensorEvent) { getVectorRotation(event) copySensorsArrays(event) getRotation() setActualDirectionInfo() } private fun getVectorRotation(event: SensorEvent) { if (event.sensor.type == TYPE_ROTATION_VECTOR) { getRotationMatrixFromVector(rotationMatrix, event.values) degrees = calculateDegrees() } } private fun copySensorsArrays(event: SensorEvent) { if (event.sensor.type == TYPE_ACCELEROMETER) { arraycopy(event.values, 0, actualAccelerometer, 0, event.values.size) isAccelerometer = true } else if (event.sensor.type == TYPE_MAGNETIC_FIELD) { arraycopy(event.values, 0, actualMagnetometer, 0, event.values.size) isMagnetometer = true } } private fun getRotation() { if (isAccelerometer && isMagnetometer) { getRotationMatrix(rotationMatrix, null, actualAccelerometer, actualMagnetometer) getOrientation(rotationMatrix, orientation) degrees = calculateDegrees() } } private fun setActualDirectionInfo() { degrees = round(degrees.toFloat()) rotateCompass.postValue((-degrees).toFloat()) rotateArrow.postValue((-degrees).toFloat() + degreesToNewLocation) val direction = when (degrees) { in 281..349 -> "NW" in 261..280 -> "W" in 191..260 -> "SW" in 171..190 -> "S" in 101..170 -> "SE" in 81..100 -> "E" in 11..80 -> "NE" else -> "N" // >= 350 || <= 10 } degreesAndDirection.set("$degrees $direction") } private fun calculateDegrees() = ((toDegrees(getOrientation(rotationMatrix, orientation)[0].toDouble()) + 360) % 360).toInt() fun checkLocationPermission(activity: MainActivity, supportFragmentManager: FragmentManager) { fragmentManager = supportFragmentManager Dexter.withActivity(activity) .withPermission(Manifest.permission.ACCESS_FINE_LOCATION) .withListener(object : PermissionListener { override fun onPermissionGranted(response: PermissionGrantedResponse) { getMyLocation(activity.applicationContext) isPermissionGranted = true } override fun onPermissionDenied(response: PermissionDeniedResponse) { } override fun onPermissionRationaleShouldBeShown(permission: PermissionRequest, token: PermissionToken) { token.continuePermissionRequest() } }).check() } fun stopSensors(sensorManager: SensorManager) { if (haveAccelerometerSensor && haveMagnetometerSensor) { sensorManager.unregisterListener(this, accelerometer) sensorManager.unregisterListener(this, magnetometer) sensorManager.unregisterListener(this, rotation) } } fun onLatLongClicked() { if (isPermissionGranted) showLatLongDialog() else checkGPSPermission.postValue(Unit) } private fun showLatLongDialog() { val dialog = NewDirectionDialog.newInstance() dialog.onSave = { destinationLatitude = it.latitude destinationLongitude = it.longitude bearingToNewLocation() } dialog.show(fragmentManager, "OpenLatLongDialog") } @SuppressLint("MissingPermission") fun bearingToNewLocation() { fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) val newLocation = setUpNewLocation() fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? -> degreesToNewLocation = location!!.bearingTo(newLocation) rotateArrow.postValue(degreesToNewLocation) showArrow.set(true) } } private fun setUpNewLocation(): Location { val newLocation = Location(LocationManager.GPS_PROVIDER) newLocation.latitude = destinationLatitude newLocation.longitude = destinationLongitude return newLocation } @SuppressLint("MissingPermission") fun getMyLocation(context: Context) { this.context = context fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? -> myLatitude.set(location?.latitude ?: 0.0) myLongitude.set(location?.longitude ?: 0.0) } } }
f7db96cbc23827da9d00659081175c8559b0590f
[ "Kotlin" ]
5
Kotlin
BartlomiejFrankow/First-compass
ca99b1573c83153a64e8a4ea3311ac4e55acde73
308a5ca9219018223c65360f456a2625ffcef683
refs/heads/master
<repo_name>araaaaan/apartment-system<file_sep>/api/publics/tests.py import json from rest_framework.test import APITestCase from rest_framework import status from api.publics.models import User class PublicTest(APITestCase): def setUp(self): User.objects.create( floor = "1004", password = "<PASSWORD>", cost = "10000.00" ) def test_public_authenticated(self): data = {"floor":"1004", "password":"<PASSWORD>"} response = self.client.post('/api/publics', data=json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), { "floor":"1004", "cost":"10000.00" }) def test_admin_authenticated_error(self): data = {"floor":"1004", "password":"<PASSWORD>"} response = self.client.post('/api/publics', data=json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)<file_sep>/api/urls.py from django.urls import path, include urlpatterns = [ path('/admin', include('api.admins.urls')), path('/public', include('api.publics.urls')), ]<file_sep>/api/admins/tests.py import json from django.contrib.auth.models import User from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from api.publics.models import User class Admintest(APITestCase): def setUp(self): self.user = User.objects.create( username = "laran89", password = "<PASSWORD>", is_staff = True ) self.token = Token.objects.create(user=self.user) User.objects.create( floor = "1004", password = "<PASSWORD>", cost = 10000.00 ) self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token}") def test_admin_authenticated(self): response = self.client.get('/api/admin') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), [{ "floor" : "1004", "password": "<PASSWORD>", "cost" : "10000.00" }]) def test_admin_authenticated_error(self): self.client.force_authenticate(user=None) response = self.client.get('/api/admin') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)<file_sep>/api/publics/urls.py from django.urls import path from .views import PublicUserDetailView urlpatterns = [ # path('', RoomAPIView.as_view()), path('/<int:pk>', PublicUserDetailView.as_view()) ]<file_sep>/Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED=1 WORKDIR /app/ # Install Production Depedencies First COPY requirements/ /app/requirements/ RUN pip install --no-cache-dir -r requirements/requirements-dev.txt # Bundle app source COPY . /app/ # Default to port 8000 for django, and 8001 and 8002 for debug ARG PORT=8000 ENV PORT $PORT EXPOSE $PORT 8001 8002 CMD ["python", "manage.py", "runserver", "--host=0.0.0.0", "-p 8000"] <file_sep>/api/publics/views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status, generics from api.admins.serializers import AccountSerializer from api.publics.serializers import UserSerializer from .models import User # class RoomAPIView(APIView): # def post(self, request): # try: # floor = request.data['floor'] # password = request.data['<PASSWORD>'] # get_id = User.objects.get(floor=floor, password=<PASSWORD>) # serializer = AccountSerializer(get_id) # return Response(serializer.data, status=status.HTTP_200_OK) # except: # return Response({"message":"CHECK_YOUR_NUMBER"},status=status.HTTP_400_BAD_REQUEST) #from indent_corp.auth import HouseHoldAuthentication #from indent_corp.models import HouseHold, DoorUseLog #from indent_corp.serializers import HouseHoldSerializer FEE_PER_COUNT = 1 # custom authentication_classes from rest_framework.authentication import BaseAuthentication class PublicUserAuthentication(BaseAuthentication): def authenticate(self, request): print("++") print(f"request : {dir(request)}") authentication = request.META.get('HTTP_AUTH', 'default') params = request.query_params.get('key') print(f"auth : {authentication}") print(f"params : {params}") return class PublicUserDetailView(generics.RetrieveAPIView): authentication_classes = [PublicUserAuthentication, ] queryset = User.objects.all() serializer_class = UserSerializer <file_sep>/README.md ># 아파트 관리비 시스템 보고서 API 아파트 관리비 확인용 페이지로써 관리비 관리를 위한 페이지입니다. * 관리자 : 각 세대의 관리비 확인 가능 * 입주민 : 개별 관리비 내역 확인 가능 > ## 폴더 구조 ``` . ├── Dockerfile ├── README.md ├── api │   ├── admins │   │   ├── admin.py │   │   ├── apps.py │   │   ├── models.py │   │   ├── serializers.py │   │   ├── tests.py │   │   ├── urls.py │   │   └── views.py │   ├── publics │   │   ├── admin.py │   │   ├── apps.py │   │   ├── models.py │   │   ├── serializers.py │   │   ├── tests.py │   │   ├── urls.py │   │   └── views.py │   └── urls.py ├── aptment │   ├── asgi.py │   ├── permissions.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── clients │   └── token-auth-test.py ├── docker-compose.yml ├── manage.py ├── my_settings.py └── requirements.txt ``` >## 관리자 권한 API - 전 세대별 관리비 확인용 관리자 생성을 할 수 있습니다. >## 보고서 API 1. 관리자는 세대별 관리비를 확인할 수 있습니다. (관리사무소용 API) - 관리자 권한 API에서 만든 관리용 아이디와 비밀번호 통과해야만 이 API에 접근할 수 있습니다. 2. 각 세대별로 자신의 관리비를 확인할 수 있습니다. (세대별 관리비 API) - 각 호수와 정해진 비밀번호를 통과해야만 이 API에 접근할 수 있습니다. >## 기능 요구사항 - API 요청과 응답은 JSON 형태이며, 메서드와 상태 코드는 HTTP 스펙을 따릅니다. - 최대 1,000 세대가 거주하는 아파트 단지입니다. - 세대별 고유번호는 네 자리입니다. (ex. 1층 첫 세대 = 0101호, 25층 마지막 세대 = 2509호) - 세대 비밀번호와 관리용 비밀번호는 네 자리입니다. - Django Rest Framework으로 작성하였습니다. - docker를 사용해서 docker가 설치된 환경에서 바로 `docker-compose`를 사용하여 server를 실행시킬 수 있도록 만듭니다. > ## 설치 방법 docker 설치 (다운로드) https://www.docker.com/products/docker-desktop git clone 실행 ``` git clone https://github.com/araaaaan/apartment-system.git ``` docker compose 실행 ``` $ docker-compose up ``` >## 사용 방법 1. api/admin/register 에서 관리자 권한의 username / password 입력 2. 인증 후 api/admin에서 전체 호수 관리비 확인 및 관리비 입력가능 3. api/publics에서 자신의 호수(4자리)와 부여 받은 비밀번호 입력 후 개인 관리비 확인가능 [관리자 계정 생성] <img width="700" alt="스크린샷 2021-07-23 오후 5 14 28" src="https://user-images.githubusercontent.com/81959334/126760986-e881e215-d82b-4cdc-bc98-0f5bccc3c93c.png"> [관리자 계정 로그인 후 관리비 입력] <img width="700" alt="스크린샷 2021-07-23 오후 5 12 23" src="https://user-images.githubusercontent.com/81959334/126761019-3e04429e-c2c5-418f-989f-8c10dcb107d3.png"> [개별 호수 계정 입력] <img width="700" alt="스크린샷 2021-07-23 오후 5 13 33" src="https://user-images.githubusercontent.com/81959334/126761013-67168d8a-885e-4b33-a12a-5741af07774e.png"> [개별 호수 관리비 확인] <img width="700" alt="스크린샷 2021-07-23 오후 5 13 46" src="https://user-images.githubusercontent.com/81959334/126761000-540174cb-965c-42a1-a835-db64e3af51c1.png"> **기능 별 url** |기능|URL| |:---:|:---:| |관리자 권한 부여|api/admin/register| |전체 관리비 확인|api/admin| |호수 별 관리비 확인|api/publics| <file_sep>/clients/token-auth-test.py import requests def client(): token_h = "Token <PASSWORD>" # credentials = {"username" : "lock", "password" : "<PASSWORD>"} # response = requests.post("http://127.0.0.1:8000/api/rest-auth/login/", data=credentials) # print("Status Codedd: ", response.status_code) headers = {"Authorization": token_h} response = requests.post("http://127.0.0.1:8000/api/rest-auth/registration/", hearders=headers) print("Status Code: ", response.status_code) response_data = response.json() print(response_data) if __name__ == "__main__": client()<file_sep>/api/publics/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_unit( self, floor, password, **extra_fields ): if not floor: raise ValueError("CHECK FLOOR") user = self.model(floor=floor, **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser( self, floor, password ): if not floor or not floor == '0000': raise ValueError('IVALID_FLOOR') user = self.create_user(floor=floor, password=<PASSWORD>) user.is_superuser = True user.save(using=self.db) class User(AbstractBaseUser.PermissionsMixin): floor = models.CharField(max_length=4, null=True, unique=True) password = models.CharField(max_length=4, null=True) cost = models.DecimalField(max_digits=8, decimal_places=2, null=True) objects = UserManager() USERNAME_FIELD = 'floor' class Meta: db_table = 'users' class DoorLog(models.Model): open_date = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'door_logs'<file_sep>/api/admins/views.py from rest_framework import viewsets from rest_framework import mixins from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from rest_framework.authentication import SessionAuthentication, TokenAuthentication from api.publics.models import User from api.publics.serializers import UserSerializer class AccountViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [TokenAuthentication, SessionAuthentication] permission_classes = [IsAuthenticated]
502e5326da29aafa10e273d0a09b1e2858fa2924
[ "Markdown", "Python", "Dockerfile" ]
10
Python
araaaaan/apartment-system
dc8986e73ef9b34ab0744ea9915e2057ce8dea1b
8f69e773d60f45a689cedbe427183661cad3e3ff
refs/heads/master
<repo_name>heeed/microbit_morse<file_sep>/morse.py # Add your Python code here. E.g. from microbit import * speed = 300 morse={'a':"01",'b':"1000",'c':"1010",'d':"100",'e':"0",'f':"0010",'g':"110",'h':"0000",'i':"00",'j':"0111",'k':"101",'l':"0100",'m':"11",'n':"10",'o':"111",'p':"0110",'q':"1101",'r':"010",'s':"000",'t':"1",'u':"001",'v':"0001",'w':"011",'x':"1001",'y':"1011",'z':"1100"} def displayCode(phrase): message=[] if stringHasSpace(phrase): message=phrase.split(" ") else: message.append(phrase) for word in phrase: for letter in word: y = str(morse[letter]) sleep(speed*3) #delay between char for x in y: display.clear() if x == "0": display.set_pixel(2,2,9) pin0.write_digital(1) sleep(speed) #one di length pin0.write_digital(0) display.clear() sleep(speed*2) #delay betwen elements (farnsworth timing) elif x == "1": display.set_pixel(1,2,9) display.set_pixel(2,2,9) display.set_pixel(3,2,9) pin0.write_digital(1) sleep(speed*3) #one dah length pin0.write_digital(0) display.clear() sleep(speed*2) #delay betwen elements (farnsworth timing) sleep(speed*7) #delay between words def stringHasSpace(string): if ' ' in string: return True else: return False display.show(Image.HEART) sleep(300) display.clear() while True: displayCode("sos sos") <file_sep>/README.md # microbit_morse morsecode on the microbit Just something thats getting put together for a workshop.
80fa52214e914facb9e3b56a8cb43f79a17c2163
[ "Markdown", "Python" ]
2
Python
heeed/microbit_morse
1ead3fb97337aa2a646b1d662a74d712d0925e42
3ebb2b9c515d755c021442605123c3f3dbb445aa
refs/heads/master
<repo_name>ismaiel-nosairat/EasySheet<file_sep>/src/main/java/com/ismaiel/easysheet/exceptions/InternalServerException.java package com.ismaiel.easysheet.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public class InternalServerException extends RuntimeException { public InternalServerException(String msg,Exception e) { super(msg); } } <file_sep>/src/main/java/com/ismaiel/easysheet/exceptions/DuplicatedException.java package com.ismaiel.easysheet.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class DuplicatedException extends RuntimeException { public DuplicatedException(String msg,Exception e) { super(msg); } } <file_sep>/src/main/java/com/ismaiel/easysheet/services/DbService.java package com.ismaiel.easysheet.services; import com.ismaiel.easysheet.entities.Entry; import com.ismaiel.easysheet.entities.Member; import com.ismaiel.easysheet.entities.Share; import com.ismaiel.easysheet.entities.Sheet; import com.ismaiel.easysheet.repositories.EntryRepo; import com.ismaiel.easysheet.repositories.MemberRepo; import com.ismaiel.easysheet.repositories.ShareRepo; import com.ismaiel.easysheet.repositories.SheetRepo; import java.util.Date; import javax.annotation.PostConstruct; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class DbService { @Autowired SheetRepo sheetRepo; @Autowired EntryRepo entryRepo; @Autowired ShareRepo shareRepo; @Autowired MemberRepo memberRepo; @PersistenceContext private EntityManager em; @PostConstruct public void init() { Sheet y=new Sheet("my first sheet", new Date(), "root", "view"); y =sheetRepo.save(y); Member m1 = new Member("Mahmoud", y); Member m2 = new Member("Othman", y); Member m3 = new Member("Ibrahem", y); Member m4 = new Member("Bassam", y); m1=memberRepo.save(m1); m2=memberRepo.save(m2); m3=memberRepo.save(m3); m4=memberRepo.save(m4); Entry e1=new Entry("Banana",1000, new Date(), m1,y); e1=entryRepo.save(e1); Share sh1=new Share(m1, e1, 500); Share sh2=new Share(m2, e1, -500); sh1=shareRepo.save(sh1); sh2=shareRepo.save(sh2); Entry e2=new Entry("Potatos",2000, new Date(), m2,y); e2=entryRepo.save(e2); Share sh3=new Share(m1, e2, -1000); Share sh4=new Share(m2, e2, 1000); sh3=shareRepo.save(sh3); sh4=shareRepo.save(sh4); Entry e3=new Entry("Drink",8000, new Date(), m3,y); e3=entryRepo.save(e3); Share sh5=new Share(m1, e3, -2000); Share sh6=new Share(m2, e3, -2000); Share sh7=new Share(m3, e3, 6000); Share sh8=new Share(m4, e3, -2000); sh5=shareRepo.save(sh5); sh6=shareRepo.save(sh6); sh7=shareRepo.save(sh7); sh8=shareRepo.save(sh8); another(); } public void another(){ Sheet y=new Sheet("حسابات شهر واحد", new Date(), "جذر", "عرض"); y =sheetRepo.save(y); Member m1 = new Member("محمود", y); Member m2 = new Member("عثمان", y); Member m3 = new Member("ابراهيم", y); Member m4 = new Member("بسام", y); m1=memberRepo.save(m1); m2=memberRepo.save(m2); m3=memberRepo.save(m3); m4=memberRepo.save(m4); Entry e1=new Entry("موز",1000, new Date(), m1,y); e1=entryRepo.save(e1); Share sh1=new Share(m1, e1, 500); Share sh2=new Share(m2, e1, -500); sh1=shareRepo.save(sh1); sh2=shareRepo.save(sh2); Entry e2=new Entry("بطاطا",2000, new Date(), m2,y); e2=entryRepo.save(e2); Share sh3=new Share(m1, e2, -1000); Share sh4=new Share(m2, e2, 1000); sh3=shareRepo.save(sh3); sh4=shareRepo.save(sh4); Entry e3=new Entry("مشروب",8000, new Date(), m3,y); e3=entryRepo.save(e3); Share sh5=new Share(m1, e3, -2000); Share sh6=new Share(m2, e3, -2000); Share sh7=new Share(m3, e3, 6000); Share sh8=new Share(m4, e3, -2000); sh5=shareRepo.save(sh5); sh6=shareRepo.save(sh6); sh7=shareRepo.save(sh7); sh8=shareRepo.save(sh8); } } <file_sep>/src/main/java/com/ismaiel/easysheet/services/MemberServices.java package com.ismaiel.easysheet.services; import com.ismaiel.easysheet.GC; import com.ismaiel.easysheet.entities.Entry; import com.ismaiel.easysheet.entities.Member; import com.ismaiel.easysheet.entities.Share; import com.ismaiel.easysheet.entities.Sheet; import com.ismaiel.easysheet.exceptions.BadOperationException; import com.ismaiel.easysheet.exceptions.NotFoundException; import com.ismaiel.easysheet.exceptions.UnAuthorizedException; import com.ismaiel.easysheet.models.MemberBalance; import com.ismaiel.easysheet.models.Report; import com.ismaiel.easysheet.models.RichShare; import com.ismaiel.easysheet.models.SheetUpdateInfo; import com.ismaiel.easysheet.repositories.EntryRepo; import com.ismaiel.easysheet.repositories.MemberRepo; import com.ismaiel.easysheet.repositories.SheetRepo; import java.math.BigInteger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service public class MemberServices { @Autowired EntityManager em; @Autowired MemberRepo memberRepo; @Autowired SheetRepo sheetRepo; @Autowired EntryRepo entryRepo; @Autowired Tools tools; public ResponseEntity list(Sheet sheet) { Sheet original = sheetRepo.findOne(sheet.getId()); if (original == null) { throw new NotFoundException("003", null); } else { tools.checkPermission(sheet, original); List<Member> findBySheet = memberRepo.findBySheet(sheet); return ResponseEntity.ok(findBySheet); } } public ResponseEntity addMember(Member member) { Sheet sheet = sheetRepo.findOne(member.getSheet().getId()); if (member.getName() == null || member.getName().length() < 3) { throw new BadOperationException("011", null); } if (sheet == null) { throw new NotFoundException("003", null); } else { tools.checkAdminPermission(sheet, member.getSheet()); tools.checkDuplicated(sheet, member); member.setSheet(sheet); memberRepo.save(member); return ResponseEntity.ok(member); } } public ResponseEntity deleteMember(Member member) { Sheet sheet = sheetRepo.findOne(member.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003", null); } else { tools.checkAdminPermission(sheet, member.getSheet()); member = memberRepo.findOne(member.getId()); if (member == null) { throw new NotFoundException("006", null); } List<Share> shares = member.getShares(); double balance = 0; if (shares != null) { balance = shares.stream().map((share) -> share.getAmount()).reduce(balance, (accumulator, _item) -> accumulator + _item); } if (balance != 0) { throw new BadOperationException("007", null); } memberRepo.delete(member.getId()); return ResponseEntity.ok(member); } } public ResponseEntity detailsMember(Member member) { Sheet sheet = sheetRepo.findOne(member.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003", null); } else { tools.checkPermission(sheet, member.getSheet()); member = memberRepo.findOne(member.getId()); if (member == null) { throw new NotFoundException("006", null); } List<Entry> entries = entryRepo.findByCreditor(member); return ResponseEntity.ok(entries); } } public ResponseEntity memberBalance(Member member) { Sheet sheet = sheetRepo.findOne(member.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003", null); } else { member = memberRepo.findOne(member.getId()); if (member == null) { throw new NotFoundException("006", null); } tools.checkPermission(sheet, member.getSheet()); MemberBalance memberBalance=new MemberBalance(); String x = GC.reportMemberBalance; Query q = em.createNativeQuery(x); q.setParameter(1, member.getId()); List<Object[]> list = q.getResultList(); //BigInteger s=new BigInteger for (Object[] ob : list) { RichShare rs=new RichShare(); rs.setEntryId( new BigInteger(ob[0].toString()).longValue()); rs.setEntryName(ob[1].toString()); rs.setShareId( new BigInteger(ob[2].toString()).longValue()); rs.setAmount( (Double) ob[3]); memberBalance.getShares().add(rs); memberBalance.setBalance(memberBalance.getBalance()+rs.getAmount() ); } return ResponseEntity.ok(memberBalance); } } public ResponseEntity<?> updateInfo(SheetUpdateInfo info) { Sheet original = sheetRepo.findOne(info.getId()); if (original == null) { return ResponseEntity.notFound().build(); } else { // Check permission if (!original.getPassword().equals(info.getPassword())) { throw new UnAuthorizedException("001", null); } original.setPassword(<PASSWORD>()); original.setViewPassword(info.getNewViewPassword()); sheetRepo.save(original); return ResponseEntity.ok(original); } // return ResponseEntity.ok(entries); } } <file_sep>/src/main/java/com/ismaiel/easysheet/services/EntryServices.java package com.ismaiel.easysheet.services; import com.ismaiel.easysheet.entities.Entry; import com.ismaiel.easysheet.entities.Member; import com.ismaiel.easysheet.entities.Share; import com.ismaiel.easysheet.entities.Sheet; import com.ismaiel.easysheet.exceptions.BadOperationException; import com.ismaiel.easysheet.exceptions.NotFoundException; import com.ismaiel.easysheet.repositories.EntryRepo; import com.ismaiel.easysheet.repositories.MemberRepo; import com.ismaiel.easysheet.repositories.ShareRepo; import com.ismaiel.easysheet.repositories.SheetRepo; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Transactional @Service public class EntryServices { @Autowired EntryRepo entryRepo; @Autowired ShareRepo shareRepo; @Autowired SheetRepo sheetRepo; @Autowired MemberRepo memberRepo; @Autowired Tools tools; public ResponseEntity list(Sheet sheet) { Sheet original = sheetRepo.findOne(sheet.getId()); if (original == null) { throw new NotFoundException("003",null); } else { tools.checkPermission(sheet, original); return ResponseEntity.ok(entryRepo.findBySheet(sheet)); } } public Entry getEntry(Entry entry) { Sheet sheet = sheetRepo.findOne(entry.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003",null); } else { tools.checkPermission(sheet, entry.getSheet()); Entry out =entryRepo.findOne(entry.getId()); return (out); } } public ResponseEntity deleteEntry(Entry entry) { Sheet sheet = sheetRepo.findOne(entry.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003",null); } else { tools.checkAdminPermission(sheet, entry.getSheet()); entry = entryRepo.findOne(entry.getId()); if (entry == null) { throw new NotFoundException("009",null); } entryRepo.delete(entry.getId()); return ResponseEntity.ok(entry); } } public ResponseEntity test() { Entry entry = entryRepo.findOne(1L); return ResponseEntity.ok(entry); } public Entry addEntry(Entry entry) { if (entry.getShares().size() < 1) { throw new BadOperationException("008",null); } Sheet sheet = sheetRepo.findOne(entry.getSheet().getId()); if (sheet == null) { throw new NotFoundException("003",null); } else { tools.checkAdminPermission(sheet, entry.getSheet()); //entry.setDate(new Date()); tools.checkIntegrity(entry); entry.setSheet(sheet); entry=entryRepo.save(entry); for (Share sh : entry.getShares()) { Member m = memberRepo.findOne(sh.getMember().getId()); if (m == null || m.getSheet().getId()!= sheet.getId()) { throw new BadOperationException("010",null); } shareRepo.save(new Share(m, entry, sh.getAmount())); } return entry; } } } <file_sep>/src/main/java/com/ismaiel/easysheet/controllers/SheetController.java package com.ismaiel.easysheet.controllers; import com.ismaiel.easysheet.models.Login; import com.ismaiel.easysheet.models.SheetItem; import com.ismaiel.easysheet.entities.Sheet; import com.ismaiel.easysheet.models.SheetUpdateInfo; import com.ismaiel.easysheet.services.SheetServices; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @CrossOrigin @RestController @RequestMapping("/sheets") public class SheetController { @Autowired SheetServices sheetServices; @Deprecated @GetMapping("/getAll") public @ResponseBody List<Sheet> getAll() { return sheetServices.getAll(); } @Deprecated @GetMapping(value = "/list") public ResponseEntity getAllSheets(@RequestParam("page") int pageNum) { return new ResponseEntity(sheetServices.listSheets(pageNum), HttpStatus.OK); } @PostMapping(value = "/signin") public ResponseEntity login(@RequestBody Login infoLogin) { return sheetServices.login(infoLogin.getId(),infoLogin.getPassword()); } @PostMapping(value = "/signup") public ResponseEntity create(@RequestBody Sheet sheet) { return sheetServices.newSheet(sheet); } @PostMapping(value = "/delete") public ResponseEntity delete(@RequestBody Sheet sheetItem) { return sheetServices.delete(sheetItem.getId()); } @PostMapping(value = "/clear") public ResponseEntity clear(@RequestBody Sheet sheetItem) { return sheetServices.clear(sheetItem.getId()); } @PostMapping("/report") public ResponseEntity<?> getReport(@RequestBody Sheet sheet ) { return sheetServices.report(sheet); } @PostMapping("/update") public ResponseEntity<?> updateSheet(@RequestBody SheetUpdateInfo info ) { return sheetServices.updateInfo(info); } } <file_sep>/src/main/java/com/ismaiel/easysheet/repositories/SheetRepo.java package com.ismaiel.easysheet.repositories; import com.ismaiel.easysheet.entities.Entry; import com.ismaiel.easysheet.entities.Sheet; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface SheetRepo extends JpaRepository<Sheet, Long>{ } <file_sep>/src/main/resources/application1.properties spring.datasource.url=jdbc:mysql://localhost/db_example spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.enable_lazy_load_no_trans: true<file_sep>/src/main/java/com/ismaiel/easysheet/models/RichShare.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ismaiel.easysheet.models; /** * * @author Ismaiel */ public class RichShare { private long entryId; private String entryName; private long shareId; private double amount; public RichShare() { } public RichShare(long entryId, String entryName, long shareId, double amount) { this.entryId = entryId; this.entryName = entryName; this.shareId = shareId; this.amount = amount; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } public String getEntryName() { return entryName; } public void setEntryName(String entryName) { this.entryName = entryName; } public long getShareId() { return shareId; } public void setShareId(long shareId) { this.shareId = shareId; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } } <file_sep>/src/main/java/com/ismaiel/easysheet/models/SheetUpdateInfo.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ismaiel.easysheet.models; /** * * @author Ismaiel */ public class SheetUpdateInfo { private long id; private String password; private String newPassword; private String newViewPassword; public SheetUpdateInfo() { } public SheetUpdateInfo(long id, String password, String newPassword, String newViewPassword) { this.id = id; this.password = <PASSWORD>; this.newPassword = newPassword; this.newViewPassword = newViewPassword; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } public String getNewViewPassword() { return newViewPassword; } public void setNewViewPassword(String newViewPassword) { this.newViewPassword = newViewPassword; } } <file_sep>/src/main/java/com/ismaiel/easysheet/repositories/EntryRepo.java package com.ismaiel.easysheet.repositories; import com.ismaiel.easysheet.entities.Entry; import com.ismaiel.easysheet.entities.Member; import com.ismaiel.easysheet.entities.Sheet; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public interface EntryRepo extends JpaRepository<Entry, Long> { public List<Entry> findBySheet(Sheet sheet); // @Transactional // @Query(value = "DELETE * FROM MEMBER WHERE SHEET_ID = ?1", nativeQuery = false) // public void deleteBySheetId(long id); @Transactional Long deleteBySheetId(long id); public List<Entry> findByCreditor(Member member); }
081617b70e2796b02b17215620f62e30bd3a5cb5
[ "Java", "INI" ]
11
Java
ismaiel-nosairat/EasySheet
7e3601fbee742436ffab988136a2ef88bf2417c9
1eba95d0947298f8b877326b381575ed22cdfe71
refs/heads/master
<file_sep>// // LeptirFrameTests.swift // LeptirFrameTests // // Created by jakouk on 2017. 7. 3.. // Copyright © 2017년 jakouk. All rights reserved. // import XCTest import LeptirFrame class LeptirFrameTests: XCTestCase { func testViewLeft_get() { let view = UIView() view.frame.origin.x = 150 XCTAssertEqual(view.left, 150) } func testViewLeft_set() { let view = UIView() view.left = 100 XCTAssertEqual(view.frame.origin.x, 100) } func testViewTop_get() { let view = UIView() view.frame.origin.y = 200 XCTAssertEqual(view.top, 200) } func testViewTop_set() { let view = UIView() view.top = 50 XCTAssertEqual(view.frame.origin.y, 50) } // 미션: // 아래 두 테스트 케이스가 통과되도록 만들어보세요. func testViewRight_get() { let view = UIView() view.width = 100 view.height = 50 view.frame.origin.x = 70 XCTAssertEqual(view.right, 100+70) } func testViewRight_set() { let view = UIView() view.width = 100 view.height = 50 view.right = 130 XCTAssertEqual(view.frame.origin.x, 130-100) } func testViewBottom_get() { let view = UIView() view.width = 100 view.height = 50 view.frame.origin.y = 70 XCTAssertEqual(view.bottom, 50 + 70 ) } func testViewBottom_set() { let view = UIView() view.width = 100; view.height = 50 view.bottom = 130 XCTAssertEqual(view.frame.origin.y, 130 - 50) } func testViewQuter_get() { let view = UIView() view.width = 200 XCTAssertEqual(view.quter, view.width / 4) } func testViewQuter_set() { let view = UIView() view.quter = 50 XCTAssertEqual(view.width , 50 * 4) } func testViewTenth_get() { let view = UIView() view.width = 150 XCTAssertEqual(view.tenth, view.width / 10) } func testViewTenth_set() { let view = UIView() view.tenth = 15 XCTAssertEqual(view.width, 15 * 10) } } <file_sep># LeptirFrame [![Build Status](https://travis-ci.org/jakouk/LeptirFrame.svg?branch=master)](https://travis-ci.org/jakouk/LeptirFrame) UIView extension
659f3f53dde5aecff886355097bde1fd69ab5ffa
[ "Swift", "Markdown" ]
2
Swift
jakouk/LeptirFrame
9dd0a9da489930a3d3cf00a200b1b9caba3734c2
0973f93a2d0ec4d209bf2cbfecb575205801b99a
refs/heads/master
<repo_name>Kocal/validator<file_sep>/README.md Validator ========= [![Build Status](https://travis-ci.org/Kocal/validator.svg?branch=master)](https://travis-ci.org/Kocal/validator) A PHP values validator that makes you able to use the great [Laravel Validator](https://laravel.com/docs/master/validation), but outside a Laravel project. Installation ------------ ```bash $ composer require kocal/validator ``` Usage ----- All Laravel validation rules except [exists](https://laravel.com/docs/master/validation#rule-exists) and [unique](https://laravel.com/docs/master/validation#rule-unique) are supported. ```php <?php use Kocal\Validator\Validator; $rules = ['field' => 'required|min:5']; $data = ['field' => 'Validation']; $validator = new Validator($rules); $validator->validate($data); $validator->passes(); // true $validator->fails(); // false $validator->errors()->toArray(); // returns array of error messages ``` Advanced usage -------------- ### Translations Available validation translation languages: see [src/lang](src/lang) directory. The default language is `fr`. ```php <?php use Kocal\Validator\Validator; $validator = new Validator([], 'es'); ``` ### Custom validation rule ```php <?php use Kocal\Validator\Validator; $validator = new Validator(['field' => 'is_foo']); $validator->extend('is_foo', function ($attribute, $value, $parameters, $validator) { return $value == 'foo'; }, "Le champ :attribute n'est pas égal à 'foo'."); $validator->validate(['field' => 'not_foo']); ``` <file_sep>/src/Validator.php <?php namespace Kocal\Validator; use Illuminate\Container\Container; use Illuminate\Filesystem\Filesystem; use Illuminate\Translation\FileLoader; use Illuminate\Translation\Translator; use Illuminate\Validation\Factory; class Validator { /** * @var string */ private $locale; /** * @var Factory */ private $validatorFactory; /** * @var array */ private $rules; /** * @var \Illuminate\Validation\Validator */ private $validator; /** * Validator constructor. * * @param array $rules * @param string $locale * @param string|null $fallback */ public function __construct(array $rules = [], $locale = 'fr', $fallback = null) { $this->rules = $rules; $this->locale = $locale; $loader = new FileLoader(new Filesystem(), __DIR__ . '/lang'); $translator = new Translator($loader, $this->locale); if ($fallback !== null) { $translator->setFallback($fallback); } $this->validatorFactory = new Factory($translator, new Container()); } /** * Register a custom validator extension. * * @param string $rule * @param \Closure|string $extension * @param string $message * * @return void */ public function extend($rule, $extension, $message = null) { $this->validatorFactory->extend($rule, $extension, $message); } /** * @param array $data * @param array $messages * @param array $customAttributes */ public function validate(array $data, array $messages = [], array $customAttributes = []) { $this->validator = $this->validatorFactory->make($data, $this->rules, $messages, $customAttributes); } /** * @return bool */ public function passes() { return $this->validator->passes(); } /** * @return bool */ public function fails() { return $this->validator->fails(); } /** * @return \Illuminate\Support\MessageBag */ public function errors() { return $this->validator->errors(); } /** * @param array $rules */ public function setRules(array $rules) { $this->rules = $rules; } /** * @return string */ public function getLocale() { return $this->locale; } } <file_sep>/spec/Validator.spec.php <?php namespace Kocal\Spec; use Kocal\Validator\Validator; use Symfony\Component\HttpFoundation\File\UploadedFile; describe(Validator::class, function () { it('should validate', function () { $validator = new Validator([ 'foo' => 'required|min:4', 'users.*.id' => 'required|distinct|integer', 'users.*.email' => 'required|distinct|email', ]); $validator->validate([ 'foo' => 'hello', 'users' => [ ['id' => 1, 'email' => '<EMAIL>'], ['id' => 2, 'email' => '<EMAIL>'], ], ]); expect($validator->passes())->toBeTruthy(); expect($validator->errors()->toArray())->toBeEmpty(); }); it('should not validate', function () { $validator = new Validator(['foo' => 'required']); $validator->validate([]); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'foo' => ["Le champ foo est obligatoire."], ]); }); it('should use custom error messages', function () { $validator = new Validator([ 'foo' => 'required', 'bar' => 'min:10', ]); $validator->validate(['bar' => 'foo'], [ 'required' => 'Le champ :attribute est réellement obligatoire.', 'bar.min' => "Un message d'erreur customisé.", ]); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'foo' => ["Le champ foo est réellement obligatoire."], 'bar' => ["Un message d'erreur customisé."], ]); }); it('should use custom attributes', function () { $validator = new Validator(['foo' => 'required']); $validator->validate([], [], ['foo' => 'FOO']); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'foo' => ["Le champ FOO est obligatoire."], ]); }); it('should use custom rule', function () { $validator = new Validator(['foo' => 'is_foo']); $validator->extend('is_foo', function ($attribute, $value, $parameters, $validator) { return $value == 'foo'; }, "Le champ :attribute n'est pas égal à 'foo'."); $validator->validate([ 'foo' => 'not_foo', ]); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'foo' => ["Le champ foo n'est pas égal à 'foo'."], ]); }); it('should use english translation', function () { $validator = new Validator(['foo' => 'max:3', 'email' => 'email'], 'en'); $validator->validate(['foo' => 'hello', 'email' => 'not-an-email']); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'foo' => ["The foo may not be greater than 3 characters."], 'email' => ["The E-mail address must be a valid email address."], ]); }); it('should use fallback translation', function () { $nonExistingLocale = 'foobar'; $fallbackLocale = 'en'; $validator = new Validator(['email' => 'email'], $nonExistingLocale, $fallbackLocale); $validator->validate(['email' => 'not-an-email']); expect($validator->fails())->toBeTruthy(); expect($validator->errors()->toArray())->toBe([ 'email' => ["The E-mail address must be a valid email address."], ]); }); it('should validate uploaded file', function () { $uploadedFile = new UploadedFile(__DIR__ . '/fixtures/image.png', null, null, null, null, true); $validator = new Validator(['a' => 'file|dimensions:width=20,height=20']); $validator->validate(['a' => $uploadedFile]); expect($validator->passes())->toBeTruthy(); }); });
5c3ac75c6945de550ee296c57aeef1fa812f4c5a
[ "Markdown", "PHP" ]
3
Markdown
Kocal/validator
bb89dabc90101de7a1cb56582c0ec008b4a7d949
3b6ff3ee3bf22cbae73b1a408e45189be7fb43c5
refs/heads/master
<file_sep>import numpy as np training_inputs = np.array([[0,0,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,1,0,0], [1,0,1,1,0,1,1,1,1,1], [1,0,1,0,1,0,1,1,0,0], [1,0,0,0,1,1,0,0,1,1], [1,0,0,1,0,1,0,1,1,1], [0,1,1,0,1,1,0,1,0,0], [1,0,1,0,0,1,0,0,0,1], [1,1,0,1,0,0,1,1,0,0]]) training_outputs = np.array([[0,0,1,1,0,0,1,1,0]]).T print (training_inputs) print (training_outputs) def nonlin(x, deriv=False): if deriv==True: return x*(1-x) return 1/(1+ np.exp(-x)) np.random.seed(1) synaptic_weight=2*np.random.random((10,1))-1 for iter in range(20000): gettrain=nonlin(np.dot(training_inputs,synaptic_weight)) training_error = training_outputs - gettrain #multiply how much we missed with the slope of the sigmoid(nonlinear) train_delta= training_error * nonlin(gettrain,True) synaptic_weight += np.dot(training_inputs.T,train_delta) test_array= np.array([1,1,0,1,1,1,1,1,1,1]) print (nonlin(np.dot(test_array,synaptic_weight))) <file_sep># Perceptron Just a simple neural network I built. Working to expand my knowledge on the subject and progress to multi layer perceptrons ## Language(s) used: Python ## Overview Neural Networks are a foundation upon which Data Science is built one. They come in layers of inputs and after giving your model some training values based on your set of rules and training it against it's output, it will be trained against those inputs for a number of iterations and then will be able to accurately predict outputs for a number of inputs, based on the same rules. As long as the rule given is a linearly seperable problem, a single perceptron will be able to give accurate results ## Dependancies Numpy module ## Author <NAME> ## Language(s) Python ## License This project is protected by the MIT License
d98dcfda4fc6e11fd92b159aad81f8fee98a768b
[ "Markdown", "Python" ]
2
Python
MSJawad/perceptron
fe7be01767b5e25206e6e38825c0584272722b8b
96cf5e33e4f4bf9b71ec5d27e4227b23cbb9ed71
refs/heads/master
<file_sep> // Custom store variables go here var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1KO--qj4tmVaqSnxhbgHhlx_ttqviLBzct5e9sYgDBNU/edit?usp=sharing'; var publicSpreadsheetUrl = 'https://cors-anywhere.herokuapp.com/https://docs.google.com/spreadsheets/d/e/2PACX-1vQcaCBt2SjGSZHUqV9TyDoV66FyYZCGr6SPNgYoyKCjpqcobDMl0ip7D9GZPpICXWqdrFM3l_tf8I_1/pub?output=csv'; var publicSpreadsheetUrl = 'https://storage.googleapis.com/mobicompra-public/rapipedido_prod.csv'+"?rand="+Math.floor(Math.random() * 100000); var phone_num = '584147660652'; // Set up Currency.js const USD = value => currency(value, { formatWithSymbol: false, precision: 2 }); const VEF = value => currency(value, { symbol: "Bs ", formatWithSymbol: false, precision: 0 }); const USD_with_symbol = value => currency(value, { formatWithSymbol: true, precision: 2 }); const VEF_with_symbol = value => currency(value, { symbol: "Bs ", formatWithSymbol: true, precision: 0 }); function init() { console.log("version 0.18"); Papa.parse(publicSpreadsheetUrl, { download: true, header: true, downloadRequestHeaders: {'origin': 'x-requested-with'}, complete: showInfo }) // Facebook Pixel Configuration // Initiate Checkout var button = document.getElementById("btn_order"); button.addEventListener( "click", function() { fbq("track", "InitiateCheckout"); }, false ); // Add to cart document.querySelectorAll(".btnplus").forEach(item => { item.addEventListener("click", event => { fbq("track", "AddToCart"); }) }); } function validProduct(item) { if (item["Precio Bs F"] != "" && item.Marca != "" && item.Imagen != "" && item.Titulo != "" && item.Descripcion != "" && item["Unidades en stock"] != "" && item["Unidades en stock"] != "#VALUE!" && item["Precio Bs F"] != "#VALUE!") { return true; } else { return false; } } function showInfo(data, tabletop) { console.log(data.data); $(".spinner").remove(); var parsed = ""; var stock = ""; var precio = ""; let lista = document.getElementById('lista'); var i = 0; $.each(data.data, function (y, item) { $.trim(item["Precio Bs F"] = item["Precio Bs F"]); $.trim(item["Precio USD"] = item["Precio USD"]); $.trim(item["Unidades en stock"] = item["Unidades en stock"]); $.trim(item.Marca = item.Marca); $.trim(item.Titulo = item.Titulo); $.trim(item.Descripcion = item.Descripcion); if (validProduct(item)) { stock = item["Unidades en stock"]; precio = VEF_with_symbol(item["Precio Bs F"]).format(); precio_secondary = USD_with_symbol(item["Precio USD"]).format(); if ($.isNumeric(parseInt(stock))) { //if(isNumberDot(precio) && $.isNumeric(parseInt(stock))){ parsed += "<div class='item'><div class='div-item-img'>"; if (item["Unidades en stock"] > 0) { parsed += "<img class='item-img'"; parsed += " src='https://ik.imagekit.io/og4bb9cly5/" + encodeURIComponent(item.Imagen) + "?tr=w-200,h-200'></div>"; parsed += "<div class='item-desc'><h3 class='desc'>" + item.Marca + " " + item.Titulo + "</h3>"; parsed += "<p>" + item.Descripcion + "</p>"; parsed += "<input type='text' name=" + item.Titulo + " class='price' value='" + precio + "' disabled='True'><input type='text' class='price-secondary' value='" + precio_secondary + "' ' disabled='True'></div>"; parsed += "<div class='item-qtd'><input type='button' class='btn' id='minus' value='-' onclick='process(-1," + i + ", " + stock + ")' />"; parsed += "<input name='quant' class='quant' size='1' type='text' value='0' disabled='True' />"; parsed += "<input type='button' class='btn btnplus' id='plus' value='+' onclick='process(1," + i + ", " + stock + ")'><br>"; parsed += "</div></div>"; } else { // OOS Items parsed += "<img class='item-img-out'"; parsed += " src='https://ik.imagekit.io/og4bb9cly5/" + encodeURIComponent(item.Imagen) + "?tr=w-200,h-200' width='88' height='88'></div>"; parsed += "<div class='item-desc'><h3 class='desc outofstock'>" + item.Marca + " " + item.Titulo + "</h3>"; parsed += "<p class='outofstock'>" + item.Descripcion + "</p>"; parsed += "<input type='text' class='price outofstock' value='" + precio + "' disabled='true'><input type='text' class='price-secondary' value='" + precio_secondary + "' ' disabled='True'></div>";; parsed += "<div class='item-qtd'>"; parsed += "<input name='quant' class='quant outofstock' size='1' type='text' value='0' disabled='True' />"; parsed += "<br>"; parsed += "</div></div>"; } i++; } } }); document.getElementById('lista').innerHTML = parsed; } function process(update_delta, i, max) { // Update Available Stock var qty_available = parseInt(document.getElementsByClassName("quant")[i].value); qty_available += update_delta; console.log("QTY Available after click: " + qty_available); if (qty_available < 0) { document.getElementsByClassName("quant")[i].value = 0; } else if (qty_available > max) { document.getElementsByClassName("quant")[i].value = max; } else { document.getElementsByClassName("quant")[i].value = qty_available; } // Recalculate Total Cart Amount var t = 0; for (var y = 0; y < document.getElementsByClassName("quant").length; y++) { console.log("VEF Amount:" + VEF_with_symbol(document.getElementsByClassName("price")[y].value) + " - Pre-parsing: " + document.getElementsByClassName("price")[y].value); console.log("Y:" + y + " Total:" + t) t = t + (parseInt(document.getElementsByClassName("quant")[y].value) * VEF_with_symbol(document.getElementsByClassName("price")[y].value).value); }; // Add price to nav bar document.getElementById("total-primary").value = VEF_with_symbol(t).format(); // Recalculate Total Cart Amount - Secondary var t_secondary = 0; for (var y = 0; y < document.getElementsByClassName("quant").length; y++) { t_secondary = t_secondary + (parseInt(document.getElementsByClassName("quant")[y].value) * USD_with_symbol(document.getElementsByClassName("price-secondary")[y].value).value); } // Add price to nav bar - Secondary document.getElementById("total-secondary").value = USD_with_symbol(t_secondary).format(); // Rewrite message msg(); } function msg() { var d = new Date(); var months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]; var base_url = "https://wa.me/" + phone_num + "/?text=" var msg = "*PEDIDO* - Fecha " + d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear(); for (var y = 0; y < document.getElementsByClassName("quant").length; y++) { if (parseInt(document.getElementsByClassName("quant")[y].value) > 0) { msg += "\r\n" + document.getElementsByClassName("quant")[y].value + "x " + document.getElementsByClassName("desc")[y].textContent; } } msg += "\r\n\r\n" + "*Total*: " + VEF_with_symbol(document.getElementById("total-primary").value).format(); msg += " | " + USD_with_symbol(document.getElementById("total-secondary").value).format(); msg += "\r\n\r\n" + "Tu pedido no está confirmado,\r\nespera una respuesta para la confirmación." // Add new text to message document.getElementById("btn_order").href = base_url + encodeURIComponent(msg); } window.addEventListener('DOMContentLoaded', init)
a0dd9d894ec2ee9cc90305f6dd6294a12d84ff2d
[ "JavaScript" ]
1
JavaScript
rapipedido/rapipedido.github.io
cc86ae4d7c6199cd8a6e4aa6b59d6e0f84808db8
ce376280abfba514e24b4b25eb6b092d1dc5de77
refs/heads/master
<repo_name>user11681/crypto<file_sep>/charshift #!node const numshift = require("./numshift").numshift; exports.charshift = function(char, shift) { return numshift(char, (shift.toUpperCase().charCodeAt() - 65) % 26); } if (require.main === module) { if (process.argv.length < 4) { throw `required 2 arguments instead of ${process.argv.length - 2}`; } console.log(exports.charshift(process.argv[2], process.argv[3])); } <file_sep>/vigenere #!node const charshift = require("./charshift").charshift; const validate = require("./numshift").validate; exports.vigenere = function(text, key) { let ciphertext = ""; let j = 0; for (const char of text) { ciphertext += charshift(char, key[j]); if (validate(char)) { j = (j + 1) % key.length; } } return ciphertext; } if (require.main === module) { const argv = process.argv; argv.splice(0, 2); if (argv.length < 2) { throw `need at least 2 arguments instead of ${argv.length - 2}`; } let result = argv.shift(); for (let key = argv.shift(); key != null; key = argv.shift()) { result = exports.vigenere(result, key); } process.stdout.write(result); }
496a5e7e3b4f826fac0c9323fd7fdd4ea1f49fdf
[ "JavaScript" ]
2
JavaScript
user11681/crypto
632434d7b985fbe2e49b02aefe2a2ff208aaa6d4
898993a3dd7af0392eb0db2a0f5f5329b02ffe1a
refs/heads/master
<file_sep>"""" MQTT MongoDB Logger """ # Importing libraries import begin import logging import logging.config import mqtt.MQTTClient as mqtt import mongodb.MongoDBStore as mongo import socket socket.getaddrinfo('localhost', 8080) # Event logging configuration file. logging.config.fileConfig('logging.conf') @begin.start @begin.convert(mqttPort=int) def run(subChannel, mqttServer="localhost", mqttPort="1883", databaseServer="localhost:27017"): logger = logging.getLogger('root') logger.info("*** Starting to store MQTT messages to the database") db = mongo.MongoDBStore(databaseServer) logger.info("*** Connecting to mqtt and subscribe ***") mqttClient = mqtt.MQTTClient(mqttServer, int(mqttPort), db) # mqttClient.subscribe("SebHome/HugoRoom") mqttClient.subscribe(subChannel) logger.info("*** Log message ***") mqttClient.mainLoop() <file_sep>"""" MQTT Client """ # Importing libraries import datetime import json import logging.config import paho.mqtt.client as mqtt class Message: HOME_STR = "home" ROOM_STR = "room" DATA_STR = "data" logger = logging.getLogger('message') def __init__(self, home="", piece="", data=None): self.home = home self.piece = piece self.home = piece self.data = data def toDicData(self, key): data = {self.HOME_STR: self.home, self.ROOM_STR: self.piece, self.DATA_STR: self.data[key]} return data def toDicData(self): data = {self.HOME_STR: self.home, self.ROOM_STR: self.piece, self.DATA_STR: self.data} return data def toString(self): return self.HOME_STR + ":" + self.home + " " + self.ROOM_STR + ":" + self.piece + " " + self.DATA_STR + str( self.data) def addData(self, key, v): self.data[key] = v def loadJSON(self, strJSON): dictJson = json.loads(strJSON) self.home = dictJson[HOME_STR] self.piece = dictJson[ROOM_STR] self.data = dictJson[DATA_STR] self.logger.debug(self.toString()) def loadMQTTMsg(self, topic, bJSON): t = topic.split('/') self.home = t[0] self.piece = t[1] s = str(bJSON) s = s[2:len(s) - 1] self.data = json.loads(s) self.data["date"] = datetime.datetime.utcnow() self.logger.debug(self.toString()) class MQTTClient: client = mqtt.Client() logger = logging.getLogger('mqtt') def __init__(self, server="localhost", port=1883, database=None): self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.connect(server, port, 60) self.database = database def subscribe(self, channel): # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. self.client.subscribe(channel) # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): self.logger.info("Connected with result code " + str(rc)) # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): self.logger.debug(msg.topic + " " + str(msg.payload)) message = Message() message.loadMQTTMsg(msg.topic, msg.payload) self.database.addMessage(message) def loop(self): # Blocking call that processes network traffic, dispatches callbacks and handles reconnecting. self.client.loop_forever() <file_sep>"""" MongoDB Store """ # Importing libraries from pymongo import MongoClient from pymongo.errors import ConnectionFailure, InvalidName import logging.config class MongoDBStore: logger = logging.getLogger('database') def __init__(self, server='localhost:27017'): try: self.client = MongoClient(server) self.logger.info("database connnection ok") except ConnectionFailure as e: self.logger.error("database connection failure") except Exception as e: self.logger.error("database connection failure with unknow exeception") def addMessage(self, message, databaseNameParam=None, collectionNameParam=None): database = None collection = None databaseName = databaseNameParam collectionName = collectionNameParam if databaseName == None: databaseName = message.home if collectionName == None: collectionName = message.piece self.logger.debug("database: " + databaseName) self.logger.debug("collection: " + collectionName) try: database = self.client[databaseName] except InvalidName as e: self.logger.error("unable to open the database:" + databaseName) try: collection = database[collectionName] except InvalidName as e1: self.logger.error("impossible to open the collection:" + collectionName) self.logger.debug("attempt to insert:") messageId = collection.insert_one(message.data).inserted_id self.logger.debug("message inserted id: " + str(messageId)) self.logger.debug("insertion ok") <file_sep># MQTT MongoDB Logger in Python Stores MQTT Message to MongoDB
97e1908ec9bd34cace9e77e800d1e9c592731773
[ "Markdown", "Python" ]
4
Python
costaruan/mqtt-mongo-logger-in-python
fbaa798fd1e33b5b3d2991cbbc6e56d26f3a2b8c
f9dfec620314c6f87b41dd8be42dd2b541a81d0a
refs/heads/master
<file_sep>#ifndef ACCOUNT_H #define ACCOUNT_H #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <typeinfo> #include <sstream> #include <limits> using namespace std; class Account{ private: bool userExists; string inputCheck; int input; int balance; string username; string password; public: Account(); void makeAccount(); }; #endif // ACCOUNT_H <file_sep>#ifndef MENUSELECTOR_H #define MENUSELECTOR_H #include "account.h" using namespace std; class MenuSelector { private: Account newAccount; bool keepGoing; bool foundUser; int input; int balance; string username; string password; public: MenuSelector(); void menu1(); void menu2(const string& username, const string& password); }; #endif // MENUSELECTOR <file_sep>#include "account.h" #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <typeinfo> #include <sstream> #include <limits> using namespace std; Account::Account(){}; void Account::makeAccount() { ofstream myfile; myfile.open("userinfo.txt", ios::app); //append the text file cout << "Please Create a Username: "; //string inputCheck;//a string to compare name cin >> inputCheck; ifstream userCheck; // a input file stream variable userCheck.open("userinfo.txt"); //Open the file stream //check to see the if the username already exists. if (userCheck.is_open()) { userExists = false; while (userCheck >> username >> password) { if (inputCheck == username) { userExists = true; break; userCheck.close(); myfile.close(); } } if (userExists) { cout << "User already exists" << endl; userCheck.close(); myfile.close(); } else { cout << "Please Create a Password: "; cin >> password; balance = 0; myfile << inputCheck << ' ' << password << ' ' << balance << endl; myfile.close(); userCheck.close(); cout << "User account '" << inputCheck << "' has been created" << endl; } //ends create a password else } //ends if userCheck is open }; <file_sep>#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <typeinfo> #include <sstream> #include <limits> #include "account.h" #include "MenuSelector.h" using namespace std; int main() { MenuSelector newMenu; newMenu.menu1(); }; <file_sep>#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <typeinfo> #include <sstream> #include <limits> #include "MenuSelector.h" using namespace std; MenuSelector::MenuSelector(){}; void MenuSelector::menu1() { while (keepGoing) { cout << ("1.Login\n2.Create Username and Password\n3.Exit") << endl; cin >> input; /////////////////////////////////////////////////////////// if (input == 1) { //LOGIN!!! //open the file ifstream user("userinfo.txt"); //CRETE IFSTREAM if (user.is_open()) { //get the username string checkUser; string checkPass; cout << "Enter username: " << endl; cin >> checkUser; bool foundUser = false; while (user >> username >> password >> balance) { if (checkUser == username) { foundUser = true; user.close(); break; } } if (foundUser) { cout << "Password: " << endl; cin >> checkPass; //get user input if (checkPass == password) { //if the password is correct cout << "Welcome back, " << username << endl; //User is logged in //menu2(checkUser, checkPass);// <-------- LOOK HERE NIGGA!*!*!*!*!*!*!*!*!* user.close(); foundUser = false; menu2(checkUser, checkPass); //put in the menu 2 function } else if (checkPass != password) { //If pass is incorrect cout << "Password incorrect." << endl; //Denied user.close(); } //end else if } //end if else { cout << "Error, could not find user" << endl; user.close(); } //end if is open } else { cout << "Unable to open file" << endl; } user.close(); } //end input 1 //end first conditional statement /////////////////////////////////////////////////////////////////////// else if (input == 2) { ; newAccount.makeAccount(); } else if (input == 3) { keepGoing = false; } else if (!(cin >> input)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input" << endl; } } } void MenuSelector::menu2(const string& username, const string& password) { bool loggedIn; loggedIn = true; string line; string checkUser = username; string checkPass = <PASSWORD>; int currentBalance; while (loggedIn) { cout << "1.Check Balance\n2.Deposit\n3.Withdraw\n4.Logout" << endl; cin >> input; if (input == 1) { string checkUser = username; //set checkUser var equal to username var ifstream myfile("userinfo.txt"); while (myfile >> checkUser >> checkPass >> balance) { if (checkUser == username) { cout << "Current Balance: " << endl; cout << "$" << balance << endl; myfile.close(); } } } else if (input == 2) { //deposit string checkUser = username; //set checkUser var equal to username var string checkPass = <PASSWORD>; ofstream outfile("pleasework.txt"); ifstream infile("userinfo.txt"); //CREATING IFSTREAM string u, p, b; int deposit; cout << "How much do you want to deposit?" << endl; //cin>>deposit; if (!(cin >> deposit)) { //If the input is not equal to the data type of deposit cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input" << endl; } else { while (infile >> u >> p >> b) { //cout<<"PLeae"<<endl; //cout<<u<<' '<<p<<' '<<b<<endl; if (checkUser == u) { int newBalance; //cout<<"Current Balance: $"<<b<<endl; //cout<<"Enter new balance: "; cout << "Your amount of $" << deposit << " has been added to your account" << endl; int fileBalance; stringstream convert(b); //object from the class stringstream convert >> fileBalance; //the objects has the value of B and newBalance = fileBalance + deposit; outfile << checkUser << ' ' << checkPass << ' ' << newBalance << endl; } else { outfile << u << ' ' << p << ' ' << b << endl; //end else } } //end while infile.close(); outfile.close(); remove("userinfo.txt"); char oldname[] = "pleasework.txt"; char newname[] = "userinfo.txt"; rename(oldname, newname); } } else if (input == 3) { string checkUser = username; //set checkUser var equal to username var string checkPass = <PASSWORD>; ofstream outfile("pleasework.txt"); ifstream infile("userinfo.txt"); //CREATING IFSTREAM string u, p, b; int withdraw; cout << "How much do you want to withdraw?" << endl; if (!(cin >> withdraw)) { //If the input is not equal to the data type of deposit cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input" << endl; } else { while (infile >> u >> p >> b) { if (checkUser == u) { int newBalance; int fileBalance; stringstream convert(b); //object from the class stringstream convert >> fileBalance; //the objects has the value of B and newBalance = fileBalance - withdraw; if (newBalance < 0) { cout << "Error: Balance cannot go below zero" << endl; newBalance = fileBalance; } else if (newBalance >= 0) { cout << "Your amount of $" << withdraw << " has been withdrawn your account" << endl; outfile << checkUser << ' ' << checkPass << ' ' << newBalance << endl; } } else { //second part of original if statement outfile << u << ' ' << p << ' ' << b << endl; } //end else } //end while infile.close(); outfile.close(); remove("userinfo.txt"); char oldname[] = "pleasework.txt"; char newname[] = "userinfo.txt"; rename(oldname, newname); } } else if (input == 4) { cout << "Thank you, " << username << ". You have successfully logged out" << endl; loggedIn = false; // foundUser = false; menu1(); } else { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input" << endl; } } }; <file_sep>#<NAME> #CS 240 #Makefile for final project BankAccount: main.o MenuSelector.o account.o g++ main.o MenuSelector.o account.o -o BankAccount main.o: main.cpp MenuSelector.h account.h g++ -c main.cpp MenuSelector.o: MenuSelector.cpp MenuSelector.h g++ -c MenuSelector.cpp account.o: account.cpp account.h g++ -c account.cpp clean: rm -f *.o rm BankAccount
6d347683b86abf3ba872f3f5c52803b2fd154536
[ "Makefile", "C++" ]
6
C++
cmparks10/Bank-Teller-Machine
eb7b7dc7a40ea8ccdcb28b1eb1ab75b76489f914
5b5f3577332ef0de59e4b1991617fb695e0e87d7
refs/heads/master
<file_sep> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope,$http) { /*$scope.firstName = "Umesh"; $scope.lastName = "Joshi"; $scope.fullName = function(){ return $scope.firstName.toUpperCase()+" "+ $scope.lastName; }*/ $scope.sortDir = false; $http.get("http://services.groupkt.com/country/get/all"). then(function(response) { $scope.countryData = response.data.RestResponse.result; }, function(error) { $scope.countryData = error.data; }) $scope.paging = function(input){ $scope.pageSize = input; $scope.currentPage = 0; $scope.numberOfPages= function(){ return Math.ceil($scope.countryData.length/$scope.pageSize); } } $scope.orderPattern = function(parameter){ $scope.orderByPattern = parameter; /*if($scope.sortDir===false){ $scope.sortDir = true; } else{ $scope.sortDir = false; }*/ $scope.sortDir = !$scope.sortDir; } $scope.addCountry = function(name,alpha2_code,alpha3_code){ var newCountry = { name: name, alpha2_code: alpha2_code, alpha3_code: alpha3_code }; $scope.countryData.push(newCountry); alert("Country has been added successfully"); } $scope.removeCountry = function(index){ if(confirm("Do you want to remove this country?") == true){ $scope.countryData.splice(index,1); } } $scope.showEditDiv = false; $scope.editCountry = function(index,name,alpha2_code,alpha3_code){ $scope.showEditDiv = true; if(confirm("Do you want to edit this country?") == true){ $scope.editName = $scope.countryData[index].name; $scope.editAlpha2 = $scope.countryData[index].alpha2_code; $scope.editAlpha3 = $scope.countryData[index].alpha3_code; $scope.indexToEdit = index; } } $scope.saveCountryChanges = function(){ $scope.countryData[$scope.indexToEdit].name = $scope.editName; $scope.countryData[$scope.indexToEdit].alpha2_code = $scope.editAlpha2; $scope.countryData[$scope.indexToEdit].alpha3_code = $scope.editAlpha3; $scope.showEditDiv = false; } }); app.filter('startFrom', function() { return function(input, start) { //first parameter i.e. input is the countryData and second parameter that comes from the html page start = +start; return input.slice(start); } });
3bda58f29357a8b5abe13e52d6e9ad70c7603e70
[ "JavaScript" ]
1
JavaScript
umesh2311/FirstAngularApp
f89a7cf8cb245dbad48bbf32e5f1ba2816b08cd0
c86174f3fa50ed0ea7a29d586e69af6c9103c989
refs/heads/master
<repo_name>Light413/kk<file_sep>/Podfile platform :ios,7.0 target "kantu" do pod 'AFNetworking', '3.1.0' pod 'Masonry', '~> 1.0.1' pod 'LKDBHelper', '~> 2.3.1' end <file_sep>/kantu/constants.h // // constants.h // kantu // // Created by gener on 16/7/19. // Copyright © 2016年 Light. All rights reserved. // #ifndef constants_h #define constants_h #define IMGFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"imgcache"] #define DefaultBgColor [UIColor colorWithRed:0.957 green:0.961 blue:0.965 alpha:1] #define CURRNET_SCREEN_WIDTH [[UIScreen mainScreen]bounds].size.width #define CURRENT_SCREEN_HEIGHT [[UIScreen mainScreen]bounds].size.height #endif /* constants_h */
a58301fd86a0a934147acfd8acf4856e08f9fabc
[ "C", "Ruby" ]
2
Ruby
Light413/kk
c353f823cbc4c43318052900c2ab0b48b06e861a
cbbeedd5681a8ff21487f1c9da55c5e6c3cfb68b
refs/heads/master
<repo_name>Feronik/django-project<file_sep>/weather/views.py from django.shortcuts import render from weather.models import City from weather.forms import CityForm import requests appid = "b69ed4124e0f156cae7e3b36ee2dda57" def weather(request): form = CityForm(request.POST) if request.method == "POST" and form.is_valid(): post_name = request.POST['city'] post_date = request.POST['date'] if City.objects.filter(city_name=post_name, weather_date=post_date).exists(): filter_weath = City.objects.filter(weather_date=post_date, city_name=post_name) message = 'Данные из базы' else: res = requests.get('http://api.openweathermap.org/data/2.5/forecast', params={'q': post_name, 'units': 'metric', 'lang': 'ru', 'APPID': appid}) json_object = res.json() weath = [] for objects in json_object['list']: if str((objects['dt_txt'])[:10]) == post_date: data_str = str((objects['dt_txt'])[:16]) + " " + str('{0:+3.0f}'.format(objects['main']['temp'])) + \ " C " + str(objects['weather'][0]['description']) weath.append(data_str) data_object = City(city_name=post_name, weather_temperature='{0:+3.0f}'.format(objects['main']['temp']), weather_sky=objects['weather'][0]['description'], weather_date=(objects['dt_txt'])[:10]) data_object.save() return render(request,'weather/weather.html', locals())<file_sep>/weather/forms.py from django import forms class CityForm(forms.Form): city = forms.CharField(max_length=100) date = forms.DateField()<file_sep>/weather/models.py from django.db import models class City(models.Model): city_name = models.CharField(max_length=100) weather_temperature = models.IntegerField(blank=True, null=True) weather_sky = models.CharField(max_length=50, default='') weather_date = models.DateTimeField() def __str__(self): return self.city_name
cd9a51623cd255f6ea8c891faa2e1d13a449c323
[ "Python" ]
3
Python
Feronik/django-project
c98f962fdbc4b7cc865b2d2e7f8a299549f911b3
a6330a85bafc2ab7ec232cad86b78183c9caa144
refs/heads/master
<repo_name>ravikanthAtGeospark/GO-JEKiOS<file_sep>/GO-JEKiOS/Utility/GoUtility.swift // // GoUtility.swift // GO-JEKiOS // // Created by GeoSpark Mac #1 on 30/05/19. // Copyright © 2019 GeoSpark, Inc. All rights reserved. // import Foundation <file_sep>/GO-JEKiOS/DataManager/DataManager.swift // // DataManager.swift // GO-JEKiOS // // Created by GeoSpark Mac #1 on 30/05/19. // Copyright © 2019 GeoSpark, Inc. All rights reserved. // import UIKit class DataManager: NSObject { }
7c663cf700d34ef2ff9810e008e608960d6e7b25
[ "Swift" ]
2
Swift
ravikanthAtGeospark/GO-JEKiOS
72c53d37819faad5dc4a624522e4f6ce5c420714
b0781dd13e6a41952cda5148ce7dc773eb466f29
refs/heads/master
<repo_name>what1995/2DGP-PROJECT<file_sep>/Project/Reimu/Reimu-Damage-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuDamage = load_image('ReimuDamage-Motion.png') def Reimu_Damage(): frame = 0 cheak=0 while(cheak<3): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 ReimuDamage.clip_draw(frame *109,0,110,90,Enemy_X,All_Y) #플레이어 ReimuDamage.clip_draw(frame *112,90,110,90,Player_X,All_Y) frame=(frame+1)%3 update_canvas() delay(0.2) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Reimu_Damage() close_canvas() <file_sep>/Project/Tensi/Tenshi-Damage-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiDamage = load_image('TenshiDamage-Motion.png') def Tenshi_Damage(): frame=0 cheak=0 while(cheak<5): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiDamage.clip_draw(frame*80,0,78,115,Enemy_X,All_Y) #플레이어 TenshiDamage.clip_draw(frame*80,115,78,115,Player_X,All_Y) frame=(frame+1)%5 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Damage() close_canvas() <file_sep>/Project/Tensi/Tenshi-Skill1-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiSkill1 = load_image('TenshiSkill1-Motion.png') TenshiSkill1effect = load_image('TenshiSkill1.png') def Tenshi_Skill1(): frame1 = [75,67,70,77,82,120,112,73,73,73,71,68,65,63,64] frame2 = [0,75,143,214,294,379,500,616,695,776,852,929,1006,1076,1146,1210] S_frame1 = [107,129,132,142,135,98,135] S_frame2 = [0,106,235,367,509,646,746,875] cheak=0 i=0 j=0 S1=0 S2=0 Sy=160 while(cheak<15): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiSkill1.clip_draw(frame2[i],0,frame1[j],160,Enemy_X,All_Y) #플레이어 TenshiSkill1.clip_draw(frame2[i],160,frame1[j],160,Player_X,All_Y) i=(i+1)%16 j=(j+1)%15 if cheak >7: #플레이어 TenshiSkill1effect.clip_draw(S_frame2[S1],0,S_frame1[S2],165,Enemy_X,All_Y+Sy) #적 TenshiSkill1effect.clip_draw(S_frame2[S1],0,S_frame1[S2],165,Player_X,All_Y+Sy) Sy -= 30 S1= (S1+1)%8 S2= (S2+1)%7 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Skill1() close_canvas() <file_sep>/Project/test/BackgroundSelection.py import game_framework import random from pico2d import * import DeckSelection import main_state import CharacterSelection #import CharacterSelection import game_world name = "backgroundSelection" Main=None logo =None BGbamboo = None BGHakureiShrine = None BGclocktower = None minibamboo = None miniHakureiShrine = None miniclocktower = None BGcheak=None cheak = None Level=None Level_Nomal=None Level_Hard=None Level_cheak=1 mouse_x,mouse_y=0,0 def enter(): global BGbamboo,BGHakureiShrine,BGclocktower,Main,minibamboo,miniHakureiShrine,miniclocktower,logo,Level,Level_Nomal,Level_Hard global cheak,BGcheak,Level_cheak Main= load_image('./FCGimage/Main.png') logo = load_image('./FCGimage/BackGround logo.png') BGbamboo = load_image('./FCGimage/BGbamboo.png') BGHakureiShrine = load_image('./FCGimage/BGHakurei Shrine.png') BGclocktower = load_image('./FCGimage/BGclock tower.png') minibamboo = load_image('./FCGimage/minibamboo.png') miniHakureiShrine = load_image('./FCGimage/miniHakurei Shrine.png') miniclocktower = load_image('./FCGimage/miniclock tower.png') cheak = load_image('./FCGimage/Character_Cheak.png') Level = load_image('./FCGimage/Level.png') Level_Nomal = load_image('./FCGimage/Level-Nomal.png') Level_Hard = load_image('./FCGimage/Level-hard.png') Level_cheak = 1 def exit(): global BGbamboo,BGHakureiShrine,BGclocktower def handle_events(): global mouse_x,mouse_y,BGcheak,Level_cheak events = get_events() for event in events: if event.type ==SDL_QUIT: game_framework.quit() if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y=event.x, 600- event.y else: if(event.type, event.key) == (SDL_KEYDOWN,SDLK_ESCAPE): game_framework.push_state(CharacterSelection) elif(event.type, event.button)==(SDL_MOUSEBUTTONDOWN,SDL_BUTTON_LEFT): if 50< mouse_x and mouse_x<250 and mouse_y<375 and mouse_y>225: BGcheak=0 game_framework.push_state(main_state) elif 300< mouse_x and mouse_x<500 and mouse_y<375 and mouse_y>225: BGcheak=1 game_framework.push_state(main_state) elif 550< mouse_x and mouse_x<750 and mouse_y<375 and mouse_y>225: BGcheak=2 game_framework.push_state(main_state) elif 260< mouse_x and mouse_x<440 and mouse_y<140 and mouse_y>60: Level_cheak=1 elif 510< mouse_x and mouse_x<690 and mouse_y<140 and mouse_y>60: Level_cheak = 2 def draw(): global mouse_x,mouse_y,BGcheak clear_canvas() Main.draw(400, 300) if 50< mouse_x and mouse_x<250 and mouse_y<375 and mouse_y>225: BGbamboo.draw(400, 300) cheak.draw(150,450) if 300< mouse_x and mouse_x<500 and mouse_y<375 and mouse_y>225: BGHakureiShrine.draw(400, 300) cheak.draw(400,450) if 550< mouse_x and mouse_x<750 and mouse_y<375 and mouse_y>225: BGclocktower.draw(400, 300) cheak.draw(650,450) minibamboo.draw(150,300) miniHakureiShrine.draw(400, 300) miniclocktower.draw(650, 300) logo.draw(400,550) Level.draw(100,100) Level_Nomal.draw(350,100) Level_Hard.draw(600,100) if Level_cheak ==1: Level_Nomal.draw(400, 400) elif Level_cheak ==2: Level_Hard.draw(400, 400) update_canvas() def update(): main_state.HPinit=1 def pause(): pass def resume(): pass <file_sep>/Project/Reimu/Reimu-Downs-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=175 ReimuDowns = load_image('Reimu-Downs-Motion.png') def Reimu_Down(): frame=[0,92, 172,272,369, 465, 576, 683, 784, 889, 970] frame2=[92,80,100,97,96,110,105,102,105,103,130] i=0 j=0 cheak=0 while(cheak<13): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #플레이어 ReimuDowns.clip_draw(frame[i],65,frame2[j],65,Player_X,All_Y) #적 ReimuDowns.clip_draw(frame[i],0,frame2[j],65,Enemy_X,All_Y) if(cheak<9): i=(i+1)%11 j=(j+1)%10 update_canvas() delay(0.3) cheak +=1 while(True): Reimu_Down() close_canvas() <file_sep>/Project/Player.py from pico2d import * import os os.chdir('C:\\2DGP\\2015180012-2DGP\\Project\\FCGimage') class BackGround: def __init__(self): self.x, self.y = 400, 300 self.backgroundselection = 1 self.Shrine = load_image('Hakurei Shrine.png') self.Bamboo = load_image('bamboo.png') self.Clock = load_image('clock tower.png') def draw(self): if self.backgroundselection ==1: self.Shrine.draw(self.x,self.y) if self.backgroundselection == 2: self.Bamboo.draw(self.x, self.y) if self.backgroundselection == 3: self.Clock.draw(self.x, self.y) class Player: def __init__(self): self.Player = 200 self.Enemy =600 self.All_Y=200 self.stat =10 ##10 레이무 20 이쿠 30 텐시 40 마리사 ######################STANDING################################## self.MStanding = load_image('MarisaStanding-Motion.png') self.RStanding = load_image('Reimu-Standing-Motion.png') self.IStanding = load_image('Iku-Standing-Motion.png') self.TStanding= load_image('TenshiStanding-Motion.png') self.Standi = 0 self.Standj = 0 self.Standcheak =0 self.frame=0 ######################SKILL1#################################### self.MSkill1 = load_image('MarisaSkill1-Motion.png') self.RSKill1 = load_image('Reimu-Skill1-Motion.png') self.ISkill1 = load_image('IkuSkill1-Motion.png') self.TSkill1 =load_image('TenshiSkill1-Motion.png') self.Skill1i = 0 self.Skill1j = 0 self.Skill1cheak = 0 self.MS1Effect = load_image('MarisaSkill1.png') self.RS1Effect = load_image('Reimu-Skill1.png') self.IS1Effect= load_image('IkuSkill1-1.png') self.IS1Effect2 =load_image('IkuSkill1-2.png') self.TS1Effect =load_image('TenshiSkill1.png') self.TenshiS1X = [0,106,235,367,509,646,746,875] self.TenshiS1Y = [107,129,132,142,135,98,135] self.Skill1Ei = 0 self.Skill1Ej = 0 self.Skill1X=80 self.S1frame=0 self.Skill1Y=160 self.Skill1Eframe1 = 0 ######################SKILL2#################################### self.MSkill2 = load_image('MarisaSkill2-Motion.png') self.RSkill2 = load_image('Reimu-Skill2-Motion.png') self.ISkill2 =load_image('IkuSkill2-Motion.png') self.TSkill2 = load_image('TenshiSkill2-Motion.png') self.Skill2i = 0 self.Skill2j = 0 self.Skill2cheak = 0 self.MS2Effect = load_image('MarisaSkill2.png') self.RS2Effect = load_image('Reimu-Skill2.png') self.IS2Effect=load_image('IkuSkill2-1.png') self.TS2Effect =load_image('TenshiSkill2-1.png') self.Skill2Ex1 = 120 self.Skill2Ex2 = 100 self.Skill2Ex3 = 80 self.TSkill2Px1=75 self.TSkill2Px2 = 75 self.TSkill2Px3 = 75 self.ISkill2Px=300 self.ISkill2Mx=330 self.S2frame=0 ######################SKILL3#################################### self.MSkill3 = load_image('MarisaSkill3-Motion.png') self.RSkill3 =load_image('Reimu-Skill3-Motion.png') self.ISkill3 =load_image('IkuSkill3-Motion.png') self.TSkill3 = load_image('TenshiSkill3-Motion.png') self.Skill3i = 0 self.Skill3j = 0 self.Skill3cheak = 0 self.MS3Effect = load_image('MarisaSKill3.png') self.RS3Effect = load_image('Reimu-Skill3.png') self.IS3Effect= load_image('IkuSkill3-1.png') self.TS3Effect = load_image('TenshiSkill3.png') self.Skill3Eframe1 = 0 self.Skill3Ex1 = 120 self.Skill3Rx = 70 self.S3frame=0 ######################LASTSPELL#################################### self.MLastspell = load_image('MarisaLastspell-Motion.png') self.RLastspell =load_image('Reimu-Last Spell-Motion.png') self.ILastspell =load_image('IkuLastspell-Motion.png') self.TLastspell =load_image('TenshiLastspell-Motion.png') self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.MLastspellEffect = load_image('MarisaLastspell.png') self.RLastspellEffect1 =load_image('Reimu-Lastspell1.png') self.RLastspellEffect2 =load_image('Reimu-Lastspell2-1.png') self.RLastspellEffect3 =load_image('Reimu-Lastspell3-2.png') self.ILastspellEffect1= load_image('IkuLastspell1-1.png') self.ILastspellEffect2=load_image('IkuLastspell1-2.png') self.TLastspellEffect1=load_image('TenshiLastspell1-1.png') self.TLastspellEffect2 =load_image('TenshiLastspell1-2.png') self.LastspellEframe1 = 0 self.Lastspellframe1 = 0 self.Lastspellframe2 = 0 self.Lastspellframe3 = 0 self.ReimuLastX = [580, 620, 600] self.ReimuLastY = [160.175,200,225,250] self.IkuLastX=[0,120,75] self.IkuLastY=[120,75] self.Lastspellc=0 self.Lastspelld=0 #########################Damage#############################3 self.RDamage =load_image('ReimuDamage-Motion.png') self.IDamage = load_image('IkuDamage-Motion.png') self.TDamage =load_image('TenshiDamage-Motion.png') self.MDamage = load_image('MarisaDamage-Motion.png') self.Damagei=0 self.Damagej=0 self.Damagecheak =0 self.Damageframe=0 ########################DOWN############################ self.RDown =load_image('Reimu-Downs-Motion.png') self.IDown =load_image('Iku-Down-Motion.png') self.TDown = load_image('TenshiDown-Motion.png') self.MDown = load_image('MarisaDown-Motion.png') self.Downcheak=0 self.Downi=0 self.Downj=0 def update(self): #####STANDING######### ###레이무 if self.stat==10: if self.Standcheak<12: self.frame =(self.frame+1)%11 self.Standcheak += 1 if self.Standcheak == 11: self.frame = 0 self.Standcheak = 0 ###이쿠 if self.stat==20: if self.Standcheak<9: self.Standi = (self.Standi + 1) % 10 self.Standj = (self.Standj + 1) % 9 self.Standcheak += 1 if self.Standcheak == 8: self.Standi = 0 self.Standj= 0 self.Standcheak = 0 ###텐시 if self.stat==30: if self.Standcheak<5: self.Standi = (self.Standi + 1) % 6 self.Standj = (self.Standj + 1) % 5 self.Standcheak += 1 if self.Standcheak == 4: self.Standi = 0 self.Standj= 0 self.Standcheak = 0 ###마리사 if self.stat==40: if self.Standcheak < 10: self.Standi = (self.Standi+1) % 11 self.Standj = (self.Standj+1) % 10 self.Standcheak += 1 if self.Standcheak == 9: self.Standi = 0 self.Standj= 0 self.Standcheak = 0 #####SKILL1######### ##레이무 if self.stat ==11: if self.Skill1cheak<12: self.RS1Effect.clip_draw(self.S1frame * 70, 0, 80, 110, self.Player + self.Skill1X, self.All_Y) self.Skill1i = (self.Skill1i + 1) % 13 self.Skill1j = (self.Skill1j + 1) % 12 self.S1frame = (self.S1frame + 1) % 13 self.Skill1X = self.Skill1X+ 30 self.Skill1cheak += 1 if self.Skill1cheak == 12: self.Skill1i = 0 self.Skill1j = 0 self.Skill1cheak = 0 self.Skill1X=80 self.S1frame=0 self.Skill1Eframe1 = 0 player.stat = 10 ###이쿠 if self.stat==21: if self.Skill1cheak<23: if self.Skill1cheak<8: self.Skill1i = (self.Skill1i + 1) % 12 self.Skill1j = (self.Skill1j + 1) % 11 if self.Skill1cheak>=8: if self.Skill1cheak<20: self.IS1Effect.clip_draw(0,self.S1frame*52,360,52,self.Player+200,self.All_Y+10) self.IS1Effect2.clip_draw(self.Skill1Eframe1 * 65,0, 68, 60, 600-10, self.All_Y + 10) self.S1frame=(self.S1frame+1)%12 self.Skill1Eframe1 = (self.Skill1Eframe1+1)%7 if self.Skill1cheak>=20: self.Skill1i = (self.Skill1i + 1) % 12 self.Skill1j = (self.Skill1j + 1) % 11 self.Skill1cheak += 1 if self.Skill1cheak == 22: self.Skill1i = 0 self.Skill1j = 0 self.S1frame =0 self.Skill1cheak = 0 self.Skill1Eframe1 = 0 player.stat = 20 ###텐시 if self.stat ==31: if self.Skill1cheak<15: self.Skill1i = (self.Skill1i + 1) % 16 self.Skill1j = (self.Skill1j + 1) % 15 if self.Skill1cheak>7: self.TS1Effect.clip_draw(self.TenshiS1X[self.S1frame],0,self.TenshiS1Y[self.Skill1Eframe1],165,600,self.All_Y+self.Skill1Y) self.Skill1Y -=30 self.S1frame = (self.S1frame + 1) % 8 self.Skill1Eframe1 = (self.Skill1Eframe1+1)%7 self.Skill1cheak +=1 if self.Skill1cheak == 14: self.Skill1i = 0 self.Skill1j = 0 self.Skill1cheak = 0 self.S1frame=0 self.Skill1Eframe1 = 0 self.Skill1Y =160 player.stat = 30 ###마리사 if self.stat ==41: if self.Skill1cheak < 18: if self.Skill1cheak < 6: self.Skill1i = (self.Skill1i + 1) % 10 self.Skill1j = (self.Skill1j + 1) % 9 if self.Skill1cheak > 6: # Player self.MS1Effect.clip_draw(self.Skill1Eframe1 * 260, 0, 260, 505, self.Enemy, self.All_Y + 150) if self.Skill1cheak < 15: self.Skill1Eframe1 = (self.Skill1Eframe1 + 1) % 9 if self.Skill1cheak >= 15: self.Skill1i = (self.Skill1i + 1) % 10 self.Skill1j = (self.Skill1j + 1) % 9 self.Skill1cheak += 1 if self.Skill1cheak == 18: self.Skill1i = 0 self.Skill1j = 0 self.Skill1cheak = 0 self.Skill1Eframe1 = 0 player.stat = 40 #####SKILL2######### ###레이무 if self.stat==12: if self.Skill2cheak <8: self.Skill2i = (self.Skill2i + 1) % 9 self.Skill2j = (self.Skill2j + 1) % 8 self.S2frame =(self.S2frame+1)%8 self.RS2Effect.clip_draw(self.S2frame *133,0,134,255,600,self.All_Y+60) self.Skill2cheak += 1 if self.Skill2cheak == 8: self.Skill2i = 0 self.Skill2j = 0 self.Skill2cheak = 0 self.S2frame=0 player.stat=10 ###이쿠 if self.stat==22: if self.Skill2cheak <19: if self.Skill2cheak<11: self.Skill2i = (self.Skill2i + 1) % 16 self.Skill2j = (self.Skill2j + 1) % 15 if self.Skill2cheak>5 and self.Skill2cheak<15: if self.Skill2cheak>8: self.ISkill2Mx += 10 self.ISkill2Px +=10 if self.Skill2cheak>=15: self.Skill2i = (self.Skill2i + 1) % 16 self.Skill2j = (self.Skill2j + 1) % 15 self.ISkill2Px -= 10 self.S2frame = (self.S2frame+1)%6 self.Skill2cheak +=1 if self.Skill2cheak == 19: self.Skill2i = 0 self.Skill2j = 0 self.S2frame=0 self.ISkill2Px=300 self.ISkill2Mx = 330 self.Skill2cheak = 0 player.stat=20 ###텐시 if self.stat==32: if self.Skill2cheak<21: if self.Skill2cheak<10: self.Skill2i = (self.Skill2i + 1) % 16 self.Skill2j = (self.Skill2j + 1) % 15 if self.Skill2cheak>=10: self.TS2Effect.clip_draw(0,self.S2frame*50,70,50,self.Player+self.TSkill2Px1,self.All_Y) self.TS2Effect.clip_draw(0, self.S2frame * 50, 70, 50, self.Player + self.TSkill2Px2, self.All_Y+25) self.TS2Effect.clip_draw(0, self.S2frame * 50, 70, 50, self.Player + self.TSkill2Px3, self.All_Y-25) self.S2frame = (self.S2frame+1)%3 if self.Skill2cheak<21: self.TSkill2Px1 += 50 self.TSkill2Px2 += 75 self.TSkill2Px3 += 90 if self.Skill2cheak>=16: self.Skill2i = (self.Skill2i + 1) % 16 self.Skill2j = (self.Skill2j + 1) % 15 self.Skill2cheak += 1 if self.Skill2cheak == 20: self.Skill2i = 0 self.Skill2j = 0 self.S2frame=0 self.TSkill2Px1= 75 self.TSkill2Px2= 75 self.TSkill2Px3= 75 self.Skill2cheak = 0 player.stat = 30 ###마리사 if self.stat ==42: if self.Skill2cheak < 7: self.Skill2i = (self.Skill2i + 1) % 8 self.Skill2j = (self.Skill2j + 1) % 7 # Player self.MS2Effect.clip_draw(0, 125, 132, 125, self.Player + self.Skill2Ex1, self.All_Y) self.MS2Effect.clip_draw(132, 125, 132, 125, self.Player + self.Skill2Ex2, self.All_Y) self.MS2Effect.clip_draw(264, 125, 132, 125, self.Player + self.Skill2Ex3, self.All_Y) self.Skill2Ex1 += 75 self.Skill2Ex2 += 75 self.Skill2Ex3 += 75 self.Skill2cheak += 1 if self.Skill2cheak == 7: self.Skill2i = 0 self.Skill2j = 0 self.Skill2Ex1 = 120 self.Skill2Ex2 = 100 self.Skill2Ex3 = 80 self.Skill2cheak = 0 player.stat=40 #####SKILL3######### ###레이무 if self.stat ==13: if self.Skill3cheak<24: if(self.Skill3cheak<5): self.Skill3i = (self.Skill3i + 1) % 11 self.Skill3j = (self.Skill3j + 1) % 10 if(self.Skill3cheak>=5): self.RS3Effect.clip_draw(self.S3frame*117,0,117,100,self.Player+self.Skill3Rx,self.All_Y) self.Skill3Rx = self.Skill3Rx + 20 if(self.Skill3cheak>=20): self.Skill3i = (self.Skill3i + 1) % 11 self.Skill3j = (self.Skill3j + 1) % 10 self.Skill3cheak += 1 if self.Skill3cheak == 24: self.Skill3i = 0 self.Skill3j = 0 self.Skill3Rx = 70 self.Skill3cheak = 0 player.stat=10 ###이쿠 if self.stat==23: if self.Skill3cheak<19: if self.Skill3cheak<5: self.Skill3i = (self.Skill3i + 1) % 7 self.Skill3j = (self.Skill3j + 1) % 6 if self.Skill3cheak>=5: self.IS3Effect.clip_draw(self.S3frame *260,0,260,250,600,self.All_Y+25) self.S3frame = (self.S3frame+1)%4 if self.Skill3cheak>17: self.Skill3i = (self.Skill3i + 1) % 7 self.Skill3j = (self.Skill3j + 1) % 6 self.Skill3cheak += 1 if self.Skill3cheak == 18: self.Skill3i = 0 self.Skill3j = 0 self.S3frame = 0 self.Skill3cheak = 0 player.stat=20 ###텐시 if self.stat==33: if self.Skill3cheak<16: if self.Skill3cheak<10: self.Skill3i = (self.Skill3i + 1) % 13 self.Skill3j = (self.Skill3j + 1) % 12 if self.Skill3cheak>6 and self.Skill3cheak<14: self.TS3Effect.clip_draw(self.S3frame*260,107,260,120,self.Player+350,self.All_Y-10) self.S3frame = (self.S3frame+1)%7 if self.Skill3cheak>=14: self.Skill3i = (self.Skill3i + 1) % 13 self.Skill3j = (self.Skill3j + 1) % 12 self.Skill3cheak +=1 if self.Skill3cheak == 15: self.Skill3i = 0 self.Skill3j = 0 self.S3frame = 0 self.Skill3cheak = 0 player.stat=30 ###마리사 if self.stat==43: if self.Skill3cheak < 17: if self.Skill3cheak < 7: self.Skill3i = (self.Skill3i + 1) % 10 self.Skill3j = (self.Skill3j + 1) % 10 if self.Skill3cheak >= 7: self.MS3Effect.clip_draw(self.Skill3Eframe1 * 260, 255, 260, 255, self.Player + self.Skill3Ex1,self.All_Y) self.Skill3Eframe1 = (self.Skill3Eframe1 + 1) % 3 self.Skill3Ex1 += 80 if self.Skill3cheak >= 13: self.Skill3i = (self.Skill3i + 1) % 10 self.Skill3j = (self.Skill3j + 1) % 10 self.Skill3cheak += 1 if self.Skill3cheak == 17: self.Skill3i = 0 self.Skill3j = 0 self.Skill3Ex1 = 120 self.Skill3cheak = 0 player.stat=40 #####LASTSPELL######### ###레이무 if self.stat==14: if self.Lastspellcheak<22: if self.Lastspellcheak<9: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 if self.Lastspellcheak>=9: if self.Lastspellcheak<14: self.RLastspellEffect1.clip_draw(self.Lastspellframe1 *133,0,133,207,600,230) self.RLastspellEffect2.clip_draw(self.Lastspellframe2 *261,0,262,126,600-10,160) self.RLastspellEffect3.clip_draw(self.Lastspellframe3 *133,0,133,126,self.ReimuLastX[self.Lastspellc],self.ReimuLastY[self.Lastspelld]) self.Lastspellc= (self.Lastspellc+1)%2 self.Lastspelld= (self.Lastspelld+1)%4 if self.Lastspellcheak >= 16: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 self.Lastspellframe1 = (self.Lastspellframe1+1)%13 self.Lastspellframe2 = (self.Lastspellframe2+1)%8 self.Lastspellframe3 = (self.Lastspellframe3+1)%3 self.Lastspellcheak += 1 if self.Lastspellcheak == 22: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellc =0 self.Lastspelld =0 self.Lastspellframe1 =0 self.Lastspellframe2 =0 self.Lastspellframe3 =0 self.Lastspellcheak = 0 self.LastspellEframe1=0 player.stat = 10 ###이쿠 if self.stat==24: if self.Lastspellcheak<19: if self.Lastspellcheak<8: self.Lastspelli = (self.Lastspelli + 1) % 10 self.Lastspellj = (self.Lastspellj + 1) % 10 if self.Lastspellcheak>=8: self.ILastspellEffect2.clip_draw(self.IkuLastX[(self.Lastspelld + 1) % 2], 0,self.IkuLastY[self.Lastspellc], 255, 600 - 50, self.All_Y + 70) self.ILastspellEffect2.clip_draw(self.IkuLastX[(self.Lastspelld + 1) % 2], 0,self.IkuLastY[self.Lastspellc], 255, 600 + 40, self.All_Y + 70) self.ILastspellEffect2.clip_draw(self.IkuLastX[self.Lastspelld], 0,self.IkuLastY[self.Lastspellc], 255, 600, self.All_Y + 70) self.ILastspellEffect1.clip_draw(self.LastspellEframe1*270, 0,270, 255, 600 +15, self.All_Y + 210) self.LastspellEframe1 =(self.LastspellEframe1+1)%4 self.Lastspelld = (self.Lastspelld+1)%2 self.Lastspellc= (self.Lastspellc+1)%1 if self.Lastspellcheak>=16: self.Lastspelli = (self.Lastspelli + 1) % 10 self.Lastspellj = (self.Lastspellj + 1) % 10 self.Lastspellcheak +=1 if self.Lastspellcheak == 18: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.LastspellEframe1=0 self.Lastspelld = 0 self.Lastspellc = 0 player.stat = 20 ###텐시 if self.stat==34: if self.Lastspellcheak <20: self.Lastspelli = (self.Lastspelli + 1) % 21 self.Lastspellj = (self.Lastspellj + 1) % 20 if self.Lastspellcheak>3: self.TLastspellEffect2.clip_draw(0,0,250,250,600,self.All_Y) if self.Lastspellcheak>4: self.TLastspellEffect1.clip_draw(self.LastspellEframe1*260,0,260,250,600,self.All_Y) if self.Lastspellcheak ==9: self.LastspellEframe1 +=1 if self.Lastspellcheak==15: self.LastspellEframe1 +=1 self.Lastspellcheak +=1 if self.Lastspellcheak == 19: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.LastspellEframe1=0 player.stat = 30 ###마리사 if self.stat==44: if self.Lastspellcheak < 18: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 if self.Lastspellcheak > 4: if self.Lastspellcheak < 11: # Player self.MLastspellEffect.clip_draw(self.LastspellEframe1 * 261, 250, 260, 250, self.Player + 400,self.All_Y - 10) self.MLastspellEframe1 = (self.LastspellEframe1 + 1) % 7 self.Lastspellcheak += 1 if self.Lastspellcheak == 18: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.LastspellEframe1=0 player.stat = 40 ########Damage###### ####레이무 if self.stat==15: if self.Damagecheak<3: self.Damageframe= (self.Damageframe+1)%3 self.Damagecheak += 1 if self.Damagecheak==3: player.stat =10 self.Damagecheak =0 self.Damageframe=0 ####이쿠 if self.stat==25: if self.Damagecheak < 3: self.Damagei = (self.Damagei+1)%4 self.Damagej = (self.Damagej+1)%3 self.Damagecheak +=1 if self.Damagecheak==3: player.stat=20 self.Damagecheak=0 self.Damagei=0 self.Damagej=0 ####텐시 if self.stat==35: if self.Damagecheak<5: self.Damageframe = (self.Damageframe+1)%5 self.Damagecheak += 1 if self.Damagecheak==5: player.stat=30 self.Damagecheak=0 self.Damageframe =0 ####마리사 if self.stat==45: if self.Damagecheak<3: self.Damagei = (self.Damagei + 1) % 4 self.Damagej = (self.Damagej + 1) % 3 self.Damagecheak += 1 if self.Damagecheak == 3: player.stat = 40 self.Damagecheak = 0 self.Damagei = 0 self.Damagej = 0 ########Damage###### ####레이무 if self.stat==16: if self.Downcheak<20: if self.Downcheak<9: self.Downi = (self.Downi+1)%11 self.Downj = (self.Downj+1)%10 self.Downcheak +=1 if self.Downcheak==20: player.stat =10 self.Downi =0 self.Downj =0 self.Downcheak=0 ####이쿠 if self.stat==26: if self.Downcheak<20: if self.Downcheak<6: self.Downi = (self.Downi + 1) % 8 self.Downj = (self.Downj + 1) % 7 self.Downcheak +=1 if self.Downcheak==20: player.stat =20 self.Downi =0 self.Downj =0 self.Downcheak=0 ####텐시 if self.stat==36: if self.Downcheak<20: if self.Downcheak<4: self.Downi = (self.Downi + 1) % 6 self.Downj = (self.Downj + 1) % 5 self.Downcheak += 1 if self.Downcheak==20: player.stat =30 self.Downi =0 self.Downj =0 self.Downcheak=0 ####마리사 if self.stat==46: if self.Downcheak<20: if self.Downcheak<6: self.Downi = (self.Downi + 1) % 7 self.Downj = (self.Downj + 1) % 7 self.Downcheak += 1 if self.Downcheak == 20: player.stat = 40 self.Downi = 0 self.Downj = 0 self.Downcheak = 0 def Stand(self): ####STANDING######## ###레이무 if self.stat==10: self.RStanding.clip_draw(self.frame *100,105,97,105,self.Player,self.All_Y) ###이쿠 if self.stat==20: self.Standframe1 =[0,73, 140, 200, 265,324, 385, 446, 510, 580] self.Standframe2 =[74,64,60,62,58,59,63,65,70] self.IStanding.clip_draw(self.Standframe1[self.Standi],130,self.Standframe2[self.Standj],130,self.Player,self.All_Y) ###텐시 if self.stat==30: self.Standframe1 =[0,65,126,196,271,345] self.Standframe2 =[65,61,70,75,74] self.TStanding.clip_draw(self.Standframe1[self.Standi], 115, self.Standframe2[self.Standj], 115,self.Player, self.All_Y) ###마리사 if self.stat==40: self.Standframe1 = [0,65,126,188,250,312,372,434,495,556,618] self.Standframe2 = [65,61,62,62,62,60,62,61,60,62] self.MStanding.clip_draw(self.Standframe1[self.Standi], 110, self.Standframe2[self.Standj], 110, self.Player,self.All_Y ) #####SKILL1######### ###레이무 if self.stat==11: self.Skill1frame1 = [0,108,213,327,434,541,638,787,936,1080,1215,1319,1425] self.Skill1frame2 = [108,105,114,107,107,97,149,149,144,135,104,106] self.RSKill1.clip_draw(self.Skill1frame1[self.Skill1i], 110, self.Skill1frame2[self.Skill1j], 110, self.Player, self.All_Y) ###이쿠 if self.stat==21: self.Skill1frame1 =[0,68,133,193,259,329,390,470,543,615,680,745] self.Skill1frame2 =[68,65,60,66,68,59,78,74,70,63,68] self.ISkill1.clip_draw(self.Skill1frame1[self.Skill1i],145,self.Skill1frame2[self.Skill1j],145,self.Player, self.All_Y) ###텐시 if self.stat ==31: self.Skill1frame1 = [0,75,143,214,294,379,500,616,695,776,852,929,1006,1076,1146,1210] self.Skill1frame2 = [75,67,70,77,82,120,112,73,73,73,71,68,65,63,64] self.TSkill1.clip_draw(self.Skill1frame1[self.Skill1i],160,self.Skill1frame2[self.Skill1j],160,self.Player, self.All_Y+30) ###마리사 if self.stat==41: self.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] self.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] self.MSkill1.clip_draw(self.Skill1frame1[self.Skill1i], 105, self.Skill1frame2[self.Skill1j], 105,self.Player, self.All_Y) #####SKILL2######### ###레이무 if self.stat==12: self.Skill2frame1 = [0,66,120,217,304,392,480,572,675] self.Skill2frame2 = [66,54,97,87,88,88,92,103] self.RSkill2.clip_draw(self.Skill2frame1[self.Skill2i],155, self.Skill2frame2[self.Skill2j],120,self.Player,self.All_Y) ###이쿠 if self.stat==22: self.Skill2frame1 =[0,70,130,200,283,356,422,490,597,732,912,1087,1247,1375,1463,1520] self.Skill2frame2 =[70,60,70,83,73,66,66,101,133,178,173,157,124,83,63] self.ISkill2.clip_draw(self.Skill2frame1[self.Skill2i],145, self.Skill2frame2[self.Skill2j],145,self.Player+self.ISkill2Px,self.All_Y) if self.Skill2cheak > 8and self.Skill2cheak<15: self.IS2Effect.clip_draw(self.S2frame * 193, 60, 193, 60, self.Player + self.ISkill2Mx, self.All_Y - 5) ###텐시 if self.stat ==32: self.Skill2frame1 =[0,70,149,228,305,378,448,520,590,664,740,814,888,960,1026,1100] self.Skill2frame2 =[70,79,79,77,73,69,68,67,70,69,66,69,66,60,60] self.TSkill2.clip_draw(self.Skill2frame1[self.Skill2i], 115, self.Skill2frame2[self.Skill2j], 115,self.Player, self.All_Y) ###마리사 if self.stat==42: self.Skill2frame1 = [0, 85, 165, 240, 318, 395, 464, 525] self.Skill2frame2 = [85, 80, 75, 78, 76, 67, 64] # 플레이어 self.MSkill2.clip_draw(self.Skill2frame1[self.Skill2i], 120, self.Skill2frame2[self.Skill2j], 120,self.Player, self.All_Y) #####SKILL3######### ###레이무 if self.stat==13: self.Skill3frame1 =[0,105, 210,315,420, 543, 659, 775, 885, 1000,1100] self.Skill3frame2 =[104,105,105,104,120,115,115,108,115,100] self.RSkill3.clip_draw(self.Skill3frame1[self.Skill3i],100,self.Skill3frame2[self.Skill3j],100,self.Player,self.All_Y) ###이쿠 if self.stat==23: self.Skill3frame1 =[0,64,126,196,268,338,405] self.Skill3frame2 =[64,62,70,72,67,68] self.ISkill3.clip_draw(self.Skill3frame1[self.Skill3i], 145, self.Skill3frame2[self.Skill3j], 145,self.Player, self.All_Y) ###텐시 if self.stat==33: self.Skill3frame1 =[0,77,155,240,340,425,528,710,876,960,1040,1110,1190] self.Skill3frame2 =[77,78,83,99,80,98,178,160,70,70,63,68] self.TSkill3.clip_draw(self.Skill3frame1[self.Skill3i], 115, self.Skill3frame2[self.Skill3j], 115,self.Player+200, self.All_Y) ###마리사 if self.stat ==43: self.Skill3frame1 = [0, 65, 125, 195, 275, 332, 412, 500, 590, 661] self.Skill3frame2 = [65, 60, 70, 80, 60, 76, 85, 89, 68, 61] # 플레이어 self.MSkill3.clip_draw(self.Skill3frame1[self.Skill3i], 110, self.Skill3frame2[self.Skill3j], 110,self.Player, self.All_Y) #####LASTSPELL######### ###레이무 if self.stat ==14: self.Lastframe1 = [0,105, 209,311,414, 517, 620, 724, 822, 910, 995,1068,1145,1242,1345,1445] self.Lastframe2 = [105,104,102,103,104,103,104,98,88,85,74,77,97,103,100] self.RLastspell.clip_draw(self.Lastframe1[self.Lastspelli], 130, self.Lastframe2[self.Lastspellj], 130, self.Player,self.All_Y+15) ###이쿠 if self.stat ==24: self.Lastframe1 =[0,60,120,180,243,315,440,570,700,825,945,1035] self.Lastframe2 =[60,60,60,63,72,125,130,130,125,120] self.ILastspell.clip_draw(self.Lastframe1[self.Lastspelli], 140, self.Lastframe2[self.Lastspellj], 140, self.Player,self.All_Y) ###텐시 if self.stat ==34: self.Lastframe1 =[0,72,142,266,435,577,715,842,928,1064,1200,1328,1430,1540,1640,1790,1965,2130,2295,2395,2465] self.Lastframe2 =[72,70,124,169,142,137,124,85,132,131,124,96,109,95,145,167,155,150,90,72] self.TLastspell.clip_draw(self.Lastframe1[self.Lastspelli], 165, self.Lastframe2[self.Lastspellj], 165, self.Player+200,self.All_Y+30) ###마리사 if self.stat == 44: self.Lastframe1 = [0, 65,127,187,251,305,386,451,536,610,680,750,815,880,943,1010,1070] self.Lastframe2 = [65,62,60,64,55,79,62,80,72,66,66,65,63,60,59,58,58] # 플레이어 self.MLastspell.clip_draw(self.Lastframe1[self.Lastspelli], 120, self.Lastframe2[self.Lastspellj], 120, self.Player+250,self.All_Y) #########Damage#############3 ####레이무 if self.stat==15: self.RDamage.clip_draw(self.Damageframe*112,90,110,90,self.Player,self.All_Y) ####이쿠 if self.stat==25: self.Damageframe1 =[0,94,174,245] self.Damageframe2 = [94,80,73] self.IDamage.clip_draw(self.Damageframe1[self.Damagei],135,self.Damageframe2[self.Damagej],135,self.Player,self.All_Y) ####텐시 if self.stat==35: self.TDamage.clip_draw(self.Damageframe*80,115,78,115,self.Player,self.All_Y) ####마리사 if self.stat==45: self.Damageframe1 =[0, 90, 175, 240] self.Damageframe2 =[90, 85, 65] self.MDamage.clip_draw(self.Damageframe1[self.Damagei], 115, self.Damageframe2[self.Damagej], 115,self.Player, self.All_Y) #########Down#############3 ####레이무 if self.stat==16: self.Downframe1 = [0,92, 172,272,369, 465, 576, 683, 784, 889, 970] self.Downframe2 = [92,80,100,97,96,110,105,102,105,103,130] self.RDown.clip_draw(self.Downframe1[self.Downi],65,self.Downframe2[self.Downj],65,self.Player,self.All_Y-25) ####이쿠 if self.stat==26: self.Downframe1 =[0,125,240,374,514,651,793,945] self.Downframe2 = [125,115,134,140,136,140,158] self.IDown.clip_draw(self.Downframe1[self.Downi], 105, self.Downframe2[self.Downj], 105, self.Player,self.All_Y -25) ####텐시 if self.stat==36: self.Downframe1 =[0,120,235,350,470,595] self.Downframe2 =[120,115,115,120,125] self.TDown.clip_draw(self.Downframe1[self.Downi], 75, self.Downframe2[self.Downj], 75, self.Player,self.All_Y-30) ####마리사 if self.stat==46: self.Downframe1 =[0,80,149,232,348,451,548,645] self.Downframe2 =[80,69,83,116,102,95,100] self.MDown.clip_draw(self.Downframe1[self.Downi], 95, self.Downframe2[self.Downj], 95, self.Player,self.All_Y - 20) def handle_events(): global running events = get_events() for event in events: if event.type == SDL_QUIT: running = False elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: running = False elif event.type == SDL_KEYDOWN and event.key == SDLK_q: player.stat = 10 elif event.type == SDL_KEYDOWN and event.key == SDLK_w: player.stat = 20 elif event.type == SDL_KEYDOWN and event.key == SDLK_e: player.stat = 30 elif event.type == SDL_KEYDOWN and event.key == SDLK_r: player.stat = 40 elif event.type == SDL_KEYDOWN and event.key == SDLK_a: player.stat += 1 elif event.type == SDL_KEYDOWN and event.key == SDLK_s: player.stat += 2 elif event.type == SDL_KEYDOWN and event.key == SDLK_d: player.stat += 3 elif event.type == SDL_KEYDOWN and event.key == SDLK_f: player.stat += 4 elif event.type == SDL_KEYDOWN and event.key == SDLK_z: player.stat += 5 elif event.type == SDL_KEYDOWN and event.key == SDLK_x: player.stat += 6 elif event.type == SDL_KEYDOWN and event.key == SDLK_1: background.backgroundselection = 1 elif event.type == SDL_KEYDOWN and event.key == SDLK_2: background.backgroundselection = 2 elif event.type == SDL_KEYDOWN and event.key == SDLK_3: background.backgroundselection = 3 open_canvas() background=BackGround() player=Player() running=True while running: handle_events() clear_canvas() background.draw() player.update() player.Stand() update_canvas() delay(0.1) # finalization code close_canvas() <file_sep>/Project/test/reimuSkill.py from pico2d import * import game_framework import main_state import DeckSelection import reimu import Enemy_reimu import EnemyHP #iku stand STAND_TIME_PER_ACTION=1.2 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=12 #skill1 SKILL1TIME_PER_ACTION=1.5 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=15 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 0.8/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=13 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=25 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=23 #Damage DAMAGETIME_PER_ACTION=0.5 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) import game_world name = 'reimuskill' class REIMU_Skill1: def __init__(self): self.effect_charm=None self.effect_shelter=None self.effect_jade=None self.effect_border=None self.effect_power_shelter=None self.effect_explosion=None if self.effect_charm==None: self.effect_charm=load_image('./FCGimage/Reimu-Skill1.png') if self.effect_shelter==None: self.effect_shelter = load_image('./FCGimage/Reimu-Skill2.png') if self.effect_jade==None: self.effect_jade=load_image('./FCGimage/Reimu-Skill3.png') if self.effect_border==None: self.effect_border = load_image('./FCGimage/Reimu-Lastspell2-1.png') if self.effect_power_shelter==None: self.effect_power_shelter = load_image('./FCGimage/Reimu-Lastspell1.png') if self.effect_explosion == None: self.effect_explosion = load_image('./FCGimage/Reimu-Lastspell3-2.png') #skill1 self.Charm_Move= 80 self.Charm_frame=0 #skill2 self.Shelter_frame=0 #skill3 self.Jade_Move=70 self.Jade_frame=0 #Last self.Explosin_PX =[580, 620, 600] self.Explosin_PY =[160.175, 200, 225, 250] self.Explosin_EX =[180, 220, 200] self.Explosin_X_frame=0 self.Explosin_Y_frame=0 self.Border_frame=0 self.Power_Shelter_frame=0 self.Explosin_frame=0 self.Lastcheak=0 def get_bb(self): pass def draw(self): if DeckSelection.character==0 and main_state.turn== 1 and main_state.Skill1_Start==True: self.effect_charm.clip_draw(int(self.Charm_frame) * 70, 0, 80, 110, 200 + self.Charm_Move, 200 + 10) if main_state.EnemyPlayer==0 and main_state.turn== -1 and main_state.Skill1_Start==True: self.effect_charm.clip_draw(int(self.Charm_frame) * 70, 0, 80, 110, 600 - self.Charm_Move, 200 + 10) if DeckSelection.character==0 and main_state.turn ==1 and main_state.Skill2_Start ==True: self.effect_shelter.clip_draw(int(self.Shelter_frame) * 133, 0, 134, 255, 600, 200 + 60) if main_state.EnemyPlayer==0 and main_state.turn == -1 and main_state.Skill2_Start ==True: self.effect_shelter.clip_draw(int(self.Shelter_frame) * 133, 0, 134, 255, 200, 200 + 60) if DeckSelection.character==0 and main_state.turn ==1 and main_state.Skill3_Start ==True: self.effect_jade.clip_draw(int(self.Jade_frame) * 117, 0, 117, 100, 200 + self.Jade_Move, 200) if main_state.EnemyPlayer==0 and main_state.turn == -1 and main_state.Skill3_Start ==True: self.effect_jade.clip_draw(int(self.Jade_frame) * 117, 0, 117, 100, 600 - self.Jade_Move, 200) if DeckSelection.character==0 and main_state.turn ==1 and main_state.Last_Start ==True: if self.Lastcheak >= 9 and self.Lastcheak<14: self.effect_power_shelter.clip_draw(int(self.Power_Shelter_frame) * 133, 0, 133, 207, 600, 230) self.effect_border.clip_draw(int(self.Border_frame) * 261, 0, 262, 126, 600 - 10, 160) self.effect_explosion.clip_draw(int(self.Explosin_frame) * 133, 0, 133, 126,self.Explosin_PX[int(self.Explosin_X_frame)],self.Explosin_PY[int(self.Explosin_Y_frame)]) if main_state.EnemyPlayer==0 and main_state.turn == -1 and main_state.Last_Start ==True: if self.Lastcheak >= 9 and self.Lastcheak<14: self.effect_power_shelter.clip_draw(int(self.Power_Shelter_frame) * 133, 0, 133, 207, 200, 230) self.effect_border.clip_draw(int(self.Border_frame) * 261, 0, 262, 126, 200 + 10, 160) self.effect_explosion.clip_draw(int(self.Explosin_frame) * 133, 0, 133, 126,self.Explosin_EX[int(self.Explosin_X_frame)],self.Explosin_PY[int(self.Explosin_Y_frame)]) def update(self): if main_state.Skill1_Start == True: if self.Charm_Move >350: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.reimu_skill1_atk_cheak = 1 if self.Charm_Move>=400: main_state.reimu_skill1_atk_cheak = 0 self.Charm_frame = (self.Charm_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 13 self.Charm_Move += int(MOTION_SPEED_PPS) * 5 if main_state.Skill1_Start == False: main_state.reimu_skill1_atk_cheak = 0 self.Charm_Move=80 if main_state.Skill2_Start ==True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.reimu_skill2_atk_cheak = 1 self.Shelter_frame = (self.Shelter_frame + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 8 if main_state.Skill2_Start == False: main_state.reimu_skill2_atk_cheak = 0 self.Shelter_frame=0 if main_state.Skill3_Start==True: if self.Jade_Move >350: main_state.reimu_skill3_atk_cheak = 1 if self.Jade_Move>=360: main_state.reimu_skill3_atk_cheak = 0 if self.Jade_Move >400: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 self.Jade_Move += int(MOTION_SPEED_PPS) * 5 self.Jade_frame = (self.Jade_frame + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 2 if main_state.Skill3_Start == False: main_state.reimu_skill3_atk_cheak = 0 self.Jade_Move=70 if main_state.Last_Start==True: self.Lastcheak= (self.Lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%23 self.Power_Shelter_frame = (self.Power_Shelter_frame+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 13 self.Border_frame = (self.Border_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 8 self.Explosin_frame = (self.Explosin_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 3 if self.Lastcheak>=9: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.reimu_last_atk_cheak = 1 self.Explosin_Y_frame = (self.Explosin_Y_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 4 self.Explosin_X_frame = (self.Explosin_X_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 2 if main_state.Last_Start==False: main_state.reimu_last_atk_cheak = 0 self.Explosin_X_frame = 0 self.Explosin_Y_frame = 0 self.Border_frame = 0 self.Power_Shelter_frame = 0 self.Explosin_frame = 0 self.Lastcheak = 0 <file_sep>/Project/Iku/Iku-Down-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =190 Enemy_X=610 All_Y=175 IkuDown = load_image('Iku-Down-Motion.png') def Iku_Down(): frame1 = [125,115,134,140,136,140,158] frame2 = [0,125,240,374,514,651,793,945] cheak=0 i=0 j=0 while(cheak<10): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuDown.clip_draw(frame2[i],0,frame1[j],105,Enemy_X,All_Y) #플레이어 IkuDown.clip_draw(frame2[i],105,frame1[j],105,Player_X,All_Y) if cheak <6: i=(i+1)%8 j=(j+1)%7 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Down() close_canvas() <file_sep>/Project/Tensi/Tenshi-Skill2-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiSkill2 = load_image('TenshiSkill2-Motion.png') TenshiSkill2effect = load_image('TenshiSkill2-1.png') def Tenshi_Skill2(): frame1 = [70,79,79,77,73,69,68,67,70,69,66,69,66,60,60] frame2 = [0,70,149,228,305,378,448,520,590,664,740,814,888,960,1026,1100] cheak=0 frame=0 i=0 j=0 Px1=75 Px2=75 Px3=75 while(cheak<21): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiSkill2.clip_draw(frame2[i],0,frame1[j],115,Enemy_X,All_Y) #플레이어 TenshiSkill2.clip_draw(frame2[i],115,frame1[j],115,Player_X,All_Y) if cheak<10: i=(i+1)%16 j=(j+1)%15 if cheak>=10: #플레이어 TenshiSkill2effect.clip_draw(0,frame*50,70,50,Player_X+Px1,All_Y) TenshiSkill2effect.clip_draw(0,frame*50,70,50,Player_X+Px2,All_Y+25) TenshiSkill2effect.clip_draw(0,frame*50,70,50,Player_X+Px3,All_Y-25) #적 TenshiSkill2effect.clip_draw(70,frame*50,70,50,Enemy_X-Px1,All_Y) TenshiSkill2effect.clip_draw(70,frame*50,70,50,Enemy_X-Px2,All_Y+25) TenshiSkill2effect.clip_draw(70,frame*50,70,50,Enemy_X-Px3,All_Y-25) frame=(frame+1)%3 if cheak <21: Px1 += 50 Px2 += 75 Px3 += 90 if cheak >=16: i=(i+1)%16 j=(j+1)%15 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Skill2() close_canvas() <file_sep>/Project/Reimu/Reimu-Skill3-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuSkill3 = load_image('Reimu-Skill3-Motion.png') ReimuSkill3effect = load_image('Reimu-Skill3.png') def Reimu_Skill3(): frame=[0,105, 210,315,420, 543, 659, 775, 885, 1000,1100] frame2=[104,105,105,104,120,115,115,108,115,100] i=0 j=0 Px=70 Ex=70 S3_frame=0 cheak=0 while(cheak<24): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #플레이어 ReimuSkill3.clip_draw(frame[i],100,frame2[j],100,Player_X,All_Y) #적 ReimuSkill3.clip_draw(frame[i],0,frame2[j],100,Enemy_X,All_Y) if(cheak<5): i=(i+1)%11 j=(j+1)%10 if(cheak>=5): #플레이어 공격 ReimuSkill3effect.clip_draw(S3_frame*117,0,117,100,Player_X+Px,All_Y) Px=Px+20 if(cheak>=20): i=(i+1)%11 j=(j+1)%10 #적 공격 ReimuSkill3effect.clip_draw(S3_frame*117,0,117,100,Enemy_X-Ex,All_Y) Ex=Ex+20 if(cheak>=20): i=(i+1)%11 j=(j+1)%10 update_canvas() delay(0.1) cheak +=1 while(True): Reimu_Skill3() close_canvas() <file_sep>/Project/test/tenshi.py from pico2d import * import Deck import main_state import game_world import game_framework import PlayerHP #tenshi stand STAND_TIME_PER_ACTION=0.8 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=6 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=16 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=22 #skill3 SKILL3TIME_PER_ACTION=1.5 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=17 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=21 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=6 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #item use ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=16 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) Stand,Skill1, Skill2,Skill3, Last, Damage,Down = range(7) Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) key_event_table = { (SDL_MOUSEBUTTONDOWN, 1): Skill1, (SDL_MOUSEBUTTONDOWN, 2): Skill2, (SDL_MOUSEBUTTONDOWN, 3): Skill3, (SDL_MOUSEBUTTONDOWN, 4): Last, (SDL_MOUSEBUTTONDOWN, 99): Damage, (SDL_MOUSEBUTTONDOWN, 98): Down, (SDL_MOUSEBUTTONDOWN, 5): Item1, (SDL_MOUSEBUTTONDOWN, 6): Item2, (SDL_MOUSEBUTTONDOWN, 7): Item3 } # Iku States HP= 0 class StandState: @staticmethod def enter(tenshi, event): tenshi.motion = 0 tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.Standframe1 = [0,65,126,196,271,345] tenshi.Standframe2 = [65,61,70,75,74] @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): tenshi.frame1 = (tenshi.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.frame2 = (tenshi.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 5 main_state.Character_Motion_Cheak = False if int(PlayerHP.damage) >252: tenshi.down_sound.play() tenshi.add_event(Down) if main_state.EnemyPlayer == 0 and main_state.reimu_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_last_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill2_atk_cheak==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill3_atk_cheak ==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_last_atk_cheak==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_last_atk_cheak== 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_last_atk_cheak== 1: tenshi.damage_sound.play() tenshi.add_event(Damage) @staticmethod def draw(tenshi): if tenshi.motion ==0: tenshi.stand.clip_draw(tenshi.Standframe1[int(tenshi.frame1)], 115, tenshi.Standframe2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Skill1State: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill1cheak = 0 tenshi.Skill1frame1 = [0,75,143,214,294,379,500,616,695,776,852,929,1006,1076,1146,1210] tenshi.Skill1frame2 = [75,67,70,77,82,120,112,73,73,73,71,68,65,63,64] tenshi.TenshiS1X = [0, 106, 235, 367, 509, 646, 746, 875] tenshi.TenshiS1Y = [107, 129, 132, 142, 135, 98, 135] if event == Skill1: tenshi.motion = 1 @staticmethod def exit(tenshi, event): pass #if event ==SPACE: # boy.fire_ball() @staticmethod def do(tenshi): main_state.Character_Motion_Cheak = True if int(tenshi.skill1cheak)<15: tenshi.frame1 = (tenshi.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Skill1_Start=True tenshi.skill1cheak =(tenshi.skill1cheak+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%16 if int(tenshi.skill1cheak)>=15: tenshi.skill1cheak=0 tenshi.add_event(Stand) main_state.Skill1_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 1: tenshi.skill1.clip_draw(tenshi.Skill1frame1[int(tenshi.frame1)],160,tenshi.Skill1frame2[int(tenshi.frame2)],160, tenshi.x, tenshi.y+30) class Skill2State: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill2cheak = 0 tenshi.Skill2frame1 = [0,70,149,228,305,378,448,520,590,664,740,814,888,960,1026,1100] tenshi.Skill2frame2 = [70,79,79,77,73,69,68,67,70,69,66,69,66,60,60] if event == Skill2: tenshi.motion = 2 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): main_state.Character_Motion_Cheak = True if int(tenshi.skill2cheak) < 21: main_state.Skill2_Start = True if int(tenshi.skill2cheak) < 10: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 if int(tenshi.skill2cheak) >= 16: tenshi.frame1 = (tenshi.frame1+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.skill2cheak = ( tenshi.skill2cheak + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%22 if int(tenshi.skill2cheak) >= 21: tenshi.skill2cheak = 0 tenshi.add_event(Stand) main_state.Skill2_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 2: tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 115, tenshi.Skill2frame2[int(tenshi.frame2)], 115,tenshi.x, tenshi.y) class Skill3State: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill3cheak = 0 tenshi.Skill3frame1 = [0,77,155,240,340,425,528,710,876,960,1040,1110,1190] tenshi.Skill3frame2 = [77,78,83,99,80,98,178,160,70,70,63,68] if event == Skill3: tenshi.motion = 3 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): main_state.Character_Motion_Cheak = True if int(tenshi.skill3cheak) < 16: if int(tenshi.skill3cheak) < 10: tenshi.frame1 = (tenshi.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.frame2 = (tenshi.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 if int(tenshi.skill3cheak)>6 and int(tenshi.skill3cheak)<14: main_state.Skill3_Start=True if int(tenshi.skill3cheak) >= 14: main_state.Skill3_Start = False tenshi.frame1 = (tenshi.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.frame2 = (tenshi.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.skill3cheak = (tenshi.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%17 if int(tenshi.skill3cheak)>= 16: tenshi.skill3cheak = 0 tenshi.add_event(Stand) main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 3: tenshi.skill3.clip_draw(tenshi.Skill3frame1[int(tenshi.frame1)], 115, tenshi.Skill3frame2[int(tenshi.frame2)], 115,tenshi.x+200, tenshi.y) class Laststate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.lastcheak = 0 tenshi.Lastframe1 = [0,72,142,266,435,577,715,842,928,1064,1200,1328,1430,1540,1640,1790,1965,2130,2295,2395,2465] tenshi.Lastframe2 = [72,70,124,169,142,137,124,85,132,131,124,96,109,95,145,167,155,150,90,72] if event == Last: tenshi.motion = 4 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): main_state.Character_Motion_Cheak = True if int(tenshi.lastcheak) < 20: tenshi.frame1 = (tenshi.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 20 tenshi.frame2 = (tenshi.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 20 main_state.Last_Start=True tenshi.lastcheak = (tenshi.lastcheak+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%21 if int(tenshi.lastcheak) >= 20: tenshi.lastcheak = 0 tenshi.add_event(Stand) main_state.Last_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 4: tenshi.Lastspell.clip_draw(tenshi.Lastframe1[int(tenshi.frame1)], 165, tenshi.Lastframe2[int(tenshi.frame2)], 165,tenshi.x+200, tenshi.y+30) class Damagestate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.Damagecheak = 0 if event == Damage: tenshi.motion = 5 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): if int(tenshi.Damagecheak) < 5: tenshi.frame1 = (tenshi.frame1 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.Damagecheak = (tenshi.Damagecheak + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 6 if int(tenshi.Damagecheak) >= 5: tenshi.Damagecheak = 0 tenshi.add_event(Stand) @staticmethod def draw(tenshi): if tenshi.motion == 5: tenshi.Damage.clip_draw(int(tenshi.frame1)*80,115,78,115, tenshi.x, tenshi.y) class Downstate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.Downcheak=0 tenshi.Downframe1 = [0,120,235,350,470,595] tenshi.Downframe2 = [120,115,115,120,125] if event == Down: tenshi.motion = 6 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): if int(tenshi.Downcheak) < 20: if int(tenshi.Downcheak) < 4: tenshi.frame1 = (tenshi.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.frame2 = (tenshi.frame2 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.Downcheak = (tenshi.Downcheak + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 21 if int(tenshi.Downcheak) >= 20: pass #tenshi.timer -= 1 @staticmethod def draw(tenshi): if tenshi.motion == 6: tenshi.Down.clip_draw(tenshi.Downframe1[int(tenshi.frame1)], 75, tenshi.Downframe2[int(tenshi.frame2)], 75, tenshi.x, tenshi.y-33) class Item_Doll: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item1: tenshi.motion = 7 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): global HP,HPcheak,skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 7: tenshi.item_use.clip_draw(0, 0, 40, 65, 200, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 115,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Item_Potion: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item2: tenshi.motion = 8 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): global HP, HPcheak, skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 8: tenshi.item_use.clip_draw(40, 0, 40, 65, 200, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 115,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Item_Clock: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item3: tenshi.motion = 9 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): global HP, HPcheak, skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(tenshi): if tenshi.motion == 9: tenshi.item_use.clip_draw(80, 0, 40, 65, 200, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 115,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:Downstate}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Tenshi: def __init__(self): self.x, self.y = 200, 200 self.stand = load_image('./FCGimage/TenshiStanding-Motion.png') self.skill1 = load_image('./FCGimage/TenshiSkill1-Motion.png') self.skill2 = load_image('./FCGimage/TenshiSkill2-Motion.png') self.skill3 = load_image('./FCGimage/TenshiSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/TenshiLastspell-Motion.png') self.Damage = load_image('./FCGimage/TenshiDamage-Motion.png') self.Down = load_image('./FCGimage/TenshiDown-Motion.png') self.skill1_sound = load_wav('./voice/tenshi-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/tenshi-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/tenshi-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/tenshi-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/tenshi-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/tenshi-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/tenshi-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): global cheak1, HP, mouse_x, mouse_y if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y = event.x, 600 - event.y if (event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT): ##스킬키 체크 if main_state.turn==1and main_state.DeckShow==1: if mouse_x > 270 and mouse_x < 330 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[Deck.spellcheak%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[Deck.spellcheak%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[Deck.spellcheak%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[Deck.spellcheak%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[Deck.spellcheak%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[Deck.spellcheak%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[Deck.spellcheak%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 370 and mouse_x < 430 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 470 and mouse_x < 530 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==5: main_state.DeckShow = 0 main_state.Player_DefBuff =0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==6: main_state.DeckShow = 0 main_state.Player_AtkBuff = 3 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==7: main_state.DeckShow = 0 main_state.P_HP -= 100 PlayerHP.damage -= 100 self.item_sound.play() self.add_event(Item3) elif (event.type, event.key) in key_event_table: key_event = key_event_table[(event.type, event.key)] self.add_event(key_event)<file_sep>/Project/test/CharacterSelection.py import game_framework import random from pico2d import * import DeckSelection #import CharacterSelection import game_world name = "characterSelection" image = None cheak = None character = None mouse_x,mouse_y=0,0 Enemycharacter=None def enter(): global image,character global cheak image = load_image('./FCGimage/CharacterSelection.png') cheak = load_image('./FCGimage/Character_Cheak.png') def exit(): global image def handle_events(): global character,Enemycharacter,mouse_x,mouse_y events = get_events() for event in events: if event.type ==SDL_QUIT: game_framework.quit() if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y=event.x, 600- event.y else: if(event.type, event.key) == (SDL_KEYDOWN,SDLK_ESCAPE): game_framework.quit() elif(event.type, event.button)==(SDL_MOUSEBUTTONDOWN,SDL_BUTTON_LEFT): if mouse_x> 0 and mouse_x < 150: character = 0 elif mouse_x> 150 and mouse_x < 300: character = 1 elif mouse_x > 300 and mouse_x < 450: character = 2 elif mouse_x> 450 and mouse_x < 600: character = 3 if mouse_x > 0 and event.x < 600 and mouse_y<400: game_framework.push_state(DeckSelection) def draw(): global mouse_x,mouse_y clear_canvas() image.draw(400,300) if 0< mouse_x and mouse_x<150 and mouse_y<400: cheak.draw(75,450) if 150< mouse_x and mouse_x<300 and mouse_y<400: cheak.draw(225,450) if 300< mouse_x and mouse_x<450 and mouse_y<400: cheak.draw(375,450) if 450< mouse_x and mouse_x<600 and mouse_y<400: cheak.draw(525,450) update_canvas() def update(): pass def pause(): global character def resume(): pass <file_sep>/Project/Iku/Iku-Skill2-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuSkill2 = load_image('IkuSkill2-Motion.png') IkuSkill2effect = load_image('IkuSkill2-1.png') def Iku_Skill2(): frame1 = [70,60,70,83,73,66,66,101,133,178,173,157,124,83,63] frame2 = [0,70,130,200,283,356,422,490,597,732,912,1087,1247,1375,1463,1520] cheak=0 Px=300 Ex=320 S_frame=0 S_Px=330 S_Ex=365 i=0 j=0 while(cheak<19): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuSkill2.clip_draw(frame2[i],0,frame1[j],145,Enemy_X-Ex,All_Y) #플레이어 IkuSkill2.clip_draw(frame2[i],145,frame1[j],145,Player_X+Px,All_Y) if cheak<11: i=(i+1)%16 j=(j+1)%15 if cheak>5: if(cheak<15): if cheak>8: #플레이어 IkuSkill2effect.clip_draw(S_frame *193,60,193,60,Player_X+S_Px,All_Y-5) #적 IkuSkill2effect.clip_draw(S_frame *193,0,193,60,Enemy_X-S_Ex,All_Y-5) S_Px += 10 S_Ex += 10 Px += 10 Ex += 10 if cheak>=15: i=(i+1)%16 j=(j+1)%15 Px -= 10 Ex -= 10 S_frame=(S_frame+1)%6 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Skill2() close_canvas() <file_sep>/Project/test/background.py from pico2d import * import BackgroundSelection import PlayerHP import EnemyHP import main_state class BackGround: def __init__(self): self.Shrine = load_image('./FCGimage/Hakurei Shrine.png') self.clock = load_image('./FCGimage/clock tower.png') self.bamboo = load_image('./FCGimage/bamboo.png') self.center =load_image('./FCGimage/center.png') self.KnockOut = load_image('./FCGimage/KO.png') self.Backtitle = load_image('./FCGimage/backtitle.png') def update(self): pass def draw(self): if BackgroundSelection.BGcheak==1: self.Shrine.draw(400, 300) if BackgroundSelection.BGcheak==0: self.bamboo.draw(400, 300) if BackgroundSelection.BGcheak==2: self.clock.draw(400, 300) self.center.draw(400, 500) if int(PlayerHP.damage) >252: self.KnockOut.draw(400,250) self.Backtitle.draw(400, 400) main_state.DeckShow =0 main_state.End=True elif int(EnemyHP.damage) >252: self.KnockOut.draw(400,250) self.Backtitle.draw(400,400) main_state.End = True <file_sep>/Project/test/reimu.py from pico2d import * import Deck import main_state import game_framework import game_world import PlayerHP #reimu stand STAND_TIME_PER_ACTION=1.2 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=12 #skill1 SKILL1TIME_PER_ACTION=1.5 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=15 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 0.8/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=13 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=25 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=23 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #item use ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 0.8/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=9 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # reimuEvent Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) key_event_table = { (SDL_MOUSEBUTTONDOWN, 1): Skill1, (SDL_MOUSEBUTTONDOWN, 2): Skill2, (SDL_MOUSEBUTTONDOWN, 3): Skill3, (SDL_MOUSEBUTTONDOWN, 4): Last, (SDL_MOUSEBUTTONDOWN, 99): Damage, (SDL_MOUSEBUTTONDOWN, 98): Down, (SDL_MOUSEBUTTONDOWN, 5): Item1, (SDL_MOUSEBUTTONDOWN, 6): Item2, (SDL_MOUSEBUTTONDOWN, 7): Item3 } # Reimu States HP= 0 class StandState: @staticmethod def enter(reimu, event): reimu.motion = 0 reimu.frame1 = 0 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): reimu.frame1 = (reimu.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 11 main_state.Character_Motion_Cheak = False if int(PlayerHP.damage) >252: reimu.down_sound.play() reimu.add_event(Down) if main_state.EnemyPlayer == 0 and main_state.reimu_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_last_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill2_atk_cheak==1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill3_atk_cheak ==1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_last_atk_cheak==1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_last_atk_cheak== 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_last_atk_cheak== 1: reimu.damage_sound.play() reimu.add_event(Damage) @staticmethod def draw(reimu): if reimu.motion ==0: reimu.stand.clip_draw(int(reimu.frame1) *100,105,97,105, reimu.x, reimu.y) class Skill1State: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill1cheak = 0 reimu.Skill1frame1 = [0,108,213,327,434,541,638,787,936,1080,1215,1319,1425] reimu.Skill1frame2 = [108,105,114,107,107,97,149,149,144,135,104,106] if event == Skill1: reimu.motion = 1 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): main_state.Character_Motion_Cheak = True if int(reimu.skill1cheak)<14: reimu.frame1 = (reimu.frame1+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 12 reimu.frame2 = (reimu.frame2+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 12 if int(reimu.skill1cheak) > 3: main_state.Skill1_Start = True reimu.skill1cheak =(reimu.skill1cheak+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%15 if int(reimu.skill1cheak)>=13: reimu.skill1cheak=0 reimu.add_event(Stand) main_state.Skill1_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 Deck.spellcheak += 3 main_state.turn = -1 @staticmethod def draw(reimu): if reimu.motion == 1: reimu.skill1.clip_draw(reimu.Skill1frame1[int(reimu.frame1)], 110, reimu.Skill1frame2[int(reimu.frame2)], 110, reimu.x, reimu.y) class Skill2State: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill2cheak = 0 reimu.Skill2frame1 = [0,66,120,217,304,392,480,572,675] reimu.Skill2frame2 = [66,54,97,87,88,88,92,103] if event == Skill2: reimu.motion = 2 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): main_state.Character_Motion_Cheak = True if int(reimu.skill2cheak) < 8: reimu.frame1 = (reimu.frame1+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 8 main_state.Skill2_Start=True if int(reimu.skill2cheak) >= 8: main_state.Skill2_Start = False reimu.skill2cheak = (reimu.skill2cheak+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%13 if int(reimu.skill2cheak) >= 12: reimu.skill2cheak = 0 reimu.add_event(Stand) main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 2: reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)],155, reimu.Skill2frame2[int(reimu.frame2)],120,reimu.x, reimu.y) class Skill3State: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill3cheak = 0 reimu.Skill3frame1 = [0,105, 210,315,420, 543, 659, 775, 885, 1000,1100] reimu.Skill3frame2 = [104,105,105,104,120,115,115,108,115,100] if event == Skill3: reimu.motion = 3 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): main_state.Character_Motion_Cheak = True if int(reimu.skill3cheak) < 24: if int(reimu.skill3cheak) < 5: reimu.frame1 = (reimu.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 reimu.frame2 = (reimu.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 if int(reimu.skill3cheak) >= 5: main_state.Skill3_Start = True if int(reimu.skill3cheak) > 20: reimu.frame1 = (reimu.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 11 reimu.frame2 = (reimu.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 reimu.skill3cheak = (reimu.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%25 if int(reimu.skill3cheak) >= 24: reimu.skill3cheak = 0 reimu.add_event(Stand) main_state.Skill3_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 3: reimu.skill3.clip_draw(reimu.Skill3frame1[int(reimu.frame1)],100,reimu.Skill3frame2[int(reimu.frame2)],100,reimu.x, reimu.y) class Laststate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.lastframe = 0 reimu.lastEframe1 = 0 reimu.lastcheak = 0 reimu.LastspellEframe1 = 0 reimu.Lastspellframe1 = 0 reimu.Lastspellframe2 = 0 reimu.Lastspellframe3 = 0 reimu.Lastspellc = 0 reimu.Lastspelld = 0 reimu.ReimuLastX = [580, 620, 600] reimu.ReimuLastY = [160.175, 200, 225, 250] reimu.Lastframe1 = [0,105, 209,311,414, 517, 620, 724, 822, 910, 995,1068,1145,1242,1345,1445] reimu.Lastframe2 = [105,104,102,103,104,103,104,98,88,85,74,77,97,103,100] if event == Last: reimu.motion = 4 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): main_state.Character_Motion_Cheak = True if int(reimu.lastcheak) < 22: if int(reimu.lastcheak) < 9: reimu.frame1 = (reimu.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 reimu.frame2 = (reimu.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 if int(reimu.lastcheak) >= 16: reimu.frame1 = (reimu.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 reimu.frame2 = (reimu.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Last_Start=True reimu.lastcheak = (reimu.lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%23 if int(reimu.lastcheak) >= 22: reimu.lastcheak = 0 reimu.add_event(Stand) main_state.Last_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 4: reimu.Lastspell.clip_draw(reimu.Lastframe1[int(reimu.frame1)], 130, reimu.Lastframe2[int(reimu.frame2)], 130,reimu.x, reimu.y+15) class Damagestate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.Damagecheak = 0 reimu.Damageframe = 0 if event == Damage: reimu.motion = 5 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): if int(reimu.Damagecheak) < 3: reimu.Damageframe = (reimu.Damageframe + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 reimu.Damagecheak = (reimu.Damagecheak+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(reimu.Damagecheak) >= 3: reimu.Damagecheak = 0 reimu.add_event(Stand) @staticmethod def draw(reimu): if reimu.motion == 5: reimu.Damage.clip_draw(int(reimu.Damageframe)*112,90,110,90, reimu.x, reimu.y) class Downstate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.Downcheak=0 reimu.Downframe1 = [0,92, 172,272,369, 465, 576, 683, 784, 889, 970] reimu.Downframe2 = [92,80,100,97,96,110,105,102,105,103,130] if event == Down: reimu.motion = 6 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): if int(reimu.Downcheak) < 20: if int(reimu.Downcheak) < 9: reimu.frame1 = (reimu.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 10 reimu.frame2 = (reimu.frame2+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 10 reimu.Downcheak = (reimu.Downcheak+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time)%21 if int(reimu.Downcheak) >= 20: pass @staticmethod def draw(reimu): if reimu.motion == 6: reimu.Down.clip_draw(reimu.Downframe1[int(reimu.frame1)],65,reimu.Downframe2[int(reimu.frame2)],65, reimu.x, reimu.y-25) class Item_Doll: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item1: reimu.motion = 7 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): global HP,HPcheak,skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = (reimu.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 7: reimu.item_use.clip_draw(0, 0, 40, 65, 200, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 155, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) class Item_Potion: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item2: reimu.motion = 8 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): global HP, HPcheak, skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = ( reimu.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 8: reimu.item_use.clip_draw(40, 0, 40, 65, 200, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 155, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) class Item_Clock: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item3: reimu.motion = 9 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): global HP, HPcheak, skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = (reimu.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(reimu): if reimu.motion == 9: reimu.item_use.clip_draw(80, 0, 40, 65, 200, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 155, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:Downstate}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Reimu: def __init__(self): self.x, self.y = 200, 200 self.stand = load_image('./FCGimage/Reimu-Standing-Motion.png') self.skill1 = load_image('./FCGimage/Reimu-Skill1-Motion.png') self.skill2 = load_image('./FCGimage/Reimu-Skill2-Motion.png') self.skill3 = load_image('./FCGimage/Reimu-Skill3-Motion.png') self.Lastspell = load_image('./FCGimage/Reimu-Last Spell-Motion.png') self.Lasteffect = load_image('./FCGimage/Reimu-Lastspell1.png') self.Lasteffect2 = load_image('./FCGimage/Reimu-Lastspell2-1.png') self.Lasteffect3 = load_image('./FCGimage/Reimu-Lastspell3-2.png') self.Damage = load_image('./FCGimage/ReimuDamage-Motion.png') self.Down = load_image('./FCGimage/Reimu-Downs-Motion.png') self.skill1_sound = load_wav('./voice/reimu-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/reimu-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/reimu-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/reimu-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/reimu-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/reimu-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/reimu-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): global cheak1, HP, mouse_x, mouse_y if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y = event.x, 600 - event.y if (event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT): ##스킬키 체크 if main_state.turn==1and main_state.DeckShow==1: if mouse_x > 270 and mouse_x < 330 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[Deck.spellcheak%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[Deck.spellcheak%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[Deck.spellcheak%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[Deck.spellcheak%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[Deck.spellcheak%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[Deck.spellcheak%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[Deck.spellcheak%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 370 and mouse_x < 430 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 470 and mouse_x < 530 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) elif (event.type, event.key) in key_event_table: key_event = key_event_table[(event.type, event.key)] self.add_event(key_event) <file_sep>/Project/Marisa/Marisa-Animation.py from pico2d import * class BackGround: def __init__(self): self.x, self.y = 400, 300 self.Shrine = load_image('Hakurei Shrine.png') def draw(self): self.Shrine.draw(self.x,self.y) class Marisa: def __init__(self): self.Player = 200 self.Enemy =600 self.All_Y=200 self.Dmage = load_image('MarisaDamage-Motion.png') self.Dmagei = 0 self.Dmagej = 0 self.Dmagecheak = 0 self.Down = load_image('MarisaDown-Motion.png') self.Downi = 0 self.Downj = 0 self.Downcheak = 0 self.Skill1 = load_image('MarisaSkill1-Motion.png') self.Skill1i =0 self.Skill1j =0 self.Skill1cheak=0 self.S1Effect = load_image('MarisaSkill1.png') self.Skill1Ei = 0 self.Skill1Ej = 0 self.Skill1Eframe1 = 0 self.Skill2 = load_image('MarisaSkill2-Motion.png') self.Skill2i = 0 self.Skill2j = 0 self.Skill2cheak=0 self.S2Effect = load_image('MarisaSkill2.png') self.Skill2Ex1 = 120 self.Skill2Ex2 = 100 self.Skill2Ex3 = 80 self.Skill3 = load_image('MarisaSkill3-Motion.png') self.Skill3i = 0 self.Skill3j = 0 self.Skill3cheak = 0 self.S3Effect = load_image('MarisaSKill3.png') self.Skill3Eframe1 =0 self.Skill3Ex1 = 120 self.Lastspell = load_image('MarisaLastspell-Motion.png') self.Lastspelli =0 self.Lastspellj=0 self.Lastspellcheak=0 self.LastspellEffect = load_image('MarisaLastspell.png') self.LastspellEframe1 =0 self.Standing = load_image('MarisaStanding-Motion.png') self.Standi = 0 self.Standj = 0 self.Standcheak =0 def update(self): pass def Damage(self): self.DamageFlame1 = [0, 90, 175, 240] self.DamageFlame2 = [90, 85, 65] #플레이어 self.Dmage.clip_draw(self.DamageFlame1[self.Dmagei], 115, self.DamageFlame2[self.Dmagej],115,self.Player,self.All_Y) #적 self.Dmage.clip_draw(self.DamageFlame1[self.Dmagei], 0, self.DamageFlame2[self.Dmagej], 115, self.Enemy, self.All_Y) if self.Dmagecheak <3: self.Dmagei = (self.Dmagei + 1) % 4 self.Dmagej = (self.Dmagej + 1) % 3 self.Dmagecheak += 1 if self.Dmagecheak ==3: self.Dmagei = 0 self.Dmagej = 0 self.Dmagecheak=0 def Downs(self): self.Downframe1 = [0,80,149,232,348,451,548,645] self.Downframe2 = [80,69,83,116,102,95,100] #플레이어 self.Down.clip_draw(self.Downframe1[self.Downi], 95, self.Downframe2[self.Downj], 95, self.Player, self.All_Y-20) #적 self.Down.clip_draw(self.Downframe1[self.Downi], 0, self.Downframe2[self.Downj], 95, self.Enemy, self.All_Y - 20) if self.Downcheak <7: self.Downi = (self.Downi + 1) % 8 self.Downj = (self.Downj + 1) % 7 self.Downcheak += 1 if self.Downcheak ==7: self.Downi = 0 self.Downj = 0 self.Downcheak=0 def Stand(self): self.Standframe1 = [0,65,126,188,250,312,372,434,495,556,618] self.Standframe2 = [65,61,62,62,62,60,62,61,60,62] #플레이어 self.Standing.clip_draw(self.Standframe1[self.Standi], 110, self.Standframe2[self.Standj], 110, self.Player,self.All_Y ) #적 self.Standing.clip_draw(self.Standframe1[self.Standi], 0, self.Standframe2[self.Standj], 110, self.Enemy,self.All_Y) if self.Standcheak < 10: self.Standi = (self.Standi+1) % 11 self.Standj = (self.Standj+1) % 10 self.Standcheak += 1 if self.Standcheak == 9: self.Standi = 0 self.Standj= 0 self.Standcheak = 0 def MSkill1(self): self.Skill1frame1 =[0, 71, 132, 197, 262, 322, 396, 468, 536, 600] self.Skill1frame2 =[71,61,65,65,58,72,72,66,60] #플레이어 self.Skill1.clip_draw(self.Skill1frame1[self.Skill1i], 105, self.Skill1frame2[self.Skill1j], 105, self.Player,self.All_Y) #적 self.Skill1.clip_draw(self.Skill1frame1[self.Skill1i], 0, self.Skill1frame2[self.Skill1j], 105, self.Enemy,self.All_Y) if self.Skill1cheak < 18: if self.Skill1cheak < 6: self.Skill1i = (self.Skill1i + 1) % 10 self.Skill1j = (self.Skill1j + 1) % 9 if self.Skill1cheak > 6: #Player self.S1Effect.clip_draw(self.Skill1Eframe1 * 260, 0, 260, 505, self.Enemy, self.All_Y+150) #Enemy self.S1Effect.clip_draw(self.Skill1Eframe1 * 260, 0, 260, 505, self.Player, self.All_Y + 150) if self.Skill1cheak < 15: self.Skill1Eframe1 = (self.Skill1Eframe1 + 1) % 9 if self.Skill1cheak >= 15: self.Skill1i = (self.Skill1i + 1) % 10 self.Skill1j = (self.Skill1j + 1) % 9 self.Skill1cheak += 1 if self.Skill1cheak == 18: self.Skill1i =0 self.Skill1j =0 self.Skill1cheak=0 self.Skill1Eframe1=0 def MSkill2(self): self.Skill2frame1 = [0, 85, 165, 240, 318, 395, 464, 525] self.Skill2frame2 = [85, 80, 75, 78, 76, 67, 64] # 플레이어 self.Skill2.clip_draw(self.Skill2frame1[self.Skill2i], 120, self.Skill2frame2[self.Skill2j], 120, self.Player,self.All_Y) # 적 self.Skill2.clip_draw(self.Skill2frame1[self.Skill2i], 0, self.Skill2frame2[self.Skill2j], 120, self.Enemy,self.All_Y) if self.Skill2cheak < 7: self.Skill2i = (self.Skill2i + 1) % 8 self.Skill2j = (self.Skill2j + 1) % 7 #Player self.S2Effect.clip_draw(0, 125, 132, 125, self.Player + self.Skill2Ex1, self.All_Y) self.S2Effect.clip_draw(132, 125, 132, 125, self.Player + self.Skill2Ex2, self.All_Y) self.S2Effect.clip_draw(264, 125, 132, 125, self.Player + self.Skill2Ex3, self.All_Y) #Enemy self.S2Effect.clip_draw(0, 0, 132, 125, self.Enemy - self.Skill2Ex1, self.All_Y) self.S2Effect.clip_draw(132, 0, 132, 125, self.Enemy - self.Skill2Ex2, self.All_Y) self.S2Effect.clip_draw(264, 0, 132, 125, self.Enemy - self.Skill2Ex3, self.All_Y) self.Skill2Ex1 += 75 self.Skill2Ex2 += 75 self.Skill2Ex3 += 75 self.Skill2cheak += 1 if self.Skill2cheak == 7: self.Skill2i = 0 self.Skill2j = 0 self.Skill2Ex1 = 120 self.Skill2Ex2 = 100 self.Skill2Ex3 = 80 self.Skill2cheak =0 def MSkill3(self): self.Skill3frame1 = [0, 65,125,195,275,332,412,500,590,661] self.Skill3frame2 = [65,60,70,80,60,76,85,89,68,61] # 플레이어 self.Skill3.clip_draw(self.Skill3frame1[self.Skill3i], 110, self.Skill3frame2[self.Skill3j], 110, self.Player,self.All_Y) # 적 self.Skill3.clip_draw(self.Skill3frame1[self.Skill3i], 0, self.Skill3frame2[self.Skill3j], 110, self.Enemy,self.All_Y) if self.Skill3cheak < 17: if self.Skill3cheak<7: self.Skill3i = (self.Skill3i + 1) % 10 self.Skill3j = (self.Skill3j + 1) % 10 if self.Skill3cheak>=7: self.S3Effect.clip_draw(self.Skill3Eframe1*260, 255, 260, 255, self.Player + self.Skill3Ex1, self.All_Y) self.Skill3Eframe1 = (self.Skill3Eframe1+1)%3 self.Skill3Ex1 += 80 if self.Skill3cheak >=13: self.Skill3i = (self.Skill3i + 1) % 10 self.Skill3j = (self.Skill3j + 1) % 10 self.Skill3cheak += 1 if self.Skill3cheak == 17: self.Skill3i = 0 self.Skill3j = 0 self.Skill3Ex1= 120 self.Skill3cheak = 0 def MLastspell(self): self.Lastframe1 = [0, 65,127,187,251,305,386,451,536,610,680,750,815,880,943,1010,1070] self.Lastframe2 = [65,62,60,64,55,79,62,80,72,66,66,65,63,60,59,58,58] # 플레이어 self.Lastspell.clip_draw(self.Lastframe1[self.Lastspelli], 120, self.Lastframe2[self.Lastspellj], 120, self.Player+250,self.All_Y) # 적 self.Lastspell.clip_draw(self.Lastframe1[self.Lastspelli], 0, self.Lastframe2[self.Lastspellj], 120, self.Enemy-250,self.All_Y) if self.Lastspellcheak < 18: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 if self.Lastspellcheak > 4: if self.Lastspellcheak < 11: #Player self.LastspellEffect.clip_draw(self.LastspellEframe1 * 261, 250, 260, 250, self.Player + 400,self.All_Y-10) #Enemy self.LastspellEffect.clip_draw(self.LastspellEframe1 * 261, 0, 260, 250, self.Enemy - 400, self.All_Y ) self.LastspellEframe1=(self.LastspellEframe1+1)%7 self.Lastspellcheak += 1 if self.Lastspellcheak == 18: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 def handle_events(): global running events = get_events() for event in events: if event.type == SDL_QUIT: running = False elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: running = False open_canvas() background=BackGround() marisa=Marisa() running=True while running: handle_events() clear_canvas() background.draw() marisa.update() #marisa.Damage() #marisa.Downs() #marisa.Stand() #marisa.MSkill1() #marisa.MSkill2() #marisa.MSkill3() marisa.MLastspell() update_canvas() delay(0.1) # finalization code close_canvas() <file_sep>/Project/test/Enemy_tenshi.py from pico2d import * import EnemyHP import main_state import random import DeckSelection import game_world import game_framework from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode import BackgroundSelection import PlayerHP #tenshi stand STAND_TIME_PER_ACTION=0.8 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=6 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=16 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=22 #skill3 SKILL3TIME_PER_ACTION=1.5 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=17 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=21 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=6 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #item use ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=16 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # iku Event Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) # Iku States ationcheak = 0 class StandState: @staticmethod def enter(tenshi, event): global ationcheak tenshi.motion = 0 tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.Standframe1 = [0,65,126,196,271,345] tenshi.Standframe2 = [65,61,70,75,74] ationcheak = 0 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): global ationcheak tenshi.frame1 = (tenshi.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.frame2 = (tenshi.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 5 main_state.Enemy_Motion_Cheak = False if DeckSelection.character == 0 and main_state.reimu_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_last_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill2_atk_cheak==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill3_atk_cheak ==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_last_atk_cheak==1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_last_atk_cheak== 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill1_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill2_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill3_atk_cheak == 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_last_atk_cheak== 1: tenshi.damage_sound.play() tenshi.add_event(Damage) if main_state.HPcheak==0 and int(EnemyHP.damage) >252: tenshi.down_sound.play() tenshi.add_event(Down) if main_state.HPcheak == 0 and int(EnemyHP.damage) < 251: if ationcheak == 1: #test tenshi.skill1_sound.play() main_state.P_HP += 20 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff tenshi.add_event(Skill1) if ationcheak == 2: #test tenshi.skill2_sound.play() main_state.P_HP += 30 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff tenshi.add_event(Skill2) if ationcheak == 3: #test tenshi.skill3_sound.play() main_state.P_HP += 40 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff tenshi.add_event(Skill3) if ationcheak == 4: #test tenshi.last_sound.play() main_state.P_HP += 50 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff tenshi.add_event(Last) if ationcheak == 5: #test tenshi.item_sound.play() main_state.Enemy_DefBuff = 0 tenshi.add_event(Item1) if ationcheak == 6: #test tenshi.item_sound.play() main_state.Enemy_AtkBuff = 3 tenshi.add_event(Item2) if ationcheak == 7: #test tenshi.item_sound.play() main_state.HP -= 100 EnemyHP.damage -= 100 tenshi.add_event(Item3) @staticmethod def draw(tenshi): if tenshi.motion ==0: tenshi.stand.clip_draw(tenshi.Standframe1[int(tenshi.frame1)], 0, tenshi.Standframe2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Skill1State: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill1cheak = 0 tenshi.Skill1frame1 = [0,75,143,214,294,379,500,616,695,776,852,929,1006,1076,1146,1210] tenshi.Skill1frame2 = [75,67,70,77,82,120,112,73,73,73,71,68,65,63,64] tenshi.TenshiS1X = [0, 106, 235, 367, 509, 646, 746, 875] tenshi.TenshiS1Y = [107, 129, 132, 142, 135, 98, 135] if event == Skill1: tenshi.motion = 1 @staticmethod def exit(tenshi, event): pass #if event ==SPACE: # boy.fire_ball() @staticmethod def do(tenshi): main_state.Enemy_Motion_Cheak = True if int(tenshi.skill1cheak)<15: tenshi.frame1 = (tenshi.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Skill1_Start = True tenshi.skill1cheak =(tenshi.skill1cheak+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%16 if int(tenshi.skill1cheak)>=15: tenshi.skill1cheak=0 tenshi.add_event(Stand) main_state.Skill1_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 1: tenshi.skill1.clip_draw(tenshi.Skill1frame1[int(tenshi.frame1)],0,tenshi.Skill1frame2[int(tenshi.frame2)],160, tenshi.x, tenshi.y+30) class Skill2State: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill2cheak = 0 tenshi.Skill2frame1 = [0,70,149,228,305,378,448,520,590,664,740,814,888,960,1026,1100] tenshi.Skill2frame2 = [70,79,79,77,73,69,68,67,70,69,66,69,66,60,60] if event == Skill2: tenshi.motion = 2 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): main_state.Enemy_Motion_Cheak = True if int(tenshi.skill2cheak) < 21: main_state.Skill2_Start = True if int(tenshi.skill2cheak) < 10: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 if int(tenshi.skill2cheak) >= 16: tenshi.frame1 = (tenshi.frame1+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.skill2cheak = ( tenshi.skill2cheak + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%22 if int(tenshi.skill2cheak) >= 21: tenshi.skill2cheak = 0 tenshi.add_event(Stand) main_state.Skill2_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 2: tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 0, tenshi.Skill2frame2[int(tenshi.frame2)], 115,tenshi.x, tenshi.y) class Skill3State: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.skill3cheak = 0 tenshi.Skill3frame1 = [0,77,155,240,340,425,528,710,876,960,1040,1110,1190] tenshi.Skill3frame2 = [77,78,83,99,80,98,178,160,70,70,63,68] if event == Skill3: tenshi.motion = 3 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): main_state.Enemy_Motion_Cheak = True if int(tenshi.skill3cheak) < 16: if int(tenshi.skill3cheak) < 10: tenshi.frame1 = (tenshi.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.frame2 = (tenshi.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 if int(tenshi.skill3cheak)>6 and int(tenshi.skill3cheak)<14: main_state.Skill3_Start=True if int(tenshi.skill3cheak) >= 14: main_state.Skill3_Start = False tenshi.frame1 = (tenshi.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.frame2 = (tenshi.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 12 tenshi.skill3cheak = (tenshi.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%17 if int(tenshi.skill3cheak)>= 16: tenshi.skill3cheak = 0 tenshi.add_event(Stand) main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 3: tenshi.skill3.clip_draw(tenshi.Skill3frame1[int(tenshi.frame1)], 0, tenshi.Skill3frame2[int(tenshi.frame2)], 115,tenshi.x-200, tenshi.y) class Laststate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.lastcheak = 0 tenshi.Lastframe1 = [0,72,142,266,435,577,715,842,928,1064,1200,1328,1430,1540,1640,1790,1965,2130,2295,2395,2465] tenshi.Lastframe2 = [72,70,124,169,142,137,124,85,132,131,124,96,109,95,145,167,155,150,90,72] if event == Last: tenshi.motion = 4 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): main_state.Enemy_Motion_Cheak = True if int(tenshi.lastcheak) < 20: tenshi.frame1 = (tenshi.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 20 tenshi.frame2 = (tenshi.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 20 main_state.Last_Start = True tenshi.lastcheak = (tenshi.lastcheak+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%21 if int(tenshi.lastcheak) >= 20: tenshi.lastcheak = 0 tenshi.add_event(Stand) main_state.Last_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 4: tenshi.Lastspell.clip_draw(tenshi.Lastframe1[int(tenshi.frame1)], 0, tenshi.Lastframe2[int(tenshi.frame2)], 165,tenshi.x-200, tenshi.y+30) class Damagestate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.Damagecheak = 0 if event == Damage: tenshi.motion = 5 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): if int(tenshi.Damagecheak) < 5: tenshi.frame1 = (tenshi.frame1 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.Damagecheak = (tenshi.Damagecheak + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 6 if int(tenshi.Damagecheak) >= 5: tenshi.Damagecheak = 0 tenshi.add_event(Stand) @staticmethod def draw(tenshi): if tenshi.motion == 5: tenshi.Damage.clip_draw(int(tenshi.frame1)*80,0,78,115, tenshi.x, tenshi.y) class Downstate: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.Downcheak=0 tenshi.Downframe1 = [0,120,235,350,470,595] tenshi.Downframe2 = [120,115,115,120,125] if event == Down: tenshi.motion = 6 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): if int(tenshi.Downcheak) < 20: if int(tenshi.Downcheak) < 4: tenshi.frame1 = (tenshi.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.frame2 = (tenshi.frame2 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 5 tenshi.Downcheak = (tenshi.Downcheak + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 21 if int(tenshi.Downcheak) >= 20: tenshi.Downcheak = 20 #tenshi.timer -= 1 @staticmethod def draw(tenshi): if tenshi.motion == 6: tenshi.Down.clip_draw(tenshi.Downframe1[int(tenshi.frame1)], 0, tenshi.Downframe2[int(tenshi.frame2)], 75, tenshi.x, tenshi.y-33) class Item_Doll: @staticmethod def enter(tenshi,event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item1: tenshi.motion = 7 @staticmethod def exit(tenshi,event): pass @staticmethod def do(tenshi): global HP,HPcheak,skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 7: tenshi.item_use.clip_draw(0, 0, 40, 65, 600, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 0,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Item_Potion: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item2: tenshi.motion = 8 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): global HP, HPcheak, skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 8: tenshi.item_use.clip_draw(40, 0, 40, 65, 600, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 0,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) class Item_Clock: @staticmethod def enter(tenshi, event): tenshi.frame1 = 0 tenshi.frame2 = 0 tenshi.item1cheak = 0 tenshi.Skill2frame1 = [0, 70, 149, 228, 305, 378, 448, 520, 590, 664, 740, 814, 888, 960, 1026, 1100] tenshi.Skill2frame2 = [70, 79, 79, 77, 73, 69, 68, 67, 70, 69, 66, 69, 66, 60, 60] if event == Item3: tenshi.motion = 9 @staticmethod def exit(tenshi, event): pass @staticmethod def do(tenshi): global HP, HPcheak, skillcheak if int(tenshi.item1cheak) < 15: tenshi.frame1 = (tenshi.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.frame2 = (tenshi.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 tenshi.item1cheak = (tenshi.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 16 if int(tenshi.item1cheak) >= 15: tenshi.item1cheak = 0 tenshi.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(tenshi): if tenshi.motion == 9: tenshi.item_use.clip_draw(80, 0, 40, 65, 600, 280) tenshi.skill2.clip_draw(tenshi.Skill2frame1[int(tenshi.frame1)], 0,tenshi.Skill2frame2[int(tenshi.frame2)], 115, tenshi.x, tenshi.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:StandState}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Enemy_Tenshi: def __init__(self): self.x, self.y = 600, 200 self.stand = load_image('./FCGimage/TenshiStanding-Motion.png') self.skill1 = load_image('./FCGimage/TenshiSkill1-Motion.png') self.skill2 = load_image('./FCGimage/TenshiSkill2-Motion.png') self.skill3 = load_image('./FCGimage/TenshiSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/TenshiLastspell-Motion.png') self.Damage = load_image('./FCGimage/TenshiDamage-Motion.png') self.Down = load_image('./FCGimage/TenshiDown-Motion.png') self.skill1_sound = load_wav('./voice/tenshi-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/tenshi-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/tenshi-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/tenshi-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/tenshi-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/tenshi-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/tenshi-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.build_behavior_tree() self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def turn_cheak(self): if main_state.turn == -1: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def action_cheak(self): global ationcheak if ationcheak ==0: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=212: ationcheak=3 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def buff_ready_cheak(self): global ationcheak if main_state.Enemy_DefBuff==0 or main_state.Enemy_AtkBuff==3: ationcheak= random.randint(1,4) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def atk_cheak(self): global ationcheak if main_state.Enemy_DefBuff == 1 and main_state.Enemy_AtkBuff == 1: ationcheak = random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_atk_buff_cheak(self): if main_state.Enemy_AtkBuff ==3: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def player_atk_buff_cheak(self): global ationcheak if main_state.Player_AtkBuff==3: success_cheak=random.randint(1,100) if success_cheak>75: ationcheak=5 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_HP_cheak(self): global ationcheak if EnemyHP.damage>200: success_cheak = random.randint(1, 100) if success_cheak>50: ationcheak=7 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def Hard_finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=102: ationcheak=4 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def build_behavior_tree(self): turn_cheak_node = LeafNode("Turn Cheak", self.turn_cheak) action_cheak_node = LeafNode("Action Stand", self.action_cheak) finish_atk_cheak_node = LeafNode("Finish_Atk", self.finish_atk_cheak) buff_ready_cheak_node = LeafNode("Buff Ready Cheak", self.buff_ready_cheak) atk_cheak_node = LeafNode("Atk", self.atk_cheak) ##Hard enemy_atk_buff_cheak_node = LeafNode("Atk_Buff_Cheak", self.enemy_atk_buff_cheak) Hard_finish_atk_cheak_node = LeafNode("Finish_Atk", self.Hard_finish_atk_cheak) player_atk_buff_cheak_node = LeafNode("Player_Buff_Cheak", self.player_atk_buff_cheak) enemy_hp_cheak_node = LeafNode("Enemy_HP_Cheak", self.enemy_HP_cheak) ##Nomal Finsh_node = SequenceNode("Finish") Finsh_node.add_children(turn_cheak_node, action_cheak_node,finish_atk_cheak_node) Buff_Atk_node =SequenceNode("BuffAtk") Buff_Atk_node.add_children(turn_cheak_node,action_cheak_node,buff_ready_cheak_node) Atk_node = SequenceNode("Atk") Atk_node.add_children(turn_cheak_node, action_cheak_node,atk_cheak_node) action_chase_node = SelectorNode("ActionChase") action_chase_node.add_children(Finsh_node, Buff_Atk_node,Atk_node) ##Hard Hard_Finsh_node = SequenceNode("Hard-Finish") Hard_Finsh_node.add_children(turn_cheak_node,action_cheak_node, enemy_atk_buff_cheak_node, Hard_finish_atk_cheak_node) Hard_Block_node = SequenceNode("Hard-Block") Hard_Block_node.add_children(turn_cheak_node, action_cheak_node,player_atk_buff_cheak_node) Hard_HP_node = SequenceNode("Hard-Block") Hard_HP_node.add_children(turn_cheak_node, action_cheak_node, enemy_hp_cheak_node) Hard_action_chase_node = SelectorNode("Hard_ActionChase") Hard_action_chase_node.add_children(Hard_Finsh_node, Hard_Block_node, Hard_HP_node,Buff_Atk_node,Atk_node) if BackgroundSelection.Level_cheak==1: self.ation = BehaviorTree(action_chase_node) if BackgroundSelection.Level_cheak == 2: self.ation = BehaviorTree(Hard_action_chase_node) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.ation.run() self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): pass <file_sep>/Project/test/DeckSelection.py import game_framework import random from pico2d import * import CharacterSelection import BackgroundSelection import main_state #import CharacterSelection import game_world name = "deckSelection" reset =None image = None next = None character = None Enemycharacter=None Enemycharacter=None Deckcheak1=0 Deck1=0 Deckcheak2=0 Deck2=[0,0,0,0,0,0,0,0,0,0,0,0] Deck3=[0,0,0,0,0,0,0,0,0,0,0,0] Deck_y=[230,230,230,230,230,230,165,165,165,165,165,165] mouse_x,mouse_y=0,0 Decklist =[0,0,0,0,0,0,0,0,0,0,0,0] skill1cheak=0 skill2cheak=0 skill3cheak=0 lastcheak=0 common1cheak=0 common2cheak=0 common3cheak=0 def enter(): global iku,reimu,tenshi,marisa,character,Enemycharacter,next global reimuSkill1, reimuSkill2, reimuSkill3,marisaSkill1,marisaSkill2,marisaSkill3,ikuSkill1,ikuSkill2,ikuSkill3 global reimuLast,marisaLast,ikuLast,tenshiLast,tenshiSkill1,tenshiSkill2,tenshiSkill3,commonItem1,commonItem2,commonItem3 global reimuDeck,marisaDeck,ikuDeck,tenshiDeck,commonDeck,reset global skill1cheak,skill2cheak,skill3cheak,lastcheak,common1cheak,common2cheak,common3cheak,Deckcheak1,Deckcheak2 reimu= load_image('./FCGimage/Reimu-Deck.png') reimuDeck= load_image('./FCGimage/RimuSpellCard.png') reimuSkill1 = load_image('./FCGimage/Reimu-Skill1-Dic.png') reimuSkill2 = load_image('./FCGimage/Reimu-Skill2-Dic.png') reimuSkill3 = load_image('./FCGimage/Reimu-Skill3-Dic.png') reimuLast = load_image('./FCGimage/Reimu-Last-Dic.png') marisa= load_image('./FCGimage/Marisa-Deck.png') marisaDeck= load_image('./FCGimage/MarisaSpellCard.png') marisaSkill1 = load_image('./FCGimage/Marisa-Skill1-Dic.png') marisaSkill2 = load_image('./FCGimage/Marisa-Skill2-Dic.png') marisaSkill3 = load_image('./FCGimage/Marisa-Skill3-Dic.png') marisaLast = load_image('./FCGimage/Marisa-Last-Dic.png') iku = load_image('./FCGimage/Iku-Deck.png') ikuDeck= load_image('./FCGimage/IkuSpellCard.png') ikuSkill1 = load_image('./FCGimage/Iku-Skill1-Dic.png') ikuSkill2 = load_image('./FCGimage/Iku-Skill2-Dic.png') ikuSkill3 = load_image('./FCGimage/Iku-Skill3-Dic.png') ikuLast =load_image('./FCGimage/Iku-Last-Dic.png') tenshi = load_image('./FCGimage/Tenshi-Deck.png') tenshiDeck= load_image('./FCGimage/TenshiSpellCard.png') tenshiSkill1 = load_image('./FCGimage/Tenshi-Skill1-Dic.png') tenshiSkill2 = load_image('./FCGimage/Tenshi-Skill2-Dic.png') tenshiSkill3 = load_image('./FCGimage/Tenshi-Skill3-Dic.png') tenshiLast = load_image('./FCGimage/Tenshi-Last-Dic.png') next=load_image('./FCGimage/Deck_Next.png') commonDeck=load_image('./FCGimage/commonCard.png') commonItem1 = load_image('./FCGimage/Common-Card1-Dic.png') commonItem2 = load_image('./FCGimage/Common-Card2-Dic.png') commonItem3 = load_image('./FCGimage/Common-Card3-Dic.png') reset=load_image('./FCGimage/Reset.png') character = CharacterSelection.character Deckcheak1 = 0 Deckcheak2 = 0 skill1cheak = 0 skill2cheak = 0 skill3cheak = 0 lastcheak = 0 common1cheak = 0 common2cheak = 0 common3cheak = 0 def exit(): global iku, reimu, tenshi, marisa def handle_events(): global character,Enemycharacter,Deckcheak,mouse_x,mouse_y,Deckcheak1,Deckcheak2 global skill1cheak,skill2cheak,skill3cheak,lastcheak,common1cheak,common2cheak,common3cheak events = get_events() for event in events: if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y=event.x, 600- event.y if event.type ==SDL_QUIT: game_framework.quit() else: if(event.type, event.key) == (SDL_KEYDOWN,SDLK_ESCAPE): Deckcheak1=0 skill1cheak, skill2cheak, skill3cheak, lastcheak, common1cheak, common2cheak, common3cheak=0,0,0,0,0,0,0 game_framework.push_state(CharacterSelection) elif(event.type, event.button)==(SDL_MOUSEBUTTONDOWN,SDL_BUTTON_LEFT): if skill1cheak <3and Deckcheak1<12 and mouse_x > 75 and mouse_x < 125 and mouse_y > 365 and mouse_y < 435: Deck3[Deckcheak1] = 0 Deck2[Deckcheak1] = 0 Decklist[Deckcheak1]=1 Deckcheak1 += 1 skill1cheak += 1 if skill2cheak <3 and Deckcheak1<12 and mouse_x > 175 and mouse_x < 225 and mouse_y > 365 and mouse_y < 435: Deck3[Deckcheak1] = 45 Deck2[Deckcheak1] = 0 Decklist[Deckcheak1] = 2 Deckcheak1 += 1 skill2cheak += 1 if skill3cheak <3 and Deckcheak1<12 and mouse_x > 275 and mouse_x < 325 and mouse_y > 365 and mouse_y < 435: Deck3[Deckcheak1] = 90 Deck2[Deckcheak1] = 0 Decklist[Deckcheak1] = 3 Deckcheak1 += 1 skill3cheak += 1 if lastcheak<2 and Deckcheak1<12 and mouse_x > 375 and mouse_x < 425 and mouse_y > 365 and mouse_y < 435: Deck3[Deckcheak1] = 135 Deck2[Deckcheak1] = 0 Decklist[Deckcheak1] = 4 Deckcheak1 += 1 lastcheak += 1 if common1cheak <3 and Deckcheak1<12 and mouse_x > 125 and mouse_x < 175 and mouse_y > 165 and mouse_y < 235: Deck2[Deckcheak1] = 65 Deck3[Deckcheak1] = 0 Decklist[Deckcheak1] = 5 Deckcheak1 += 1 common1cheak += 1 if common2cheak <3 and Deckcheak1<12 and mouse_x > 225 and mouse_x < 275 and mouse_y > 165 and mouse_y < 235: Deck2[Deckcheak1] = 65 Deck3[Deckcheak1] = 45 Decklist[Deckcheak1] = 6 Deckcheak1 += 1 common2cheak += 1 if common3cheak <3 and Deckcheak1<12 and mouse_x > 325 and mouse_x < 375 and mouse_y > 165 and mouse_y < 235: Deck2[Deckcheak1] = 65 Deck3[Deckcheak1] = 90 Decklist[Deckcheak1] = 7 Deckcheak1 += 1 common3cheak += 1 if Deckcheak1==12 and mouse_x > 625 and mouse_x < 750 and mouse_y>450and mouse_y<550: game_framework.push_state(BackgroundSelection) if mouse_x > 550 and mouse_x < 750 and mouse_y>30and mouse_y<90: Deckcheak1 = 0 Deckcheak2 = 0 skill1cheak = 0 skill2cheak = 0 skill3cheak = 0 lastcheak = 0 common1cheak = 0 common2cheak = 0 common3cheak = 0 def draw(): global Deck1,Deck2,Deckcheak1,Deckcheak2,mouse_x,mouse_y,reset Deck1 = 0 clear_canvas() if character ==0: reimu.draw(400,300) for D in range(0, 4): reimuDeck.clip_draw(45*D,0,45,65,100*(D+1),400) for C in range(0,3): commonDeck.clip_draw(40*C, 0, 40, 65, 50+100*(C+1), 200) elif character ==1: marisa.draw(400,300) for D in range(0, 4): marisaDeck.clip_draw(45*D,0,45,65,100*(D+1),400) for C in range(0,3): commonDeck.clip_draw(40*C, 0, 40, 65, 50+100*(C+1), 200) elif character ==2: iku.draw(400,300) for D in range(0, 4): ikuDeck.clip_draw(45*D,0,45,65,100*(D+1),400) for C in range(0,3): commonDeck.clip_draw(40*C, 0, 40, 65, 50+100*(C+1), 200) elif character ==3: tenshi.draw(400,300) for D in range(0, 4): tenshiDeck.clip_draw(45*D,0,45,65,100*(D+1),400) for C in range(0,3): commonDeck.clip_draw(40*C, 0, 40, 65, 50+100*(C+1), 200) if mouse_x > 75 and mouse_x < 125 and mouse_y > 365 and mouse_y < 435: if character==0: reimuSkill1.draw(620, 360) if character == 1: marisaSkill1.draw(620, 360) if character==2: ikuSkill1.draw(620,360) if character==3: tenshiSkill1.draw(620,360) if mouse_x > 175 and mouse_x < 225 and mouse_y > 365 and mouse_y < 435: if character==0: reimuSkill2.draw(620, 360) if character == 1: marisaSkill2.draw(620, 360) if character==2: ikuSkill2.draw(620,360) if character==3: tenshiSkill2.draw(620,360) if mouse_x > 275 and mouse_x < 325 and mouse_y > 365 and mouse_y < 435: if character==0: reimuSkill3.draw(620, 360) if character == 1: marisaSkill3.draw(620, 360) if character==2: ikuSkill3.draw(620,360) if character==3: tenshiSkill3.draw(620,360) if mouse_x > 375 and mouse_x < 425 and mouse_y > 365 and mouse_y < 435: if character == 0: reimuLast.draw(620, 360) if character == 1: marisaLast.draw(620, 360) if character == 2: ikuLast.draw(620, 360) if character == 3: tenshiLast.draw(620, 360) if mouse_x > 125 and mouse_x < 175 and mouse_y > 165 and mouse_y < 235: commonItem1.draw(620,360) if mouse_x > 225 and mouse_x < 275 and mouse_y > 165 and mouse_y < 235: commonItem2.draw(620,360) if mouse_x > 325 and mouse_x < 375 and mouse_y > 165 and mouse_y < 235: commonItem3.draw(620,360) reset.draw(650, 50) next.draw(700,500) for Deck1 in range(0,Deckcheak1): if character == 0: reimuDeck.clip_draw(Deck3[Deck1], Deck2[Deck1], 45, 65, 510 + 45 * (Deck1 % 6), Deck_y[Deck1]) elif character == 1: marisaDeck.clip_draw(Deck3[Deck1], Deck2[Deck1], 45, 65, 510 + 45 * (Deck1 % 6), Deck_y[Deck1]) elif character == 2: ikuDeck.clip_draw(Deck3[Deck1], Deck2[Deck1], 45, 65, 510+45*(Deck1%6), Deck_y[Deck1]) elif character == 3: tenshiDeck.clip_draw(Deck3[Deck1], Deck2[Deck1], 45, 65, 510+45*(Deck1%6), Deck_y[Deck1]) update_canvas() def update(): global character,Enemycharacter Enemycharacter = random.randint(0, 3) def pause(): global character def resume(): pass <file_sep>/Project/FCG.py import game_framework import pico2d import FCG_title pico2d.open_canvas() game_framework.run(FCG_title) pico2d.close_canvas() <file_sep>/Project/Tensi/Tenshi-Standing-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiStanding = load_image('TenshiStanding-Motion.png') def Tenshi_Standing(): frame1 = [65,61,70,75,74] frame2 = [0,65,126,196,271,345] cheak=0 i=0 j=0 while(cheak<5): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiStanding.clip_draw(frame2[i],0,frame1[j],115,Enemy_X,All_Y) #플레이어 TenshiStanding.clip_draw(frame2[i],115,frame1[j],115,Player_X,All_Y) i=(i+1)%6 j=(j+1)%5 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Standing() close_canvas() <file_sep>/Project/Tensi/Tenshi-Lastspell-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiLastspell = load_image('TenshiLastspell-Motion.png') TenshiLastspelleffect = load_image('TenshiLastspell1-1.png') TenshiLastspelleffect2 = load_image('TenshiLastspell1-2.png') def Tenshi_Lastspell(): frame1 = [72,70,124,169,142,137,124,85,132,131,124,96,109,95,145,167,155,150,90,72] frame2 = [0,72,142,266,435,577,715,842,928,1064,1200,1328,1430,1540,1640,1790,1965,2130,2295,2395,2465] cheak=0 S_frame=0 i=0 j=0 while(cheak<20): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiLastspell.clip_draw(frame2[i],0,frame1[j],165,Enemy_X-200,All_Y) #플레이어 TenshiLastspell.clip_draw(frame2[i],165,frame1[j],165,Player_X+200,All_Y) i=(i+1)%21 j=(j+1)%20 if cheak >3: #플레이어 TenshiLastspelleffect2.clip_draw(0,0,250,250,Enemy_X,All_Y) #적 TenshiLastspelleffect2.clip_draw(0,0,250,250,Player_X,All_Y) if cheak >4: #플레이어 TenshiLastspelleffect.clip_draw(S_frame*260,0,260,250,Enemy_X,All_Y) #적 TenshiLastspelleffect.clip_draw(S_frame*260,0,260,250,Player_X,All_Y) if cheak ==9: S_frame +=1 if cheak ==15: S_frame +=1 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Lastspell() close_canvas() <file_sep>/Project/Iku/Iku-Damage-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuDamage = load_image('IkuDamage-Motion.png') def Iku_Damage(): frame2 = [94,80,73] frame1 = [0,94,174,245] cheak=0 i=0 j=0 while(cheak<3): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuDamage.clip_draw(frame1[i],0,frame2[j],135,Enemy_X,All_Y) #플레이어 IkuDamage.clip_draw(frame1[i],135,frame2[j],135,Player_X,All_Y) i=(i+1)%4 j=(j+1)%3 update_canvas() delay(0.2) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Damage() close_canvas() <file_sep>/Project/test/PlayerHP.py from pico2d import * import main_state import Enemy_iku #speed PIXEL_PER_METER=(10.0/0.3) Damage_SPEED_KMPH = 0.1 Damage_SPEED_MPM = (Damage_SPEED_KMPH*1000.0/60.0) Damage_SPEED_MPS=(Damage_SPEED_MPM/60.0) Damage_SPEED_PPS=(Damage_SPEED_MPS*PIXEL_PER_METER) attack=None damage=0 class Player_HP: def __init__(self): global attack self.x = 200 self.y = 500 self.damage=0 self.Power= 1 self.stop=0 self.HPBar = load_image('./FCGimage/HP-Damege.png') self.HP = load_image('./FCGimage/HP-HP.png') def update(self): global damage self.Power = main_state.P_HP if main_state.P_HPcheak == 1: if damage < self.Power: damage += Damage_SPEED_PPS if int(damage) == int(self.Power): main_state.P_HPcheak = 0 if main_state.P_HPinit == 1: damage = 0 main_state.P_HP = 0 main_state.P_HPinit = 0 if damage <0: damage=0 if main_state.P_HP <0: main_state.P_HP=0 def draw(self): global damage self.HPBar.draw(self.x, self.y) self.HP.clip_draw(0, 0, 252 - int(damage), 15, self.x + (damage // 2), self.y) <file_sep>/Project/Iku/Iku-Lastspell-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuLastspell = load_image('IkuLastspell-Motion.png') IkuLastspelleffect1 = load_image('IkuLastspell1-1.png') IkuLastspelleffect2 = load_image('IkuLastspell1-2.png') def Iku_Lastspell(): frame1 = [60,60,60,63,72,125,130,130,125,120] frame2 = [0,60,120,180,243,315,440,570,700,825,945,1035] cheak=0 S_frame=0 S2_frame1=[120,75] S2_frame2=[0,120,75] i=0 j=0 s=0 c=0 while(cheak<19): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuLastspell.clip_draw(frame2[i],0,frame1[j],140,Enemy_X,All_Y) #플레이어 IkuLastspell.clip_draw(frame2[i],140,frame1[j],140,Player_X,All_Y) if cheak<8: i=(i+1)%10 j=(j+1)%9 if cheak>=8: #플레이어 IkuLastspelleffect2.clip_draw(S2_frame2[(s+1)%2],0,S2_frame1[c],255,Enemy_X-50,All_Y+70) IkuLastspelleffect2.clip_draw(S2_frame2[(s+1)%2],0,S2_frame1[c],255,Enemy_X+40,All_Y+70) IkuLastspelleffect2.clip_draw(S2_frame2[s],0,S2_frame1[c],255,Enemy_X,All_Y+70) IkuLastspelleffect1.clip_draw(S_frame *270,0,270,255,Enemy_X+15,All_Y+210) #적 #IkuLastspelleffect2.clip_draw(S2_frame2[(s+1)%2],0,S2_frame1[c],255,Player_X+50,All_Y+70) #IkuLastspelleffect2.clip_draw(S2_frame2[(s+1)%2],0,S2_frame1[c],255,Player_X-40,All_Y+70) #IkuLastspelleffect2.clip_draw(S2_frame2[s],0,S2_frame1[c],255,Player_X,All_Y+70) #IkuLastspelleffect1.clip_draw(S_frame *270,0,270,255,Player_X+25,All_Y+210) S_frame= (S_frame+1)%4 s=(s+1)%2 c=(c+1)%1 if cheak>=16: i=(i+1)%10 j=(j+1)%10 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Lastspell() close_canvas() <file_sep>/Project/test/main_state.py import random import json import EnemyHP import os #os.chdir('C:\\2DGP\\2015180012-2DGP-PROJECT\\2DGP-PROJECT\\Project\\test\\FCGimage') from pico2d import * import game_framework import FCG_title import DeckSelection import Deck import ikuSkill import marisaSkill import reimuSkill import tenshiSkill import game_world import EnemyHP import PlayerHP from iku import Iku from reimu import Reimu from tenshi import Tenshi from marisa import Marisa from background import BackGround from PlayerHP import Player_HP from EnemyHP import Enemy_HP from Enemy_marisa import Enemy_Marisa from Enemy_reimu import Enemy_Reimu from Enemy_tenshi import Enemy_Tenshi from Enemy_iku import Enemy_Iku from Deck import PlayDeck from backgroundmusic import BG_Music #from ikuSkill import IKU_Skill1 name = "MainState" turncheak=0 iku = None reimu=None tenshi=None marisa=None Enemy_marisa=None Enemy_reimu =None Enemy_tenshi=None Enemy_iku=None EnemyPlayer=None deck=None Bg_Music=None turn = 1 DeckShow=1 Character_Motion_Cheak=False Enemy_Motion_Cheak=False End=False reimu_skill1_atk_cheak=0 reimu_skill2_atk_cheak=0 reimu_skill3_atk_cheak=0 reimu_last_atk_cheak=0 marisa_skill1_atk_cheak=None marisa_skill2_atk_cheak=None marisa_skill3_atk_cheak=None marisa_last_atk_cheak=None iku_skill1_atk_cheak=None iku_skill2_atk_cheak=None iku_skill3_atk_cheak=None iku_last_atk_cheak=None tenshi_skill1_atk_cheak=None tenshi_skill2_atk_cheak=None tenshi_skill3_atk_cheak=None tenshi_last_atk_cheak=None reimu_skill1_effect=None marisa_skill1_effect=None iku_skill1_effect=None tenshi_skill1_effect=None enemy_reimu_skill1_effect=None enemy_marisa_skill1_effect=None enemy_iku_skill1_effect=None enemy_tenshi_skill1_effect=None Player_AtkBuff=1 Player_DefBuff=1 Enemy_AtkBuff=1 Enemy_DefBuff=1 HPcheak=0 HP=0 #enemy P_HP=0 P_HPcheak=0 HPinit = 0 P_HPinit = 0 Skill1_Start= False Skill2_Start= False Skill3_Start= False Last_Start= False def enter(): global iku, background,reimu,tenshi,marisa,PlayerHP,EnemyHP,Enemy_marisa,Enemy_reimu,Enemy_tenshi,Enemy_iku,EnemyPlayer,turn,deck,damageheak global reimu_skill1_effect,marisa_skill1_effect,iku_skill1_effect,tenshi_skill1_effect, Bg_Music,HPinit,P_HPinit,DeckShow,End global enemy_reimu_skill1_effect,enemy_marisa_skill1_effect,enemy_iku_skill1_effect,enemy_tenshi_skill1_effect,Character_Motion_Cheak,Enemy_Motion_Cheak Character_Motion_Cheak = False Enemy_Motion_Cheak = False End=False EnemyPlayer=DeckSelection.Enemycharacter Bg_Music =BG_Music() game_world.add_object(Bg_Music, 0) HPinit=1 P_HPinit=1 turn=1 DeckShow=1 if EnemyPlayer == 0: Enemy_reimu = Enemy_Reimu() enemy_reimu_skill1_effect = reimuSkill.REIMU_Skill1() game_world.add_object(enemy_reimu_skill1_effect, 2) game_world.add_object(Enemy_reimu, 1) elif EnemyPlayer == 1: Enemy_marisa = Enemy_Marisa() enemy_marisa_skill1_effect = marisaSkill.MARISA_Skill1() game_world.add_object(enemy_marisa_skill1_effect, 2) game_world.add_object(Enemy_marisa, 1) elif EnemyPlayer == 2: Enemy_iku = Enemy_Iku() enemy_iku_skill1_effect=ikuSkill.IKU_Skill1() game_world.add_object(enemy_iku_skill1_effect, 2) game_world.add_object(Enemy_iku, 1) elif EnemyPlayer == 3: Enemy_tenshi = Enemy_Tenshi() enemy_tenshi_skill1_effect=tenshiSkill.TENSHI_Skill1() game_world.add_object(enemy_tenshi_skill1_effect, 2) game_world.add_object(Enemy_tenshi, 1) if DeckSelection.character == 0: reimu = Reimu() reimu_skill1_effect = reimuSkill.REIMU_Skill1() game_world.add_object(reimu_skill1_effect, 2) game_world.add_object(reimu, 1) elif DeckSelection.character == 1: marisa = Marisa() marisa_skill1_effect=marisaSkill.MARISA_Skill1() game_world.add_object(marisa_skill1_effect, 2) game_world.add_object(marisa, 1) elif DeckSelection.character == 2: iku = Iku() game_world.add_object(iku, 1) iku_skill1_effect = ikuSkill.IKU_Skill1() game_world.add_object(iku_skill1_effect, 2) elif DeckSelection.character == 3: tenshi = Tenshi() tenshi_skill1_effect = tenshiSkill.TENSHI_Skill1() game_world.add_object(tenshi_skill1_effect, 2) game_world.add_object(tenshi, 1) background = BackGround() PlayerHP=Player_HP() EnemyHP=Enemy_HP() deck=PlayDeck() game_world.add_object(deck, 1) game_world.add_object(background,0) game_world.add_object(PlayerHP, 0) game_world.add_object(EnemyHP, 0) def exit(): EnemyHP.damage = 0 game_world.clear() def pause(): pass def resume(): pass def handle_events(): global iku, background, reimu, tenshi, marisa, PlayerHP, EnemyHP, Enemy_marisa, Enemy_reimu, Enemy_tenshi, Enemy_iku, EnemyPlayer, turn,turncheak global damageheak,Bg_Music,HP,HPinit,P_HPinit global reimu_skill1_effect, marisa_skill1_effect, iku_skill1_effect, tenshi_skill1_effect, Bg_Music global enemy_reimu_skill1_effect, enemy_marisa_skill1_effect, enemy_iku_skill1_effect, enemy_tenshi_skill1_effect events = get_events() for event in events: if event.type == SDL_QUIT: game_framework.quit() elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE: if End==True and Enemy_Motion_Cheak == False and Character_Motion_Cheak ==False: HPinit = 1 P_HPinit = 1 game_world.remove_object(reimu_skill1_effect) game_world.remove_object(marisa_skill1_effect) game_world.remove_object(iku_skill1_effect) game_world.remove_object(tenshi_skill1_effect) game_world.remove_object(enemy_reimu_skill1_effect) game_world.remove_object(enemy_marisa_skill1_effect) game_world.remove_object(enemy_iku_skill1_effect) game_world.remove_object(enemy_tenshi_skill1_effect) game_world.remove_object(reimu) game_world.remove_object(marisa) game_world.remove_object(iku) game_world.remove_object(tenshi) game_world.remove_object(Enemy_reimu) game_world.remove_object(Enemy_marisa) game_world.remove_object(Enemy_iku) game_world.remove_object(Enemy_tenshi) game_world.remove_object(background) game_world.remove_object(PlayerHP) game_world.remove_object(EnemyHP) game_world.remove_object(deck) game_framework.push_state(FCG_title) else: if DeckSelection.character == 0 and turn ==1: reimu.handle_event(event) if DeckSelection.character == 1and turn ==1: marisa.handle_event(event) if DeckSelection.character == 2and turn ==1: iku.handle_event(event) if DeckSelection.character == 3and turn ==1: tenshi.handle_event(event) def update(): global skill1_atk_cheak,skill2_atk_cheak,skill3_atk_cheak,last_atk_cheak for game_objcet in game_world.all_objects(): game_objcet.update() def draw(): clear_canvas() for game_object in game_world.all_objects(): game_object.draw() update_canvas() <file_sep>/Project/test/Deck.py import game_framework import random from pico2d import * import CharacterSelection import DeckSelection import main_state #import CharacterSelection import game_world name = "deck" image = None next = None Enemycharacter=None Enemycharacter=None mouse_x,mouse_y=0,0 PlayerDeck=[0,0,0,0,0,0,0,0,0,0,0,0] temp=0 s1=0 s2=0 spellcheak=0 def shuffle(): global PlayerDeck,temp,s1,s2 for i in range(0,12): PlayerDeck[i]=DeckSelection.Decklist[i] for s in range(0,50): s1 = random.randint(0, 11) s2 = random.randint(0, 11) temp = PlayerDeck[s1] PlayerDeck[s1] = PlayerDeck[s2] PlayerDeck[s2] = temp class PlayDeck: def __init__(self): shuffle() self.x, self.y = 300, 100 self.ikuDeck= load_image('./FCGimage/IkuSpellCard.png') self.reimuDeck= load_image('./FCGimage/RimuSpellCard.png') self.marisaDeck= load_image('./FCGimage/MarisaSpellCard.png') self.tenshiDeck= load_image('./FCGimage/TenshiSpellCard.png') self.Deckimage=load_image('./FCGimage/Deck.png') def update(self): global spellcheak if spellcheak == 12: shuffle() spellcheak = 0 pass def draw(self): if main_state.turn==1 and main_state.DeckShow==1: if CharacterSelection.character==0: for i in range(1, 8): if PlayerDeck[spellcheak%12] == i: if i < 5: self.Deckimage.draw(self.x-5, self.y) self.reimuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x, self.y) else: self.Deckimage.draw(self.x-5, self.y) self.reimuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x, self.y) if PlayerDeck[(spellcheak+1)%12] == i: if i < 5: self.Deckimage.draw(self.x + 95, self.y) self.reimuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x+ 100, self.y) else: self.Deckimage.draw(self.x+ 95, self.y) self.reimuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x+ 100, self.y) if PlayerDeck[(spellcheak+2)%12] == i: if i < 5: self.Deckimage.draw(self.x + 195, self.y) self.reimuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x + 200, self.y) else: self.Deckimage.draw(self.x + 195, self.y) self.reimuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 200, self.y) if CharacterSelection.character==1: for i in range(0,12): for i in range(1, 8): if PlayerDeck[spellcheak % 12] == i: if i < 5: self.Deckimage.draw(self.x-5, self.y) self.marisaDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x, self.y) else: self.Deckimage.draw(self.x-5, self.y) self.marisaDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x, self.y) if PlayerDeck[(spellcheak + 1) % 12] == i: if i < 5: self.Deckimage.draw(self.x + 95, self.y) self.marisaDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x + 100, self.y) else: self.Deckimage.draw(self.x + 95, self.y) self.marisaDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 100, self.y) if PlayerDeck[(spellcheak + 2) % 12] == i: if i < 5: self.Deckimage.draw(self.x + 195, self.y) self.marisaDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x + 200, self.y) else: self.Deckimage.draw(self.x + 195, self.y) self.marisaDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 200, self.y) if CharacterSelection.character==2: for i in range(1, 8): if PlayerDeck[spellcheak%12] == i: if i < 5: self.Deckimage.draw(self.x-5, self.y) self.ikuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x, self.y) else: self.Deckimage.draw(self.x-5, self.y) self.ikuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x, self.y) if PlayerDeck[(spellcheak+1)%12] == i: if i < 5: self.Deckimage.draw(self.x + 95, self.y) self.ikuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x+ 100, self.y) else: self.Deckimage.draw(self.x+ 95, self.y) self.ikuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x+ 100, self.y) if PlayerDeck[(spellcheak+2)%12] == i: if i < 5: self.Deckimage.draw(self.x + 195, self.y) self.ikuDeck.clip_draw(45*(i-1), 0, 45, 65, self.x + 200, self.y) else: self.Deckimage.draw(self.x + 195, self.y) self.ikuDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 200, self.y) if CharacterSelection.character==3: for i in range(0,12): for i in range(1, 8): if PlayerDeck[spellcheak % 12] == i: if i < 5: self.Deckimage.draw(self.x-5, self.y) self.tenshiDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x, self.y) else: self.Deckimage.draw(self.x-5, self.y) self.tenshiDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x, self.y) if PlayerDeck[(spellcheak + 1) % 12] == i: if i < 5: self.Deckimage.draw(self.x + 95, self.y) self.tenshiDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x + 100, self.y) else: self.Deckimage.draw(self.x + 95, self.y) self.tenshiDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 100, self.y) if PlayerDeck[(spellcheak + 2) % 12] == i: if i < 5: self.Deckimage.draw(self.x + 195, self.y) self.tenshiDeck.clip_draw(45 * (i - 1), 0, 45, 65, self.x + 200, self.y) else: self.Deckimage.draw(self.x + 195, self.y) self.tenshiDeck.clip_draw(45 * (i - 5), 65, 45, 65, self.x + 200, self.y) def handle_event(self, event): pass<file_sep>/Project/test/marisaSkill.py from pico2d import * import game_framework import main_state import DeckSelection import marisa import Enemy_marisa import EnemyHP #marisa stand STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=20 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=9 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=20 #Damage DAMAGETIME_PER_ACTION=0.5 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) import game_world name = 'marisaskill' class MARISA_Skill1: def __init__(self): self.effect_Boom =None self.effect_Balls=None self.effect_MagicShot=None self.effect_Lazer=None if self.effect_Boom==None: self.effect_Boom = load_image('./FCGimage/MarisaSkill1.png') if self.effect_Balls==None: self.effect_Balls = load_image('./FCGimage/MarisaSkill2.png') if self.effect_MagicShot==None: self.effect_MagicShot = load_image('./FCGimage/MarisaSKill3.png') if self.effect_Lazer==None: self.effect_Lazer = load_image('./FCGimage/MarisaLastspell.png') #skill1 self.Boom_Px = 600 self.Boom_Ex = 200 self.Boom_frame=0 #skill2 self.Balls_First = 120 self.Balls_Second = 100 self.Balls_Third =80 #skill3 self.MagicShot_Fly =120 self.MagicShot_frame = 0 #Last self.Lazer_frame=0 def get_bb(self): pass def draw(self): if DeckSelection.character==1 and main_state.turn== 1 and main_state.Skill1_Start==True: self.effect_Boom.clip_draw(int(self.Boom_frame) * 260, 0, 260, 505, self.Boom_Px, 200+150) if main_state.EnemyPlayer==1 and main_state.turn== -1 and main_state.Skill1_Start==True: self.effect_Boom.clip_draw(int(self.Boom_frame) * 260, 0, 260, 505,self.Boom_Ex, 200+150) if DeckSelection.character==1 and main_state.turn ==1 and main_state.Skill2_Start ==True: self.effect_Balls.clip_draw(0, 125, 132, 125, 200 + self.Balls_First, 200) self.effect_Balls.clip_draw(132, 125, 132, 125, 200 + self.Balls_Second, 200) self.effect_Balls.clip_draw(264, 125, 132, 125, 200 + self.Balls_Third,200) if main_state.EnemyPlayer==1 and main_state.turn == -1 and main_state.Skill2_Start ==True: self.effect_Balls.clip_draw(0, 125, 132, 125, 600 - self.Balls_First, 200) self.effect_Balls.clip_draw(132, 125, 132, 125, 600 - self.Balls_Second, 200) self.effect_Balls.clip_draw(264, 125, 132, 125, 600 - self.Balls_Third, 200) if DeckSelection.character==1 and main_state.turn ==1 and main_state.Skill3_Start ==True: self.effect_MagicShot.clip_draw(int(self.MagicShot_frame) * 260, 255, 260, 255, 200 + self.MagicShot_Fly,200 + 25) if main_state.EnemyPlayer==1 and main_state.turn == -1 and main_state.Skill3_Start ==True: self.effect_MagicShot.clip_draw(int(self.MagicShot_frame) * 260, 0, 260, 255, 600 - self.MagicShot_Fly,200 + 25) if DeckSelection.character==1 and main_state.turn ==1 and main_state.Last_Start ==True: self.effect_Lazer.clip_draw(int(self.Lazer_frame) * 261, 250, 260, 250, 200 + 405, 200 - 10) if main_state.EnemyPlayer==1 and main_state.turn == -1 and main_state.Last_Start ==True: self.effect_Lazer.clip_draw(int(self.Lazer_frame) * 261, 0, 260, 250, 600 - 405, 200 - 10) def update(self): if main_state.Skill1_Start == True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.marisa_skill1_atk_cheak=1 self.Boom_frame = (self.Boom_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 if main_state.Skill1_Start==False: main_state.marisa_skill1_atk_cheak = 0 self.Boom_frame=0 if main_state.Skill2_Start ==True: if self.Balls_First >350 and self.Balls_First<360: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.marisa_skill2_atk_cheak=1 if self.Balls_First>=360: main_state.marisa_skill2_atk_cheak=0 self.Balls_First += int(MOTION_SPEED_PPS) * 5 self.Balls_Second += int(MOTION_SPEED_PPS) * 5 self.Balls_Third += int(MOTION_SPEED_PPS) * 5 if main_state.Skill2_Start ==False: main_state.marisa_skill2_atk_cheak = 0 self.Balls_First = 120 self.Balls_Second = 100 self.Balls_Third = 80 if main_state.Skill3_Start==True: if self.MagicShot_Fly >350 and self.MagicShot_Fly<360: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.marisa_skill3_atk_cheak=1 if self.MagicShot_Fly>=360: main_state.marisa_skill3_atk_cheak=0 self.MagicShot_frame = (self.MagicShot_frame + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 3 self.MagicShot_Fly += int(MOTION_SPEED_PPS) * 5 if main_state.Skill3_Start==False: main_state.marisa_skill3_atk_cheak = 0 self.MagicShot_Fly = 120 if main_state.Last_Start==True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.marisa_last_atk_cheak = 1 self.Lazer_frame = (self.Lazer_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 7 if main_state.Last_Start==False: main_state.marisa_last_atk_cheak = 0 <file_sep>/Project/test/ikuSkill.py from pico2d import * import game_framework import main_state import DeckSelection import iku import Enemy_iku import EnemyHP #iku stand STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=24 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=20 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 0.5/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=35 #Damage DAMAGETIME_PER_ACTION=0.5 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) import game_world name = 'ikuskill' test=0 class IKU_Skill1: def __init__(self): self.effect_Line = None self.effect_Ball = None self.drill=None self.effect_lightning = None self.effect_Last_Ball = None self.effect_Last_Lightning =None if self.effect_Line ==None: self.effect_Line = load_image('./FCGimage/IkuSkill1-1.png') if self.effect_Ball ==None: self.effect_Ball = load_image('./FCGimage/IkuSkill1-2.png') if self.drill ==None: self.drill = load_image('./FCGimage/ikuSkill2-1.png') if self.effect_lightning == None: self.effect_lightning = load_image('./FCGimage/ikuSkill3-1.png') if self.effect_Last_Ball ==None: self.effect_Last_Ball = load_image('./FCGimage/IkuLastspell1-1.png') if self.effect_Last_Lightning ==None: self.effect_Last_Lightning = load_image('./FCGimage/IkuLastspell1-2.png') #skill1 self.Line_Px, self.Line_Py = 400, 210 self.Ball_Px, self.Ball_Py = 600-10, 210 self.Line_Ex, self.Line_Ey = 390, 210 self.Ball_Ex, self.Ball_Ey = 200 + 10, 210 self.Line_frame = 0 self.Ball_frame =0 #skill2 self.Drill_Pmove = 530 self.Drill_Emove=270 self.Drill_frame =0 #skill3 self.Lightning_Px = 600 self.Lightning_Ex = 200 self.Lightning_frame = 0 #Last self.Last_Px = [0, 120, 75] self.Last_Py = [120, 75] self.Last_Ball_frame =0 self.Last_Lightning_frame=0 self.Last_Lightning_frame2 = 0 def draw(self): if DeckSelection.character==2 and main_state.turn== 1 and main_state.Skill1_Start==True: self.effect_Line.clip_draw(0, int(self.Line_frame) * 52, 360, 52,self.Line_Px,self.Line_Py) self.effect_Ball.clip_draw(int(self.Ball_frame) * 65, 0, 68, 60, self.Ball_Px,self.Ball_Py) if main_state.EnemyPlayer==2 and main_state.turn== -1 and main_state.Skill1_Start==True: self.effect_Line.clip_draw(0, int(self.Line_frame) * 52, 360, 52,self.Line_Ex,self.Line_Ey) self.effect_Ball.clip_draw(int(self.Ball_frame) * 65, 0, 68, 60, self.Ball_Ex,self.Ball_Ey) if DeckSelection.character==2 and main_state.turn ==1 and main_state.Skill2_Start ==True: self.drill.clip_draw(int(self.Drill_frame) * 193, 60, 193, 60, self.Drill_Pmove, 200-5) if main_state.EnemyPlayer==2 and main_state.turn == -1 and main_state.Skill2_Start ==True: self.drill.clip_draw(int(self.Drill_frame) * 193, 0, 193, 60, self.Drill_Emove, 200-5) if DeckSelection.character==2 and main_state.turn ==1 and main_state.Skill3_Start ==True: self.effect_lightning.clip_draw(int(self.Lightning_frame) * 260, 0, 260, 250, self.Lightning_Px, 200 + 25) if main_state.EnemyPlayer==2 and main_state.turn == -1 and main_state.Skill3_Start ==True: self.effect_lightning.clip_draw(int(self.Lightning_frame) * 260, 0, 260, 250, self.Lightning_Ex, 200 + 25) if DeckSelection.character==2 and main_state.turn ==1 and main_state.Last_Start ==True: self.effect_Last_Lightning.clip_draw(self.Last_Px[int((self.Last_Lightning_frame + 1) % 2)], 0, self.Last_Py[int(self.Last_Lightning_frame2)],255, 600 - 50, 200 + 70) self.effect_Last_Lightning.clip_draw(self.Last_Px[int((self.Last_Lightning_frame + 1) % 2)], 0, self.Last_Py[int(self.Last_Lightning_frame2)],255, 600 + 40, 200 + 70) self.effect_Last_Lightning.clip_draw(self.Last_Px[int(self.Last_Lightning_frame)], 0, self.Last_Py[int(self.Last_Lightning_frame2)], 255, 600,200 + 70) self.effect_Last_Ball.clip_draw(int(self.Last_Ball_frame) * 270, 0, 270, 255, 600 + 15, 200 + 210) if main_state.EnemyPlayer==2 and main_state.turn == -1 and main_state.Last_Start ==True: self.effect_Last_Lightning.clip_draw(self.Last_Px[int((self.Last_Lightning_frame + 1) % 2)], 0,self.Last_Py[int(self.Last_Lightning_frame2)], 255, 200 - 50, 200 + 70) self.effect_Last_Lightning.clip_draw(self.Last_Px[int((self.Last_Lightning_frame + 1) % 2)], 0,self.Last_Py[int(self.Last_Lightning_frame2)], 255, 200 + 40, 200 + 70) self.effect_Last_Lightning.clip_draw(self.Last_Px[int(self.Last_Lightning_frame)], 0,self.Last_Py[int(self.Last_Lightning_frame2)], 255, 200, 200 + 70) self.effect_Last_Ball.clip_draw(int(self.Last_Ball_frame) * 270, 0, 270, 255, 200 + 15, 200 + 210) def update(self): global test if main_state.Skill1_Start == True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.iku_skill1_atk_cheak=1 self.Line_frame = (self.Line_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 12 self.Ball_frame = (self.Ball_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 7 if main_state.Skill1_Start==False: main_state.iku_skill1_atk_cheak = 0 if main_state.Skill2_Start == False: main_state.iku_skill2_atk_cheak = 0 self.Drill_Pmove = 530 self.Drill_Emove = 270 if main_state.Skill2_Start ==True: if self.Drill_Pmove >550: if main_state.turn == 1: main_state.HPcheak = 1 if self.Drill_Emove >250: if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.iku_skill2_atk_cheak = 1 if main_state.turn == 1: self.Drill_Pmove += int(MOTION_SPEED_PPS) if main_state.turn == -1: self.Drill_Emove -= int(MOTION_SPEED_PPS) self.Drill_frame = (self.Drill_frame + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 6 if main_state.Skill3_Start==True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.iku_skill3_atk_cheak=1 self.Lightning_frame = (self.Lightning_frame + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 4 if main_state.Skill3_Start == False: main_state.iku_skill3_atk_cheak=0 if main_state.Last_Start==True: if main_state.turn==1: main_state.HPcheak = 1 if main_state.turn== -1: main_state.P_HPcheak=1 main_state.iku_last_atk_cheak=1 self.Last_Ball_frame = (self.Last_Ball_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 4 self.Last_Lightning_frame = (self.Last_Lightning_frame + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 2 self.Last_Lightning_frame2 = (self.Last_Lightning_frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 2 if main_state.Last_Start == False: main_state.iku_last_atk_cheak = 0 <file_sep>/Project/Marisa/Marisa Test.py from pico2d import * import Player class BackGround: def __init__(self): self.x, self.y = 400, 300 self.Shrine = load_image('Hakurei Shrine.png') def draw(self): self.Shrine.draw(self.x,self.y) class Marisa: def __init__(self): self.Player = 200 self.Enemy =600 self.All_Y=200 self.stat =1 self.MStanding = load_image('MarisaStanding-Motion.png') self.Standi = 0 self.Standj = 0 self.Standcheak =0 self.MLastspell = load_image('MarisaLastspell-Motion.png') self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.MLastspellEffect = load_image('MarisaLastspell.png') self.LastspellEframe1 = 0 def update(self): if self.stat==0: if self.Standcheak < 10: self.Standi = (self.Standi+1) % 11 self.Standj = (self.Standj+1) % 10 self.Standcheak += 1 if self.Standcheak == 9: self.Standi = 0 self.Standj= 0 self.Standcheak = 0 if self.stat==1: if self.Lastspellcheak < 18: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 if self.Lastspellcheak > 4: if self.Lastspellcheak < 11: # Player self.MLastspellEffect.clip_draw(self.LastspellEframe1 * 261, 250, 260, 250, self.Player + 400, self.All_Y - 10) # Enemy # self.LastspellEffect.clip_draw(self.LastspellEframe1 * 261, 0, 260, 250, self.Enemy - 400,self.All_Y) self.MLastspellEframe1 = (self.LastspellEframe1 + 1) % 7 self.Lastspellcheak += 1 if self.Lastspellcheak == 18: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 marisa.stat = 0 def Stand(self): if self.stat==0: self.Standframe1 = [0,65,126,188,250,312,372,434,495,556,618] self.Standframe2 = [65,61,62,62,62,60,62,61,60,62] #플레이어 self.MStanding.clip_draw(self.Standframe1[self.Standi], 110, self.Standframe2[self.Standj], 110, self.Player,self.All_Y ) #적 # self.Standing.clip_draw(self.Standframe1[self.Standi], 0, self.Standframe2[self.Standj], 110, self.Enemy,self.All_Y) if self.stat == 1: self.Lastframe1 = [0, 65,127,187,251,305,386,451,536,610,680,750,815,880,943,1010,1070] self.Lastframe2 = [65,62,60,64,55,79,62,80,72,66,66,65,63,60,59,58,58] # 플레이어 self.MLastspell.clip_draw(self.Lastframe1[self.Lastspelli], 120, self.Lastframe2[self.Lastspellj], 120, self.Player+250,self.All_Y) # 적 # self.Lastspell.clip_draw(self.Lastframe1[self.Lastspelli], 0, self.Lastframe2[self.Lastspellj], 120, self.Enemy-250,self.All_Y) class Enemy: def __init__(self): self.Enemy = 600 self.All_Y = 200 self.stat = 0 self.Standing = load_image('MarisaStanding-Motion.png') self.Standi = 0 self.Standj = 0 self.Standcheak = 0 self.Lastspell = load_image('MarisaLastspell-Motion.png') self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 self.LastspellEffect = load_image('MarisaLastspell.png') self.LastspellEframe1 = 0 def update(self): if self.stat == 0: if self.Standcheak < 10: self.Standi = (self.Standi + 1) % 11 self.Standj = (self.Standj + 1) % 10 self.Standcheak += 1 if self.Standcheak == 9: self.Standi = 0 self.Standj = 0 self.Standcheak = 0 if self.stat == 1: if self.Lastspellcheak < 18: self.Lastspelli = (self.Lastspelli + 1) % 17 self.Lastspellj = (self.Lastspellj + 1) % 17 if self.Lastspellcheak > 4: if self.Lastspellcheak < 11: # Enemy self.LastspellEffect.clip_draw(self.LastspellEframe1 * 261, 0, 260, 250, self.Enemy - 400,self.All_Y) self.LastspellEframe1 = (self.LastspellEframe1 + 1) % 7 self.Lastspellcheak += 1 if self.Lastspellcheak == 18: self.Lastspelli = 0 self.Lastspellj = 0 self.Lastspellcheak = 0 enemy.stat = 0 def Stand(self): if self.stat == 0: self.Standframe1 = [0, 65, 126, 188, 250, 312, 372, 434, 495, 556, 618] self.Standframe2 = [65, 61, 62, 62, 62, 60, 62, 61, 60, 62] # 적 self.Standing.clip_draw(self.Standframe1[self.Standi], 0, self.Standframe2[self.Standj], 110,self.Enemy, self.All_Y) if self.stat == 1: self.Lastframe1 = [0, 65, 127, 187, 251, 305, 386, 451, 536, 610, 680, 750, 815, 880, 943, 1010, 1070] self.Lastframe2 = [65, 62, 60, 64, 55, 79, 62, 80, 72, 66, 66, 65, 63, 60, 59, 58, 58] # 적 self.Lastspell.clip_draw(self.Lastframe1[self.Lastspelli], 0, self.Lastframe2[self.Lastspellj], 120,self.Enemy - 250, self.All_Y) def handle_events(): global running events = get_events() for event in events: if event.type == SDL_QUIT: running = False elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: running = False elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE: marisa.stat =1 elif event.type == SDL_KEYDOWN and event.key == SDLK_a: enemy.stat = 1 open_canvas() background=BackGround() marisa=Marisa() enemy=Enemy() running=True while running: handle_events() clear_canvas() #background.draw() #marisa.update() #enemy.update() #marisa.Stand() Player.Player.Stand(Player) #enemy.Stand() update_canvas() delay(0.1) # finalization code close_canvas() <file_sep>/Project/Reimu/Reimu-Standing-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuStanding = load_image('Reimu-Standing-Motion.png') def Reimu_Standing(): frame = 0 cheak=0 while(cheak<11): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 ReimuStanding.clip_draw(frame *100,0,97,105,Enemy_X,All_Y) #플레이어 ReimuStanding.clip_draw(frame *100,105,97,105,Player_X,All_Y) frame=(frame+1)%11 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Reimu_Standing() close_canvas() <file_sep>/Project/Tensi/Tenshi-Skill3-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =400 Enemy_X=400 All_Y=200 TenshiSkill3 = load_image('TenshiSkill3-Motion.png') TenshiSkill3effect = load_image('TenshiSkill3.png') def Tenshi_Skill3(): frame1 = [77,78,83,99,80,98,178,160,70,70,63,68] frame2 = [0,77,155,240,340,425,528,710,876,960,1040,1110,1190] cheak=0 i=0 j=0 frame=0 while(cheak<13): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiSkill3.clip_draw(frame2[i],0,frame1[j],115,Enemy_X,All_Y) #플레이어 TenshiSkill3.clip_draw(frame2[i],115,frame1[j],115,Player_X,All_Y) if cheak <11: i=(i+1)%13 j=(j+1)%12 if cheak >6: #플레이어 TenshiSkill3effect.clip_draw(frame*260,107,260,120,Player_X+150,All_Y-10) #적 TenshiSkill3effect.clip_draw(frame*260,0,260,107,Enemy_X-150,All_Y) frame= (frame+1)%7 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Skill3() close_canvas() <file_sep>/Project/Iku/Iku-Standing-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuStanding = load_image('Iku-Standing-Motion.png') def Iku_Standing(): frame1 = [74,64,60,62,58,59,63,65,70] frame2 = [0,73, 140, 200, 265,324, 385, 446, 510, 580] cheak=0 i=0 j=0 while(cheak<9): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuStanding.clip_draw(frame2[i],0,frame1[j],130,Enemy_X,All_Y) #플레이어 IkuStanding.clip_draw(frame2[i],130,frame1[j],130,Player_X,All_Y) i=(i+1)%10 j=(j+1)%9 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Standing() close_canvas() <file_sep>/Project/test/Enemy_iku.py from pico2d import * from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode import BackgroundSelection import EnemyHP import PlayerHP import random import game_world import game_framework import main_state import DeckSelection STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=24 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=20 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 0.5/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=35 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #ItemUse ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=7 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # iku Event Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) # Iku States ationcheak = 0 damagecheak=1 class StandState: @staticmethod def enter(iku, event): global ationcheak,damagecheak iku.motion = 0 iku.frame1 = 0 iku.frame2 = 0 iku.Standframe1 = [0, 73, 140, 200, 265, 324, 385, 446, 510, 580] iku.Standframe2 = [74, 64, 60, 62, 58, 59, 63, 65, 70] ationcheak = 0 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): global ationcheak,damagecheak,ation iku.frame1 = (iku.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 iku.frame2 = (iku.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 main_state.Enemy_Motion_Cheak = False if DeckSelection.character == 0 and main_state.reimu_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_last_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill2_atk_cheak==1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill3_atk_cheak ==1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_last_atk_cheak==1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_last_atk_cheak== 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_last_atk_cheak== 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.HPcheak==0 and int(EnemyHP.damage) >252: iku.down_sound.play() iku.add_event(Down) if main_state.HPcheak == 0and int(EnemyHP.damage) < 251: if ationcheak == 1: #test iku.skill1_sound.play() main_state.P_HP += 20 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff iku.add_event(Skill1) if ationcheak == 2: #test iku.skill2_sound.play() main_state.P_HP += 30 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff iku.add_event(Skill2) if ationcheak == 3: #test iku.skill3_sound.play() main_state.P_HP += 40 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff iku.add_event(Skill3) if ationcheak == 4: #test iku.last_sound.play() main_state.P_HP += 50 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff iku.add_event(Last) if ationcheak == 5: #test iku.item_sound.play() main_state.Enemy_DefBuff = 0 iku.add_event(Item1) if ationcheak == 6: #test iku.item_sound.play() main_state.Enemy_AtkBuff = 3 iku.add_event(Item2) if ationcheak == 7: #test iku.item_sound.play() main_state.HP -= 100 EnemyHP.damage -= 100 iku.add_event(Item3) @staticmethod def draw(iku): if iku.motion ==0: iku.stand.clip_draw(iku.Standframe1[int(iku.frame1)], 0, iku.Standframe2[int(iku.frame2)], 130, iku.x, iku.y) class Skill1State: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.skill1cheak = 0 iku.Skill1frame1 = [0, 68, 133, 193, 259, 329, 390, 470, 543, 615, 680, 745] iku.Skill1frame2 = [68, 65, 60, 66, 68, 59, 78, 74, 70, 63, 68] if event == Skill1: iku.motion = 1 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): main_state.Enemy_Motion_Cheak = True global HP, HPcheak , ationcheak if int(iku.skill1cheak) < 8: iku.frame1 = (iku.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 if int(iku.skill1cheak) >= 7 and int(iku.skill1cheak) < 20: main_state.Skill1_Start = True if int(iku.skill1cheak) > 20: iku.frame1 = (iku.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.skill1cheak = (iku.skill1cheak + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 24 if int(iku.skill1cheak) >= 22: iku.skill1cheak=0 iku.add_event(Stand) main_state.Skill1_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 1: iku.skill1.clip_draw(iku.Skill1frame1[int(iku.frame1)], 0, iku.Skill1frame2[int(iku.frame2)], 145, iku.x, iku.y) class Skill2State: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.S2frame = 0 iku.Skill2Eframe1 = 0 iku.skill2cheak = 0 iku.skill2Px = 300 iku.skill2Mx = 330 iku.Skill2frame1 = [0, 70, 130, 200, 283, 356, 422, 490, 597, 732, 912, 1087, 1247, 1375, 1463, 1520] iku.Skill2frame2 = [70, 60, 70, 83, 73, 66, 66, 101, 133, 178, 173, 157, 124, 83, 63] if event == Skill2: iku.motion = 2 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): main_state.Enemy_Motion_Cheak = True global HP, HPcheak if int(iku.skill2cheak) < 11: iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 if int(iku.skill2cheak) > 5 and int(iku.skill2cheak) < 15: if iku.skill2cheak > 8: main_state.Skill2_Start = True iku.skill2Px += int(MOTION_SPEED_PPS) if int(iku.skill2cheak) >= 15: iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Skill2_Start = False iku.skill2Px -= int(MOTION_SPEED_PPS) iku.skill2cheak = (iku.skill2cheak + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 20 if int(iku.skill2cheak) >= 19: iku.skill2cheak = 0 iku.add_event(Stand) main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 2: iku.skill2.clip_draw(iku.Skill2frame1[int(iku.frame1)], 0, iku.Skill2frame2[int(iku.frame2)], 145,iku.x-iku.skill2Px, iku.y) class Skill3State: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.S3frame = 0 iku.Skill3Eframe1 = 0 iku.skill3cheak = 0 iku.Skill3frame1 = [0, 64, 126, 196, 268, 338, 405] iku.Skill3frame2 = [64, 62, 70, 72, 67, 68] if event == Skill3: iku.motion = 3 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): main_state.Enemy_Motion_Cheak = True global HP, HPcheak if int(iku.skill3cheak) < 19: if int(iku.skill3cheak) < 5: iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 if int(iku.skill3cheak) >= 5: main_state.Skill3_Start=True if int(iku.skill3cheak) > 17: iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.skill3cheak = (iku.skill3cheak + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 20 if int(iku.skill3cheak) >= 18: iku.skill3cheak = 0 iku.add_event(Stand) main_state.Skill3_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 3: iku.skill3.clip_draw(iku.Skill3frame1[int(iku.frame1)], 0, iku.Skill3frame2[int(iku.frame2)], 145,iku.x, iku.y) class Laststate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.lastcheak = 0 iku.Lastframe1 = [0, 60, 120, 180, 243, 315, 440, 570, 700, 825, 945, 1035] iku.Lastframe2 = [60, 60, 60, 63, 72, 125, 130, 130, 125, 120] if event == Last: iku.motion = 4 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): main_state.Enemy_Motion_Cheak = True if int(iku.lastcheak) < 34: if int(iku.lastcheak) < 8: iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 if int(iku.lastcheak) >= 8: main_state.Last_Start=True if int(iku.lastcheak) >= 32: iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.lastcheak = (iku.lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) %35 if int(iku.lastcheak) >= 34: iku.lastcheak = 0 iku.add_event(Stand) main_state.Last_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 4: iku.Lastspell.clip_draw(iku.Lastframe1[int(iku.frame1)], 0, iku.Lastframe2[int(iku.frame2)], 140,iku.x, iku.y) class Damagestate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.Damagecheak = 0 iku.Damageframe = 0 iku.Damageframe1 = [0, 94, 174, 245] iku.Damageframe2 = [94, 80, 73] if event == Damage: iku.motion = 5 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): if int(iku.Damagecheak) < 3: iku.frame1 = (iku.frame1+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 iku.frame2 = (iku.frame2 +DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 iku.Damagecheak = ( iku.Damagecheak + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(iku.Damagecheak) >= 3: iku.Damagecheak = 0 iku.add_event(Stand) @staticmethod def draw(iku): if iku.motion == 5: iku.Damage.clip_draw(iku.Damageframe1[int(iku.frame1)],0,iku.Damageframe2[int(iku.frame2)],135, iku.x, iku.y) class Downstate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.Downcheak=0 iku.Downframe1 = [0, 125, 240, 374, 514, 651, 793, 945] iku.Downframe2 = [125, 115, 134, 140, 136, 140, 158] if event == Down: iku.motion = 6 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): if int(iku.Downcheak) < 20: if int(iku.Downcheak) < 6: iku.frame1 = (iku.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 iku.frame2 = (iku.frame2 +DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 iku.Downcheak = (iku.Downcheak + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time)%21 if int(iku.Downcheak) >= 20: iku.Downcheak = 20 #iku.add_event(Stand) #iku.timer -= 1 @staticmethod def draw(iku): if iku.motion == 6: iku.Down.clip_draw(iku.Downframe1[int(iku.frame1)], 0, iku.Downframe2[int(iku.frame2)], 105, iku.x, iku.y-30) class Item_Doll: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item1cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item1: iku.motion = 7 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item1cheak) < 6: if int(iku.item1cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item1cheak = (iku.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item1cheak) >= 6: iku.item1cheak = 0 iku.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 7: iku.item_use.clip_draw(0, 0, 40, 65, 600, 280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145,iku.x, iku.y) class Item_Potion: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item2cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item2: iku.motion = 8 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item2cheak) < 6: if int(iku.item2cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item2cheak = (iku.item2cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item2cheak) >= 6: iku.item2cheak = 0 iku.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 8: iku.item_use.clip_draw(40, 0, 40, 65, 600, 280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y) class Item_Clock: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item3cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item3: iku.motion = 9 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item3cheak) < 6: if int(iku.item3cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item3cheak = (iku.item3cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item3cheak) >= 6: iku.item3cheak = 0 iku.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(iku): if iku.motion == 9: iku.item_use.clip_draw(80, 0, 40, 65, 600, 280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState,Down:Downstate}, Skill2State: {Skill2: StandState, Stand:StandState,Down:Downstate}, Skill3State: {Skill3: StandState ,Stand: StandState,Down:Downstate}, Laststate: {Last:StandState,Stand: StandState,Down:Downstate}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:StandState,Skill1: StandState,Skill2: StandState,Skill3: StandState,Last:StandState,Item1:StandState,Item2:StandState,Item3:StandState}, Item_Doll:{Item1:StandState, Stand:StandState,Down:Downstate}, Item_Potion:{Item2:StandState, Stand:StandState,Down:Downstate}, Item_Clock:{Item3:StandState, Stand:StandState,Down:Downstate} } class Enemy_Iku: def __init__(self): self.x, self.y = 600, 200 self.stand = load_image('./FCGimage/Iku-Standing-Motion.png') self.skill1 = load_image('./FCGimage/IkuSkill1-Motion.png') self.skill2 = load_image('./FCGimage/IkuSkill2-Motion.png') self.skill3 = load_image('./FCGimage/IkuSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/IkuLastspell-Motion.png') self.Lasteffect = load_image('./FCGimage/IkuLastspell1-1.png') self.Lasteffect2 = load_image('./FCGimage/IkuLastspell1-2.png') self.Damage = load_image('./FCGimage/IkuDamage-Motion.png') self.Down = load_image('./FCGimage/Iku-Down-Motion.png') self.skill1_sound = load_wav('./voice/iku-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/iku-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/iku-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/iku-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/iku-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/iku-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/iku-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.build_behavior_tree() self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def turn_cheak(self): if main_state.turn == -1: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def action_cheak(self): global ationcheak if ationcheak ==0: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=212: ationcheak=3 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def buff_ready_cheak(self): global ationcheak if main_state.Enemy_DefBuff==0 or main_state.Enemy_AtkBuff==3: ationcheak= random.randint(1,4) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def atk_cheak(self): global ationcheak if main_state.Enemy_DefBuff == 1 and main_state.Enemy_AtkBuff == 1: ationcheak = random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_atk_buff_cheak(self): if main_state.Enemy_AtkBuff ==3: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def player_atk_buff_cheak(self): global ationcheak if main_state.Player_AtkBuff==3: success_cheak=random.randint(1,100) if success_cheak>75: ationcheak=5 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_HP_cheak(self): global ationcheak if EnemyHP.damage>200: success_cheak = random.randint(1, 100) if success_cheak>50: ationcheak=7 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def Hard_finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=102: ationcheak=4 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def build_behavior_tree(self): turn_cheak_node = LeafNode("Turn Cheak", self.turn_cheak) action_cheak_node = LeafNode("Action Stand", self.action_cheak) finish_atk_cheak_node = LeafNode("Finish_Atk", self.finish_atk_cheak) buff_ready_cheak_node = LeafNode("Buff Ready Cheak", self.buff_ready_cheak) atk_cheak_node = LeafNode("Atk", self.atk_cheak) ##Hard enemy_atk_buff_cheak_node = LeafNode("Atk_Buff_Cheak", self.enemy_atk_buff_cheak) Hard_finish_atk_cheak_node = LeafNode("Finish_Atk", self.Hard_finish_atk_cheak) player_atk_buff_cheak_node = LeafNode("Player_Buff_Cheak", self.player_atk_buff_cheak) enemy_hp_cheak_node = LeafNode("Enemy_HP_Cheak", self.enemy_HP_cheak) ##Nomal Finsh_node = SequenceNode("Finish") Finsh_node.add_children(turn_cheak_node, action_cheak_node,finish_atk_cheak_node) Buff_Atk_node =SequenceNode("BuffAtk") Buff_Atk_node.add_children(turn_cheak_node,action_cheak_node,buff_ready_cheak_node) Atk_node = SequenceNode("Atk") Atk_node.add_children(turn_cheak_node, action_cheak_node,atk_cheak_node) action_chase_node = SelectorNode("ActionChase") action_chase_node.add_children(Finsh_node, Buff_Atk_node,Atk_node) ##Hard Hard_Finsh_node = SequenceNode("Hard-Finish") Hard_Finsh_node.add_children(turn_cheak_node,action_cheak_node, enemy_atk_buff_cheak_node, Hard_finish_atk_cheak_node) Hard_Block_node = SequenceNode("Hard-Block") Hard_Block_node.add_children(turn_cheak_node, action_cheak_node,player_atk_buff_cheak_node) Hard_HP_node = SequenceNode("Hard-Block") Hard_HP_node.add_children(turn_cheak_node, action_cheak_node, enemy_hp_cheak_node) Hard_action_chase_node = SelectorNode("Hard_ActionChase") Hard_action_chase_node.add_children(Hard_Finsh_node, Hard_Block_node, Hard_HP_node,Buff_Atk_node,Atk_node) if BackgroundSelection.Level_cheak==1: self.ation = BehaviorTree(action_chase_node) if BackgroundSelection.Level_cheak == 2: self.ation = BehaviorTree(Hard_action_chase_node) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.ation.run() self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): pass <file_sep>/Project/test/Enemy_marisa.py from pico2d import * import game_framework import EnemyHP import main_state import random import DeckSelection from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode import BackgroundSelection import PlayerHP import game_world #marisa stand STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=20 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=9 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=20 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #itemuse ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=10 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # marisa Event Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) # marisa States ationcheak = 0 class StandState: @staticmethod def enter(marisa, event): global ationcheak marisa.motion = 0 marisa.frame1 = 0 marisa.frame2 = 0 marisa.Standframe1 = [0,65,126,188,250,312,372,434,495,556,618] marisa.Standframe2 = [65,61,62,62,62,60,62,61,60,62] ationcheak=0 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): global ationcheak marisa.frame1 = (marisa.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 main_state.Enemy_Motion_Cheak = False if DeckSelection.character == 0 and main_state.reimu_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_last_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill2_atk_cheak==1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill3_atk_cheak ==1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_last_atk_cheak==1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_last_atk_cheak== 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_last_atk_cheak== 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.HPcheak==0 and int(EnemyHP.damage) >252: marisa.down_sound.play() marisa.add_event(Down) if main_state.HPcheak == 0 and int(EnemyHP.damage) < 251: if ationcheak == 1: #test marisa.skill1_sound.play() main_state.P_HP += 20 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff marisa.add_event(Skill1) if ationcheak == 2: #test marisa.skill2_sound.play() main_state.P_HP += 30 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff marisa.add_event(Skill2) if ationcheak == 3: #test marisa.skill3_sound.play() main_state.P_HP += 40 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff marisa.add_event(Skill3) if ationcheak == 4: #test marisa.last_sound.play() main_state.P_HP += 50 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff marisa.add_event(Last) if ationcheak == 5: #test marisa.item_sound.play() main_state.Enemy_DefBuff = 0 marisa.add_event(Item1) if ationcheak == 6: #test marisa.item_sound.play() main_state.Enemy_AtkBuff = 3 marisa.add_event(Item2) if ationcheak == 7: #test marisa.item_sound.play() main_state.HP -= 100 EnemyHP.damage -= 100 marisa.add_event(Item3) @staticmethod def draw(marisa): if marisa.motion ==0: marisa.stand.clip_draw(marisa.Standframe1[int(marisa.frame1)], 0, marisa.Standframe2[int(marisa.frame2)], 110, marisa.x, marisa.y) class Skill1State: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.skill1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Skill1: marisa.motion = 1 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): main_state.Enemy_Motion_Cheak = True if int(marisa.skill1cheak) < 6: marisa.frame1 = (marisa.frame1 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(marisa.skill1cheak) >6: if marisa.skill1cheak < 15: main_state.Skill1_Start = True if int(marisa.skill1cheak) >= 15: main_state.Skill1_Start = False marisa.frame1 = (marisa.frame1+SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.skill1cheak =(marisa.skill1cheak+SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.skill1cheak)>=18: marisa.skill1cheak=0 marisa.add_event(Stand) main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 1: marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 0, marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Skill2State: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.skill2cheak = 0 marisa.Skill2frame1 = [0, 85, 165, 240, 318, 395, 464, 525] marisa.Skill2frame2 = [85, 80, 75, 78, 76, 67, 64] if event == Skill2: marisa.motion = 2 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): main_state.Enemy_Motion_Cheak = True if int(marisa.skill2cheak) < 7: marisa.frame1 = (marisa.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 7 marisa.frame2 = (marisa.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 7 main_state.Skill2_Start = True marisa.skill2cheak = (marisa.skill2cheak+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%9 if int(marisa.skill2cheak) >= 7: marisa.skill2cheak = 0 marisa.add_event(Stand) main_state.Skill2_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 2: marisa.skill2.clip_draw(marisa.Skill2frame1[int(marisa.frame1)], 0, marisa.Skill2frame2[int(marisa.frame2)], 120,marisa.x, marisa.y) class Skill3State: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.skill3cheak = 0 marisa.Skill3frame1 = [0, 65, 125, 195, 275, 332, 412, 500, 590, 661] marisa.Skill3frame2 = [65, 60, 70, 80, 60, 76, 85, 89, 68, 61] if event == Skill3: marisa.motion = 3 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): main_state.Enemy_Motion_Cheak = True if int(marisa.skill3cheak) < 17: if int(marisa.skill3cheak) < 7: marisa.frame1 = (marisa.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.skill3cheak) >= 7: main_state.Skill3_Start=True if int(marisa.skill3cheak) >= 13: marisa.frame1 = (marisa.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.skill3cheak = (marisa.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.skill3cheak) >= 17: marisa.skill3cheak = 0 marisa.add_event(Stand) main_state.Skill3_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 3: marisa.skill3.clip_draw(marisa.Skill3frame1[int(marisa.frame1)], 0, marisa.Skill3frame2[int(marisa.frame2)], 110,marisa.x, marisa.y) class Laststate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.lastframe = 0 marisa.lastEframe1 = 0 marisa.lastcheak = 0 marisa.LastspellEframe1 = 0 marisa.Lastspellframe1 = 0 marisa.Lastspellframe2 = 0 marisa.Lastspellframe3 = 0 marisa.Lastspellc = 0 marisa.Lastspelld = 0 marisa.Lastframe1 = [0, 65,127,187,251,305,386,451,536,610,680,750,815,880,943,1010,1070] marisa.Lastframe2 = [65,62,60,64,55,79,62,80,72,66,66,65,63,60,59,58,58] if event == Last: marisa.motion = 4 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): main_state.Enemy_Motion_Cheak = True if int(marisa.lastcheak) < 18: marisa.frame1 = (marisa.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 17 marisa.frame2 = (marisa.frame2+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 17 if int(marisa.lastcheak) > 4 and int(marisa.lastcheak)<11: main_state.Last_Start = True marisa.lastcheak = (marisa.lastcheak+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.lastcheak) >= 18: marisa.lastcheak = 0 marisa.add_event(Stand) main_state.Last_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 4: marisa.Lastspell.clip_draw(marisa.Lastframe1[int(marisa.frame1)], 0, marisa.Lastframe2[int(marisa.frame2)], 120,marisa.x-250, marisa.y) class Damagestate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.Damagecheak = 0 marisa.Damageframe = 0 marisa.Damageframe1 = [0, 90, 175, 240] marisa.Damageframe2 = [90, 85, 65] if event == Damage: marisa.motion = 5 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): if int(marisa.Damagecheak) < 3: marisa.frame1 = (marisa.frame1 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 marisa.frame2 = (marisa.frame2 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 marisa.Damagecheak = (marisa.Damagecheak+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(marisa.Damagecheak) >= 3: marisa.Damagecheak = 0 marisa.add_event(Stand) @staticmethod def draw(marisa): if marisa.motion == 5: marisa.Damage.clip_draw(marisa.Damageframe1[int(marisa.frame1)],0,marisa.Damageframe2[int(marisa.frame2)],115, marisa.x, marisa.y) class Downstate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.Downcheak=0 marisa.Downframe1 = [0,80,149,232,348,451,548,645] marisa.Downframe2 = [80,69,83,116,102,95,100] if event == Down: marisa.motion = 6 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): if int(marisa.Downcheak) < 20: if int(marisa.Downcheak) < 6: marisa.frame1 = (marisa.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 marisa.frame2 = (marisa.frame2 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 marisa.Downcheak = (marisa.Downcheak+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) if int(marisa.Downcheak) >= 20: marisa.Downcheak=20 #marisa.timer -= 1 @staticmethod def draw(marisa): if marisa.motion == 6: marisa.Down.clip_draw(marisa.Downframe1[int(marisa.frame1)], 0, marisa.Downframe2[int(marisa.frame2)], 95, marisa.x, marisa.y-20) class Item_Doll: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item1: marisa.motion = 7 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): global HP,HPcheak,skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 7: marisa.item_use.clip_draw(0, 0, 40, 65, 600, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 0,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Item_Potion: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item2: marisa.motion = 8 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): global HP, HPcheak, skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 8: marisa.item_use.clip_draw(40, 0, 40, 65, 600, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 0,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Item_Clock: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item3: marisa.motion = 9 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): global HP, HPcheak, skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(marisa): if marisa.motion == 9: marisa.item_use.clip_draw(80, 0, 40, 65, 600, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 0,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState,Down:Downstate}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:StandState}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Enemy_Marisa: def __init__(self): self.x, self.y = 600, 200 self.stand = load_image('./FCGimage/MarisaStanding-Motion.png') self.skill1 = load_image('./FCGimage/MarisaSkill1-Motion.png') self.skill2 = load_image('./FCGimage/MarisaSkill2-Motion.png') self.skill3 = load_image('./FCGimage/MarisaSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/MarisaLastspell-Motion.png') self.Damage = load_image('./FCGimage/MarisaDamage-Motion.png') self.Down = load_image('./FCGimage/MarisaDown-Motion.png') self.skill1_sound = load_wav('./voice/marisa-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/marisa-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/marisa-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/marisa-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/marisa-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/marisa-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/marisa-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.build_behavior_tree() self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def turn_cheak(self): if main_state.turn == -1: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def action_cheak(self): global ationcheak if ationcheak ==0: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=212: ationcheak=3 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def buff_ready_cheak(self): global ationcheak if main_state.Enemy_DefBuff==0 or main_state.Enemy_AtkBuff==3: ationcheak= random.randint(1,4) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def atk_cheak(self): global ationcheak if main_state.Enemy_DefBuff == 1 and main_state.Enemy_AtkBuff == 1: ationcheak = random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_atk_buff_cheak(self): if main_state.Enemy_AtkBuff ==3: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def player_atk_buff_cheak(self): global ationcheak if main_state.Player_AtkBuff==3: success_cheak=random.randint(1,100) if success_cheak>75: ationcheak=5 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_HP_cheak(self): global ationcheak if EnemyHP.damage>200: success_cheak = random.randint(1, 100) if success_cheak>50: ationcheak=7 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def Hard_finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=102: ationcheak=4 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def build_behavior_tree(self): turn_cheak_node = LeafNode("Turn Cheak", self.turn_cheak) action_cheak_node = LeafNode("Action Stand", self.action_cheak) finish_atk_cheak_node = LeafNode("Finish_Atk", self.finish_atk_cheak) buff_ready_cheak_node = LeafNode("Buff Ready Cheak", self.buff_ready_cheak) atk_cheak_node = LeafNode("Atk", self.atk_cheak) ##Hard enemy_atk_buff_cheak_node = LeafNode("Atk_Buff_Cheak", self.enemy_atk_buff_cheak) Hard_finish_atk_cheak_node = LeafNode("Finish_Atk", self.Hard_finish_atk_cheak) player_atk_buff_cheak_node = LeafNode("Player_Buff_Cheak", self.player_atk_buff_cheak) enemy_hp_cheak_node = LeafNode("Enemy_HP_Cheak", self.enemy_HP_cheak) ##Nomal Finsh_node = SequenceNode("Finish") Finsh_node.add_children(turn_cheak_node, action_cheak_node,finish_atk_cheak_node) Buff_Atk_node =SequenceNode("BuffAtk") Buff_Atk_node.add_children(turn_cheak_node,action_cheak_node,buff_ready_cheak_node) Atk_node = SequenceNode("Atk") Atk_node.add_children(turn_cheak_node, action_cheak_node,atk_cheak_node) action_chase_node = SelectorNode("ActionChase") action_chase_node.add_children(Finsh_node, Buff_Atk_node,Atk_node) ##Hard Hard_Finsh_node = SequenceNode("Hard-Finish") Hard_Finsh_node.add_children(turn_cheak_node,action_cheak_node, enemy_atk_buff_cheak_node, Hard_finish_atk_cheak_node) Hard_Block_node = SequenceNode("Hard-Block") Hard_Block_node.add_children(turn_cheak_node, action_cheak_node,player_atk_buff_cheak_node) Hard_HP_node = SequenceNode("Hard-Block") Hard_HP_node.add_children(turn_cheak_node, action_cheak_node, enemy_hp_cheak_node) Hard_action_chase_node = SelectorNode("Hard_ActionChase") Hard_action_chase_node.add_children(Hard_Finsh_node, Hard_Block_node, Hard_HP_node,Buff_Atk_node,Atk_node) if BackgroundSelection.Level_cheak==1: self.ation = BehaviorTree(action_chase_node) if BackgroundSelection.Level_cheak == 2: self.ation = BehaviorTree(Hard_action_chase_node) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.ation.run() self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): pass <file_sep>/Project/Reimu/Reimu-Lastspell-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuLastSpell = load_image('Reimu-Last Spell-Motion.png') ReimuLastSpelleffect1 = load_image('Reimu-Lastspell1.png') ReimuLastSpelleffect2 = load_image('Reimu-Lastspell2-1.png') ReimuLastSpelleffect3 = load_image('Reimu-Lastspell3-2.png') def Reimu_LastSpell(): frame=[0,105, 209,311,414, 517, 620, 724, 822, 910, 995,1068,1145,1242,1345,1445] frame2=[105,104,102,103,104,103,104,98,88,85,74,77,97,103,100] PSx = [580, 620, 600] SSy = [160.175,200,225,250] ESx = [180,220,200] i=0 j=0 c=0 d=0 cheak=0 S_frame=0 S1_frame=0 S2_frame=0 while(cheak<22): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #플레이어 ReimuLastSpell.clip_draw(frame[i],130,frame2[j],130,Player_X,All_Y) #적 ReimuLastSpell.clip_draw(frame[i],0,frame2[j],130,Enemy_X,All_Y) if (cheak<9): i=(i+1)%16 j=(j+1)%15 if cheak>=9: if cheak<14: #플레이어 공격 ReimuLastSpelleffect1.clip_draw(S_frame *133,0,133,207,Enemy_X,230) ReimuLastSpelleffect2.clip_draw(S1_frame *261,0,262,126,Enemy_X-10,160) ReimuLastSpelleffect3.clip_draw(S2_frame *133,0,133,126,PSx[c],SSy[d]) #적 공격 ReimuLastSpelleffect1.clip_draw(S_frame *133,0,133,207,Player_X,230) ReimuLastSpelleffect2.clip_draw(S1_frame *261,0,262,126,Player_X-10,160) ReimuLastSpelleffect3.clip_draw(S2_frame *133,0,133,126,ESx[c],SSy[d]) c =(c+1)%2 d=(d+1)%4 if cheak>=16: i=(i+1)%16 j=(j+1)%15 S_frame=(S_frame+1)%13 S1_frame=(S1_frame+1)%8 S2_frame=(S1_frame+1)%3 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Reimu_LastSpell() close_canvas() <file_sep>/Project/Tensi/Tenshi-Down-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 TenshiDown = load_image('TenshiDown-Motion.png') def Tenshi_Down(): frame1 = [120,115,115,120,125] frame2 = [0,120,235,350,470,595] cheak=0 i=0 j=0 while(cheak<9): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 TenshiDown.clip_draw(frame2[i],0,frame1[j],75,Enemy_X,All_Y-30) #플레이어 TenshiDown.clip_draw(frame2[i],75,frame1[j],75,Player_X,All_Y-30) if cheak<4: i=(i+1)%6 j=(j+1)%5 update_canvas() delay(0.13) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Tenshi_Down() close_canvas() <file_sep>/Project/boy.py from pico2d import * # Boy Event # fill here RIGHT_DOWN, LEFT_DOWN, RIGHT_UP, LEFT_UP ,DASH_DOWN,DASH_UP,Stand= range(7) key_event_table = { (SDL_KEYDOWN, SDLK_RIGHT): RIGHT_DOWN, (SDL_KEYDOWN, SDLK_LEFT): LEFT_DOWN, (SDL_KEYUP, SDLK_RIGHT): RIGHT_UP, (SDL_KEYUP, SDLK_LEFT): LEFT_UP, (SDL_KEYDOWN, SDLK_a): DASH_DOWN, (SDL_KEYUP, SDLK_a): DASH_UP, } # Boy States class IdleState: @staticmethod def enter(boy): boy.frame1 = 0 boy.frame2 = 0 boy.Standframe1 = [0, 73, 140, 200, 265, 324, 385, 446, 510, 580] boy.Standframe2 = [74, 64, 60, 62, 58, 59, 63, 65, 70] boy.timer=1000 @staticmethod def exit(boy): pass @staticmethod def do(boy): boy.frame1 = (boy.frame1 + 1) % 9 boy.frame2 = (boy.frame2 + 1) % 9 if boy.velocity==2: boy.add_event(RIGHT_DOWN) delay(0.1) @staticmethod def draw(boy): if boy.dir ==1: boy.stand.clip_draw(boy.Standframe1[boy.frame1], 130, boy.Standframe2[boy.frame2], 130, boy.x, boy.y) #else: # boy.image.clip_draw(boy.frame * 100, 200, 100, 100, boy.x, boy.y) class RunState: @staticmethod def enter(boy): boy.frame1=0 boy.frame2=0 boy.S1frame = 0 boy.Skill1Eframe1 = 0 boy.skill1cheak = 0 boy.Standframe1 = [0,68,133,193,259,329,390,470,543,615,680,745] boy.Standframe2 = [68,65,60,66,68,59,78,74,70,63,68] #boy.dir = boy.velocity @staticmethod def exit(boy): pass @staticmethod def do(boy): if boy.skill1cheak<8: boy.frame1 = (boy.frame1 + 1) % 11 boy.frame2 = (boy.frame2 + 1) % 11 if boy.skill1cheak>=8 and boy.skill1cheak<20: boy.S1effect.clip_draw(0, boy.S1frame * 52, 360, 52, boy.x + 200, boy.y + 10) boy.S1effect2.clip_draw(boy.Skill1Eframe1 * 65, 0, 68, 60, 600 - 10, boy.y + 10) boy.S1frame = (boy.S1frame + 1) % 12 boy.Skill1Eframe1 = (boy.Skill1Eframe1 + 1) % 7 if boy.skill1cheak>=20: boy.frame1 = (boy.frame1 + 1) % 11 boy.frame2 = (boy.frame2 + 1) % 11 boy.skill1cheak +=1 if boy.skill1cheak==23: boy.skill1cheak=0 boy.add_event(Stand) delay(0.1) #if boy.skill1cheak == 22: #boy.x += boy.velocity boy.x= clamp(25,boy.x,800-25) @staticmethod def draw(boy): if boy.velocity == 1: boy.skill1.clip_draw(boy.Standframe1[boy.frame1], 145, boy.Standframe2[boy.frame2], 145, boy.x, boy.y) if boy.skill1cheak >= 8 and boy.skill1cheak < 20: boy.S1effect.clip_draw(0, boy.S1frame * 52, 360, 52, boy.x + 200, boy.y + 10) boy.S1effect2.clip_draw(boy.Skill1Eframe1 * 65, 0, 68, 60, 600 - 10, boy.y + 10) #else: # boy.image.clip_draw(boy.frame * 100, 0, 100, 100, boy.x, boy.y) # fill here next_state_table = { IdleState: {RIGHT_UP:RunState,LEFT_UP:RunState,RIGHT_DOWN:RunState,LEFT_DOWN:RunState,DASH_DOWN:RunState,DASH_UP:RunState}, RunState:{RIGHT_UP:RunState,LEFT_UP:IdleState,LEFT_DOWN:IdleState,RIGHT_DOWN:IdleState,DASH_DOWN:IdleState,DASH_UP:IdleState,Stand:IdleState} # fill here } class Boy: def __init__(self): self.x, self.y = 200, 200 self.stand = load_image('Iku-Standing-Motion.png') self.skill1=load_image('IkuSkill1-Motion.png') self.S1effect = load_image('IkuSkill1-1.png') self.S1effect2 = load_image('IkuSkill1-2.png') self.dir = 1 self.velocity = 0 self.event_que = [] self.cur_state=IdleState self.cur_state.enter(self) # fill here pass def change_state(self, state): self.cur_state.exit(self) self.cur_state = state self.cur_state.enter(self) # fill here def add_event(self, event): self.event_que.insert(0,event) def update(self): self.cur_state.do(self) if len(self.event_que)>0: event=self.event_que.pop() self.change_state(next_state_table[self.cur_state][event]) def draw(self): self.cur_state.draw(self) def handle_event(self, event): if(event.type,event.key) in key_event_table: key_event = key_event_table[(event.type,event.key)] if key_event ==RIGHT_DOWN: self.velocity =1 elif key_event ==LEFT_DOWN: self.velocity -=1 # elif key_event == RIGHT_UP: # self.velocity -=1 elif key_event==LEFT_UP: self.velocity +=1 elif key_event==DASH_DOWN: self.velocity -=5 elif key_event == DASH_UP: self.velocity += 5 self.add_event(key_event) if SDL_MOUSEBUTTONDOWN and SDL_BUTTON_LEFT: self.velocity = 2 <file_sep>/Project/Reimu/Reimu-Skill1-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuSkill1 = load_image('Reimu-Skill1-Motion.png') ReimuSkill1effect = load_image('Reimu-Skill1.png') def Reimu_Skill1(): frame=[0,108,213,327,434,541,638,787,936,1080,1215,1319,1425] frame2=[108,105,114,107,107,97,149,149,144,135,104,106] S_frame=0 i=0 j=0 x = 80 cheak=0 while(cheak<12): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #플레이어 ReimuSkill1.clip_draw(frame[i],110,frame2[j],110,Player_X,All_Y) ReimuSkill1effect.clip_draw(S_frame *70,0,80,110,Player_X+x,All_Y) #적 ReimuSkill1.clip_draw(frame[i],0,frame2[j],110,Enemy_X,All_Y) ReimuSkill1effect.clip_draw(S_frame *70,0,80,110,Enemy_X-x,All_Y) i=(i+1)%13 j=(j+1)%12 S_frame=(S_frame+1)%13 x=x+30 update_canvas() delay(0.1) cheak +=1 while(True): Reimu_Skill1() close_canvas() <file_sep>/Project/test/Enemy_reimu.py from pico2d import * import main_state import game_world import game_framework import EnemyHP import random import DeckSelection from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode import BackgroundSelection import PlayerHP #reimu stand STAND_TIME_PER_ACTION=1.2 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=12 #skill1 SKILL1TIME_PER_ACTION=1.5 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=15 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 0.8/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=13 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=25 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=23 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #item use ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 0.8/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=9 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # reimuEvent Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) # Reimu States ationcheak = 0 class StandState: @staticmethod def enter(reimu, event): global ationcheak reimu.motion = 0 reimu.frame1 = 0 reimu.frame2 = 0 ationcheak = 0 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): global ationcheak reimu.frame1 = (reimu.frame1+ STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 11 main_state.Enemy_Motion_Cheak = False if DeckSelection.character == 0 and main_state.reimu_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 0 and main_state.reimu_last_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill2_atk_cheak==1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_skill3_atk_cheak ==1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 1 and main_state.marisa_last_atk_cheak==1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 2 and main_state.iku_last_atk_cheak== 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill1_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill2_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_skill3_atk_cheak == 1: reimu.damage_sound.play() reimu.add_event(Damage) if DeckSelection.character == 3 and main_state.tenshi_last_atk_cheak== 1: reimu.damage_sound.play() reimu.add_event(Damage) if main_state.HPcheak==0 and int(EnemyHP.damage) >252: reimu.down_sound.play() reimu.add_event(Down) if main_state.HPcheak == 0and int(EnemyHP.damage) < 251: if ationcheak == 1: #test reimu.skill1_sound.play() main_state.P_HP += 20 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff reimu.add_event(Skill1) if ationcheak == 2: #test reimu.skill2_sound.play() main_state.P_HP += 30 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff reimu.add_event(Skill2) if ationcheak == 3: #test reimu.skill3_sound.play() main_state.P_HP += 40 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff reimu.add_event(Skill3) if ationcheak == 4: #test reimu.last_sound.play() main_state.P_HP += 50 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff reimu.add_event(Last) if ationcheak == 5: #test reimu.item_sound.play() main_state.Enemy_DefBuff = 0 reimu.add_event(Item1) if ationcheak == 6: #test reimu.item_sound.play() main_state.Enemy_AtkBuff = 3 reimu.add_event(Item2) if ationcheak == 7: #test reimu.item_sound.play() main_state.HP -= 100 EnemyHP.damage -= 100 reimu.add_event(Item3) @staticmethod def draw(reimu): if reimu.motion ==0: reimu.stand.clip_draw(int(reimu.frame1) *100,0,97,105, reimu.x, reimu.y) class Skill1State: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill1cheak = 0 reimu.Skill1frame1 = [0,108,213,327,434,541,638,787,936,1080,1215,1319,1425] reimu.Skill1frame2 = [108,105,114,107,107,97,149,149,144,135,104,106] if event == Skill1: reimu.motion = 1 @staticmethod def exit(reimu, event): pass #if event ==SPACE: # boy.fire_ball() @staticmethod def do(reimu): main_state.Enemy_Motion_Cheak = True if int(reimu.skill1cheak)<14: reimu.frame1 = (reimu.frame1+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 12 reimu.frame2 = (reimu.frame2+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 12 if int(reimu.skill1cheak) > 3: main_state.Skill1_Start=True reimu.skill1cheak =(reimu.skill1cheak+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%15 if int(reimu.skill1cheak)>=13: reimu.skill1cheak=0 reimu.add_event(Stand) main_state.Skill1_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 1: reimu.skill1.clip_draw(reimu.Skill1frame1[int(reimu.frame1)], 0, reimu.Skill1frame2[int(reimu.frame2)], 110, reimu.x, reimu.y) class Skill2State: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill2cheak = 0 reimu.Skill2frame1 = [0,66,120,217,304,392,480,572,675] reimu.Skill2frame2 = [66,54,97,87,88,88,92,103] if event == Skill2: reimu.motion = 2 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): main_state.Enemy_Motion_Cheak = True if int(reimu.skill2cheak) < 8: reimu.frame1 = (reimu.frame1+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 8 main_state.Skill2_Start = True if int(reimu.skill2cheak) > 8: main_state.Skill2_Start = False reimu.skill2cheak = (reimu.skill2cheak+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%13 if int(reimu.skill2cheak) >= 12: reimu.skill2cheak = 0 reimu.add_event(Stand) main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 2: reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)],0, reimu.Skill2frame2[int(reimu.frame2)],120,reimu.x, reimu.y) class Skill3State: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.skill3cheak = 0 reimu.Skill3frame1 = [0,105, 210,315,420, 543, 659, 775, 885, 1000,1100] reimu.Skill3frame2 = [104,105,105,104,120,115,115,108,115,100] if event == Skill3: reimu.motion = 3 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): main_state.Enemy_Motion_Cheak = True if int(reimu.skill3cheak) < 24: if int(reimu.skill3cheak) < 5: reimu.frame1 = (reimu.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 reimu.frame2 = (reimu.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 if int(reimu.skill3cheak) >= 5: main_state.Skill3_Start = True if int(reimu.skill3cheak) > 20: reimu.frame1 = (reimu.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 11 reimu.frame2 = (reimu.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 reimu.skill3cheak = (reimu.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%25 if int(reimu.skill3cheak) >= 24: reimu.skill3cheak = 0 reimu.add_event(Stand) main_state.Skill3_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 3: reimu.skill3.clip_draw(reimu.Skill3frame1[int(reimu.frame1)],0,reimu.Skill3frame2[int(reimu.frame2)],100,reimu.x, reimu.y) class Laststate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.lastframe = 0 reimu.lastEframe1 = 0 reimu.lastcheak = 0 reimu.LastspellEframe1 = 0 reimu.Lastspellframe1 = 0 reimu.Lastspellframe2 = 0 reimu.Lastspellframe3 = 0 reimu.Lastspellc = 0 reimu.Lastspelld = 0 reimu.ReimuLastX = [180, 220, 200] reimu.ReimuLastY = [160.175, 200, 225, 250] reimu.Lastframe1 = [0,105, 209,311,414, 517, 620, 724, 822, 910, 995,1068,1145,1242,1345,1445] reimu.Lastframe2 = [105,104,102,103,104,103,104,98,88,85,74,77,97,103,100] if event == Last: reimu.motion = 4 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): main_state.Enemy_Motion_Cheak = True if int(reimu.lastcheak) < 22: if int(reimu.lastcheak) < 9: reimu.frame1 = (reimu.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 reimu.frame2 = (reimu.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 if int(reimu.lastcheak) >= 16: reimu.frame1 = (reimu.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 reimu.frame2 = (reimu.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Last_Start = True reimu.lastcheak = (reimu.lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%23 if int(reimu.lastcheak) >= 22: reimu.lastcheak = 0 reimu.add_event(Stand) main_state.Last_Start = False main_state.Enemy_AtkBuff = 1 main_state.Player_DefBuff = 1 main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 4: reimu.Lastspell.clip_draw(reimu.Lastframe1[int(reimu.frame1)], 0, reimu.Lastframe2[int(reimu.frame2)], 130,reimu.x, reimu.y+15) class Damagestate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.Damagecheak = 0 reimu.Damageframe = 0 if event == Damage: reimu.motion = 5 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): if int(reimu.Damagecheak) < 3: reimu.Damageframe = (reimu.Damageframe + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 reimu.Damagecheak = (reimu.Damagecheak+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(reimu.Damagecheak) >= 3: reimu.Damagecheak = 0 reimu.add_event(Stand) @staticmethod def draw(reimu): if reimu.motion == 5: reimu.Damage.clip_draw(int(reimu.Damageframe)*112,0,110,90, reimu.x, reimu.y) class Downstate: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.Downcheak=0 reimu.Downframe1 = [0,92, 172,272,369, 465, 576, 683, 784, 889, 970] reimu.Downframe2 = [92,80,100,97,96,110,105,102,105,103,130] if event == Down: reimu.motion = 6 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): if int(reimu.Downcheak) < 20: if int(reimu.Downcheak) < 9: reimu.frame1 = (reimu.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 10 reimu.frame2 = (reimu.frame2+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 10 reimu.Downcheak = (reimu.Downcheak+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time)%21 if int(reimu.Downcheak) >= 20: reimu.Downcheak = 20 @staticmethod def draw(reimu): if reimu.motion == 6: reimu.Down.clip_draw(reimu.Downframe1[int(reimu.frame1)],0,reimu.Downframe2[int(reimu.frame2)],65, reimu.x, reimu.y-25) class Item_Doll: @staticmethod def enter(reimu,event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item1: reimu.motion = 7 @staticmethod def exit(reimu,event): pass @staticmethod def do(reimu): global HP,HPcheak,skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = (reimu.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 7: reimu.item_use.clip_draw(0, 0, 40, 65, 600, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 0, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) class Item_Potion: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item2: reimu.motion = 8 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): global HP, HPcheak, skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = ( reimu.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 8: reimu.item_use.clip_draw(40, 0, 40, 65, 600, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 0, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) class Item_Clock: @staticmethod def enter(reimu, event): reimu.frame1 = 0 reimu.frame2 = 0 reimu.item1cheak = 0 reimu.Skill2frame1 = [0, 66, 120, 217, 304, 392, 480, 572, 675] reimu.Skill2frame2 = [66, 54, 97, 87, 88, 88, 92, 103] if event == Item3: reimu.motion = 9 @staticmethod def exit(reimu, event): pass @staticmethod def do(reimu): global HP, HPcheak, skillcheak if int(reimu.item1cheak) < 8: reimu.frame1 = (reimu.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.frame2 = (reimu.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 8 reimu.item1cheak = (reimu.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(reimu.item1cheak) >= 8: reimu.item1cheak = 0 reimu.add_event(Stand) main_state.turn = 1 main_state.DeckShow = 1 @staticmethod def draw(reimu): if reimu.motion == 9: reimu.item_use.clip_draw(80, 0, 40, 65, 600, 280) reimu.skill2.clip_draw(reimu.Skill2frame1[int(reimu.frame1)], 0, reimu.Skill2frame2[int(reimu.frame2)],120, reimu.x, reimu.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:StandState}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Enemy_Reimu: def __init__(self): self.x, self.y = 600, 200 self.stand = load_image('./FCGimage/Reimu-Standing-Motion.png') self.skill1 = load_image('./FCGimage/Reimu-Skill1-Motion.png') self.skill2 = load_image('./FCGimage/Reimu-Skill2-Motion.png') self.skill3 = load_image('./FCGimage/Reimu-Skill3-Motion.png') self.Lastspell = load_image('./FCGimage/Reimu-Last Spell-Motion.png') self.Lasteffect = load_image('./FCGimage/Reimu-Lastspell1.png') self.Lasteffect2 = load_image('./FCGimage/Reimu-Lastspell2-1.png') self.Lasteffect3 = load_image('./FCGimage/Reimu-Lastspell3-2.png') self.Damage = load_image('./FCGimage/ReimuDamage-Motion.png') self.Down = load_image('./FCGimage/Reimu-Downs-Motion.png') self.skill1_sound = load_wav('./voice/reimu-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/reimu-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/reimu-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/reimu-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/reimu-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/reimu-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/reimu-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.build_behavior_tree() self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def turn_cheak(self): if main_state.turn == -1: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def action_cheak(self): global ationcheak if ationcheak ==0: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=212: ationcheak=3 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def buff_ready_cheak(self): global ationcheak if main_state.Enemy_DefBuff==0 or main_state.Enemy_AtkBuff==3: ationcheak= random.randint(1,4) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def atk_cheak(self): global ationcheak if main_state.Enemy_DefBuff == 1 and main_state.Enemy_AtkBuff == 1: ationcheak = random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_atk_buff_cheak(self): if main_state.Enemy_AtkBuff ==3: return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def player_atk_buff_cheak(self): global ationcheak if main_state.Player_AtkBuff==3: success_cheak=random.randint(1,100) if success_cheak>75: ationcheak=5 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def enemy_HP_cheak(self): global ationcheak if EnemyHP.damage>200: success_cheak = random.randint(1, 100) if success_cheak>50: ationcheak=7 return BehaviorTree.SUCCESS else: ationcheak=random.randint(1, 7) return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def Hard_finish_atk_cheak(self): global ationcheak if PlayerHP.damage >=102: ationcheak=4 return BehaviorTree.SUCCESS else: return BehaviorTree.FAIL def build_behavior_tree(self): turn_cheak_node = LeafNode("Turn Cheak", self.turn_cheak) action_cheak_node = LeafNode("Action Stand", self.action_cheak) finish_atk_cheak_node = LeafNode("Finish_Atk", self.finish_atk_cheak) buff_ready_cheak_node = LeafNode("Buff Ready Cheak", self.buff_ready_cheak) atk_cheak_node = LeafNode("Atk", self.atk_cheak) ##Hard enemy_atk_buff_cheak_node = LeafNode("Atk_Buff_Cheak", self.enemy_atk_buff_cheak) Hard_finish_atk_cheak_node = LeafNode("Finish_Atk", self.Hard_finish_atk_cheak) player_atk_buff_cheak_node = LeafNode("Player_Buff_Cheak", self.player_atk_buff_cheak) enemy_hp_cheak_node = LeafNode("Enemy_HP_Cheak", self.enemy_HP_cheak) ##Nomal Finsh_node = SequenceNode("Finish") Finsh_node.add_children(turn_cheak_node, action_cheak_node,finish_atk_cheak_node) Buff_Atk_node =SequenceNode("BuffAtk") Buff_Atk_node.add_children(turn_cheak_node,action_cheak_node,buff_ready_cheak_node) Atk_node = SequenceNode("Atk") Atk_node.add_children(turn_cheak_node, action_cheak_node,atk_cheak_node) action_chase_node = SelectorNode("ActionChase") action_chase_node.add_children(Finsh_node, Buff_Atk_node,Atk_node) ##Hard Hard_Finsh_node = SequenceNode("Hard-Finish") Hard_Finsh_node.add_children(turn_cheak_node,action_cheak_node, enemy_atk_buff_cheak_node, Hard_finish_atk_cheak_node) Hard_Block_node = SequenceNode("Hard-Block") Hard_Block_node.add_children(turn_cheak_node, action_cheak_node,player_atk_buff_cheak_node) Hard_HP_node = SequenceNode("Hard-Block") Hard_HP_node.add_children(turn_cheak_node, action_cheak_node, enemy_hp_cheak_node) Hard_action_chase_node = SelectorNode("Hard_ActionChase") Hard_action_chase_node.add_children(Hard_Finsh_node, Hard_Block_node, Hard_HP_node,Buff_Atk_node,Atk_node) if BackgroundSelection.Level_cheak==1: self.ation = BehaviorTree(action_chase_node) if BackgroundSelection.Level_cheak == 2: self.ation = BehaviorTree(Hard_action_chase_node) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.ation.run() self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): pass <file_sep>/Project/test/iku.py from pico2d import * import game_framework import main_state import Deck import PlayerHP import Enemy_iku import EnemyHP #iku stand STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=24 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=20 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 0.5/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=35 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #ItemUse ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=7 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) import game_world cheak1 = 0 skillcheak=0 # iku Event Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) key_event_table = { (SDL_MOUSEBUTTONDOWN, 1): Skill1, (SDL_MOUSEBUTTONDOWN, 2): Skill2, (SDL_MOUSEBUTTONDOWN, 3): Skill3, (SDL_MOUSEBUTTONDOWN, 4): Last, (SDL_MOUSEBUTTONDOWN, 99): Damage, (SDL_MOUSEBUTTONDOWN, 98): Down, (SDL_MOUSEBUTTONDOWN, 5): Item1, (SDL_MOUSEBUTTONDOWN, 6): Item2, (SDL_MOUSEBUTTONDOWN, 7): Item3 } name = 'iku' # Iku States turn =None HP=0 mouse_x,mouse_y=0,0 skillstart=False class StandState: @staticmethod def enter(iku, event): iku.motion = 0 iku.frame1 = 0 iku.frame2 = 0 iku.Standframe1 = [0, 73, 140, 200, 265, 324, 385, 446, 510, 580] iku.Standframe2 = [74, 64, 60, 62, 58, 59, 63, 65, 70] @staticmethod def exit(iku, event): pass @staticmethod def do(iku): iku.frame1 = (iku.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 iku.frame2 = (iku.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 main_state.Character_Motion_Cheak=False if int(PlayerHP.damage) >252: iku.down_sound.play() iku.add_event(Down) if main_state.EnemyPlayer == 0 and main_state.reimu_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_last_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill2_atk_cheak==1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill3_atk_cheak ==1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_last_atk_cheak==1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_last_atk_cheak== 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill1_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill2_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill3_atk_cheak == 1: iku.damage_sound.play() iku.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_last_atk_cheak== 1: iku.damage_sound.play() iku.add_event(Damage) @staticmethod def draw(iku): if iku.motion ==0: iku.stand.clip_draw(iku.Standframe1[int(iku.frame1)], 130, iku.Standframe2[int(iku.frame2)], 130, iku.x, iku.y) class Skill1State: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.S1frame = 0 iku.Skill1Eframe1 = 0 iku.skill1cheak = 0 iku.Skill1frame1 = [0, 68, 133, 193, 259, 329, 390, 470, 543, 615, 680, 745] iku.Skill1frame2 = [68, 65, 60, 66, 68, 59, 78, 74, 70, 63, 68] if event == Skill1: iku.motion = 1 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak,skillstart main_state.Character_Motion_Cheak = True if int(iku.skill1cheak)<8: iku.frame1 = (iku.frame1+ SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 if int(iku.skill1cheak)>=7 and int(iku.skill1cheak)<20: skillcheak=1 main_state.Skill1_Start=True if int(iku.skill1cheak)>20: iku.frame1 = (iku.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11 iku.skill1cheak =(iku.skill1cheak + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%24 if int(iku.skill1cheak)>=22: skillcheak=0 iku.add_event(Stand) main_state.Skill1_Start=False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 1: iku.skill1.clip_draw(iku.Skill1frame1[int(iku.frame1)], 145, iku.Skill1frame2[int(iku.frame2)], 145, iku.x, iku.y) class Skill2State: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.skill2cheak = 0 iku.skill2Px = 300 iku.Skill2frame1 = [0, 70, 130, 200, 283, 356, 422, 490, 597, 732, 912, 1087, 1247, 1375, 1463, 1520] iku.Skill2frame2 = [70, 60, 70, 83, 73, 66, 66, 101, 133, 178, 173, 157, 124, 83, 63] if event == Skill2: iku.motion = 2 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak main_state.Character_Motion_Cheak = True if int(iku.skill2cheak) < 11: iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 if int(iku.skill2cheak) > 5 and int(iku.skill2cheak) < 15: skillcheak=1 if iku.skill2cheak > 8: main_state.Skill2_Start = True iku.skill2Px += int(MOTION_SPEED_PPS) if int(iku.skill2cheak) >= 15: iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15 main_state.Skill2_Start = False iku.skill2Px -= int(MOTION_SPEED_PPS) iku.skill2cheak = (iku.skill2cheak+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%20 if int(iku.skill2cheak) >= 19: skillcheak=0 iku.skill2cheak = 0 iku.add_event(Stand) main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 2: iku.skill2.clip_draw(iku.Skill2frame1[int(iku.frame1)], 145, iku.Skill2frame2[int(iku.frame2)], 145,iku.x+iku.skill2Px, iku.y) class Skill3State: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.skill3cheak = 0 iku.Skill3frame1 = [0, 64, 126, 196, 268, 338, 405] iku.Skill3frame2 = [64, 62, 70, 72, 67, 68] if event == Skill3: iku.motion = 3 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak main_state.Character_Motion_Cheak = True if int(iku.skill3cheak) < 19: if int(iku.skill3cheak) < 5: iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 if int(iku.skill3cheak) >= 5: main_state.Skill3_Start=True if int(iku.skill3cheak) > 17: iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6 iku.skill3cheak = (iku.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%20 if int(iku.skill3cheak) >= 18: iku.skill3cheak = 0 iku.add_event(Stand) main_state.Skill3_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 3: iku.skill3.clip_draw(iku.Skill3frame1[int(iku.frame1)], 145, iku.Skill3frame2[int(iku.frame2)], 145,iku.x, iku.y) class Laststate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.lastframe = 0 iku.lastEframe1 = 0 iku.lastcheak = 0 iku.LastspellEframe1 = 0 iku.Lastspellframe1 = 0 iku.Lastspellframe2 = 0 iku.Lastspellframe3 = 0 iku.Lastspellc = 0 iku.Lastspelld = 0 iku.IkuLastX = [0, 120, 75] iku.IkuLastY = [120, 75] iku.Lastframe1 = [0, 60, 120, 180, 243, 315, 440, 570, 700, 825, 945, 1035] iku.Lastframe2 = [60, 60, 60, 63, 72, 125, 130, 130, 125, 120] iku.timer = pico2d.get_time() if event == Last: iku.motion = 4 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): global HP,HPcheak main_state.Character_Motion_Cheak = True if int(iku.lastcheak) < 34: if int(iku.lastcheak) < 8: iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 if int(iku.lastcheak) >= 8: main_state.Last_Start=True if int(iku.lastcheak) >= 32: iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10 iku.lastcheak = (iku.lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) %35 if int(iku.lastcheak) >= 34: iku.lastcheak = 0 iku.add_event(Stand) main_state.Last_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 4: iku.Lastspell.clip_draw(iku.Lastframe1[int(iku.frame1)], 140, iku.Lastframe2[int(iku.frame2)], 140,iku.x, iku.y) class Damagestate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.Damagecheak = 0 iku.Damageframe = 0 iku.Damageframe1 = [0, 94, 174, 245] iku.Damageframe2 = [94, 80, 73] if event == Damage: iku.motion = 5 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): if int(iku.Damagecheak) < 3: iku.frame1 = (iku.frame1+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 iku.frame2 = (iku.frame2 +DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 iku.Damagecheak = ( iku.Damagecheak + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(iku.Damagecheak) >= 3: iku.Damagecheak = 0 iku.add_event(Stand) @staticmethod def draw(iku): if iku.motion == 5: iku.Damage.clip_draw(iku.Damageframe1[int(iku.frame1)],135,iku.Damageframe2[int(iku.frame2)],135, iku.x, iku.y) class Downstate: @staticmethod def enter(iku, event): iku.frame1 = 0 iku.frame2 = 0 iku.Downcheak=0 iku.Downframe1 = [0, 125, 240, 374, 514, 651, 793, 945] iku.Downframe2 = [125, 115, 134, 140, 136, 140, 158] if event == Down: iku.motion = 6 @staticmethod def exit(iku, event): pass @staticmethod def do(iku): if int(iku.Downcheak) < 20: if int(iku.Downcheak) < 6: iku.frame1 = (iku.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 iku.frame2 = (iku.frame2 +DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 iku.Downcheak = (iku.Downcheak + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time)%21 if int(iku.Downcheak) >= 20: pass #iku.timer -= 1 @staticmethod def draw(iku): if iku.motion == 6: iku.Down.clip_draw(iku.Downframe1[int(iku.frame1)], 105, iku.Downframe2[int(iku.frame2)], 105, iku.x, iku.y-30) class Item_Doll: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item1cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item1: iku.motion = 7 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item1cheak) < 6: if int(iku.item1cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item1cheak = (iku.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item1cheak) >= 6: iku.item1cheak = 0 iku.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 7: iku.item_use.clip_draw(0,0,40,65,200,280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 145, iku.item1frame2[int(iku.frame2)], 145,iku.x, iku.y) class Item_Potion: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item2cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item2: iku.motion = 8 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item2cheak) < 6: if int(iku.item2cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item2cheak = (iku.item2cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item2cheak) >= 6: iku.item2cheak = 0 iku.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 8: iku.item_use.clip_draw(40, 0, 40, 65, 200, 280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 145, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y) class Item_Clock: @staticmethod def enter(iku,event): iku.frame1 = 0 iku.frame2 = 0 iku.item3cheak = 0 iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405] iku.item1frame2 = [64, 62, 70, 72, 67, 68] if event == Item3: iku.motion = 9 @staticmethod def exit(iku,event): pass @staticmethod def do(iku): global HP,HPcheak,skillcheak if int(iku.item3cheak) < 6: if int(iku.item3cheak) < 5: iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6 iku.item3cheak = (iku.item3cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7 if int(iku.item3cheak) >= 6: iku.item3cheak = 0 iku.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(iku): if iku.motion == 9: iku.item_use.clip_draw(80, 0, 40, 65, 200, 280) iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 145, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:Downstate}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Iku: def __init__(self): self.x, self.y = 200, 200 self.stand = load_image('./FCGimage/Iku-Standing-Motion.png') self.skill1 = load_image('./FCGimage/IkuSkill1-Motion.png') self.skill2 = load_image('./FCGimage/IkuSkill2-Motion.png') self.skill3 = load_image('./FCGimage/IkuSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/IkuLastspell-Motion.png') self.Lasteffect = load_image('./FCGimage/IkuLastspell1-1.png') self.Lasteffect2 = load_image('./FCGimage/IkuLastspell1-2.png') self.Damage = load_image('./FCGimage/IkuDamage-Motion.png') self.Down = load_image('./FCGimage/Iku-Down-Motion.png') self.skill1_sound = load_wav('./voice/iku-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/iku-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/iku-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/iku-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/iku-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/iku-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/iku-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): global cheak1,HP,mouse_x,mouse_y,AtkBuff,DefBuff if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y=event.x, 600- event.y if (event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT): ##스킬키 체크 if main_state.turn==1and main_state.DeckShow==1: if mouse_x > 270 and mouse_x < 330 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[Deck.spellcheak%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[Deck.spellcheak%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[Deck.spellcheak%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[Deck.spellcheak%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[Deck.spellcheak%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[Deck.spellcheak%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[Deck.spellcheak%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 370 and mouse_x < 430 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==2: main_state.HP += 30 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 470 and mouse_x < 530 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==2: main_state.HP += 30 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) elif (event.type, event.key) in key_event_table: key_event = key_event_table[(event.type, event.key)] self.add_event(key_event) <file_sep>/Project/test/tenshiSkill.py from pico2d import * import game_framework import main_state import DeckSelection import tenshi import Enemy_tenshi import EnemyHP #tenshi stand STAND_TIME_PER_ACTION=0.8 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=6 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=16 #skill2 SKILL2TIME_PER_ACTION=2 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=22 #skill3 SKILL3TIME_PER_ACTION=1.5 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=17 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=21 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=6 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) import game_world name = 'tenshiskill' class TENSHI_Skill1: def __init__(self): self.hight_stone = None self.mini_ston=None self.lazerbeam=None self.circle=None self.letter=None if self.hight_stone==None: self.hight_stone=load_image('./FCGimage/TenshiSkill1.png') if self.mini_ston==None: self.mini_ston = load_image('./FCGimage/TenshiSkill2-1.png') if self.lazerbeam==None: self.lazerbeam =load_image('./FCGimage/TenshiSkill3.png') if self.circle==None: self.circle=load_image('./FCGimage/TenshiLastspell1-2.png') if self.letter==None: self.letter=load_image('./FCGimage/TenshiLastspell1-1.png') #skill1 self.Hight_Stone_frame=0 self.Hight_Stone_FX_frame = 0 self.Hight_Stone_FY_frame = 0 self.Hight_Stone_FX = [0, 106, 235, 367, 509, 646, 746, 875] self.Hight_Stone_FY = [107, 129, 132, 142, 135, 98, 135] self.Hight_Stone_Move=160 self.SKill1cheak=0 #skill2 self.Mini_Stone_frame=0 self.Mini_Stone_First = 75 self.Mini_Stone_Second = 95 self.Mini_Stone_Third = 85 self.Skill2cheak=0 #skill3 self.Lazerbeam_frame =0 #Last self.Letter_frame=0 self.Lastcheak=0 def get_bb(self): pass def draw(self): if DeckSelection.character==3 and main_state.turn== 1 and main_state.Skill1_Start==True: if self.SKill1cheak > 7: self.hight_stone.clip_draw(self.Hight_Stone_FX[int(self.Hight_Stone_FX_frame)], 0,self.Hight_Stone_FY[int(self.Hight_Stone_FY_frame)], 165, 600, 200+self.Hight_Stone_Move) if main_state.EnemyPlayer==3 and main_state.turn== -1 and main_state.Skill1_Start==True: if self.SKill1cheak > 7: self.hight_stone.clip_draw(self.Hight_Stone_FX[int(self.Hight_Stone_FX_frame)], 0,self.Hight_Stone_FY[int(self.Hight_Stone_FY_frame)], 165, 200, 200+self.Hight_Stone_Move) if DeckSelection.character==3 and main_state.turn ==1 and main_state.Skill2_Start ==True: self.mini_ston.clip_draw(0, int(self.Mini_Stone_frame) * 50, 70, 50, 50 + self.Mini_Stone_First , 200) self.mini_ston.clip_draw(0, int(self.Mini_Stone_frame) * 50, 70, 50, 50 + self.Mini_Stone_Second, 200 + 25) self.mini_ston.clip_draw(0, int(self.Mini_Stone_frame) * 50, 70, 50, 50 + self.Mini_Stone_Third , 200 - 25) if main_state.EnemyPlayer==3 and main_state.turn == -1 and main_state.Skill2_Start ==True: self.mini_ston.clip_draw(70, int(self.Mini_Stone_frame) * 50, 70, 50, 750 - self.Mini_Stone_First, 200) self.mini_ston.clip_draw(70, int(self.Mini_Stone_frame) * 50, 70, 50, 750 - self.Mini_Stone_Second, 200 + 25) self.mini_ston.clip_draw(70, int(self.Mini_Stone_frame) * 50, 70, 50, 750 - self.Mini_Stone_Third, 200 - 25) if DeckSelection.character==3 and main_state.turn ==1 and main_state.Skill3_Start ==True: self.lazerbeam.clip_draw(int(self.Lazerbeam_frame) * 260, 107, 260, 120, 200 + 350, 200 - 10) if main_state.EnemyPlayer==3 and main_state.turn == -1 and main_state.Skill3_Start ==True: self.lazerbeam.clip_draw(int(self.Lazerbeam_frame) * 260, 0, 260, 120, 600 - 350, 200 - 10) if DeckSelection.character==3 and main_state.turn ==1 and main_state.Last_Start ==True: if int(self.Lastcheak) > 3: self.circle.clip_draw(0,0,250,250,600, 200 ) if int(self.Lastcheak) > 4: self.letter.clip_draw(self.Letter_frame *260,0,260,250,600, 200 ) if main_state.EnemyPlayer==3 and main_state.turn == -1 and main_state.Last_Start ==True: if int(self.Lastcheak) > 3: self.circle.clip_draw(0,0,250,250,200, 200 ) if int(self.Lastcheak) > 4: self.letter.clip_draw(self.Letter_frame *260,0,260,250,200, 200 ) def update(self): if main_state.Skill1_Start == True: if self.Hight_Stone_Move <135: main_state.tenshi_skill1_atk_cheak =1 if self.Hight_Stone_Move <130: main_state.tenshi_skill1_atk_cheak=0 self.SKill1cheak=(self.SKill1cheak + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 16 if self.SKill1cheak > 7: self.Hight_Stone_FX_frame = (self.Hight_Stone_FX_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 8 self.Hight_Stone_FY_frame = (self.Hight_Stone_FY_frame + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 7 if self.SKill1cheak >9: self.Hight_Stone_Move -= int(MOTION_SPEED_PPS) * 3 if self.Hight_Stone_Move < 10: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 if main_state.Skill1_Start == False: main_state.tenshi_skill1_atk_cheak = 0 self.Hight_Stone_frame = 0 self.Hight_Stone_FX_frame = 0 self.Hight_Stone_FY_frame = 0 self.Hight_Stone_Move = 160 self.SKill1cheak = 0 if main_state.Skill2_Start == False: main_state.tenshi_skill2_atk_cheak = 0 self.Mini_Stone_frame=(self.Mini_Stone_frame + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 3 self.Mini_Stone_First = 75 self.Mini_Stone_Second = 95 self.Mini_Stone_Third = 85 self.Skill2cheak=0 if main_state.Skill2_Start ==True: if self.Mini_Stone_Second >450: main_state.tenshi_skill2_atk_cheak=1 if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 if self.Mini_Stone_Second >470: main_state.tenshi_skill2_atk_cheak = 0 self.Skill2cheak=( self.Skill2cheak + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%22 self.Mini_Stone_frame = (self.Mini_Stone_frame + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 3 if self.Skill2cheak >2: self.Mini_Stone_First += int(MOTION_SPEED_PPS) * 5 if self.Skill2cheak >4: self.Mini_Stone_Second += int(MOTION_SPEED_PPS) * 5 if self.Skill2cheak >6: self.Mini_Stone_Third += int(MOTION_SPEED_PPS) * 5 if main_state.Skill3_Start==True: if int(self.Lazerbeam_frame)==4: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.tenshi_skill3_atk_cheak=1 if int(self.Lazerbeam_frame)==5: main_state.tenshi_skill3_atk_cheak=0 self.Lazerbeam_frame = (self.Lazerbeam_frame + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 7 if main_state.Skill3_Start == False: main_state.tenshi_skill3_atk_cheak = 0 self.Lazerbeam_frame=0 if main_state.Last_Start==True: self.Lastcheak = (self.Lastcheak+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%21 if int(self.Lastcheak) == 6: if main_state.turn == 1: main_state.HPcheak = 1 if main_state.turn == -1: main_state.P_HPcheak = 1 main_state.tenshi_last_atk_cheak=1 if int(self.Lastcheak) == 9: self.Letter_frame = 1 if int(self.Lastcheak) == 15: self.Letter_frame = 2 if main_state.Last_Start == False: main_state.tenshi_last_atk_cheak = 0 self.Letter_frame = 0 self.Lastcheak = 0 <file_sep>/Project/test/mygame.py import game_framework import pico2d import FCG_title pico2d.open_canvas(800, 600) game_framework.run(FCG_title) pico2d.close_canvas()<file_sep>/Project/test/EnemyHP.py from pico2d import * import main_state import iku attack1=1 attack2=2 attack3=3 attack4=4 damage = 0 Damagecheak=0 #speed PIXEL_PER_METER=(10.0/0.3) Damage_SPEED_KMPH = 0.1 Damage_SPEED_MPM = (Damage_SPEED_KMPH*1000.0/60.0) Damage_SPEED_MPS=(Damage_SPEED_MPM/60.0) Damage_SPEED_PPS=(Damage_SPEED_MPS*PIXEL_PER_METER) class Enemy_HP: def __init__(self): self.x = 600 self.y = 500 self.Power = 0 self.Damage=0 self.HPBar = load_image('./FCGimage/HP-Damege.png') self.HP = load_image('./FCGimage/HP-HP.png') def update(self): global attack1, attack2, attack3, attack4,damage self.Power = main_state.HP if main_state.HPcheak==1: if damage < self.Power: damage +=Damage_SPEED_PPS if int(damage) == int(self.Power): main_state.HPcheak=0 if main_state.HPinit==1: damage=0 main_state.HP=0 main_state.HPinit=0 if damage <0: damage=0 if main_state.HP <0: main_state.HP=0 def draw(self): global damage self.HPBar.draw(self.x, self.y) self.HP.clip_draw(0, 0,252-int(damage),15,self.x-(damage//2),self.y) <file_sep>/Project/test/backgroundmusic.py from pico2d import * import BackgroundSelection class BG_Music: def __init__(self): if BackgroundSelection.BGcheak==0: self.bgm = load_music('./Background/bamboo.mp3') self.bgm.set_volume(25) self.bgm.repeat_play() if BackgroundSelection.BGcheak==1: self.bgm = load_music('./Background/shrine.mp3') self.bgm.set_volume(25) self.bgm.repeat_play() if BackgroundSelection.BGcheak==2: self.bgm = load_music('./Background/clocktower.mp3') self.bgm.set_volume(25) self.bgm.repeat_play() def update(self): pass def draw(self): pass <file_sep>/Project/Reimu/Reimu-Skill2-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 ReimuSkill2 = load_image('Reimu-Skill2-Motion.png') ReimuSkill2effect = load_image('Reimu-Skill2.png') def Reimu_Skill2(): frame=[0,66,120,217,304,392,480,572,675] frame2=[66,54,97,87,88,88,92,103] i=0 j=0 cheak=0 S_frame=0 while(cheak<8): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 ReimuSkill2.clip_draw(frame[i],0,frame2[j],120,Enemy_X,200) #플레이어 ReimuSkill2.clip_draw(frame[i],155,frame2[j],120,Player_X,200) #적스킬 ReimuSkill2effect.clip_draw(S_frame *133,0,134,255,Player_X,260) #플레이어 스킬 ReimuSkill2effect.clip_draw(S_frame *133,0,134,255,Enemy_X,260) i=(i+1)%9 j=(j+1)%8 S_frame=(S_frame+1)%8 update_canvas() delay(0.1) cheak +=1 while(True): Reimu_Skill2() close_canvas() <file_sep>/Project/test/marisa.py from pico2d import * import game_framework import Deck import main_state import PlayerHP import game_world #marisa stand STAND_TIME_PER_ACTION=1 STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION STAND_PER_ACTION=9 #skill1 SKILL1TIME_PER_ACTION=2 SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION SKILL1_PER_ACTION=20 #skill2 SKILL2TIME_PER_ACTION=1 SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION SKILL2_PER_ACTION=9 #skill3 SKILL3TIME_PER_ACTION=2 SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION SKILL3_PER_ACTION=20 # iku lastspell Action Speed LASTTIME_PER_ACTION=2 LASTACTION_PER_TIME= 1.0/LASTTIME_PER_ACTION LASTCHEAK_PER_ACTION=20 #Damage DAMAGETIME_PER_ACTION=1 DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION DAMAGE_PER_ACTION=4 #Down DOWNTIME_PER_ACTION=3 DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION DOWN_PER_ACTION=21 #itemuse ITEM1TIME_PER_ACTION=1 ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION ITEM1_PER_ACTION=10 #motion speed PIXEL_PER_METER=(10.0/0.3) MOTION_SPEED_KMPH = 0.2 MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0) MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0) MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER) # marisa Event Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10) key_event_table = { (SDL_MOUSEBUTTONDOWN, 1): Skill1, (SDL_MOUSEBUTTONDOWN, 2): Skill2, (SDL_MOUSEBUTTONDOWN, 3): Skill3, (SDL_MOUSEBUTTONDOWN, 4): Last, (SDL_MOUSEBUTTONDOWN, 99): Damage, (SDL_MOUSEBUTTONDOWN, 98): Down, (SDL_MOUSEBUTTONDOWN, 5): Item1, (SDL_MOUSEBUTTONDOWN, 6): Item2, (SDL_MOUSEBUTTONDOWN, 7): Item3 } # marisa States HP= 0 class StandState: @staticmethod def enter(marisa, event): marisa.motion = 0 marisa.frame1 = 0 marisa.frame2 = 0 marisa.Standframe1 = [0,65,126,188,250,312,372,434,495,556,618] marisa.Standframe2 = [65,61,62,62,62,60,62,61,60,62] @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): marisa.frame1 = (marisa.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9 main_state.Character_Motion_Cheak = False if int(PlayerHP.damage) >252: marisa.down_sound.play() marisa.add_event(Down) if main_state.EnemyPlayer == 0 and main_state.reimu_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 0 and main_state.reimu_last_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill2_atk_cheak==1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_skill3_atk_cheak ==1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 1 and main_state.marisa_last_atk_cheak==1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 2 and main_state.iku_last_atk_cheak== 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill1_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill2_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_skill3_atk_cheak == 1: marisa.damage_sound.play() marisa.add_event(Damage) if main_state.EnemyPlayer == 3 and main_state.tenshi_last_atk_cheak== 1: marisa.damage_sound.play() marisa.add_event(Damage) @staticmethod def draw(marisa): if marisa.motion ==0: marisa.stand.clip_draw(marisa.Standframe1[int(marisa.frame1)], 110, marisa.Standframe2[int(marisa.frame2)], 110, marisa.x, marisa.y) class Skill1State: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.S1frame = 0 marisa.Skill1Eframe1 = 0 marisa.skill1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Skill1: marisa.motion = 1 @staticmethod def exit(marisa, event): pass #if event ==SPACE: # boy.fire_ball() @staticmethod def do(marisa): main_state.Character_Motion_Cheak = True if int(marisa.skill1cheak) < 6: marisa.frame1 = (marisa.frame1 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 if int(marisa.skill1cheak) >6: if marisa.skill1cheak < 15: main_state.Skill1_Start=True if int(marisa.skill1cheak) >= 15: main_state.Skill1_Start = False marisa.frame1 = (marisa.frame1+SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2 +SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.skill1cheak =(marisa.skill1cheak+SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.skill1cheak)>=18: marisa.skill1cheak=0 marisa.add_event(Stand) main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 1: marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 105, marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Skill2State: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.skill2cheak = 0 marisa.Skill2frame1 = [0, 85, 165, 240, 318, 395, 464, 525] marisa.Skill2frame2 = [85, 80, 75, 78, 76, 67, 64] if event == Skill2: marisa.motion = 2 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): main_state.Character_Motion_Cheak = True if int(marisa.skill2cheak) < 7: marisa.frame1 = (marisa.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 7 marisa.frame2 = (marisa.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 7 main_state.Skill2_Start=True marisa.skill2cheak = (marisa.skill2cheak+ SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time)%9 if int(marisa.skill2cheak) >= 7: marisa.skill2cheak = 0 marisa.add_event(Stand) main_state.Skill2_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 2: marisa.skill2.clip_draw(marisa.Skill2frame1[int(marisa.frame1)], 120, marisa.Skill2frame2[int(marisa.frame2)], 120,marisa.x, marisa.y) class Skill3State: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.skill3cheak = 0 marisa.Skill3frame1 = [0, 65, 125, 195, 275, 332, 412, 500, 590, 661] marisa.Skill3frame2 = [65, 60, 70, 80, 60, 76, 85, 89, 68, 61] if event == Skill3: marisa.motion = 3 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): main_state.Character_Motion_Cheak = True if int(marisa.skill3cheak) < 17: if int(marisa.skill3cheak) < 7: marisa.frame1 = (marisa.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.skill3cheak) >= 7: main_state.Skill3_Start = True if int(marisa.skill3cheak) >= 13: marisa.frame1 = (marisa.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.frame2 = (marisa.frame2+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 10 marisa.skill3cheak = (marisa.skill3cheak+ SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.skill3cheak) >= 17: marisa.skill3cheak = 0 marisa.add_event(Stand) main_state.Skill3_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 3: marisa.skill3.clip_draw(marisa.Skill3frame1[int(marisa.frame1)], 110, marisa.Skill3frame2[int(marisa.frame2)], 110,marisa.x, marisa.y) class Laststate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.lastframe = 0 marisa.lastEframe1 = 0 marisa.lastcheak = 0 marisa.LastspellEframe1 = 0 marisa.Lastspellframe1 = 0 marisa.Lastspellframe2 = 0 marisa.Lastspellframe3 = 0 marisa.Lastspellc = 0 marisa.Lastspelld = 0 marisa.Lastframe1 = [0, 65,127,187,251,305,386,451,536,610,680,750,815,880,943,1010,1070] marisa.Lastframe2 = [65,62,60,64,55,79,62,80,72,66,66,65,63,60,59,58,58] if event == Last: marisa.motion = 4 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): main_state.Character_Motion_Cheak = True if int(marisa.lastcheak) < 18: marisa.frame1 = (marisa.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 17 marisa.frame2 = (marisa.frame2+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 17 if int(marisa.lastcheak) > 4 and int(marisa.lastcheak)<11: main_state.Last_Start=True marisa.lastcheak = (marisa.lastcheak+ LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time)%20 if int(marisa.lastcheak) >= 18: marisa.lastcheak = 0 marisa.add_event(Stand) main_state.Last_Start = False main_state.Player_AtkBuff = 1 main_state.Enemy_DefBuff = 1 main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 4: marisa.Lastspell.clip_draw(marisa.Lastframe1[int(marisa.frame1)], 120, marisa.Lastframe2[int(marisa.frame2)], 120,marisa.x+250, marisa.y) class Damagestate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.Damagecheak = 0 marisa.Damageframe = 0 marisa.Damageframe1 = [0, 90, 175, 240] marisa.Damageframe2 = [90, 85, 65] if event == Damage: marisa.motion = 5 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): if int(marisa.Damagecheak) < 3: marisa.frame1 = (marisa.frame1 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 marisa.frame2 = (marisa.frame2 + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3 marisa.Damagecheak = (marisa.Damagecheak+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4 if int(marisa.Damagecheak) >= 3: marisa.Damagecheak = 0 marisa.add_event(Stand) @staticmethod def draw(marisa): if marisa.motion == 5: marisa.Damage.clip_draw(marisa.Damageframe1[int(marisa.frame1)],115,marisa.Damageframe2[int(marisa.frame2)],115, marisa.x, marisa.y) class Downstate: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.Downcheak=0 marisa.Downframe1 = [0,80,149,232,348,451,548,645] marisa.Downframe2 = [80,69,83,116,102,95,100] if event == Down: marisa.motion = 6 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): if int(marisa.Downcheak) < 20: if int(marisa.Downcheak) < 6: marisa.frame1 = (marisa.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 marisa.frame2 = (marisa.frame2 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7 marisa.Downcheak = (marisa.Downcheak+ DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) if int(marisa.Downcheak) >= 20: pass #marisa.timer -= 1 @staticmethod def draw(marisa): if marisa.motion == 6: marisa.Down.clip_draw(marisa.Downframe1[int(marisa.frame1)], 95, marisa.Downframe2[int(marisa.frame2)], 95, marisa.x, marisa.y-20) class Item_Doll: @staticmethod def enter(marisa,event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item1: marisa.motion = 7 @staticmethod def exit(marisa,event): pass @staticmethod def do(marisa): global HP,HPcheak,skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 7: marisa.item_use.clip_draw(0, 0, 40, 65, 200, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 105,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Item_Potion: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item2: marisa.motion = 8 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): global HP, HPcheak, skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 8: marisa.item_use.clip_draw(40, 0, 40, 65, 200, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 105,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) class Item_Clock: @staticmethod def enter(marisa, event): marisa.frame1 = 0 marisa.frame2 = 0 marisa.item1cheak = 0 marisa.Skill1frame1 = [0, 71, 132, 197, 262, 322, 396, 468, 536, 600] marisa.Skill1frame2 = [71, 61, 65, 65, 58, 72, 72, 66, 60] if event == Item3: marisa.motion = 9 @staticmethod def exit(marisa, event): pass @staticmethod def do(marisa): global HP, HPcheak, skillcheak if int(marisa.item1cheak) < 9: marisa.frame1 = (marisa.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.frame2 = (marisa.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 9 marisa.item1cheak = (marisa.item1cheak + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 10 if int(marisa.item1cheak) >= 9: marisa.item1cheak = 0 marisa.add_event(Stand) main_state.turn = -1 Deck.spellcheak += 3 @staticmethod def draw(marisa): if marisa.motion == 9: marisa.item_use.clip_draw(80, 0, 40, 65, 200, 280) marisa.skill1.clip_draw(marisa.Skill1frame1[int(marisa.frame1)], 105,marisa.Skill1frame2[int(marisa.frame2)], 105, marisa.x, marisa.y) next_state_table = { StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock}, Skill1State: {Skill1: StandState, Stand:StandState}, Skill2State: {Skill2: StandState, Stand:StandState}, Skill3State: {Skill3: StandState ,Stand: StandState}, Laststate: {Last:StandState,Stand: StandState}, Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate}, Downstate: {Down:StandState,Stand:StandState,Damage:Downstate}, Item_Doll:{Item1:StandState, Stand:StandState}, Item_Potion:{Item2:StandState, Stand:StandState}, Item_Clock:{Item3:StandState, Stand:StandState} } class Marisa: def __init__(self): self.x, self.y = 200, 200 self.stand = load_image('./FCGimage/MarisaStanding-Motion.png') self.skill1 = load_image('./FCGimage/MarisaSkill1-Motion.png') self.skill2 = load_image('./FCGimage/MarisaSkill2-Motion.png') self.skill3 = load_image('./FCGimage/MarisaSkill3-Motion.png') self.Lastspell = load_image('./FCGimage/MarisaLastspell-Motion.png') self.Damage = load_image('./FCGimage/MarisaDamage-Motion.png') self.Down = load_image('./FCGimage/MarisaDown-Motion.png') self.skill1_sound = load_wav('./voice/marisa-skill1.wav') self.skill1_sound.set_volume(50) self.skill2_sound = load_wav('./voice/marisa-skill2.wav') self.skill2_sound.set_volume(50) self.skill3_sound = load_wav('./voice/marisa-skill3.wav') self.skill3_sound.set_volume(50) self.last_sound = load_wav('./voice/marisa-Last.wav') self.last_sound.set_volume(50) self.damage_sound = load_wav('./voice/marisa-damage.wav') self.damage_sound.set_volume(30) self.down_sound = load_wav('./voice/marisa-down.wav') self.down_sound.set_volume(70) self.item_sound = load_wav('./voice/marisa-item.wav') self.item_sound.set_volume(50) self.item_use = load_image('./FCGimage/commonCard.png') self.dir = 1 self.motion = 0 self.frame = 0 self.timer = 0 self.event_que = [] self.cur_state = StandState self.cur_state.enter(self, None) def add_event(self, event): self.event_que.insert(0, event) def update(self): self.cur_state.do(self) if len(self.event_que) > 0: event = self.event_que.pop() self.cur_state.exit(self, event) self.cur_state = next_state_table[self.cur_state][event] self.cur_state.enter(self, event) def draw(self): self.cur_state.draw(self) def handle_event(self, event): global cheak1, HP, mouse_x, mouse_y if event.type == SDL_MOUSEMOTION: mouse_x, mouse_y = event.x, 600 - event.y if (event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT): ##스킬키 체크 if main_state.turn==1and main_state.DeckShow==1: if mouse_x > 270 and mouse_x < 330 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[Deck.spellcheak%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[Deck.spellcheak%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[Deck.spellcheak%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[Deck.spellcheak%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[Deck.spellcheak%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[Deck.spellcheak%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[Deck.spellcheak%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 370 and mouse_x < 430 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+1)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) if mouse_x > 470 and mouse_x < 530 and mouse_y > 55 and mouse_y < 145: if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==1: main_state.HP += 20 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill1_sound.play() self.add_event(Skill1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==2: main_state.HP += 30* main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill2_sound.play() self.add_event(Skill2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==3: main_state.HP += 40 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.skill3_sound.play() self.add_event(Skill3) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==4: main_state.HP += 50 * main_state.Player_AtkBuff * main_state.Enemy_DefBuff main_state.DeckShow = 0 self.last_sound.play() self.add_event(Last) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==5: main_state.Player_DefBuff =0 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item1) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==6: main_state.Player_AtkBuff = 3 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item2) if Deck.PlayerDeck[(Deck.spellcheak+2)%12]==7: main_state.P_HP -= 100 PlayerHP.damage -= 100 main_state.DeckShow = 0 self.item_sound.play() self.add_event(Item3) elif (event.type, event.key) in key_event_table: key_event = key_event_table[(event.type, event.key)] self.add_event(key_event)<file_sep>/Project/CharacterSelection.py import game_framework from pico2d import * #import CharacterSelection name = "CharacterSelection" image = None start = None def enter(): global image global start image = load_image('CharacterSelection.png') def exit(): global image global start del(image) del(start) def handle_events(): events = get_events() for event in events: if event.type ==SDL_QUIT: game_framework.quit() else: if(event.type, event.key) == (SDL_KEYDOWN,SDLK_ESCAPE): game_framework.quit() elif(event.type, event.key)==(SDL_KEYDOWN,SDLK_SPACE): pass #game_framework.change_state(CharacterSelection) def draw(): clear_canvas() image.draw(400,300) update_canvas() def update(): pass def pause(): pass def resume(): pass <file_sep>/Project/Iku/Iku-Skill3-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuSkill3 = load_image('IkuSkill3-Motion.png') IkuSkill3effect = load_image('IkuSkill3-1.png') def Iku_Skill3(): frame1 = [64,62,70,72,67,68] frame2 = [0,64,126,196,268,338,405] cheak=0 S_frame=0 i=0 j=0 while(cheak<19): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuSkill3.clip_draw(frame2[i],0,frame1[j],145,Enemy_X,All_Y) #플레이어 IkuSkill3.clip_draw(frame2[i],145,frame1[j],145,Player_X,All_Y) if cheak<5: i=(i+1)%7 j=(j+1)%6 if cheak >=5: #플레이어 IkuSkill3effect.clip_draw(S_frame *260,0,260,250,Enemy_X,All_Y+25) #적 IkuSkill3effect.clip_draw(S_frame *260,0,260,250,Player_X,All_Y+25) S_frame =(S_frame+1)%4 if cheak >17: i=(i+1)%7 j=(j+1)%6 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Skill3() close_canvas() <file_sep>/Project/Iku/Iku-Skill1-Animation.py from pico2d import * open_canvas() BgShrine = load_image('Hakurei Shrine.png') Player_X =200 Enemy_X=600 All_Y=200 IkuSkill1 = load_image('IkuSkill1-Motion.png') IkuSkill1effect = load_image('IkuSkill1-1.png') IkuSkill1effect2 = load_image('IkuSkill1-2.png') def Iku_Skill1(): frame1 = [68,65,60,66,68,59,78,74,70,63,68] frame2 = [0,68,133,193,259,329,390,470,543,615,680,745] cheak=0 Sframe=0 Sframe1=0 i=0 j=0 while(cheak<23): clear_canvas() BgShrine.clip_draw(0,0,800,600,400,300) #적 IkuSkill1.clip_draw(frame2[i],0,frame1[j],145,Enemy_X,All_Y) #플레이어 IkuSkill1.clip_draw(frame2[i],145,frame1[j],145,Player_X,All_Y) if cheak<8: i=(i+1)%12 j=(j+1)%11 if cheak>=8: if cheak<20: #플레이어 IkuSkill1effect.clip_draw(0,Sframe*52,360,52,Player_X+200,All_Y+10) IkuSkill1effect2.clip_draw(Sframe1*65,0,68,60,Enemy_X-10,All_Y+10) #적 IkuSkill1effect.clip_draw(0,Sframe*52,360,52,Enemy_X-210,All_Y+10) IkuSkill1effect2.clip_draw(Sframe1*66,0,68,60,Player_X+10,All_Y+10) Sframe = (Sframe+1)%12 Sframe1 = (Sframe1+1)%7 if cheak>=20: i=(i+1)%12 j=(j+1)%11 update_canvas() delay(0.1) cheak +=1 while(True): BgShrine.clip_draw(0,0,800,600,400,300) Iku_Skill1() close_canvas()
eed9b84ce5ce833af3aca85e703fcbd57ad15f4b
[ "Python" ]
49
Python
what1995/2DGP-PROJECT
38c3567cd574988ec34dcb9b207ff4511888d567
561dc6a65b6f0870484116830f0d3809ff2202f6
refs/heads/master
<file_sep>#pragma once #ifndef __Pixel__ #define __Pixel__ #include <Eigen/Dense> class Pixel { public: Pixel(); Pixel(float iR, float iG, float iB); ~Pixel(); float r, g, b; void Average(float newR, float newG, float newB); void AveragePx(Pixel other); bool HasColor(); private: }; #endif <file_sep>#pragma once #ifndef __Sphere__ #define __Sphere__ #include <Eigen/Dense> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Shape.hpp" #include "Ray.hpp" #include "VectorMath.hpp" class Sphere: public Shape { public: Sphere(); Sphere(Eigen::Vector3f c); Sphere(float r); Sphere(Eigen::Vector3f c, float r); ~Sphere(); // Shape has a center and radius, the only components of a sphere virtual Eigen::Vector3f GetNormal(Eigen::Vector3f hitPt); float checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir); private: }; #endif <file_sep>/* * Base code for this parser from http://mrl.nyu.edu/~dzorin/cg05/handouts/pov-parser/index.html */ #ifndef __PARSE_H__ #define __PARSE_H__ #include <stdio.h> #include "Scene.hpp" int Parse(FILE* infile, Scene &scene); #endif /* __PARSE_H__ */ <file_sep>#include <Picture.hpp> #include <stdio.h> #include <iostream> #include <stdlib.h> using namespace std; Picture::Picture() { width = 0; height = 0; Pixels.clear(); } Picture::Picture(int w, int h) { width = 0; height = 0; Pixels.clear(); resize(w, h); } Picture::~Picture() { Pixels.clear(); } void Picture::setPixel(int x, int y, Pixel newP) { int idx = getIdx(x, y); if (idx != -1) Pixels[idx] = newP; } Pixel Picture::getPixel(int x, int y) { int idx = getIdx(x, y); if (idx != -1) return Pixels[idx]; else { cout << "ERROR! Index out of bounds" << endl; return Pixels[0]; } } void Picture::resize(int w, int h) { int oldSize = width * height; int newSize = w * h; width = w; height = h; Pixels.resize(newSize); for(int i = oldSize; i < newSize; ++i) { Pixels[i] = Pixel(); } } int Picture::getIdx(int x, int y) { int ret = 0; ret = x + y * width; return ret; } void Picture::Print(string fileName) { //ofstream myfile; //myfile.open(fileName.c_str()); Image *img; color_t clr; Pixel temp; img = new Image(width, height); for (int y = height - 1; y >= 0; --y) { for (int x = 0; x < width; ++x) { temp = getPixel(x, y); clr.r = temp.r; clr.g = temp.g; clr.b = temp.b; clr.f = 1.0; img->pixel(x, y, clr); /*if (getPixel(x, y).HasColor()) { myfile << "*"; } else { myfile << " "; }*/ } //myfile << "\n"; } //myfile.close(); char *holdName = (char *)fileName.c_str(); img->WriteTga(holdName, true); } <file_sep>/* * Base code for this parser from http://mrl.nyu.edu/~dzorin/cg05/handouts/pov-parser/index.html */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <iostream> #include <math.h> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include "Tokens.hpp" #include "types.h" #include "Triangle.hpp" #include "Sphere.hpp" #include "Plane.hpp" #include "Parse.hpp" using namespace Eigen; using namespace std; /* Functions in this file implement parsing operations for each object type. The main function to be called is Parse(). Each parsing function assigns values retrieved from the file to a set of local variables that can be used to create objects. Parsing stops at the first error and the program exits through function Error() defined in tokens.c, after printing the current line number and an error message. (A real parser would have better error recovery, but this simple approach greatly simplifies the code and is sufficient for our purposes). */ struct Finish { double ambient; double diffuse; double specular; double roughness; double phong; double phong_size; double reflection; int metallic; } typedef Finish; struct ModifierStruct { color_t pigment; struct Finish finish; double interior; } typedef ModifierStruct; /* a collection of functions for syntax verification */ void ParseLeftAngle() { GetToken(); if(Token.id != T_LEFT_ANGLE ) Error("Expected <"); } void ParseRightAngle() { GetToken(); if(Token.id != T_RIGHT_ANGLE ) Error("Expected >"); } double ParseDouble() { GetToken(); if(Token.id != T_DOUBLE ) Error("Expected a number"); return Token.double_value; } void ParseLeftCurly() { GetToken(); if(Token.id != T_LEFT_CURLY ) Error("Expected {"); } void ParseRightCurly() { GetToken(); if(Token.id != T_RIGHT_CURLY ) Error("Expected }"); } void ParseComma() { GetToken(); if(Token.id != T_COMMA ) Error("Expected ,"); } void ParseVector(Vector3f &v) { ParseLeftAngle(); v[0] = ParseDouble(); ParseComma(); v[1] = ParseDouble(); ParseComma(); v[2] = ParseDouble(); ParseRightAngle(); } void ParseRGBFColor(color_t &c) { ParseLeftAngle(); c.r = ParseDouble(); ParseComma(); c.g = ParseDouble(); ParseComma(); c.b = ParseDouble(); ParseComma(); c.f = ParseDouble(); ParseRightAngle(); } void ParseRGBColor(color_t &c) { ParseLeftAngle(); c.r = ParseDouble(); ParseComma(); c.g = ParseDouble(); ParseComma(); c.b = ParseDouble(); c.f = 0.0; ParseRightAngle(); } void ParseColor(color_t &c) { GetToken(); if(Token.id == T_RGB) ParseRGBColor(c); else if ( Token.id == T_RGBF ) ParseRGBFColor(c); else Error("Expected rgb or rgbf"); } void PrintColor(color_t &c) { printf("rgbf <%.3g,%.3g,%.3g,%.3g>", c.r, c.g, c.b, c.f); } void ParsePigment(color_t &pigment) { ParseLeftCurly(); while(1) { GetToken(); if(Token.id == T_COLOR) ParseColor(pigment); else if(Token.id == T_RIGHT_CURLY) return; else Error("error parsing pigment: unexpected token"); } } void PrintPigment(color_t &pigment) { printf("\tpigment { color "); PrintColor(pigment); printf("}"); } void ParseFinish(Finish &finish) { ParseLeftCurly(); while(1) { GetToken(); switch(Token.id) { case T_AMBIENT: finish.ambient = ParseDouble(); break; case T_DIFFUSE: finish.diffuse = ParseDouble(); break; case T_SPECULAR: finish.specular= ParseDouble(); break; case T_ROUGHNESS: finish.roughness= ParseDouble(); break; case T_PHONG: finish.phong = ParseDouble(); break; case T_PHONG_SIZE: finish.phong_size = ParseDouble(); break; case T_REFLECTION: finish.reflection = ParseDouble(); break; case T_METALLIC: finish.metallic = (ParseDouble() != 0.0 ? 1: 0); break; case T_RIGHT_CURLY: return; default: Error("Error parsing finish: unexpected token"); } } } void PrintFinish(Finish &finish) { printf("\tfinish { ambient %.3g diffuse %.3g phong %.3g phong_size %.3g reflection %.3g metallic %d }\n", finish.ambient, finish.diffuse, finish.phong, finish.phong_size, finish.reflection, finish.metallic); } void ParseInterior(double interior) { ParseLeftCurly(); while(1) { GetToken(); if( Token.id == T_RIGHT_CURLY) return; else if (Token.id == T_IOR) { interior = ParseDouble(); } else Error("Error parsing interior: unexpected token\n"); } } void InitModifiers(ModifierStruct &modifiers) { modifiers.pigment.r = 0; modifiers.pigment.g = 0; modifiers.pigment.b = 0; modifiers.pigment.f = 0; modifiers.finish.ambient = 0.1; modifiers.finish.diffuse = 0.6; modifiers.finish.phong = 0.0; modifiers.finish.phong_size = 40.0; modifiers.finish.reflection = 0; modifiers.finish.roughness = 0.05; modifiers.finish.specular = 0.0; modifiers.interior = 1.0; } void PrintModifiers(ModifierStruct &modifiers) { PrintPigment(modifiers.pigment); printf("\n"); PrintFinish(modifiers.finish); printf("\tinterior { ior %.3g }\n", modifiers.interior); } void ParseModifiers(Material &mat) { ModifierStruct modifiers; InitModifiers(modifiers); while(1) { GetToken(); switch(Token.id) { case T_SCALE: case T_ROTATE: case T_TRANSLATE: case T_PIGMENT: ParsePigment(modifiers.pigment); break; case T_FINISH: ParseFinish(modifiers.finish); break; case T_INTERIOR: ParseInterior(modifiers.interior); break; default: UngetToken(); mat.rgb = Eigen::Vector3f(modifiers.pigment.r, modifiers.pigment.g, modifiers.pigment.b); mat.ambient = modifiers.finish.ambient; mat.diffuse = modifiers.finish.diffuse; mat.specular = modifiers.finish.specular; mat.roughness = modifiers.finish.roughness; mat.shine = 1 / modifiers.finish.roughness; return; } } } void ParseCamera(Camera &camera) { double angle; int done = FALSE; ParseLeftCurly(); // parse camera parameters while(!done) { GetToken(); switch(Token.id) { case T_LOCATION: ParseVector(camera.position); break; case T_RIGHT: ParseVector(camera.right); break; case T_UP: ParseVector(camera.up); break; case T_LOOK_AT: ParseVector(camera.look_at); break; case T_ANGLE: angle = M_PI * ParseDouble() / 180.0; break; default: done = TRUE; UngetToken(); break; } } ParseRightCurly(); } void ParseSphere(vector<Sphere> &spheres) { Vector3f center; double radius; Material mat; center = Vector3f(0, 0, 0); radius = 1.0; ParseLeftCurly(); ParseVector(center); ParseComma(); radius = ParseDouble(); ParseModifiers(mat); ParseRightCurly(); spheres.push_back(Sphere(center, radius)); spheres.back().SetMaterialToMat(mat); } void ParseTriangle(vector<Triangle> &triangles) { Vector3f vert1, vert2, vert3; Material mat; ParseLeftCurly(); ParseVector(vert1); ParseComma(); ParseVector(vert2); ParseComma(); ParseVector(vert3); ParseModifiers(mat); ParseRightCurly(); triangles.push_back(Triangle(vert1, vert2, vert3)); triangles.back().SetMaterialToMat(mat); } void ParsePlane(vector<Plane> &planes) { Eigen::Vector3f normal; float dist; Material mat; ParseLeftCurly(); ParseVector(normal); ParseComma(); dist = (float) ParseDouble(); ParseModifiers(mat); ParseRightCurly(); planes.push_back(Plane(Eigen::Vector3f(0,dist,0), normal, -1)); planes.back().SetMaterialToMat(mat); } void ParseLightSource(vector<Light> &lights) { Light light; ParseLeftCurly(); ParseVector(light.location); GetToken(); if(Token.id != T_COLOR) Error("Error parsing light source: missing color"); ParseColor(light.color); ParseRightCurly(); lights.push_back(light); } void ParseGlobalSettings() { color_t ambient; ParseLeftCurly(); while(1) { GetToken(); if(Token.id == T_AMBIENT_LIGHT) { ParseLeftCurly(); GetToken(); if(Token.id != T_COLOR) Error("Error parsing light source: missing color"); ParseColor(ambient); ParseRightCurly(); } else if(Token.id == T_RIGHT_CURLY) { break; } else Error("error parsing default settings: unexpected token"); } } /* main parsing function calling functions to parse each object; */ int Parse(FILE* infile, Scene &scene) { int numObjects = 0; InitializeToken(infile); GetToken(); while(Token.id != T_EOF) { switch(Token.id) { case T_CAMERA: ParseCamera(scene.camera); break; case T_TRIANGLE: ParseTriangle(scene.triangles); break; case T_SPHERE: ParseSphere(scene.spheres); break; case T_PLANE: ParsePlane(scene.planes); break; case T_LIGHT_SOURCE: ParseLightSource(scene.lights); break; case T_GLOBAL_SETTINGS: ParseGlobalSettings(); break; default: Error("Unknown statement"); } GetToken(); ++numObjects; } return numObjects; } <file_sep>CU=nvcc CC=icpc CFLAGS=-ansi -pedantic -Wno-deprecated -std=c++0x -Wall -pedantic -O3 -fopenmp -xHost INC=-I$(EIGEN3_INCLUDE_DIR) -I./ -I/usr/local/cuda/include LIB=-DGL_GLEXT_PROTOTYPES -lglut -lGL -lGLU OBJECT = Image.o main.o Parse.o Picture.o Pixel.o Plane.o Ray.o Scene.o Sphere.o Shape.o Triangle.o Tokens.o VectorMath.o ifdef DEBUG CFLAGS += -D DEBUG endif all: $(OBJECT) $(CC) -g $(CFLAGS) $(INC) $(OBJECT) $(LIB) -o rt %.o: %.cpp $(CC) -g -c $< $(CFLAGS) $(INC) $(LIB) %.cpp: %.h touch $@ %.cpp: %.hpp touch $@ %.o: %.cu $(CU) -g -c -m64 $< $(LIBS) $(OPTS) %.cu: %.h touch $@ ball: ./rt ../resources/bunny_small.pov tri: ./rt ../resources/bunny_small_tris.pov good: ./rt ../resources/simp_cam.pov good2: ./rt ../resources/simp_cam2.pov clean: rm -f *~ *.o a.out rt clear: $(OBJECT) clear rm -f *~ *.o a.out rt $(CC) $(CFLAGS) $(INC) *.cpp $(LIB) -o rt fast: $(OBJECT) rm -f *~ *.o a.out rt clear $(CC) $(CFLAGS) $(INC) *.cpp $(LIB) -o rt ./rt ../resources/bunny_small.pov <file_sep>#include <Pixel.hpp> Pixel::Pixel() { r = 0; g = 0; b = 0; } Pixel::Pixel(float iR, float iG, float iB) { r = iR; g = iG; b = iB; } Pixel::~Pixel() { } void Pixel::Average(float newR, float newG, float newB) { r += newR; r = r/2.0f; g += newB; g = g/2.0f; b += newB; b = b/2.0f; } void Pixel::AveragePx(Pixel other) { r += other.r; r = r/2.0f; g += other.g; g = g/2.0f; b += other.b; b = b/2.0f; } bool Pixel::HasColor() { if (r <= .0001 && g <= .0001 && b <= .0001) { return false; } return true; } <file_sep>#pragma once #ifndef __Triangle__ #define __Triangle__ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Ray.hpp" #include "VectorMath.h" #include "Shape.hpp" class Triangle: public Shape { public: Triangle(); Triangle(Vector3f pta, Vector3f ptb, Vector3f ptc); ~Triangle(); __device__ __host__ virtual Vector3f GetNormal(Vector3f hitPt); __device__ __host__ float checkHit(Vector3f eye, Vector3f dir); // Parts of a triangle Vector3f a, b, c; Vector3f normal; float areaSqr; void Initialize(); }; #endif <file_sep>#pragma once #ifndef __Picture__ #define __Picture__ #include <Pixel.hpp> #include <vector> #include <iostream> #include <fstream> #include "Image.hpp" class Picture { public: Picture(); Picture(int w, int h); ~Picture(); int width, height; std::vector<Pixel> pixels; void setPixel(int x, int y, Pixel newP); Pixel getPixel(int x, int y); void resize(int w, int h); void Print(std::string fileName); private: int getIdx(int x, int y); }; #endif <file_sep>#include <Eigen/Dense> #include <math.h> #include "VectorMath.hpp" float magnitude(Eigen::Vector3f V) { return sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2]); } Eigen::Vector3f normalize(Eigen::Vector3f V) { float mag = magnitude(V); return Eigen::Vector3f(V[0] / mag, V[1] / mag, V[2] / mag); } Eigen::Vector3f cross(Eigen::Vector3f U, Eigen::Vector3f V) { float x = U[1] * V[2] - U[2] * V[1]; float y = U[2] * V[0] - U[0] * V[2]; float z = U[0] * V[1] - U[1] * V[0]; return Eigen::Vector3f(x,y,z); } float dot(Eigen::Vector3f U, Eigen::Vector3f V) { float ret = U[0]*V[0] + U[1]*V[1] + U[2]*V[2]; return ret; } float angle(Eigen::Vector3f U, Eigen::Vector3f V) { return acos(dot(U, V) / (magnitude(U) * magnitude(V))); } <file_sep>#include "Plane.hpp" using namespace std; #define kEpsilon 1e-5 Plane::Plane() { center = Eigen::Vector3f(0,0,0); normal = Eigen::Vector3f(0,0,-1); radius = 1.0f; #ifndef CULLING isFlat = true; #endif } Plane::Plane(Eigen::Vector3f c, Eigen::Vector3f n, float r) { center = c; normal = n; radius = r; #ifndef CULLING isFlat = true; #endif } Plane::~Plane(){ } Eigen::Vector3f Plane::GetNormal(Eigen::Vector3f hitPt) { return normal; } float Plane::checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir) { float t = -1; // assuming vectors are all normalized double denom = dot(normal, dir); if (fabs(denom) > kEpsilon) { Eigen::Vector3f p0l0 = center - eye; t = dot(p0l0, normal) / denom; } if (t < 0) return 0; if (radius < 0) { return t; } Eigen::Vector3f p = eye + dir * t; Eigen::Vector3f v = p - center; double d2 = dot(v, v); if (d2 <= radius*radius) return t; return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <iostream> #include <string> #include <vector> #include "Tokens.hpp" #define MAX_STR_LENGTH 128 using namespace std; /* Tokeninzing part of the parser; the parsing routines call GetToken() and UngetToken() to retrieve tokens from the input stream. GetToken reads the input stream of characters stripping the comments until a complete token is produced. Then the token is placed into the global variable Token, from which it can ber retrieved by the calling routines. */ Token_Struct Token; /* * Simple method for checking for reserved words. * The words currently not supported are commented out. * * This could be done more efficiently with a map or hash table * but C++98 doesn't have pleasant intializers for those does it? */ static enum TokenIDs FindReserved(string str) { //if(!str.compare("rotate")) return T_ROTATE; //if(!str.compare("translate")) return T_TRANSLATE; //if(!str.compare("scale")) return T_SCALE; //if(!str.compare("matrix")) return T_MATRIX; //if(!str.compare("polygon")) return T_POLYGON; if(!str.compare("triangle")) return T_TRIANGLE; if(!str.compare("sphere")) return T_SPHERE; if(!str.compare("plane")) return T_PLANE; //if(!str.compare("box")) return T_BOX; //if(!str.compare("cylinder")) return T_CYLINDER; //if(!str.compare("cone")) return T_CONE; //if(!str.compare("quadric")) return T_QUADRIC; if(!str.compare("camera")) return T_CAMERA; if(!str.compare("location")) return T_LOCATION; if(!str.compare("right")) return T_RIGHT; if(!str.compare("up")) return T_UP; if(!str.compare("look_at")) return T_LOOK_AT; if(!str.compare("angle")) return T_ANGLE; if(!str.compare("global_settings")) return T_GLOBAL_SETTINGS; if(!str.compare("ambient_light")) return T_AMBIENT_LIGHT; if(!str.compare("light_source")) return T_LIGHT_SOURCE; if(!str.compare("finish")) return T_FINISH; if(!str.compare("pigment")) return T_PIGMENT; if(!str.compare("rgb")) return T_RGB; if(!str.compare("color")) return T_COLOR; if(!str.compare("rgbf")) return T_RGBF; if(!str.compare("reflection")) return T_REFLECTION; if(!str.compare("ambient")) return T_AMBIENT; if(!str.compare("diffuse")) return T_DIFFUSE; if(!str.compare("specular")) return T_SPECULAR; if(!str.compare("roughness")) return T_ROUGHNESS; if(!str.compare("phong")) return T_PHONG; if(!str.compare("metallic")) return T_METALLIC; if(!str.compare("phong_size")) return T_PHONG_SIZE; if(!str.compare("interior")) return T_INTERIOR; if(!str.compare("ior")) return T_IOR; return T_NULL; } #define CR '\010' #define LF '\0' void Error(string str) { cout << "Line " << Token.lineNumber << ": " << str << endl; exit(EXIT_FAILURE); } /* should be called before GetToken() */ void InitializeToken(FILE* infile) { Token.unget_flag = 0; Token.id = T_NULL; Token.infile = infile; Token.lineNumber = 1; } static void SkipSpaces() { int c; while(1) { c = getc(Token.infile); if( c == '\n') Token.lineNumber++; if (c == EOF ) return; if( c == '/') { /* we use slash only as a part of the comment begin sequence; if something other than another slash follows it, it is an error */ if( getc(Token.infile) == '/') { /* skip everything till the end of the line */ while( c != '\n' && c != '\r' && c != EOF ) { c = getc(Token.infile); } Token.lineNumber++; } else Error("Missing second slash in comment"); } if(!isspace(c)) break; } ungetc(c, Token.infile); } void ReadDouble() { /* this is cheating -- we'd better parse the number definition ourselves, to make sure it conforms to a known standard and to do error hanndling properly, but for our purposes this is good enough */ int res; res = fscanf( Token.infile, "%le", &Token.double_value); if( res == 1 ) Token.id = T_DOUBLE; else Error("Could not read a number"); } static void ReadName() { char str[MAX_STR_LENGTH]; int str_index; int c; str_index = 0; while (1) { c = getc(Token.infile); if (c == EOF) { Error("Could not read a name"); } if (isalpha(c) || isdigit(c) || c == '_') { /* if the name is too long, ignore extra characters */ if( str_index < MAX_STR_LENGTH - 1) { str[str_index++] = c; } } else { ungetc(c, Token.infile); break; } } str[str_index++] = '\0'; Token.id = FindReserved(str); if(Token.id == T_NULL) { fprintf(stderr, "%s: ", str); Error("Unknown reserved word"); } } /* * Sets the global struct Token to the * next input token, if there is one. * if there is no legal token in the input, * returns 0, otherwise returns 1. */ void GetToken() { int c; if(Token.unget_flag) { Token.unget_flag = FALSE; return; } SkipSpaces(); c = getc(Token.infile); if( c == EOF ) { Token.id = T_EOF; return; } if(isalpha(c)) { ungetc(c, Token.infile); ReadName(); } else if(isdigit(c) || c == '.' || c == '-' || c == '+' ) { ungetc(c, Token.infile); ReadDouble(); } else { switch(c) { case ',': Token.id = T_COMMA; break; case '{': Token.id = T_LEFT_CURLY; break; case '}': Token.id = T_RIGHT_CURLY; break; case '<': Token.id = T_LEFT_ANGLE; break; case '>': Token.id = T_RIGHT_ANGLE; break; default: Error("Unknown token"); } } } /* Assumes that GetToken() was called at least once. Cannot be called two times without a GetToken() between the calls */ void UngetToken() { assert(!Token.unget_flag); Token.unget_flag = TRUE; } <file_sep>#pragma once #ifndef __Triangle__ #define __Triangle__ #include <Eigen/Dense> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Ray.hpp" #include "VectorMath.hpp" #include "Shape.hpp" class Triangle: public Shape { public: Triangle(); Triangle(Eigen::Vector3f pta, Eigen::Vector3f ptb, Eigen::Vector3f ptc); ~Triangle(); virtual Eigen::Vector3f GetNormal(Eigen::Vector3f hitPt); float checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir); protected: // Parts of a triangle Eigen::Vector3f a, b, c; Eigen::Vector3f normal; float areaSqr; void Initialize(); }; #endif <file_sep>#pragma once #ifndef __Scene__ #define __Scene__ #include <vector> #include <cuda_runtime.h> #include <stdint.h> #include "Shape.hpp" #include "Triangle.hpp" #include "Sphere.hpp" #include "Plane.hpp" #include "types.h" #include "Pixel.hpp" #include "Vector3f.h" #include "VectorMath.h" #define TILE_WIDTH 32 typedef struct hit_t { Shape *hitShape; double t; bool isHit; float nx; float ny; float nz; } hit_t; class Scene { public: Scene(); ~Scene(); void setupCudaMem(int bufferSize); void getCudaMem(Pixel *pixels_h, int bufferSize); Camera camera; std::vector<Light> lights; std::vector<Triangle> triangles; std::vector<Sphere> spheres; std::vector<Plane> planes; Light *lights_d; Triangle *triangles_d; Sphere *spheres_d; Plane *planes_d; Pixel *pixels_d; private: }; void renderStart(int width, int height, Vector3f backgroundCol, Vector3f CameraRight, Vector3f CameraUp, Vector3f CameraPos, Vector3f CameraDirection, Pixel *pixels, Light *lights, int numLights, Plane *planes, int numPlanes, Triangle *triangles, int numTriangles, Sphere *spheres, int numSpheres); void checkCudaErrors(int errorCode, char const *callName); __device__ hit_t checkHit(Ray testRay, Shape *exclude, Plane *planes, int numPlanes, Triangle *triangles, int numTriangles, Sphere *spheres, int numSpheres); __device__ Pixel ComputeLighting(Ray laser, hit_t hitResult, Light *lights, int numLights, Plane *planes, int numPlanes, Triangle *triangles, int numTriangles, Sphere *spheres, int numSpheres); __global__ void renderScene(float aspectRatio, int width, int height, Vector3f backgroundCol, Vector3f CameraRight, Vector3f CameraUp, Vector3f CameraPos, Vector3f CameraDirection, Pixel *pixels, Light *lights, int numLights, Plane *planes, int numPlanes, Triangle *triangles, int numTriangles, Sphere *spheres, int numSpheres); __device__ float plane_CheckHit(Plane *plane, Vector3f eye, Vector3f dir); __device__ float sphere_CheckHit(Sphere *sphere, Vector3f eye, Vector3f dir); __device__ float triangle_CheckHit(Triangle *tri, Vector3f eye, Vector3f dir); #endif <file_sep>#pragma once #ifndef __PLANE_H__ #define __PLANE_H__ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Shape.hpp" #include "Ray.hpp" #include "Vector3f.h" #include "VectorMath.h" class Plane: public Shape { public: Plane(); Plane(Vector3f c, Vector3f n, float r); ~Plane(); Vector3f normal; __device__ __host__ virtual Vector3f GetNormal(Vector3f hitPt); // Shape has a center and radius, the only components of a Plane __device__ __host__ float checkHit(Vector3f eye, Vector3f dir); private: }; #endif <file_sep>#pragma once #ifndef __Pixel__ #define __Pixel__ #include <cuda_runtime.h> class Pixel { public: __device__ __host__ Pixel(); __device__ __host__ Pixel(float iR, float iG, float iB); __device__ __host__ ~Pixel(); float r, g, b; __device__ __host__ void Average(float newR, float newG, float newB); __device__ __host__ void AveragePx(Pixel other); __device__ __host__ bool HasColor(); private: }; #endif <file_sep>#pragma once #ifndef __RAY_H__ #define __RAY_H__ #include <cuda_runtime.h> #include "Vector3f.h" #include "VectorMath.h" class Ray { public: __device__ __host__ Ray(); __device__ __host__ Ray(Vector3f d); __device__ __host__ Ray(Vector3f e, Vector3f d); __device__ __host__ ~Ray(); Vector3f eye, direction; private: }; #endif <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> //#include <memory> #include "Picture.hpp" #include "Scene.hpp" #include "Sphere.hpp" #include "Sphere.hpp" #include "Triangle.hpp" #include "Ray.hpp" #include "Shape.hpp" #include "Parse.hpp" #include "VectorMath.h" #include "Vector3f.h" #include <vector> #include <math.h> #include <cuda_runtime.h> using namespace std; Vector3f backgroundCol; Picture pic; Scene scene; Vector3f Up = Vector3f(0,1,0); Vector3f CameraPos, CameraDirection, CameraRight, CameraUp; bool USE_DIRECTION = false; int width = 600; int height = 600; void InitCamera() { CameraPos = Vector3f(0,0,10); CameraDirection = normalize(Vector3f(0,0,-1)); CameraRight = cross(CameraDirection, Up); CameraUp = cross(CameraRight, CameraDirection); } void InitCamera(Camera &camera) { CameraPos = camera.position; CameraDirection = normalize(camera.look_at - camera.position); CameraRight = camera.right; CameraUp = cross(CameraRight, CameraDirection); #ifdef DEBUG cout << "Camera:\n" << "\tPOSITION: " << CameraPos[0] << ", " << CameraPos[1] << ", " << CameraPos[2] << endl << "\tDIRECTION: " << CameraDirection[0] << ", " << CameraDirection[1] << ", " << CameraDirection[2] << endl << "\tRIGHT: " << CameraRight[0] << ", " << CameraRight[1] << ", " << CameraRight[2] << endl << "\tUP: " << CameraUp[0] << ", " << CameraUp[1] << ", " << CameraUp[2] << endl; #endif } void loadScene() { pic = Picture(width, height); backgroundCol = Vector3f(0, 0, 0); InitCamera(scene.camera); } void SetupPicture() { #ifdef DEBUG cout << "Triangles: " << scene.triangles.size() << endl; cout << "Spheres: " << scene.spheres.size() << endl; cout << "Planes: " << scene.planes.size() << endl; cout << "Lights: " << scene.lights.size() << endl; #endif scene.setupCudaMem(pic.pixels.size()*sizeof(Pixel)); renderStart(width, height, backgroundCol, CameraRight, CameraUp, CameraPos, CameraDirection, scene.pixels_d, scene.lights_d, (uint32_t) scene.lights.size(), scene.planes_d, (uint32_t) scene.planes.size(), scene.triangles_d, (uint32_t) scene.triangles.size(), scene.spheres_d, (uint32_t) scene.spheres.size()); scene.getCudaMem(&(pic.pixels[0]), pic.pixels.size()*sizeof(Pixel)); } void PrintPicture() { pic.Print("results.tga"); } int main(int argc, char **argv) { FILE* infile; scene = Scene(); if(argc < 2) { cout << "Usage: rt <input_scene.pov>" << endl; exit(EXIT_FAILURE); } infile = fopen(argv[1], "r"); if(infile) { cout << Parse(infile, scene) << " objects parsed from scene file" << endl; } else { perror("fopen"); exit(EXIT_FAILURE); } //Scene starts here loadScene(); SetupPicture(); PrintPicture(); return 0; } <file_sep>#pragma once #ifndef __VECTOR3F_H__ #define __VECTOR3F_H__ #include <cuda_runtime.h> class Vector3f { public: __device__ __host__ Vector3f(); __device__ __host__ Vector3f(float a, float b, float c); __device__ __host__ ~Vector3f(); __device__ __host__ Vector3f Add(Vector3f &other); __device__ __host__ Vector3f Subtract(Vector3f &other); __device__ __host__ Vector3f Dot(Vector3f &other); __device__ __host__ Vector3f Cross(Vector3f &other); __device__ __host__ float Magnitude(); __device__ __host__ Vector3f Normalize(); __device__ __host__ inline Vector3f operator+ (const Vector3f& other) { return Vector3f(this->data[0] + other.data[0], this->data[1] + other.data[1], this->data[2] + other.data[2]); } __device__ __host__ inline Vector3f operator- (const Vector3f& other) { return Vector3f(this->data[0] - other.data[0], this->data[1] - other.data[1], this->data[2] - other.data[2]); } __device__ __host__ inline Vector3f operator-() { return Vector3f(-this->data[0], -this->data[1], -this->data[2]); } __device__ __host__ inline Vector3f operator* (const float val) { return Vector3f(this->data[0] * val, this->data[1] * val, this->data[2] * val); } __device__ __host__ inline float& operator[] (int index) { return (data[index]); // No OOB checking for efficiency, so be careful } private: float data[3]; }; //template <typename T> __device__ __host__ //operator*(T scalar, const Vector3f &obj); #endif <file_sep>#pragma once #ifndef __SPHERE_H__ #define __SPHERE_H__ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Shape.hpp" #include "Ray.hpp" #include "VectorMath.h" #include "Vector3f.h" class Sphere: public Shape { public: Sphere(); Sphere(Vector3f c); Sphere(float r); Sphere(Vector3f c, float r); ~Sphere(); // Shape has a center and radius, the only components of a sphere __device__ __host__ virtual Vector3f GetNormal(Vector3f hitPt); __device__ __host__ float checkHit(Vector3f eye, Vector3f dir); private: }; #endif <file_sep>#include "Shape.hpp" using namespace std; Shape::Shape() { //SetMaterialByNum(rand() % NUM_MATS); //center = Eigen::Vector3f(0,0,0); } Shape::~Shape(){ } void Shape::SetMaterialToMat(Material newMat) { mat = newMat; } void Shape::SetMaterialByNum(int colorNum) { Eigen::Vector3f col; float shine, a, s, d, r; switch (colorNum) { case 0: col = Eigen::Vector3f(.8, .2, .2); a = .1; d = .7; s = .5; r = .3; shine = 16; break; case 1: col = Eigen::Vector3f(.2, .2, .8); a = .1; d = .7; s = .5; r = .4; shine = 128; break; case 2: col = Eigen::Vector3f(.2, .8, .2); a = .1; d = .7; s = .5; r = .6; shine = 8; break; case 3: col = Eigen::Vector3f(.8, .2, .8); a = .1; d = .7; s = .5; r = .6; shine = 128; break; case 4: col = Eigen::Vector3f(.8, .2, .8); a = .1; d = .7; s = .5; r = .6; shine = 16; break; case 5: col = Eigen::Vector3f(.8, .8, .0); a = .1; d = .7; s = .5; r = .7; shine = 128; break; default: col = Eigen::Vector3f(.6, .6, .6); a = .1; d = .5; s = .9; r = .8; shine = 256; break; } mat.ambient = a; mat.diffuse = d; mat.specular = s; mat.shine = shine; mat.rgb = col; mat.roughness = r; } void Shape::SetMaterial(string colorName) { if(colorName == "red") { SetMaterialByNum(0); } else if(colorName == "blue") { SetMaterialByNum(1); } else if(colorName == "green"){ SetMaterialByNum(2); } else if(colorName == "purple"){ SetMaterialByNum(3); } else if(colorName == "teal"){ SetMaterialByNum(4); } else if(colorName == "orange"){ SetMaterialByNum(5); } else { cout << "ERROR! " << colorName << " is not a valid color! Here is teal, the color you should have picked" << endl; SetMaterialByNum(4); } } // return vector: inxex 1: how many answers there are // index 2: the positive output // index 3: the negative output Eigen::Vector3f QuadraticFormula(double A, double B, double C) { double discriminate = B*B - 4*A*C; if (discriminate < 0) { return Eigen::Vector3f(0,0,0); } double sqrtDisc = sqrt(discriminate); float plusOp = (-B + sqrtDisc)/(2*A); if (discriminate == 0) { return Eigen::Vector3f(1, plusOp, 0); } float minOp = (-B - sqrtDisc)/(2*A); return Eigen::Vector3f(2, plusOp, minOp); } <file_sep>#ifndef __TYPES_H__ #define __TYPES_H__ #include <vector> #include "Triangle.hpp" #include "Sphere.hpp" #include "Vector3f.h" /* Color struct */ typedef struct color_struct { double r; double g; double b; double f; // "filter" or "alpha" } color_t; typedef struct Camera { Vector3f position; Vector3f look_at; Vector3f right; Vector3f up; } Camera; typedef struct Light { color_t color; Vector3f location; } Light; typedef struct DirLight { color_t color; Vector3f direction; } DirLight; #endif <file_sep>CU=nvcc CC=icpc CFLAGS=-ansi -pedantic -Wno-deprecated -std=c++0x -Wall -pedantic -O3 -fopenmp -xHost -lcudadevrt -lcudart LDFLAGS=-ansi -pedantic -Wno-deprecated -std=c++0x -Wall -pedantic -O3 -fopenmp -xHost -lcudadevrt -lcudart -o INC=-I./ -I/usr/local/cuda/include LIB= CUFLAGS=-rdc=true OBJECT = Image.o main.o Parse.o Picture.o Pixel.o Plane.o Ray.o Scene.o Sphere.o Shape.o Triangle.o Tokens.o VectorMath.o Vector3f.o ifdef NOCUDA CFLAGS += -D NOCUDA else CFLAGS += -lcuda -lcudart endif ifdef NOMP CFLAGS += -D NOMP endif ifdef NOPHI CFLAGS += -D NOPHI endif ifdef DEBUG CFLAGS += -D DEBUG endif all: $(OBJECT) nvcc -g -arch=sm_30 -ccbin=icpc -Xcompiler "$(LDFLAGS) $(INC) $(LIB)" $(OBJECT) -o rt %.o: %.cpp $(CC) -g -c $< $(CFLAGS) $(INC) $(LIB) %.cpp: %.h touch $@ %.cpp: %.hpp touch $@ %.o: %.cu $(CU) -g -c -m64 -arch=sm_30 $< $(LIBS) $(INC) $(CUFLAGS) $(OPTS) %.cu: %.h touch $@ ball: ./rt resources/bunny_small.pov tri: ./rt resources/bunny_small_tris.pov triTest: ./rt resources/triTest.pov good: ./rt resources/simp_cam.pov good2: ./rt resources/simp_cam2.pov clean: rm -f *~ *.o a.out rt clear: $(OBJECT) clear rm -f *~ *.o a.out rt $(CC) $(CFLAGS) $(INC) *.cpp $(LIB) -o rt fast: $(OBJECT) rm -f *~ *.o a.out rt clear $(CC) $(CFLAGS) $(INC) *.cpp $(LIB) -o rt ./rt resources/bunny_small.pov <file_sep>#include "Triangle.hpp" using namespace std; #define kEpsilon 1e-5 Triangle::Triangle() { //SetMaterialByNum(rand() % NUM_MATS); a = Eigen::Vector3f(); b = Eigen::Vector3f(); c = Eigen::Vector3f(); Initialize(); } Triangle::Triangle(Eigen::Vector3f pta, Eigen::Vector3f ptb, Eigen::Vector3f ptc) { //SetMaterialByNum(rand() % NUM_MATS); a = pta; b = ptb; c = ptc; Initialize(); } Triangle::~Triangle(){ } void Triangle::Initialize() { // compute plane's normal Eigen::Vector3f ab = b - a; Eigen::Vector3f ac = c - a; // no need to normalize normal = cross(ab, ac); areaSqr = normal.norm(); // the not offsetted center of the circumsphere center = cross(normal, ab) * magnitude(ac) + cross(ac, normal) * magnitude(ab); // radius ofthe circumsphere radius = magnitude(center); // offset the center properly in the world center += a; normal.normalize(); #ifndef CULLING isFlat = true; #endif } Eigen::Vector3f Triangle::GetNormal(Eigen::Vector3f hitPt) { return normal; } // http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution float Triangle::checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir) { double u, v, t; // first check for circumsphere hit Eigen::Vector3f dist = eye - center; double A = dot(dir, dir); double B = dot((2*dir), dist); double C = dot(dist, dist) - radius*radius; Eigen::Vector3f quad = QuadraticFormula(A, B, C); float result; if (quad(0) == 0) { //SHOULD BE AN ERROR result = 0; } if (quad(0) == 1) { result = quad(1); } if (fabs(quad(1)) <= fabs(quad(2))) { result = quad(1); } else { result = quad(2); } // failure to even hit the circumsphere if (result < 0) { return 0; } Eigen::Vector3f ab = b - a; Eigen::Vector3f ac = c - a; Eigen::Vector3f pvec = dir.cross(ac); double det = dot(ab, pvec); #ifdef CULLING // if the determinant is negative the triangle is backfacing // if the determinant is close to 0, the ray misses the triangle if (det < kEpsilon) return 0; #else // ray and triangle are parallel if det is close to 0 if (fabs(det) < kEpsilon) return 0; #endif double invDet = 1 / det; Eigen::Vector3f tvec = eye - a; u = dot(tvec, pvec) * invDet; if (u < 0 || u > 1) return 0; Eigen::Vector3f qvec = tvec.cross(ab); v = dot(dir, qvec) * invDet; if (v < 0 || u + v > 1) return 0; t = dot(ac, qvec) * invDet; return t; } <file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> #endif #ifdef __unix__ #include <GL/glut.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <memory> #include "Picture.hpp" #include "Scene.hpp" #include "Sphere.hpp" #include "Sphere.hpp" #include "Triangle.hpp" #include "Ray.hpp" #include "Shape.hpp" #include "Parse.hpp" #include "VectorMath.hpp" #include <Eigen/Dense> #include <Eigen/Geometry> #include <vector> #include <math.h> #include <cuda_runtime.h> using namespace std; Eigen::Vector3f backgroundCol; Picture pic; Scene scene; Eigen::Vector3f Up = Eigen::Vector3f(0,1,0); Eigen::Vector3f CameraPos, CameraDirection, CameraRight, CameraUp; bool USE_DIRECTION = false; int width = 600; int height = 600; float aspectRatio; void InitCamera() { CameraPos = Eigen::Vector3f(0,0,10); CameraDirection = normalize(Eigen::Vector3f(0,0,-1)); CameraRight = normalize(cross(CameraDirection, Up)); CameraUp = normalize(cross(CameraRight, CameraDirection)); } void InitCamera(Camera &camera) { CameraPos = camera.position; CameraDirection = normalize(camera.look_at - camera.position); CameraRight = normalize(camera.right); CameraUp = normalize(cross(CameraRight, CameraDirection)); #ifdef DEBUG cout << "Camera:\n" << "\tPOSITION: " << CameraPos[0] << ", " << CameraPos[1] << ", " << CameraPos[2] << endl << "\tDIRECTION: " << CameraDirection[0] << ", " << CameraDirection[1] << ", " << CameraDirection[2] << endl << "\tRIGHT: " << CameraRight[0] << ", " << CameraRight[1] << ", " << CameraRight[2] << endl << "\tUP: " << CameraUp[0] << ", " << CameraUp[1] << ", " << CameraUp[2] << endl; #endif } void loadScene() { pic = Picture(width, height); aspectRatio = (double) width / height; backgroundCol = Eigen::Vector3f(0,0,0); InitCamera(scene.camera); } Ray ComputeCameraRay(int i, int j) { float normalized_i, normalized_j; if(aspectRatio > 1) { normalized_i = ((i/(float)pic.width) - 0.5) * aspectRatio; normalized_j = (j/(float)pic.height) - 0.5; } else { normalized_i = (i/(float)pic.width) - 0.5; normalized_j = ((j/(float)pic.height) - 0.5) / aspectRatio; } Eigen::Vector3f imagePoint = normalized_i * CameraRight + normalized_j * CameraUp + CameraPos + CameraDirection; Eigen::Vector3f ray_direction = normalize(imagePoint - CameraPos); return Ray(CameraPos, ray_direction); } void SetupPicture() { Ray laser; #ifdef DEBUG int noHitCount = 0; cout << "Triangles: " << scene.triangles.size() << endl; cout << "Spheres: " << scene.spheres.size() << endl; cout << "Planes: " << scene.planes.size() << endl; cout << "Lights: " << scene.lights.size() << endl; #endif for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { laser = ComputeCameraRay(x, y); hit_t hitShape = scene.checkHit(laser); if (hitShape.isHit) { pic.setPixel(x, y, scene.ComputeLighting(laser, hitShape, false)); } else { pic.setPixel(x, y, Pixel(backgroundCol[0], backgroundCol[1], backgroundCol[2])); #ifdef DEBUG ++noHitCount; #endif } #ifdef DEBUG cout << "Pixel: " << x * height + y << "\r"; #endif } } #ifdef DEBUG cout << "Rays with no hit: " << noHitCount << endl; #endif } void PrintPicture() { pic.Print("results.tga"); } int main(int argc, char **argv) { FILE* infile; scene = Scene(); if(argc != 2 && argc != 4) { cout << "Usage: rt <input_scene.pov>" << endl; cout << "Usage: rt <input_scene.pov> <width> <height>" << endl; exit(EXIT_FAILURE); } if(argc == 4) { width = std::stoi(argv[2]); height = std::stoi(argv[3]); } infile = fopen(argv[1], "r"); if(infile) { cout << Parse(infile, scene) << " objects parsed from scene file" << endl; } else { perror("fopen"); exit(EXIT_FAILURE); } //Scene starts here loadScene(); SetupPicture(); PrintPicture(); return 0; } <file_sep>#pragma once #ifndef __Scene__ #define __Scene__ #include <Eigen/Dense> #include <vector> #include "Shape.hpp" #include "Triangle.hpp" #include "Sphere.hpp" #include "Plane.hpp" #include "types.h" #include "Pixel.hpp" typedef struct hit_struct { Shape *hitShape; double t; bool isHit; } hit_t; class Scene { public: Scene(); ~Scene(); Camera camera; std::vector<Light> lights; hit_t checkHit(Ray testRay); hit_t checkHit(Ray testRay, Shape *exclude); std::vector<Triangle> triangles; std::vector<Sphere> spheres; std::vector<Plane> planes; Pixel ComputeLighting(Ray laser, hit_t hitResult, bool print); private: }; #endif <file_sep>#ifndef __VECTOR_MATH_H__ #define __VECTOR_MATH_H__ #include <Eigen/Dense> float magnitude(Eigen::Vector3f V); Eigen::Vector3f normalize(Eigen::Vector3f V); Eigen::Vector3f cross(Eigen::Vector3f U, Eigen::Vector3f V); float dot(Eigen::Vector3f U, Eigen::Vector3f V); float angle(Eigen::Vector3f U, Eigen::Vector3f V); #endif <file_sep>#pragma once #ifndef __Plane__ #define __Plane__ #include <Eigen/Dense> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Shape.hpp" #include "Ray.hpp" #include "VectorMath.hpp" class Plane: public Shape { public: Plane(); Plane(Eigen::Vector3f c, Eigen::Vector3f n, float r); ~Plane(); Eigen::Vector3f normal; virtual Eigen::Vector3f GetNormal(Eigen::Vector3f hitPt); // Shape has a center and radius, the only components of a Plane float checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir); private: }; #endif <file_sep>#include <Ray.hpp> Ray::Ray() { direction = Eigen::Vector3f(0,0,1); eye = Eigen::Vector3f(0,0,0); } Ray::Ray(Eigen::Vector3f d) { direction = d; eye = Eigen::Vector3f(0,0,0); } Ray::Ray(Eigen::Vector3f e, Eigen::Vector3f d) { direction = d; eye = e; } Ray::~Ray() { }<file_sep>#pragma once #ifndef __Ray__ #define __Ray__ #include <Eigen/Dense> class Ray { public: Ray(); Ray(Eigen::Vector3f d); Ray(Eigen::Vector3f e, Eigen::Vector3f d); ~Ray(); Eigen::Vector3f eye, direction; private: }; #endif <file_sep>#include "Scene.hpp" #include "Sphere.hpp" #include "Triangle.hpp" #define PI 3.1415926 #define H_PI 1.5707963 #define D_EPSILON 0.001 using namespace std; Scene::Scene() { lights.clear(); triangles.clear(); spheres.clear(); } Scene::~Scene() { lights.clear(); triangles.clear(); spheres.clear(); } hit_t Scene::checkHit(Ray testRay) { Shape* hitShape = NULL; bool hit = false; float bestT = 1000000; for (unsigned int i = 0; i < planes.size(); ++i) { float t = planes[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { //MERP idk if t > 0 is right hitShape = &(planes[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } for (unsigned int i = 0; i < triangles.size(); ++i) { float t = triangles[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { //MERP idk if t > 0 is right hitShape = &(triangles[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } for (unsigned int i = 0; i < spheres.size(); ++i) { float t = spheres[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { //MERP idk if t > 0 is right hitShape = &(spheres[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } if (!hit) { hitShape = NULL; } hit_t ret; ret.hitShape = hitShape; ret.isHit = hit; ret.t = bestT; return ret; } hit_t Scene::checkHit(Ray testRay, Shape *exclude) { Shape* hitShape = NULL; bool hit = false; float bestT = 1000000; for (unsigned int i = 0; i < planes.size(); ++i) { if(&(planes[i]) != exclude) { float t = planes[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { hitShape = &(planes[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } } for (unsigned int i = 0; i < triangles.size(); ++i) { if(&(triangles[i]) != exclude) { float t = triangles[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { hitShape = &(triangles[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } } for (unsigned int i = 0; i < spheres.size(); ++i) { if(&(spheres[i]) != exclude) { float t = spheres[i].checkHit(testRay.eye, testRay.direction); if (t > 0 && t < bestT) { hitShape = &(spheres[i]); bestT = t; hit = true; #ifdef DEBUG2 cout << "New best hit, position of shape: " << (*hitShape).center[0] << ", " << (*hitShape).center[1] << ", " << (*hitShape).center[2] << endl; #endif } } } if (!hit) { hitShape = NULL; } hit_t ret; ret.hitShape = hitShape; ret.isHit = hit; ret.t = bestT; return ret; } Pixel Scene::ComputeLighting(Ray laser, hit_t hitResult, bool print) { Eigen::Vector3f hitPt = laser.eye + laser.direction * (hitResult.t - D_EPSILON); Eigen::Vector3f viewVec = -laser.direction; Eigen::Vector3f rgb = hitResult.hitShape->mat.rgb; Eigen::Vector3f ambient = rgb*hitResult.hitShape->mat.ambient; Eigen::Vector3f n = hitResult.hitShape->GetNormal(hitPt); Eigen::Vector3f color = Eigen::Vector3f(0,0,0); bool inShadow; // calculate if the point is in a shadow. If so, we later return the pixel as all black for (int i = 0; i < lights.size(); ++i) { inShadow = false; Eigen::Vector3f shadowDir = normalize(lights[i].location - hitPt); Eigen::Vector3f l = shadowDir; Ray shadowRay = Ray(hitPt, shadowDir); hit_t shadowHit = checkHit(shadowRay, hitResult.hitShape); if (shadowHit.isHit) { if (shadowHit.hitShape != hitResult.hitShape) inShadow = true; } if (!inShadow) { #ifndef CULLING if(hitResult.hitShape->isFlat && angle(n, l) > H_PI) { n *= -1; } #endif Eigen::Vector3f r = (2 * dot(n,l) * n) - l; r = normalize(r); float specMult = max(dot(viewVec, r), 0.0f); specMult = min(pow(specMult, hitResult.hitShape->mat.shine), 1.0f); Eigen::Vector3f colorS = specMult * rgb; float hold = min(max(dot(l, n), 0.0f), 1.0f); Eigen::Vector3f colorD = hold * rgb; Eigen::Vector3f toAdd = colorD * hitResult.hitShape->mat.diffuse + colorS * hitResult.hitShape->mat.specular; //spec + diffuse setup toAdd[0] *= lights[i].color.r; toAdd[1] *= lights[i].color.g; toAdd[2] *= lights[i].color.b; //actually add spec + diffuse color += toAdd; } //ambient addition color[0] += ambient[0] * lights[i].color.r; color[1] += ambient[1] * lights[i].color.g; color[2] += ambient[2] * lights[i].color.b; //make sure in range still color[0] = min(max(color[0],0.0f),1.0f); color[1] = min(max(color[1],0.0f),1.0f); color[2] = min(max(color[2],0.0f),1.0f); } return Pixel(color(0), color(1), color(2)); } <file_sep>#pragma once #ifndef __SHAPE__ #define __SHAPE__ #include <Eigen/Dense> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Ray.hpp" #define NUM_MATS 7 // POV-ray material struct Material { Eigen::Vector3f rgb; float ambient, diffuse, specular, roughness, shine; } typedef Material; class Shape { public: Shape(); ~Shape(); Material mat; // No matter the shape we generate a bounding sphere Eigen::Vector3f center; float radius; #ifndef CULLING bool isFlat; // flat objects need to have 2 faces checked #endif void SetMaterialToMat(Material newMat); void SetMaterialByNum(int colorNum); void SetMaterial(std::string colorName); virtual Eigen::Vector3f GetNormal(Eigen::Vector3f hitPt) { std::cout << "In Shape GetNormal()...\n"; return Eigen::Vector3f(); } float checkHit(Ray ray) { return checkHit(ray.eye, ray.direction); } virtual float checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir) { //std::cout << "BAD BAD BAD!" << std::endl; return 0; } private: }; // return vector: inxex 1: how many answers there are // index 2: the positive output // index 3: the negative output Eigen::Vector3f QuadraticFormula(double A, double B, double C); #endif <file_sep>#pragma once #ifndef __VECTOR_MATH_H__ #define __VECTOR_MATH_H__ #include <cuda_runtime.h> #include <math.h> #include "Vector3f.h" __device__ __host__ float magnitude(Vector3f V); __device__ __host__ Vector3f normalize(Vector3f V); __device__ __host__ Vector3f cross(Vector3f U, Vector3f V); __device__ __host__ float dot(Vector3f U, Vector3f V); __device__ __host__ float angle(Vector3f U, Vector3f V); #endif <file_sep>#pragma once #ifndef __SHAPE_H__ #define __SHAPE_H__ #include <math.h> #include <iostream> #include "Vector3f.h" #include "VectorMath.h" #include "Ray.hpp" #define NUM_MATS 7 // POV-ray material struct Material { Vector3f rgb; float ambient, diffuse, specular, roughness, shine; } typedef Material; class Shape { public: Shape(); ~Shape(); Material mat; // No matter the shape we generate a bounding sphere Vector3f center; float radius; void SetMaterialToMat(Material newMat); void SetMaterialByNum(int colorNum); void SetMaterial(std::string colorName); __device__ __host__ virtual Vector3f GetNormal(Vector3f hitPt) { return Vector3f(); } __device__ __host__ float checkHit(Ray ray) { return checkHit(ray.eye, ray.direction); } __device__ __host__ virtual float checkHit(Vector3f eye, Vector3f dir) { return 0; } private: }; // return vector: inxex 1: how many answers there are // index 2: the positive output // index 3: the negative output __device__ __host__ Vector3f QuadraticFormula(double A, double B, double C); #endif <file_sep>#include "Sphere.hpp" using namespace std; Sphere::Sphere() { //SetMaterialByNum(rand() % NUM_MATS); center = Eigen::Vector3f(0,0,0); radius = 1.0f; #ifndef CULLING isFlat = false; #endif } Sphere::Sphere(Eigen::Vector3f c) { //SetMaterialByNum(rand() % NUM_MATS); center = c; radius = 1.0f; #ifndef CULLING isFlat = false; #endif } Sphere::Sphere(float r){ //SetMaterialByNum(rand() % NUM_MATS); center = Eigen::Vector3f(0,0,0); radius = r; #ifndef CULLING isFlat = false; #endif } Sphere::Sphere(Eigen::Vector3f c, float r){ //SetMaterialByNum(rand() % NUM_MATS); center = c; radius = r; #ifndef CULLING isFlat = false; #endif } Sphere::~Sphere(){ } Eigen::Vector3f Sphere::GetNormal(Eigen::Vector3f hitPt) { return normalize(hitPt - center); } float Sphere::checkHit(Eigen::Vector3f eye, Eigen::Vector3f dir) { Eigen::Vector3f dist = eye - center; double A = dot(dir, dir); double B = dot((2*dir), dist); double C = dot(dist, dist) - radius*radius; Eigen::Vector3f quad = QuadraticFormula(A, B, C); if (quad(0) == 0) { //SHOULD BE AN ERROR return 0; } if (quad(0) == 1) { return quad(1); } if (fabs(quad(1)) <= fabs(quad(2))) { return quad(1); } else { return quad(2); } }
4bded662bc785d60823dca08ea5fcc6d5e8c85e6
[ "C", "Makefile", "C++" ]
35
C++
aquira246/Parallel_Ray_Tracer
9e53604a2e3cf2d3c2283e443426721edd290c4f
fe1311b21cdbf9c1412e5cade18b9356217b65f2
refs/heads/master
<file_sep>FROM ubuntu ARG USER="unsunghero" ARG EMAIL="<EMAIL>" RUN apt-get update &&\ apt-get -y install git &&\ mkdir /root/.ssh RUN git config --global user.name $USER &&\ git config --global user.email $EMAIL RUN apt-get install -y vim <file_sep># Cloudant shell script [IBM Cloudant](https://www.ibm.com/cloud/cloudant) is a managed CouchDB offering by IBM. This script sets up a few things locally in your environment so that you can easily run simple queries to your Cloudant DB via curl. It gets an IAM token, exports a few Cloudant-related variables and creates a curl alias `acurl` which uses this token transparently to you. Run like: `. cloudant_setup.sh api_key external_endpoint_url` You can then do cloudant queries simply by: `acurl ${CLOUDANT_URL}/api-query` e.g. `acurl ${CLOUDANT_URL}/_all_dbs` ### Notes: Use `jq` to further print or process the returned json. E.g. `acurl ${CLOUDANT_URL}/_all_dbs | jq .` <file_sep># toolbox Small scripts and tools <file_sep>#!/usr/bin/env bash export CLOUDANT_API_KEY=$1 export CLOUDANT_URL=$2 alias acurl='curl -k -X GET -H "Content-type: application/json" -H "Authorization: '"$CLOUDANT_TOKEN"'" ' TOKEN=$(curl -s -k -X POST \ --header "Content-Type: application/x-www-form-urlencoded" \ --header "Accept: application/json" \ --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey" \ --data-urlencode "apikey=${CLOUDANT_API_KEY}" \ "https://iam.cloud.ibm.com/identity/token" | jq '.access_token' | tr -d '"') export CLOUDANT_TOKEN="Bearer $TOKEN" <file_sep># gitcloak A very simple docker image that when run masks your regular local git username and password with the ones you built it with. # Preconditions - You need to set up locally a new ssh key and add it to your github account ([follow this guide](https://help.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account)). The user, email account you will use for this key must match the ones you will use on the Build step. - You need docker installed on your computer. # Build clone this repo and cd into `gitcloak` directory. Then build by: `docker build -t gitcloak --build-arg USER=usernameyouwant --build-arg EMAIL=emailyouwant .` # Run - cd into the dir of your project - run docker image ``docker run -it --rm -v `pwd`:`pwd` -v '/absolute/path/to/your/home/.ssh':'/root/.ssh' -w `pwd` gitcloak bash`` - once inside the container perform your usual git operations (`git add .; git commit -m; etc`) - the user and email will have been cloaked by the user and email you built the image with ``` localhost$ run -it --rm -v `pwd`:`pwd` -v '/Users/zerogvt/.ssh':'/root/.ssh' -w `pwd` gitcloak bash root@ctnr$ git config --list user.name=usernameyouwant user.email=emailyouwant ```
c448f87b1f38585389de1143cafec64c78f388a7
[ "Markdown", "Dockerfile", "Shell" ]
5
Dockerfile
zerogvt/toolbox
ad1f4a7fc4a396bfc26c165c1d674d193d07f1c7
17a705f9de5aa2c0a9a7e9b92f0f867f5364dd66
refs/heads/master
<file_sep>// Generated from /Users/rahulprajapati/Google Drive/CSCE Courses/CSCE 322/Homework/1/startercode/part1/csce322hmwrk01prt01.g4 by ANTLR 4.8 import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class csce322hmwrk01prt01Lexer extends Lexer { static { RuntimeMetaData.checkVersion("4.8", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int SECTION_BEGIN=1, SECTION_END=2, SECTION_TYPE=3, VALUE_ASSIGNMENT=4, VALUE_SEPERATOR=5, NUMERICAL=6, MOVES=7, ROW_SEPERATOR=8, BOARD_BEGIN=9, BOARD_END=10, LIST_BEGIN=11, LIST_END=12, WS=13; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; private static String[] makeRuleNames() { return new String[] { "SECTION_BEGIN", "SECTION_END", "SECTION_TYPE", "VALUE_ASSIGNMENT", "VALUE_SEPERATOR", "NUMERICAL", "MOVES", "ROW_SEPERATOR", "BOARD_BEGIN", "BOARD_END", "LIST_BEGIN", "LIST_END", "WS" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'<<alpha'", "'omega>>'", null, "'='", "'&'", null, null, "'$'", "'{'", "'}'", "'['", "']'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "SECTION_BEGIN", "SECTION_END", "SECTION_TYPE", "VALUE_ASSIGNMENT", "VALUE_SEPERATOR", "NUMERICAL", "MOVES", "ROW_SEPERATOR", "BOARD_BEGIN", "BOARD_END", "LIST_BEGIN", "LIST_END", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public csce322hmwrk01prt01Lexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "csce322hmwrk01prt01.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\17V\b\1\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5"+ "\49\n\4\3\5\3\5\3\6\3\6\3\7\6\7@\n\7\r\7\16\7A\3\b\3\b\3\t\3\t\3\n\3\n"+ "\3\13\3\13\3\f\3\f\3\r\3\r\3\16\6\16Q\n\16\r\16\16\16R\3\16\3\16\2\2\17"+ "\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\3\2\5"+ "\3\2\62;\6\2ffnnttww\5\2\13\f\17\17\"\"\2X\2\3\3\2\2\2\2\5\3\2\2\2\2\7"+ "\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2"+ "\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3"+ "\35\3\2\2\2\5%\3\2\2\2\78\3\2\2\2\t:\3\2\2\2\13<\3\2\2\2\r?\3\2\2\2\17"+ "C\3\2\2\2\21E\3\2\2\2\23G\3\2\2\2\25I\3\2\2\2\27K\3\2\2\2\31M\3\2\2\2"+ "\33P\3\2\2\2\35\36\7>\2\2\36\37\7>\2\2\37 \7c\2\2 !\7n\2\2!\"\7r\2\2\""+ "#\7j\2\2#$\7c\2\2$\4\3\2\2\2%&\7q\2\2&\'\7o\2\2\'(\7g\2\2()\7i\2\2)*\7"+ "c\2\2*+\7@\2\2+,\7@\2\2,\6\3\2\2\2-.\7O\2\2./\7q\2\2/\60\7x\2\2\60\61"+ "\7g\2\2\619\7u\2\2\62\63\7R\2\2\63\64\7w\2\2\64\65\7|\2\2\65\66\7|\2\2"+ "\66\67\7n\2\2\679\7g\2\28-\3\2\2\28\62\3\2\2\29\b\3\2\2\2:;\7?\2\2;\n"+ "\3\2\2\2<=\7(\2\2=\f\3\2\2\2>@\t\2\2\2?>\3\2\2\2@A\3\2\2\2A?\3\2\2\2A"+ "B\3\2\2\2B\16\3\2\2\2CD\t\3\2\2D\20\3\2\2\2EF\7&\2\2F\22\3\2\2\2GH\7}"+ "\2\2H\24\3\2\2\2IJ\7\177\2\2J\26\3\2\2\2KL\7]\2\2L\30\3\2\2\2MN\7_\2\2"+ "N\32\3\2\2\2OQ\t\4\2\2PO\3\2\2\2QR\3\2\2\2RP\3\2\2\2RS\3\2\2\2ST\3\2\2"+ "\2TU\b\16\2\2U\34\3\2\2\2\6\28AR\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }<file_sep>Multi-Language Boss Puzzle ----------------------------- ![](http://tekhkids.jjrsystems.com/images/SJOBS.PNG) Class project to explore different types of languages fundamentally. 1. [ANTRL - ANother Tool for Language Recognition](https://www.antlr.org) 2. [JavaScript](https://www.javascript.com) 3. [Haskell - Functional Programming](https://www.haskell.org) 4. [Prolog - Logical Programming](https://www.swi-prolog.org) **Note:** Please use this repository just as a reference. Copying the code may result in a violation of academic integrity and I won't take any responsiblity. <file_sep>var helpers = require( './helpers' ); var part = require( './csce322hmwrk02prt03' ); const diffDefault = require('jest-diff').default; for(var numTest=1; numTest<=10; numTest++){ var test_ = numTest.toString().padStart(2,0) console.log(`Test Case: ${test_}`) var puzzle = helpers.readPuzzleFile( `test/part03test${test_}.puzzle.bpf` ); var moves = helpers.readMovesFile( `test/part03test${test_}.moves.bpf` ); var solution = helpers.readSolutionFile(`test/part03test${test_}.solution`); var theFunction = part.puzzleSolvable( puzzle ); var after = theFunction(); console.log(diffDefault(solution.replace('\n', ''), after.toString())) } <file_sep>module.exports = { manyMoves: manyMoves } function swap(from, to, puzzle){ try{ if(to[0] > -1 && to[1] > -1 && puzzle[to[0]][to[1]]){ var temp = puzzle[to[0]][to[1]] puzzle[to[0]][to[1]] = puzzle[from[0]][from[1]] puzzle[from[0]][from[1]] = temp } }catch(err){ return puzzle } return puzzle; } function find_zero(puzzle){ for(var i=0; i<puzzle.length; i++){ for(var j=0; j<puzzle[0].length; j++){ if(puzzle[i][j] == 0) return [i, j]; } } } function manyMoves(puzzle){ function whatever(directions){ directions.forEach(direction => { var zero_idxs = find_zero(puzzle); switch(direction){ case 'r': puzzle = swap(zero_idxs, [zero_idxs[0], zero_idxs[1]-1], puzzle) break; case 'l': puzzle = swap(zero_idxs, [zero_idxs[0], zero_idxs[1]+1], puzzle) break; case 'u': puzzle = swap(zero_idxs, [zero_idxs[0]+1, zero_idxs[1]], puzzle) break; case 'd': puzzle = swap(zero_idxs, [zero_idxs[0]-1, zero_idxs[1]], puzzle) break; } }); return puzzle; } return whatever; }<file_sep>// Generated from /Users/rahulprajapati/Google Drive/CSCE Courses/CSCE 322/Homework/1/startercode/part2/csce322hmwrk01prt02.g4 by ANTLR 4.8 import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class csce322hmwrk01prt02Lexer extends Lexer { static { RuntimeMetaData.checkVersion("4.8", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int SECTION_BEGIN=1, SECTION_END=2, SECTION_TYPE=3, VALUE_ASSIGNMENT=4, VALUE_SEPERATOR=5, PUZZLE_VALUE=6, MOVES=7, ROW_SEPERATOR=8, BOARD_BEGIN=9, BOARD_END=10, LIST_BEGIN=11, LIST_END=12, WS=13, ERROR=14; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; private static String[] makeRuleNames() { return new String[] { "SECTION_BEGIN", "SECTION_END", "SECTION_TYPE", "VALUE_ASSIGNMENT", "VALUE_SEPERATOR", "PUZZLE_VALUE", "MOVES", "ROW_SEPERATOR", "BOARD_BEGIN", "BOARD_END", "LIST_BEGIN", "LIST_END", "WS", "ERROR" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'<<alpha'", "'omega>>'", null, "'='", "'&'", null, null, "'$'", "'{'", "'}'", "'['", "']'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "SECTION_BEGIN", "SECTION_END", "SECTION_TYPE", "VALUE_ASSIGNMENT", "VALUE_SEPERATOR", "PUZZLE_VALUE", "MOVES", "ROW_SEPERATOR", "BOARD_BEGIN", "BOARD_END", "LIST_BEGIN", "LIST_END", "WS", "ERROR" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public csce322hmwrk01prt02Lexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "csce322hmwrk01prt02.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\20^\b\1\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3"+ "\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\5\4;\n\4\3\5\3\5\3\6\3\6\3\7\6\7B\n\7\r\7\16\7C\3\7\3\7\5\7H"+ "\n\7\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\r\3\r\3\16\6\16W\n\16"+ "\r\16\16\16X\3\16\3\16\3\17\3\17\2\2\20\3\3\5\4\7\5\t\6\13\7\r\b\17\t"+ "\21\n\23\13\25\f\27\r\31\16\33\17\35\20\3\2\5\3\2\62;\6\2ffnnttww\5\2"+ "\13\f\17\17\"\"\2a\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13"+ "\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2"+ "\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\3\37\3\2\2\2\5"+ "\'\3\2\2\2\7:\3\2\2\2\t<\3\2\2\2\13>\3\2\2\2\rG\3\2\2\2\17I\3\2\2\2\21"+ "K\3\2\2\2\23M\3\2\2\2\25O\3\2\2\2\27Q\3\2\2\2\31S\3\2\2\2\33V\3\2\2\2"+ "\35\\\3\2\2\2\37 \7>\2\2 !\7>\2\2!\"\7c\2\2\"#\7n\2\2#$\7r\2\2$%\7j\2"+ "\2%&\7c\2\2&\4\3\2\2\2\'(\7q\2\2()\7o\2\2)*\7g\2\2*+\7i\2\2+,\7c\2\2,"+ "-\7@\2\2-.\7@\2\2.\6\3\2\2\2/\60\7O\2\2\60\61\7q\2\2\61\62\7x\2\2\62\63"+ "\7g\2\2\63;\7u\2\2\64\65\7R\2\2\65\66\7w\2\2\66\67\7|\2\2\678\7|\2\28"+ "9\7n\2\29;\7g\2\2:/\3\2\2\2:\64\3\2\2\2;\b\3\2\2\2<=\7?\2\2=\n\3\2\2\2"+ ">?\7(\2\2?\f\3\2\2\2@B\t\2\2\2A@\3\2\2\2BC\3\2\2\2CA\3\2\2\2CD\3\2\2\2"+ "DH\3\2\2\2EF\7/\2\2FH\7\63\2\2GA\3\2\2\2GE\3\2\2\2H\16\3\2\2\2IJ\t\3\2"+ "\2J\20\3\2\2\2KL\7&\2\2L\22\3\2\2\2MN\7}\2\2N\24\3\2\2\2OP\7\177\2\2P"+ "\26\3\2\2\2QR\7]\2\2R\30\3\2\2\2ST\7_\2\2T\32\3\2\2\2UW\t\4\2\2VU\3\2"+ "\2\2WX\3\2\2\2XV\3\2\2\2XY\3\2\2\2YZ\3\2\2\2Z[\b\16\2\2[\34\3\2\2\2\\"+ "]\13\2\2\2]\36\3\2\2\2\7\2:CGX\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }<file_sep>var helpers = require( './helpers' ); var part = require( './csce322hmwrk02prt01' ); const diffDefault = require('jest-diff').default; var total_test = 30 for (var test=1; test <= total_test; test++){ var test_ = test.toString().padStart(2,0) console.log(`Testing: ${test_}`) var puzzle = helpers.readPuzzleFile( `test/part01test${test_}.puzzle.bpf` ); var moves = helpers.readMovesFile( `test/part01test${test_}.moves.bpf` ); var solution = helpers.readSolutionFile(`test/part01test${test_}.solution`); var theFunction = part.oneMove( puzzle ); var output = moves[0] + '\n' // console.log( moves[0] ); var after = theFunction( moves[0] ); function build_output(line){ output += '[' for(var i=0; i<line.length; i++){ if(i == line.length-1) output += ` '${line[i]}' ]\n`; else output += ` '${line[i]}',`; } } for( var i = 0; i < after.length; i++ ){ // console.log( after[i] ); build_output(after[i]) } console.log(diffDefault(solution, output)) } <file_sep>// Generated from /Users/rahulprajapati/Google Drive/CSCE Courses/CSCE 322/Homework/1/startercode/part1/csce322hmwrk01prt01.g4 by ANTLR 4.8 import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class csce322hmwrk01prt01Parser extends Parser { static { RuntimeMetaData.checkVersion("4.8", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int SECTION_BEGIN=1, SECTION_END=2, SECTION_TYPE=3, VALUE_ASSIGNMENT=4, VALUE_SEPERATOR=5, NUMERICAL=6, MOVES=7, ROW_SEPERATOR=8, BOARD_BEGIN=9, BOARD_END=10, LIST_BEGIN=11, LIST_END=12, WS=13; public static final int RULE_boss = 0, RULE_moves = 1, RULE_move_symbol = 2, RULE_puzzles = 3, RULE_puzzle_symbol = 4, RULE_eof = 5; private static String[] makeRuleNames() { return new String[] { "boss", "moves", "move_symbol", "puzzles", "puzzle_symbol", "eof" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'<<alpha'", "'omega>>'", null, "'='", "'&'", null, null, "'$'", "'{'", "'}'", "'['", "']'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "SECTION_BEGIN", "SECTION_END", "SECTION_TYPE", "VALUE_ASSIGNMENT", "VALUE_SEPERATOR", "NUMERICAL", "MOVES", "ROW_SEPERATOR", "BOARD_BEGIN", "BOARD_END", "LIST_BEGIN", "LIST_END", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "csce322hmwrk01prt01.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public csce322hmwrk01prt01Parser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class BossContext extends ParserRuleContext { public EofContext eof() { return getRuleContext(EofContext.class,0); } public List<PuzzlesContext> puzzles() { return getRuleContexts(PuzzlesContext.class); } public PuzzlesContext puzzles(int i) { return getRuleContext(PuzzlesContext.class,i); } public List<MovesContext> moves() { return getRuleContexts(MovesContext.class); } public MovesContext moves(int i) { return getRuleContext(MovesContext.class,i); } public BossContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_boss; } } public final BossContext boss() throws RecognitionException { BossContext _localctx = new BossContext(_ctx, getState()); enterRule(_localctx, 0, RULE_boss); int _la; try { int _alt; setState(37); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { { setState(13); _errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { setState(12); puzzles(); } } break; default: throw new NoViableAltException(this); } setState(15); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,0,_ctx); } while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ); setState(18); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(17); moves(); } } setState(20); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << SECTION_BEGIN) | (1L << SECTION_END) | (1L << SECTION_TYPE) | (1L << VALUE_ASSIGNMENT) | (1L << VALUE_SEPERATOR) | (1L << MOVES) | (1L << LIST_BEGIN) | (1L << LIST_END))) != 0) ); setState(22); eof(); } } break; case 2: enterOuterAlt(_localctx, 2); { { setState(25); _errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { setState(24); moves(); } } break; default: throw new NoViableAltException(this); } setState(27); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,2,_ctx); } while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ); setState(30); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(29); puzzles(); } } setState(32); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << SECTION_BEGIN) | (1L << SECTION_END) | (1L << SECTION_TYPE) | (1L << VALUE_ASSIGNMENT) | (1L << VALUE_SEPERATOR) | (1L << NUMERICAL) | (1L << ROW_SEPERATOR) | (1L << BOARD_BEGIN) | (1L << BOARD_END))) != 0) ); setState(34); eof(); } } break; case 3: enterOuterAlt(_localctx, 3); { setState(36); eof(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class MovesContext extends ParserRuleContext { public Token SECTION_BEGIN; public Token SECTION_TYPE; public Token VALUE_ASSIGNMENT; public Token SECTION_END; public TerminalNode SECTION_BEGIN() { return getToken(csce322hmwrk01prt01Parser.SECTION_BEGIN, 0); } public TerminalNode SECTION_TYPE() { return getToken(csce322hmwrk01prt01Parser.SECTION_TYPE, 0); } public TerminalNode VALUE_ASSIGNMENT() { return getToken(csce322hmwrk01prt01Parser.VALUE_ASSIGNMENT, 0); } public TerminalNode LIST_BEGIN() { return getToken(csce322hmwrk01prt01Parser.LIST_BEGIN, 0); } public Move_symbolContext move_symbol() { return getRuleContext(Move_symbolContext.class,0); } public TerminalNode LIST_END() { return getToken(csce322hmwrk01prt01Parser.LIST_END, 0); } public TerminalNode SECTION_END() { return getToken(csce322hmwrk01prt01Parser.SECTION_END, 0); } public MovesContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_moves; } } public final MovesContext moves() throws RecognitionException { MovesContext _localctx = new MovesContext(_ctx, getState()); enterRule(_localctx, 2, RULE_moves); try { setState(50); _errHandler.sync(this); switch (_input.LA(1)) { case SECTION_BEGIN: enterOuterAlt(_localctx, 1); { setState(39); ((MovesContext)_localctx).SECTION_BEGIN = match(SECTION_BEGIN); System.out.println("Start Section: " + (((MovesContext)_localctx).SECTION_BEGIN!=null?((MovesContext)_localctx).SECTION_BEGIN.getText():null)); } break; case SECTION_TYPE: enterOuterAlt(_localctx, 2); { setState(41); ((MovesContext)_localctx).SECTION_TYPE = match(SECTION_TYPE); System.out.println("Section: " + (((MovesContext)_localctx).SECTION_TYPE!=null?((MovesContext)_localctx).SECTION_TYPE.getText():null)); } break; case VALUE_ASSIGNMENT: enterOuterAlt(_localctx, 3); { setState(43); ((MovesContext)_localctx).VALUE_ASSIGNMENT = match(VALUE_ASSIGNMENT); System.out.println("Assignment: " + (((MovesContext)_localctx).VALUE_ASSIGNMENT!=null?((MovesContext)_localctx).VALUE_ASSIGNMENT.getText():null)); } break; case LIST_BEGIN: enterOuterAlt(_localctx, 4); { setState(45); match(LIST_BEGIN); } break; case VALUE_SEPERATOR: case MOVES: enterOuterAlt(_localctx, 5); { setState(46); move_symbol(); } break; case LIST_END: enterOuterAlt(_localctx, 6); { setState(47); match(LIST_END); } break; case SECTION_END: enterOuterAlt(_localctx, 7); { setState(48); ((MovesContext)_localctx).SECTION_END = match(SECTION_END); System.out.println("End Section: " + (((MovesContext)_localctx).SECTION_END!=null?((MovesContext)_localctx).SECTION_END.getText():null)); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Move_symbolContext extends ParserRuleContext { public Token MOVES; public TerminalNode MOVES() { return getToken(csce322hmwrk01prt01Parser.MOVES, 0); } public TerminalNode VALUE_SEPERATOR() { return getToken(csce322hmwrk01prt01Parser.VALUE_SEPERATOR, 0); } public Move_symbolContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_move_symbol; } } public final Move_symbolContext move_symbol() throws RecognitionException { Move_symbolContext _localctx = new Move_symbolContext(_ctx, getState()); enterRule(_localctx, 4, RULE_move_symbol); try { enterOuterAlt(_localctx, 1); { setState(55); _errHandler.sync(this); switch (_input.LA(1)) { case MOVES: { setState(52); ((Move_symbolContext)_localctx).MOVES = match(MOVES); System.out.println("Move: " + (((Move_symbolContext)_localctx).MOVES!=null?((Move_symbolContext)_localctx).MOVES.getText():null)); } break; case VALUE_SEPERATOR: { setState(54); match(VALUE_SEPERATOR); } break; default: throw new NoViableAltException(this); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class PuzzlesContext extends ParserRuleContext { public Token SECTION_BEGIN; public Token SECTION_TYPE; public Token VALUE_ASSIGNMENT; public Token BOARD_BEGIN; public Token BOARD_END; public Token SECTION_END; public TerminalNode SECTION_BEGIN() { return getToken(csce322hmwrk01prt01Parser.SECTION_BEGIN, 0); } public TerminalNode SECTION_TYPE() { return getToken(csce322hmwrk01prt01Parser.SECTION_TYPE, 0); } public TerminalNode VALUE_ASSIGNMENT() { return getToken(csce322hmwrk01prt01Parser.VALUE_ASSIGNMENT, 0); } public TerminalNode BOARD_BEGIN() { return getToken(csce322hmwrk01prt01Parser.BOARD_BEGIN, 0); } public Puzzle_symbolContext puzzle_symbol() { return getRuleContext(Puzzle_symbolContext.class,0); } public TerminalNode BOARD_END() { return getToken(csce322hmwrk01prt01Parser.BOARD_END, 0); } public TerminalNode SECTION_END() { return getToken(csce322hmwrk01prt01Parser.SECTION_END, 0); } public PuzzlesContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_puzzles; } } public final PuzzlesContext puzzles() throws RecognitionException { PuzzlesContext _localctx = new PuzzlesContext(_ctx, getState()); enterRule(_localctx, 6, RULE_puzzles); try { setState(70); _errHandler.sync(this); switch (_input.LA(1)) { case SECTION_BEGIN: enterOuterAlt(_localctx, 1); { setState(57); ((PuzzlesContext)_localctx).SECTION_BEGIN = match(SECTION_BEGIN); System.out.println("Start Section: " + (((PuzzlesContext)_localctx).SECTION_BEGIN!=null?((PuzzlesContext)_localctx).SECTION_BEGIN.getText():null)); } break; case SECTION_TYPE: enterOuterAlt(_localctx, 2); { setState(59); ((PuzzlesContext)_localctx).SECTION_TYPE = match(SECTION_TYPE); System.out.println("Section: " + (((PuzzlesContext)_localctx).SECTION_TYPE!=null?((PuzzlesContext)_localctx).SECTION_TYPE.getText():null)); } break; case VALUE_ASSIGNMENT: enterOuterAlt(_localctx, 3); { setState(61); ((PuzzlesContext)_localctx).VALUE_ASSIGNMENT = match(VALUE_ASSIGNMENT); System.out.println("Assignment: " + (((PuzzlesContext)_localctx).VALUE_ASSIGNMENT!=null?((PuzzlesContext)_localctx).VALUE_ASSIGNMENT.getText():null)); } break; case BOARD_BEGIN: enterOuterAlt(_localctx, 4); { setState(63); ((PuzzlesContext)_localctx).BOARD_BEGIN = match(BOARD_BEGIN); System.out.println("Start Puzzle: " + (((PuzzlesContext)_localctx).BOARD_BEGIN!=null?((PuzzlesContext)_localctx).BOARD_BEGIN.getText():null)); } break; case VALUE_SEPERATOR: case NUMERICAL: case ROW_SEPERATOR: enterOuterAlt(_localctx, 5); { setState(65); puzzle_symbol(); } break; case BOARD_END: enterOuterAlt(_localctx, 6); { setState(66); ((PuzzlesContext)_localctx).BOARD_END = match(BOARD_END); System.out.println("End Puzzle: " + (((PuzzlesContext)_localctx).BOARD_END!=null?((PuzzlesContext)_localctx).BOARD_END.getText():null)); } break; case SECTION_END: enterOuterAlt(_localctx, 7); { setState(68); ((PuzzlesContext)_localctx).SECTION_END = match(SECTION_END); System.out.println("End Section: " + (((PuzzlesContext)_localctx).SECTION_END!=null?((PuzzlesContext)_localctx).SECTION_END.getText():null)); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Puzzle_symbolContext extends ParserRuleContext { public Token NUMERICAL; public Token ROW_SEPERATOR; public TerminalNode NUMERICAL() { return getToken(csce322hmwrk01prt01Parser.NUMERICAL, 0); } public TerminalNode VALUE_SEPERATOR() { return getToken(csce322hmwrk01prt01Parser.VALUE_SEPERATOR, 0); } public TerminalNode ROW_SEPERATOR() { return getToken(csce322hmwrk01prt01Parser.ROW_SEPERATOR, 0); } public Puzzle_symbolContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_puzzle_symbol; } } public final Puzzle_symbolContext puzzle_symbol() throws RecognitionException { Puzzle_symbolContext _localctx = new Puzzle_symbolContext(_ctx, getState()); enterRule(_localctx, 8, RULE_puzzle_symbol); try { enterOuterAlt(_localctx, 1); { setState(77); _errHandler.sync(this); switch (_input.LA(1)) { case NUMERICAL: { setState(72); ((Puzzle_symbolContext)_localctx).NUMERICAL = match(NUMERICAL); System.out.println("Tile: " + (((Puzzle_symbolContext)_localctx).NUMERICAL!=null?((Puzzle_symbolContext)_localctx).NUMERICAL.getText():null)); } break; case VALUE_SEPERATOR: { setState(74); match(VALUE_SEPERATOR); } break; case ROW_SEPERATOR: { setState(75); ((Puzzle_symbolContext)_localctx).ROW_SEPERATOR = match(ROW_SEPERATOR); System.out.println("End Row: " + (((Puzzle_symbolContext)_localctx).ROW_SEPERATOR!=null?((Puzzle_symbolContext)_localctx).ROW_SEPERATOR.getText():null)); } break; default: throw new NoViableAltException(this); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class EofContext extends ParserRuleContext { public TerminalNode EOF() { return getToken(csce322hmwrk01prt01Parser.EOF, 0); } public EofContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_eof; } } public final EofContext eof() throws RecognitionException { EofContext _localctx = new EofContext(_ctx, getState()); enterRule(_localctx, 10, RULE_eof); try { enterOuterAlt(_localctx, 1); { setState(79); match(EOF); System.out.println("End of File"); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\17U\4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\3\2\6\2\20\n\2\r\2\16\2\21\3\2\6\2"+ "\25\n\2\r\2\16\2\26\3\2\3\2\3\2\6\2\34\n\2\r\2\16\2\35\3\2\6\2!\n\2\r"+ "\2\16\2\"\3\2\3\2\3\2\5\2(\n\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\5\3\65\n\3\3\4\3\4\3\4\5\4:\n\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3"+ "\5\3\5\3\5\3\5\3\5\5\5I\n\5\3\6\3\6\3\6\3\6\3\6\5\6P\n\6\3\7\3\7\3\7\3"+ "\7\2\2\b\2\4\6\b\n\f\2\2\2c\2\'\3\2\2\2\4\64\3\2\2\2\69\3\2\2\2\bH\3\2"+ "\2\2\nO\3\2\2\2\fQ\3\2\2\2\16\20\5\b\5\2\17\16\3\2\2\2\20\21\3\2\2\2\21"+ "\17\3\2\2\2\21\22\3\2\2\2\22\24\3\2\2\2\23\25\5\4\3\2\24\23\3\2\2\2\25"+ "\26\3\2\2\2\26\24\3\2\2\2\26\27\3\2\2\2\27\30\3\2\2\2\30\31\5\f\7\2\31"+ "(\3\2\2\2\32\34\5\4\3\2\33\32\3\2\2\2\34\35\3\2\2\2\35\33\3\2\2\2\35\36"+ "\3\2\2\2\36 \3\2\2\2\37!\5\b\5\2 \37\3\2\2\2!\"\3\2\2\2\" \3\2\2\2\"#"+ "\3\2\2\2#$\3\2\2\2$%\5\f\7\2%(\3\2\2\2&(\5\f\7\2\'\17\3\2\2\2\'\33\3\2"+ "\2\2\'&\3\2\2\2(\3\3\2\2\2)*\7\3\2\2*\65\b\3\1\2+,\7\5\2\2,\65\b\3\1\2"+ "-.\7\6\2\2.\65\b\3\1\2/\65\7\r\2\2\60\65\5\6\4\2\61\65\7\16\2\2\62\63"+ "\7\4\2\2\63\65\b\3\1\2\64)\3\2\2\2\64+\3\2\2\2\64-\3\2\2\2\64/\3\2\2\2"+ "\64\60\3\2\2\2\64\61\3\2\2\2\64\62\3\2\2\2\65\5\3\2\2\2\66\67\7\t\2\2"+ "\67:\b\4\1\28:\7\7\2\29\66\3\2\2\298\3\2\2\2:\7\3\2\2\2;<\7\3\2\2<I\b"+ "\5\1\2=>\7\5\2\2>I\b\5\1\2?@\7\6\2\2@I\b\5\1\2AB\7\13\2\2BI\b\5\1\2CI"+ "\5\n\6\2DE\7\f\2\2EI\b\5\1\2FG\7\4\2\2GI\b\5\1\2H;\3\2\2\2H=\3\2\2\2H"+ "?\3\2\2\2HA\3\2\2\2HC\3\2\2\2HD\3\2\2\2HF\3\2\2\2I\t\3\2\2\2JK\7\b\2\2"+ "KP\b\6\1\2LP\7\7\2\2MN\7\n\2\2NP\b\6\1\2OJ\3\2\2\2OL\3\2\2\2OM\3\2\2\2"+ "P\13\3\2\2\2QR\7\2\2\3RS\b\7\1\2S\r\3\2\2\2\13\21\26\35\"\'\649HO"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
d724347cd823a35c16769708aa4a7c355ef6a498
[ "Markdown", "Java", "JavaScript" ]
7
Java
LordVoldemort28/multilanguage-boss-puzzle
e6b029dfd6bb6283e95436beb4c0c979a8781c74
7f5b37ad7fcbf412fc0bead1a3497f5727c9b51b
refs/heads/main
<file_sep>import mysql.connector #aller sur http://www.maxifoot.fr/calendrier-ligue-1-france.htm date = str(input("Entrez une date (ex: 01/01/2021): ")) con = mysql.connector.connect(host='127.0.0.1', database='programme', user='root', password='') cursor = con.cursor() cursor.execute(""" SELECT * FROM match_de_foot """) #on fait une requête qui va sélectionner la table match_de_foot match = cursor.fetchall() #variable match qui prend les résultats de la requête, càd la table match_de_foot for i in match: #pour i un element dans match if i[0]==date: #si les matchs d'une ligne correspondent à la date entrée print(i) #affiche la ligne, et donc cette ligne contiendra les matchs else: print("Soit ces match ne correspondent pas à votre date entrée ou soit il n'y a pas de match ce jour-là")<file_sep>import mysql.connector date = str(input("Entrez une date (ex: 01/01/2021): ")) con = mysql.connector.connect(host='127.0.0.1', database='programme', user='root', password='') cursor = con.cursor() cursor.execute(""" SELECT * FROM match_de_foot WHERE date = date """) match = cursor.fetchall() for i in match: #pour i un element dans match if i[0]==date: #si la ligne des match correspond à la date entrée print(i) #il va afficher la ligne des matchs qu'il y aura à la date entrée
efd2e012f8318dc84051ff52e9769e21259682bb
[ "Python" ]
2
Python
sidy92/Projet
5f0410adf980339cf92331a76e4c2e790445a615
3b0c14352e5887ab8f09cdf19efd41784675932d
refs/heads/master
<repo_name>wtk34500000/spring-annotation-demo<file_sep>/src/data.properties Today is a nice day Today is a bad day Today is a worse day Today is a wonderful day today is a awesome day <file_sep>/src/sport.properties foo.email=<EMAIL> foo.team=nyc team<file_sep>/src/com/springdemo/WeeklyFortuneService.java package com.springdemo; public class WeeklyFortuneService implements FortuneService { @Override public String getFortune() { return "You are so happy this week!"; } } <file_sep>/src/com/springdemo/PingpongCoach.java package com.springdemo; public class PingpongCoach implements Coach { private FortuneService fortuneService; public PingpongCoach(FortuneService theFortuneService) { this.fortuneService=theFortuneService; } @Override public String getDailyWorkout() { return "swing you paddle 1000 times!"; } @Override public String getDailyFortune() { // TODO Auto-generated method stub return fortuneService.getFortune(); } }
c6756bdae8376654d9e3fa72b56462bda4540bea
[ "Java", "INI" ]
4
INI
wtk34500000/spring-annotation-demo
af9a161fe773a41464870ab70de7cc6dbb3778e4
1e0736333a5cb1d63b649b7aed8cb80a46114920
refs/heads/master
<repo_name>garyyeap/easy-fullscreen<file_sep>/README.md # easy-fullscreen: Fullscreen API wrapper ### API and Usage ```javascript import Fullscreen from 'easy-fullscreen'; var fullscreenElement = doucument.getElementById('fullscreen-container'); var fullscreenButton = document.getElementById('button'); // check if fullscreen enabled if (Fullscreen.isEnabled) { fullscreenButton.onclick = function () { // check if is in fullscreen mode if (Fullscreen.isFullscreen) { // exit fullscreen Fullscreen.exit(); } else { // request to enter fullscreen Fullscreen.request(fullscreenElement); } }; } var onChangeHandler = function () { if (Fullscreen.isFullscreen) { console.log('Entered fullscreen'); } else { console.log('Exited fullscreen'); } }; // subscribe to fullscreen change event Fullscreen.on('change', onChangeHandler); // unsubscribe from fullscreen change event Fullscreen.off('change', onChangeHandler); var onErrorHandler = function (e) { console.log(e); }; // subscribe to fullscreen error event Fullscreen.on('error', onErrorHandler); // unsubscribe from fullscreen error event Fullscreen.off('error', onErrorHandler); ``` <file_sep>/Fullscreen.d.ts interface Fullscreen { isEnabled: boolean; isFullscreen: boolean; on (eventType: string, callback: Function): void; off (eventType: string, callback: Function): void; exit (): void; request (element: HTMLElement): void; } declare var Fullscreen: Fullscreen; export = Fullscreen;
0ac4e70b540d7b13fcac15b9c2db01f045d10056
[ "Markdown", "TypeScript" ]
2
Markdown
garyyeap/easy-fullscreen
989c632a32b0af3989f1ea82c343d28df7d564d0
e6d4984aac378eea641275c00facd14f8af837cf
refs/heads/master
<file_sep>\name{RNentropy-package} \alias{RNentropy-package} \docType{package} \title{ \packageTitle{RNentropy} } \description{ \packageDescription{RNentropy} } \author{ \packageAuthor{RNentropy} Maintainer: \packageMaintainer{RNentropy} } \references{doi = {10.1093/nar/gky055} doi = {10.1007/978-1-0716-1307-8_6} } \keyword{ package } \examples{ #load expression values and experiment design data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN). Results <- RN_calc(RN_Brain_Example_tpm[1:10000,], RN_Brain_Example_design) #select only genes with significant changes of expression Results <- RN_select(Results) #Compute the Point Mutual information Matrix Results <- RN_pmi(Results) #load expression values and experiment design data("RN_BarresLab_FPKM", "RN_BarresLab_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN) Results_B <- RN_calc(RN_BarresLab_FPKM[1:10000,], RN_BarresLab_design) #select only genes with significant changes of expression Results_B <- RN_select(Results_B) #Compute the Point Mutual information matrix Results_B <- RN_pmi(Results_B) } <file_sep> <!-- README.md is generated from README.Rmd. Please edit that file --> # RNentropy <!-- badges: start --> <!-- badges: end --> This is the implementation of a method based on information theory devised for the identification of genes showing a significant variation of expression across multiple conditions. Given expression estimates from any number of RNA-Seq samples and conditions it identifies genes or transcripts with a significant variation of expression across all the conditions studied, together with the samples in which they are over- or under-expressed. [Z<NAME>. et al. (2018)](https://doi.org/10.1093/nar/gky055). A detailed walk-through on how to use RNentropy is available at [<NAME>., <NAME>. (2021)](https://doi.org/10.1007/978-1-0716-1307-8_6) ## Installation You can install the development version of RNentropy like so: ``` r install.packages("RNentropy") ``` ## Example This is a basic example showing how to use RNentropy. Please see [<NAME>., <NAME>. (2021)](https://doi.org/10.1007/978-1-0716-1307-8_6) for more info. ``` r library(RNentropy) # basic example code ##load expression values and experiment design data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #Run RNentropy Results <- RN_calc(RN_Brain_Example_tpm, RN_Brain_Example_design) #select only genes with significant changes of expression Results <- RN_select(Results) #Compute the Point Mutual information Matrix Results <- RN_pmi(Results) ``` <file_sep>\name{RN_calc} \alias{RN_calc} %- Also NEED an '\alias' for EACH other topic documented here. \title{ %% ~~function to do ... ~~ RN_calc } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ Computes both global and local p-values, and returns the results in a list containing for each gene the original expression values and the associated global and local p-values (as -log10(p-value)). } \usage{ RN_calc(X, design) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ %% ~~Describe \code{X} here~~ data.frame with expression values. It may contain additional non numeric columns (eg. a column with gene names). } \item{design}{ %% ~~Describe \code{design} here~~ The RxC design matrix where R (rows) corresponds to the number of numeric columns (samples) in 'file' and C (columns) to the number of conditions. It must be a binary matrix with one and only one '1' for every row, corresponding to the condition (column) for which the sample corresponding to the row has to be considered a biological ot technical replicate. See the example 'RN_Brain_Example_design' for the design matrix of 'RN_Brain_Example_tpm' which has three replicates for three conditions (three rows) for a total of nine samples (nine rows). design defaults to a square matrix of independent samples (diagonal = 1, everything else = 0) } } \value{ %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... \item{gpv}{-log10 of the global p-values} \item{lpv}{-log10 of the local p-values} \item{c_like}{results formatted as in the output of the C++ implementation of RNentropy.} \item{res}{The results data.frame with the original expression values and the associated -log10 of global and local p-values.} \item{design}{the experimental design matrix} } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } %% ~Make other sections like Warning with \section{Warning }{....} ~ \examples{ data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN) Results <- RN_calc(RN_Brain_Example_tpm[1:10000,], RN_Brain_Example_design) ## The function is currently defined as function(X, design = NULL) { if(is.null(design)) { design <- .RN_default_design(sum(sapply(X, is.numeric))) } Results <- list(expr = X, design = design) GPV <- RN_calc_GPV(X, bind = FALSE) LPV <- RN_calc_LPV(X, design = design, bind = FALSE) TABLE = cbind(X,'---',GPV,'---',LPV) Results$gpv <- GPV Results$lpv <- LPV Results$c_like <- TABLE Results$res <- cbind(X, GPV, LPV) return(Results) } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") \keyword{ Run }% __ONLY ONE__ keyword per line <file_sep>\name{RN_select} \alias{RN_select} %- Also NEED an '\alias' for EACH other topic documented here. \title{ %% ~~function to do ... ~~ Select transcripts/genes with significant p-values. } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ Select transcripts with global p-value lower than an user defined threshold and provide a summary of over- or under-expression according to local p-values. } \usage{ RN_select(Results, gpv_t = 0.01, lpv_t = 0.01, method = "BH") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{Results}{ %% ~~Describe \code{Results} here~~ The output of RNentropy or RN_calc. } \item{gpv_t}{ %% ~~Describe \code{gpv_t} here~~ Threshold for global p-value. (Default: 0.01) } \item{lpv_t}{ %% ~~Describe \code{lpv_t} here~~ Threshold for local p-value. (Default: 0.01) } \item{method}{ %% ~~Describe \code{method} here~~ Multiple test correction method. Available methods are the ones of p.adjust. Type p.adjust.methods to see the list. Default: BH (Benjamini & Hochberg) } } \value{ The original input containing \item{gpv}{-log10 of the global p-values} \item{lpv}{-log10 of the local p-values} \item{c_like}{results formatted as in the output of the C++ implementation of RNentropy.} \item{res}{The results data.frame containing the original expression values together with the -log10 of global and local p-values.} \item{design}{The experimental design matrix.} and a new dataframe \item{selected}{Transcripts/genes with a corrected global p-value lower than gpv_t. For each condition it will contain a column where values can be -1,0,1 or NA. 1 means that all the replicates of this condition have expression value higher than the average and local p-value <= lpv_t (thus the corresponding gene will be over-expressed in this condition). -1 means that all the replicates of this condition have expression value lower than the average and local p-value <= lpv_t (thus the corresponding gene will be under-expressed in this condition). 0 means that at least one of the replicates has a local p-value > lpv_t. NA means that the local p-values of the replicates are not consistent for this condition, that is, at least one replicate results to be over-expressed and at least one results to be under-expressed.} %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } \examples{ data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN) Results <- RN_calc(RN_Brain_Example_tpm[1:10000,], RN_Brain_Example_design) Results <- RN_select(Results) ## The function is currently defined as function (Results, gpv_t = 0.01, lpv_t = 0.01, method = "BH") { lpv_t <- -log10(lpv_t) gpv_t <- -log10(gpv_t) Results$gpv_bh <- -log10(p.adjust(10^-Results$gpv, method = method)) true_rows <- (Results$gpv_bh >= gpv_t) design_b <- t(Results$design > 0) Results$lpv_sel <- data.frame(row.names = rownames(Results$lpv)[true_rows]) for (d in seq_along(design_b[, 1])) { col <- apply(Results$lpv[true_rows, ], 1, ".RN_select_lpv_row", design_b[d, ], lpv_t) Results$lpv_sel <- cbind(Results$lpv_sel, col) colnames(Results$lpv_sel)[length(Results$lpv_sel)] <- paste("condition", d, sep = "_") } lbl <- Results$res[, !sapply(Results$res, is.numeric)] Results$selected <- cbind(lbl[true_rows], Results$gpv[true_rows], Results$gpv_bh[true_rows], Results$lpv_sel) colnames(Results$selected) <- c(names(which(!sapply(Results$res, is.numeric))), "GL_LPV", "Corr. GL_LPV", colnames(Results$lpv_sel)) Results$selected <- Results$selected[order(Results$selected[,3], decreasing=TRUE),] Results$lpv_sel <- NULL return(Results) } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") \keyword{ Select }% __ONLY ONE__ keyword per line <file_sep>RN_pmi <- function(Results) { if(is.null(Results$selected)) Results <- RN_select(Results) Results$pmi <- matrix(nrow = ncol(Results$design), ncol = ncol(Results$design)) colnames(Results$pmi) <- colnames(Results$design) rownames(Results$pmi) <- colnames(Results$design) Results$npmi <- Results$pmi colshift <- ncol(Results$selected) - ncol(Results$design) for(x in 1:nrow(Results$pmi)) { for(y in 1:nrow(Results$pmi)) { if(x > y) { Results$pmi[x,y] <- Results$pmi[y,x] Results$npmi[x,y] <- Results$npmi[y,x] next } else { sum_x <- sum(Results$selected[,x+colshift] == 1, na.rm = TRUE) sum_y <- sum(Results$selected[,y+colshift] == 1, na.rm = TRUE) sum_xy <- sum(Results$selected[,x+colshift] == 1 & Results$selected[,y+colshift] == 1, na.rm = TRUE) freq_x <- sum_x / nrow(Results$selected) freq_y <- sum_y / nrow(Results$selected) freq_xy <- sum_xy / nrow(Results$selected) h_xy <- log2(1/freq_xy) Results$pmi[x,y] <- log2(freq_xy / (freq_x * freq_y)) Results$npmi[x,y] <- Results$pmi[x,y] / h_xy } } } return (Results) }<file_sep>RN_calc_LPV <- function(X, design = NULL, bind = TRUE) { if(is.null(design)) { design <- .RN_default_design(sum(sapply(X, is.numeric))) } rnums <- sapply(X, is.numeric) .RN_design_check(X, design, rnums) RL <- .RN_get_replicate_list(design) l1 <- rep("LOC_LPV", length(X[rnums])) l2 <- colnames(X[rnums]) PV <- apply(X[rnums], 1, '.RN_calc_LPV_row', RL = RL) PV <- t(PV) colnames(PV) <- paste(l1, l2, sep="_") if(bind) { return (cbind(X, PV)) } else return (PV) } <file_sep>\name{RN_calc_GPV} \alias{RN_calc_GPV} %- Also NEED an '\alias' for EACH other topic documented here. \title{ %% ~~function to do ... ~~ RN_calc_GPV } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ This function calculates global p-values from expression data, represented as -log10(p-values). } \usage{ RN_calc_GPV(X, bind = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ %% ~~Describe \code{X} here~~ data.frame with expression values. It may contain additional non numeric columns (eg. a column with gene names) } \item{bind}{ %% ~~Describe \code{bind} here~~ See Value (Default: TRUE) } } \value{ %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... If bind is TRUE the function returns a data.frame with the original expression values from 'X' and an attached column with the -log10() of the global p-value, otherwise only the numeric vector of -log10(p-values) is returned. } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } \examples{ data("RN_Brain_Example_tpm") GPV <- RN_calc_GPV(RN_Brain_Example_tpm) ## The function is currently defined as function (X, bind = TRUE) { rnums <- sapply(X, is.numeric) GL_LPV <- apply(X[rnums], 1, ".RN_calc_GPV_row") if (bind) { GPV <- cbind(X, GL_LPV) return(GPV) } else { return(GL_LPV) } } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") <file_sep>\name{RN_BarresLab_design} \alias{RN_BarresLab_design} \docType{data} \title{ %% ~~ data name/kind ... ~~ RN_BarresLab_design } \description{ %% ~~ A concise (1-5 lines) description of the dataset. ~~ The experiment design matrix for RN_BarresLab_design } \usage{data("RN_Brain_Example_design")} \format{ The format is: num[1:9,1:3] } \details{ %% ~~ If necessary, more details than the __description__ above ~~ A binary matrix where conditions correspond to columns and samples to rows. In this example there are seven conditions (cell types) and seven samples with the expression measured by mean FPKM. } \examples{ data(RN_Brain_Example_design) } \keyword{datasets} <file_sep>\name{RNentropy} \alias{RNentropy} %- Also NEED an '\alias' for EACH other topic documented here. \title{ RNentropy } \description{ This function runs RNentropy on a file containing normalized expression values. } \usage{ RNentropy(file, tr.col, design, header = TRUE, skip = 0, skip.col = NULL, col.names = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{file}{ %% ~~Describe \code{file} here~~ Expression data file. It must contain a column with univocal identifiers for each row (typically transcript or gene ids). } \item{tr.col}{ %% ~~Describe \code{tr.col} here~~ The column # (1 based) in the file containing the univocal identifiers (usually transcript or gene ids). } \item{design}{ %% ~~Describe \code{design} here~~ The RxC design matrix where R (rows) corresponds to the number of numeric columns (samples) in 'file' and C (columns) to the number of conditions. It must be a binary matrix with one and only one '1' for every row, corresponding to the condition (column) for which the sample corresponding to the row has to be considered a biological ot technical replicate. See the example 'RN_Brain_Example_design' for the design matrix of 'RN_Brain_Example_tpm' which has three replicates for three conditions (three rows) for a total of nine samples (nine rows). } \item{header}{ %% ~~Describe \code{header} here~~ Set this to FALSE if 'file' does not have an header row. If header is TRUE the read.table function used by RNentropy will try to assign names to each column using the header. Default = TRUE } \item{skip}{ %% ~~Describe \code{skip} here~~ Number of rows to skip at the beginning of 'file'. Rows beginning with a '#' token will be skipped even if skip is set to 0. } \item{skip.col}{ %% ~~Describe \code{skip.col} here~~ Columns that will not be imported from 'file' (1 based) and not included in the subsequent analysis. Useful if you have more than annotation column, e.g. gene name in the first, transcript ID in the second columns. } \item{col.names}{ %% ~~Describe \code{col.names} here~~ Assign names to the imported columns. The number of names must correspond to the columns effectively imported (thus, no name for the skipped ones). Also, tr.col is not considered an imported column. Useful to assign sample names to expression columns. } } \value{ Refer to the help for RN_calc. %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } \examples{ #load expression values and experiment design data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN) Results <- RN_calc(RN_Brain_Example_tpm[1:10000,], RN_Brain_Example_design) #select only genes with significant changes of expression Results <- RN_select(Results) ## The function is currently defined as function (file, tr.col, design, header = TRUE, skip = 0, skip.col = NULL, col.names = NULL) { TABLE <- read.table(file, row.names = tr.col, header = header, skip = skip, blank.lines.skip = TRUE, comment.char = "#") if (!is.null(skip.col)) { TABLE <- .RN_delete_col(TABLE, tr.col, skip.col) } if (!is.null(col.names)) { colnames(TABLE) <- col.names } return(RN_calc(TABLE, design)) } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") <file_sep>\name{RN_BarresLab_FPKM} \alias{RN_BarresLab_FPKM} \docType{data} \title{ %% ~~ data name/kind ... ~~ RN_BarresLab_FPKM } \description{ %% ~~ A concise (1-5 lines) description of the dataset. ~~ Data expression values (mean FPKM) for different cerebral cortex cell from Zhang et al: "An RNA-Seq transcriptome and splicing database of glia, neurons, and vascular cells of the cerebral cortex", J Neurosci 2014 Sep. RN_BarresLab_design is the corresponding design matrix. } \usage{data("RN_BarresLab_FPKM")} \format{ A data frame with 12978 observations on the following 7 variables. \describe{ \item{\code{Astrocyte}}{a numeric vector} \item{\code{Neuron}}{a numeric vector} \item{\code{OPC}}{a numeric vector} \item{\code{NFO }}{a numeric vector} \item{\code{MO}}{a numeric vector} \item{\code{Microglia}}{a numeric vector} \item{\code{Endothelial}}{a numeric vector} } } \source{ %% ~~ reference to a publication or URL from which the data were obtained ~~ <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. An RNA-sequencing transcriptome and splicing database of glia, neurons, and vascular cells of the cerebral cortex. J Neurosci. 2014 Sep 3;34(36):11929-47. doi: 10.1523/JNEUROSCI.1860-14.2014. Erratum in: J Neurosci. 2015 Jan 14;35(2):846-6. PubMed PMID: 25186741; PubMed Central PMCID: PMC4152602. Data were downloaded from https://web.stanford.edu/group/barres_lab/brain_rnaseq.html } \examples{ data(RN_BarresLab_FPKM) } \keyword{datasets} <file_sep>\name{RN_pmi} \alias{RN_pmi} %- Also NEED an '\alias' for EACH other topic documented here. \title{ %% ~~function to do ... ~~ Compute point mutual information matrix for the experimental conditions. } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ Compute point mutual information for experimental conditions from the overxexpressed genes identified by RN_select. } \usage{ RN_pmi(Results) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{Results}{ %% ~~Describe \code{Results} here~~ The output of RNentropy, RN_calc or RN_select. If RN_select has not already run on the results it will be invoked by RN_pmi using default arguments. } } \value{ The original input containing \item{gpv}{-log10 of the Global p-values} \item{lpv}{-log10 of the Local p-values} \item{c_like}{a table similar to the one you obtain running the C++ implementation of RNentropy.} \item{res}{The results data.frame containing the original expression values together with the -log10 of Global and Local p-values.} \item{design}{The experimental design matrix.} \item{selected}{Transcripts/genes with a corrected Global p-value lower than gpv_t. Each condition N gets a condition_N column which values can be -1,0,1 or NA. 1 means that all the replicates of this condition seems to be consistently over-expressed w.r.t the overall expression of the transcript in all the conditions (that is, all the replicates of condition N have a positive Local p-value <= lpv_t). -1 means that all the replicates of this condition seems to be consistently under-expressed w.r.t the overall expression of the transcript in all the conditions (that is, all the replicates of condition N have a negative Local p-value and abs(Local p-values) <= lpv_t). 0 means that one or more replicates have an abs(Local p-value) > lpv_t. NA means that the Local p-values of the replicates are not consistent for this condition.} And two new matrices: \item{pmi}{Point mutual information matrix of the conditions.} \item{npmi}{Normalized point mutual information matrix of the conditions.} %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } \examples{ data("RN_Brain_Example_tpm", "RN_Brain_Example_design") #compute statistics and p-values (considering only a subset of genes due to #examples running time limit of CRAN) Results <- RN_calc(RN_Brain_Example_tpm[1:10000,], RN_Brain_Example_design) Results <- RN_select(Results) Results <- RN_pmi(Results) ## The function is currently defined as RN_pmi <- function(Results) { if(is.null(Results$selected)) Results <- RN_select(Results) Results$pmi <- matrix(nrow = ncol(Results$design), ncol = ncol(Results$design)) colnames(Results$pmi) <- colnames(Results$design) rownames(Results$pmi) <- colnames(Results$design) Results$npmi <- Results$pmi colshift <- ncol(Results$selected) - ncol(Results$design) for(x in 1:nrow(Results$pmi)) { for(y in 1:nrow(Results$pmi)) { if(x > y) { Results$pmi[x,y] <- Results$pmi[y,x] Results$npmi[x,y] <- Results$npmi[y,x] next } else { sum_x <- sum(Results$selected[,x+colshift] == 1, na.rm = TRUE) sum_y <- sum(Results$selected[,y+colshift] == 1, na.rm = TRUE) sum_xy <- sum(Results$selected[,x+colshift] == 1 & Results$selected[,y+colshift] == 1, na.rm = TRUE) freq_x <- sum_x / nrow(Results$selected) freq_y <- sum_y / nrow(Results$selected) freq_xy <- sum_xy / nrow(Results$selected) h_xy <- log2(1/freq_xy) Results$pmi[x,y] <- log2(freq_xy / (freq_x * freq_y)) Results$npmi[x,y] <- Results$pmi[x,y] / h_xy } } } return (Results) } } \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") \keyword{ PMI }% __ONLY ONE__ keyword per line <file_sep>RN_calc_GPV <- function (X, bind=TRUE) { rnums <- sapply(X, is.numeric) GL_LPV <- apply(X[rnums], 1, '.RN_calc_GPV_row') if(bind) { GPV <- cbind(X, GL_LPV) return(GPV) } else { return(GL_LPV) } } <file_sep>RNentropy <- function(file, tr.col, design = NULL, header = TRUE, skip = 0, skip.col = NULL, col.names = NULL) { TABLE <- read.table(file, row.names = tr.col, header = header, skip = skip, blank.lines.skip = TRUE, comment.char = "#") if(!is.null(skip.col)) { TABLE <- .RN_delete_col(TABLE, tr.col, skip.col) } if(!is.null(col.names)) { colnames(TABLE) <- col.names } return (RN_calc(TABLE, design)) } <file_sep># RNentropy 1.2.3 - Fixed small bug in .RN_design_check preventing compatibility with R >=4.2.0 - Added reference to new publication - Removed unneeded initialization of .Random.seed - Fixed a few typos in the documentation - Added README.md, NEWS.md, and cran-comments.md files<file_sep>RN_select <- function(Results, gpv_t = 0.01, lpv_t = 0.01, method = "BH") { lpv_t <- -log10(lpv_t) gpv_t <- -log10(gpv_t) Results$gpv_bh <- -log10(p.adjust(10 ^ -Results$gpv, method=method)) true_rows <- (Results$gpv_bh >= gpv_t) design_b <- t(Results$design > 0) Results$lpv_sel <- data.frame(row.names = rownames(Results$lpv)[true_rows]) boh <- list() for(d in seq_along(design_b[,1])) { Results$lpv_sel <- cbind(Results$lpv_sel, apply(as.matrix(Results$lpv[true_rows,design_b[d,, drop = F]]), 1, ".RN_select_lpv_row", lpv_t)) } colnames(Results$lpv_sel) <- colnames(Results$design) lbl <- Results$res[,!sapply(Results$res, is.numeric), drop = FALSE] Results$selected <- cbind(lbl[true_rows,], Results$gpv[true_rows], Results$gpv_bh[true_rows], Results$lpv_sel) colnames(Results$selected) <- c(names(which(!sapply(Results$res, is.numeric))), "GL_LPV", "Corr. GL_LPV", colnames(Results$lpv_sel)) Results$selected <- Results$selected[order(Results$selected[,3], decreasing=TRUE),] Results$lpv_sel <- NULL return (Results) } <file_sep>\name{RN_calc_LPV} \alias{RN_calc_LPV} %- Also NEED an '\alias' for EACH other topic documented here. \title{ %% ~~function to do ... ~~ RN_calc_LPV } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ This function calculates local p-values from expression data, output as -log10(p-value). } \usage{ RN_calc_LPV(X, design, bind = TRUE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ %% ~~Describe \code{X} here~~ data.frame with expression values. It may contain additional non numeric columns (eg. a column with gene names) } \item{design}{ %% ~~Describe \code{design} here~~ The design matrix. Refer to the help for RN_calc for further info. } \item{bind}{ %% ~~Describe \code{bind} here~~ See Value (Default = TRUE) } } \value{ %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... If bind is TRUE the function returns a data.frame with the original expression values from data.frame X and attached columns with the -log10(p-values) computed for each sample, otherwise only the matrix of -log10(p-values) is returned. } \author{ %% ~~who you are~~ <NAME> - Dep. of Biosciences, University of Milan <NAME> - Dep. of Biosciences, University of Milan } \examples{ data("RN_Brain_Example_tpm", "RN_Brain_Example_design") LPV <- RN_calc_LPV(RN_Brain_Example_tpm, RN_Brain_Example_design) ## The function is currently defined as function(X, design = NULL, bind = TRUE) { if(is.null(design)) { design <- .RN_default_design(sum(sapply(X, is.numeric))) } rnums <- sapply(X, is.numeric) .RN_design_check(X, design, rnums) RL <- .RN_get_replicate_list(design) l1 <- rep("LOC_LPV", length(X[rnums])) l2 <- colnames(X[rnums]) PV <- apply(X[rnums], 1, '.RN_calc_LPV_row', RL = RL) PV <- t(PV) colnames(PV) <- paste(l1, l2, sep="_") if(bind) { return (cbind(X, PV)) } else return (PV) } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ RNentropy }% use one of RShowDoc("KEYWORDS") <file_sep>\name{RN_Brain_Example_tpm} \alias{RN_Brain_Example_tpm} \docType{data} \title{ %% ~~ data name/kind ... ~~ RN_Brain_Example_tpm } \description{ %% ~~ A concise (1-5 lines) description of the dataset. ~~ Example data expression values from brain of three different individuals, each with three replicates. RN_Brain_Example_design is the corresponding design matrix. } \usage{data("RN_Brain_Example_tpm")} \format{ A data frame with 78699 observations on the following 9 variables. \describe{ \item{\code{GENE}}{a factor vector} \item{\code{BRAIN_2_1}}{a numeric vector} \item{\code{BRAIN_2_2}}{a numeric vector} \item{\code{BRAIN_2_3}}{a numeric vector} \item{\code{BRAIN_3_1}}{a numeric vector} \item{\code{BRAIN_3_2}}{a numeric vector} \item{\code{BRAIN_3_3}}{a numeric vector} \item{\code{BRAIN_1_1}}{a numeric vector} \item{\code{BRAIN_1_2}}{a numeric vector} \item{\code{BRAIN_1_3}}{a numeric vector} } } \examples{ data(RN_Brain_Example_tpm) } \keyword{datasets} <file_sep>\name{RN_Brain_Example_design} \alias{RN_Brain_Example_design} \docType{data} \title{ %% ~~ data name/kind ... ~~ RN_Brain_Example_design } \description{ %% ~~ A concise (1-5 lines) description of the dataset. ~~ The example design matrix for RN_Brain_Example_tpm } \usage{data("RN_Brain_Example_design")} \format{ The format is: num[1:9,1:3] } \details{ %% ~~ If necessary, more details than the __description__ above ~~ A binary matrix where conditions correspond to the columns and samples to the rows. In this example there are three conditions (individuals) and nine samples, with three replicates for each condition. } \examples{ data(RN_Brain_Example_design) } \keyword{datasets} <file_sep>RN_calc <- function(X, design = NULL) { if(is.null(design)) { design <- .RN_default_design(sum(sapply(X, is.numeric))) } Results <- list(expr = X, design = design) GPV <- RN_calc_GPV(X, bind = FALSE) LPV <- RN_calc_LPV(X, design = design, bind = FALSE) TABLE = cbind(X,'---',GPV,'---',LPV) Results$gpv <- GPV Results$lpv <- LPV Results$c_like <- TABLE Results$res <- cbind(X, GPV, LPV) return(Results) }
3fc4ed6a6c1559e2359274520a4606d7298333d2
[ "Markdown", "R" ]
19
R
cran/RNentropy
8d0a617d24b64e139771e2f62873c0f7f51fa851
da02f9c70408d1a794566ce03b1a6ed5ed9e338d
refs/heads/master
<repo_name>nickolaevv/avito-properties<file_sep>/src/App.js import React, {Component} from 'react'; import PropertiesList from './components/PropertiesList'; import FullPropertyInfo from './components/FullPropertyInfo'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; class App extends Component { constructor(props){ super(props); this.state = { }; this.getPropertyId = this.getPropertyId.bind(this); } getPropertyId = (id) => { this.setState({ propertyId: id }) }; render() { return( <Router> <Switch> <Route exact path='/' component={(props) => <PropertiesList{...props} sendId = {this.getPropertyId}/>}/> <Route exact path={`/${this.state.propertyId}`} component={(props) => <FullPropertyInfo advertismentId = {this.state.propertyId}/>}/> </Switch> </Router> ) } } export default App; <file_sep>/src/components/FullPropertyInfo.js import React, {Component} from 'react'; import axios from 'axios'; import ImageView from './ImageView'; import SellerIcon from './icons/SellerIcon'; import LocationIcon from './icons/LocationIcon'; class FullPropertyInfo extends Component { constructor(props){ super(props); this.state = { listIsEmpty: true, } this.getFullPropertyInfo = this.getFullPropertyInfo.bind(this); this.getFullPropertyInfo(); } getFullPropertyInfo() { axios.get(`http://134.209.138.34/item/${this.props.advertismentId}`) .then((response) => { this.setState({ fullInfoList: response.data }) if (this.state.fullInfoList.length == 0) { this.setState({ listIsEmpty: true }) } else ( this.setState({ listIsEmpty: false }) ) }) } render() { return( <div> {this.state.listIsEmpty ? <div> No full data </div> : <div className = 'flexAlignCenter' style = {{height:'100vh'}}> <ImageView imageArray = {this.state.fullInfoList[0].images} imageId = {this.state.fullInfoList[0].id}/> <div className = 'full-advert-info'> <div style = {{fontSize:'20px', marginBottom:'15px',marginTop:'15px'}}><SellerIcon/> {this.state.fullInfoList[0].sellerName} </div> <div style = {{fontSize:'30px', marginBottom:'15px'}}> {this.state.fullInfoList[0].title} </div> <div style = {{fontSize:'20px', color:'#989898', marginBottom:'15px'}}><LocationIcon/> {this.state.fullInfoList[0].address} </div> <div style = {{fontSize:'20px', fontWeight:'bold',marginBottom:'15px'}}> {this.state.fullInfoList[0].price} </div> <div style = {{fontSize:'20px'}}> {this.state.fullInfoList[0].description} </div> </div> </div> } </div> ) } } export default FullPropertyInfo; <file_sep>/src/components/ImageView.js import React, {Component} from 'react'; import BackwardArrow from './icons/BackwardArrow'; import ForwardArrow from './icons/ForwardArrow'; class ImageView extends Component { constructor(props) { super(props); this.state = { selectedImage: 0 } this.selectImage = this.selectImage.bind(this); this.forwardImage = this.forwardImage.bind(this); this.backwardImage = this.backwardImage.bind(this); } selectImage = (index) => { this.setState({ selectImage: index }) } forwardImage = (event) => { var currentIndex = this.state.selectedImage; if (currentIndex < this.props.imageArray.length-1){ currentIndex++ } else { currentIndex = 0 } this.setState({ selectedImage: currentIndex }) } backwardImage = (event) => { var currentIndex = this.state.selectedImage; if (currentIndex > 0){ currentIndex-- } else { currentIndex = this.props.imageArray.length-1 } this.setState({ selectedImage: currentIndex }) } render() { return( <div className = 'flexRow'> <div className = 'flexRowAlignCenter'> <button className = 'image-handle-button' onClick = {this.backwardImage}><BackwardArrow/></button> <div align = 'center' style = {{width:'750px', height:'500px', display:'flex', alignItems:'center', justifyContent:'center'}}><img src = {this.props.imageArray[this.state.selectedImage]}/></div> <button className = 'image-handle-button' onClick = {this.forwardImage}><ForwardArrow/></button> </div> { this.props.imageArray.map((imageId,index) => ( <img className = 'image-preview' src = {imageId} alt = 'Не удалось загрузить изображение' onClick = {() => this.setState({ selectedImage: index})}/> )) } </div> ) } } export default ImageView; <file_sep>/src/components/icons/PropertyLogo.js import React, {Component} from 'react'; class PropertyLogo extends Component { render() { return( <svg width="20" height="26" viewBox="0 0 14 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M0 7C0 3.13 3.13 0 7 0C10.87 0 14 3.13 14 7C14 11.17 9.58 16.92 7.77 19.11C7.37 19.59 6.64 19.59 6.24 19.11C4.42 16.92 0 11.17 0 7ZM4.5 7C4.5 8.38 5.62 9.5 7 9.5C8.38 9.5 9.5 8.38 9.5 7C9.5 5.62 8.38 4.5 7 4.5C5.62 4.5 4.5 5.62 4.5 7Z" fill="#A975D0"/> </svg> ) } } export default PropertyLogo; <file_sep>/src/components/icons/ForwardArrow.js import React, {Component} from 'react'; class ForwardArrow extends Component { render() { return( <svg width="14" height="24" viewBox="0 0 14 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0.75 0.980482C-0.0624999 1.79298 -0.0624999 3.10548 0.75 3.91798L8.83333 12.0013L0.75 20.0846C-0.0624999 20.8971 -0.0624999 22.2096 0.75 23.0221C1.5625 23.8346 2.875 23.8346 3.6875 23.0221L13.25 13.4596C14.0625 12.6471 14.0625 11.3346 13.25 10.5221L3.6875 0.959649C2.89583 0.167982 1.5625 0.167982 0.75 0.980482Z" fill="#484848"/> </svg> ) } } export default ForwardArrow;
71b38789a5cd58128b3d995235000c1644b9e22b
[ "JavaScript" ]
5
JavaScript
nickolaevv/avito-properties
39519c67814d85b097ac67102e85745c4ad21cdf
a4d725cf02bafbfe5ba4879f42196938bce6d2d2
refs/heads/master
<file_sep>var calcEngine = (function () { var leftVal = 0, rightVal = 0, opCode = '', result = 0; var execute = function () { switch (opCode) { case '+': result = leftVal + rightVal; break; case '-': result = leftVal - rightVal; break; case '*': result = leftVal * rightVal; break; case '/': result = rightVal !== 0 ? leftVal / rightVal : 0; break; } }; var setLeftVal = function (x) { leftVal = x ;}; var setRightVal = function (x) { rightVal = x; }; var setOpCode = function (x) { opCode = x; }; var getOpCode = function () { return opCode; }; var getRightVal = function () { return rightVal; }; var getLeftVal = function () { return leftVal; }; var getResult = function () { return result; }; var clear = function () { leftVal = 0; rightVal = 0; opCode = ''; result = 0; }; return { setLeftVal: setLeftVal, setRightVal: setRightVal, setOpCode: setOpCode, setLeftVal: setLeftVal, getRightVal: getRightVal, getLeftVal: getLeftVal, getOpCode: getOpCode, clear: clear, getResult: getResult, execute: execute }; })();
3510dacdbc40c23ce4b71ccdc9479ddbdcefc55b
[ "JavaScript" ]
1
JavaScript
apexpred/freecodecamp-calculator
dba748d07ec58bbb11d923a214a23a93530df9ac
db7d34961d44a2460db2a8680dc3a10e07c2bafa
refs/heads/main
<repo_name>leenaAhmed/GPBackEnd<file_sep>/models/Meetings.js const mongoose = require("mongoose"); // const date = require("date-and-time"); const slugify = require("slugify"); const MeetingsSchema = new mongoose.Schema({ name: { type: String, required: [true, "Please add a name"], maxlength: [50, "Name can not be more than 50 characters"], }, slug: String, startDateTime: { type: Date, default: Date.now(), }, duration: { type: String, }, file: { type: Buffer, }, status: { type: String, default: "Pending", }, isExpaired: { type: Boolean, default: false, }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, JoinURL: { type: String, }, createdAt: { type: Date, default: Date.now(), }, recordUrl: { type: String, default: "having no record", }, participent: [String], }); MeetingsSchema.pre("save", function (next) { this.slug = slugify(this.name, { lower: true }); next(); }); // MeetingsSchema.pre("save", function (next) { // this.startDateTime = date.format(startDateTime, "ddd, MMM DD YYYY"); // next(); // }); module.exports = mongoose.model("Meetings", MeetingsSchema); <file_sep>/app.js const path = require("path"); const express = require("express"); const dotenv = require("dotenv"); const morgan = require("morgan"); const cors = require("cors"); const colors = require("colors"); const cookieParser = require("cookie-parser"); const loggar = require("./middleware/logger"); const errorHandler = require("./middleware/error"); const connectDB = require("./config/db"); // load env const app = express(); dotenv.config({ path: "./config/config.env" }); connectDB(); app.use(cors()); app.use(express.json()); const meetings = require("./routes/meetings"); const auth = require("./routes/auth"); const users = require("./routes/users"); // Dev logging middleware if (process.env.NODE_ENV === "development") { app.use(morgan("dev")); } app.use(loggar); // routers app.use("/api/v1/meetings", meetings); app.use("/api/v1/auth", auth); app.use("/api/v1/users", users); // error handler app.use(errorHandler); // cookie-parser app.use(cookieParser); // listining to the port const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running in mode on port ${PORT}`); }); // handel promis rejaction process.on("unhandledRejection", (err, promise) => { console.log(`Error: ${err.message}`); });
8e4eef259a62904eccb585e2d6045ad82c8f89d8
[ "JavaScript" ]
2
JavaScript
leenaAhmed/GPBackEnd
39e799415a2f0f2a872603f8b605b6fc22462c2c
14a83218c68c318511c5ad09b1d1c3805e78092d
refs/heads/master
<repo_name>anteamartin/canvas-game<file_sep>/js/obstacle.js function Obstacle(game) { this.game = game; //Math.floor(Math.random()*(max-min+1)*min) this.x = this.game.canvas.width; this.y = 650; this.w = 50; this.h = -80; } Obstacle.prototype.draw = function() { this.game.ctx.fillStyle = "brown"; this.game.ctx.fillRect(this.x, this.y, this.w, this.h); }; Obstacle.prototype.move = function() { this.x -= 10; }; <file_sep>/js/game.js function Game(canvadId) { this.canvas = document.getElementById(canvadId); this.ctx = this.canvas.getContext("2d"); this.background = new Background (this); this.player = new Player (this); this.obstacles = [new Obstacle(this)]; this.interval; this.fps = 60; this.framesCounter = 0; this.reset(); } Game.prototype.start = function() { this.player.setListeners(); this.interval = setInterval(function(){ this.framesCounter++; if (this.framesCounter > 1000) this.framesCounter = 0; this.clear(); this.clearObstacles(); this.moveAll(); this.draw(); this.player.animateImg(); if (this.framesCounter % 100 === 0) { this.generateObstacle(); } if (this.isCollision()) { this.gameOver(); } }.bind(this), 1000/this.fps); }; Game.prototype.stop = function() { }; Game.prototype.gameOver = function() { this.stop(); if(confirm("GAME OVER. Play again?")) { this.reset(); this.start(); } }; Game.prototype.reset = function() { }; Game.prototype.isCollision = function() { var collision = false; this.obstacles.forEach(function(o){ if ((this.player.x + this.player.w) > o.x && this.player.x < o.x + o.w && (this.player.y + this.player.h) >= o.y) { collision = true; } }.bind(this)); return collision; }; Game.prototype.clearObstacles = function() { this.obstacles = this.obstacles.filter(function(o) { return o.x > 0; }) }; Game.prototype.generateObstacle = function() { this.obstacles.push(new Obstacle(this)); }; Game.prototype.clear = function() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); }; Game.prototype.draw = function() { this.background.draw(); this.player.draw(); this.obstacles.forEach(function(o) { o.draw(); }) }; Game.prototype.moveAll = function() { this.background.move(); this.player.move(); this.obstacles.forEach(function(o) { o.move(); }) }; <file_sep>/js/player.js function Player(game) { this.game = game; this.x = 50; this.y0 = 550; this.y = this.y0; this.w = 100; this.h = 100; this.img = new Image(); this.img.src = "./img/player.png" this.img.frames = 3; this.frameIndex = 2; this.isJumping = false; this.vy = 9; this.bullets = []; //this.gravity = 25; } Player.prototype.draw = function () { this.game.ctx.drawImage( this.img, this.frameIndex * (this.img.width / this.img.frames), 0, this.img.width / this.img.frames, this.img.height, this.x, this.y, this.w, this.h ); this.bullets.forEach(function(b){ b.draw(); }) }; Player.prototype.setListeners = function () { document.onkeydown = function (event) { if (event.keyCode === 32) { this.isJumping = true; } else if (event.keyCode === 38) { this.shoot(); } }.bind(this); } Player.prototype.gravity = function () { if (this.y < this.y0) { this.y += this.vy; } }; Player.prototype.jump = function () { if (this.isJumping) { this.y -= 18 if (this.y < 400) { this.isJumping = false } } }; Player.prototype.shoot = function () { this.bullets.push(new Bullet (this.game)) }; Player.prototype.animateImg = function () { if (this.game.framesCounter % 10 === 0 && !this.isJumping) { this.frameIndex += 1; if (this.frameIndex > 2) { this.frameIndex = 0; } } }; Player.prototype.move = function () { this.gravity(); this.jump(); this.bullets.forEach(function(b){ b.move(); }) };
a15d171c87e2ee5e4e2e1a66ec3b42fcb8d2d18c
[ "JavaScript" ]
3
JavaScript
anteamartin/canvas-game
1dc248337002aa7a165a4e0b225b79cac67f4e7f
f3731a1a9b08236f2f0246cf7e0301434e95d07e
refs/heads/master
<file_sep>#include "net/Connector.h" #include "tools/BlockingQueue.h" #include "tools/ThreadPool.h" #include "tools/Logger.h" #include <boost/asio.hpp> #include <functional> #include <memory> using namespace std; using namespace Prometheus; using namespace boost::asio; class MockHost{ public: MockHost(BlockingQueue<UDPPacket>& OutQueue_, BlockingQueue<UDPPacket>& inQueue_,Logger& logger) :OutQueue(OutQueue_),inQueue(inQueue_),logger_(logger) {} void send(ip::udp::endpoint& ep) { UDPPacket p("hello world!",ep); OutQueue.put(p); sleep(1); send(ep); } void callback() { UDPPacket p=inQueue.take(); logger_.Log(LogLevel::debug,p.content); } private: BlockingQueue<UDPPacket>& OutQueue; BlockingQueue<UDPPacket>& inQueue; Logger logger_; }; int main(int argc, char* argv[]) { assert(argc == 3); ip::udp::endpoint remoteEp(ip::address::from_string("127.0.0.1"),atoi(argv[1])); ip::udp::endpoint localEp(ip::address_v4(),atoi(argv[2])); BlockingQueue<UDPPacket> inQueue; // BlockingQueue<UDPPacket> outQueue; Prometheus::Logger logger("net"); shared_ptr<MockHost> mh(new MockHost(outQueue,inQueue,logger)); logger.SetLevel(LogLevel::debug); io_service iosvc; io_service::work w(iosvc); shared_ptr<UDPConnector> c(new UDPConnector(outQueue,inQueue,iosvc,logger,localEp)); c->registerCallback(bind(&MockHost::callback,mh.get())); c->connect(); ThreadPool tp("net"); tp.start(3); tp.run(bind(&MockHost::send,mh.get(),remoteEp)); tp.run(bind(&UDPConnector::recv,c.get())); tp.run(bind(&UDPConnector::run,c.get())); iosvc.run(); return 0; }<file_sep>file(GLOB sources "*.cpp" "*.h") add_library(net ${sources}) target_link_libraries(net PUBLIC tools)<file_sep>#include "kademlia/h256.h" #include "kademlia/tools.h" #include "kademlia/common.h" #include <iostream> using namespace Prometheus; using namespace std; size_t distance(NodeID& a,NodeID& b) { const size_t distanceTable[]={ 8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; NodeID c = a ^ b; size_t result = 256; int i = 0; for(int i = 0;i<32;i++) { result -= distanceTable[c[i]]; if(c[i]>0) break; } return result; } int main() { Randomizer r; NodeID a = r.getRandomSHA256(); cout<<distance(a,a)<<endl; NodeID b = a; a[0] = b[0] ^ 1<<7; cout<<distance(a,b)<<endl; a[0]=b[0]; a[31]=b[31]^1; cout<<distance(a,b)<<endl; }<file_sep>/** * This file is part of Prometheus. * @author 郑聪 * @date 2020/05/03 **/ #include "kademlia/kademliaHost.h" #include "kademlia/common.h" #include "kademlia/tools.h" #include "kademlia/nodeTable.h" #include "kademlia/h256.h" #include "tools/Logger.h" #include <boost/asio.hpp> #include <memory> #include <iostream> using namespace std; using namespace Prometheus; int main() { Randomizer r; NodeID myid = r.getRandomSHA256(); cout<<xordistance(myid,myid)<<endl; cout<<char2hex(myid.data(),32)<<endl; Logger l("logger"); vector<NodeID> IDset; NodeTable table(myid,l); for(int i = 0;i<32;i++) { for(int j = 7;j>=0;j--) { NodeID insert = myid; insert[i] ^= 1<<j; IDset.push_back(insert); NodeID temp = insert ^ myid; boost::asio::ip::udp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"),1234); shared_ptr<NodeInformation> pn(new NodeInformation(insert,ep.address(),ep.port())); table.addNode(pn); } } auto bucket = table.getBucket(); for(auto i:bucket) { for(auto j:i) { cout<<char2hex(j->nodeID.data(),32)<<endl; } cout<<endl; } cout<<endl<<"input="<<char2hex(IDset[5].data(),32)<<endl; auto nearestNodes = table.LookUpKNearestNodes(IDset[5]); for(auto i:nearestNodes) { cout<<char2hex(i->nodeID.data(),32)<<endl; } nearestNodes = table.LookUpKNearestNodes(myid); for(auto i:nearestNodes) { cout<<char2hex(i->nodeID.data(),32)<<endl; } nearestNodes = table.LookUpKNearestNodes(IDset[IDset.size()-1]); for(auto i:nearestNodes) { cout<<char2hex(i->nodeID.data(),32)<<endl; } nearestNodes = table.LookUpKNearestNodes(IDset[IDset.size()-2]); for(auto i:nearestNodes) { cout<<char2hex(i->nodeID.data(),32)<<endl; } nearestNodes = table.LookUpKNearestNodes(IDset[0]); for(auto i:nearestNodes) { cout<<char2hex(i->nodeID.data(),32)<<endl; } return 0; } <file_sep>#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::asio; void print(const boost::system::error_code &ec) { cout<<"Hello,world!"<<endl; } int main() { io_service io; deadline_timer t(io,boost::posix_time::seconds(5)); t.async_wait(print); io.run(); return 0; } <file_sep>/* This file is part of Prometheus. */ #ifndef _COMMON_H_ #define _COMMON_H_ #include <list> #include <array> #include <boost/asio.hpp> #include <vector> namespace Prometheus { typedef unsigned char byte; using NodeID = std::array<unsigned char,32>; typedef std::array<unsigned char,32> ValueID; typedef std::vector<char> bytes; namespace bi = boost::asio::ip; namespace ba = boost::asio; const int NodeIDSize = 32; /** @brief 存储节点ID、IP地址、UDP端口的三元组 */ struct NodeInformation { NodeInformation(NodeID& _nodeID,const boost::asio::ip::address& _NodeAddress,const unsigned short _UDPPort): nodeID(_nodeID),NodeAddress(_NodeAddress),UDPPort(_UDPPort) {} NodeInformation(){} NodeID nodeID; /**< 节点ID */ boost::asio::ip::address NodeAddress; /**< 节点的IP地址 */ uint16_t UDPPort; /**< 节点的UDP端口 */ bool Visited; /**< 在进行findNode请求时需要寻找未在之前几轮访问过的节点 */ bool Pending; /**< 被ping但是未回复 */ }; struct File_info { typedef unsigned long long Size_type; Size_type filesize; size_t filename_size; File_info() : filesize(0), filename_size(0) {} }; } // namespace Prometheus #endif <file_sep>/** @file Logger.h * @author 郑聪 * @date 2020/03/30 * * This file is part of Prometheus. */ #ifndef _LOGGER_H_ #define _LOGGER_H_ #include <spdlog/spdlog.h> #include <memory> #include <string> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/async.h> namespace Prometheus { enum class LogLevel{ trace = SPDLOG_LEVEL_TRACE, debug = SPDLOG_LEVEL_DEBUG, info = SPDLOG_LEVEL_INFO, warn = SPDLOG_LEVEL_WARN, error = SPDLOG_LEVEL_ERROR, critical = SPDLOG_LEVEL_CRITICAL, off = SPDLOG_LEVEL_OFF, n_levels }; /** @brief 包装了spdlog的日志类。 * 使用异步日志。该异步日志使用内建的线程池。 * 将日志的等级分为5级,并支持多线程的日志。 */ class Logger { public: Logger(const std::string& name) { logger_ = spdlog::stdout_color_mt<spdlog::async_factory>(name); } void SetLevel(LogLevel level) { logger_->set_level(static_cast<spdlog::level::level_enum>(level)); } void Log(LogLevel level, const std::string& content) { if(level == LogLevel::info) { logger_->trace(content); } else if(level == LogLevel::debug) { logger_->debug(content); } else if(level == LogLevel::trace) { logger_->trace(content); } else if(level == LogLevel::error) { logger_->error(content); } else if(level == LogLevel::warn) { logger_->warn(content); } else if(level == LogLevel::critical) { logger_->critical(content); } } private: std::shared_ptr<spdlog::logger> logger_; }; } // namespace Prometheus #endif<file_sep>#include <iostream> using namespace std; #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/sinks/sink.h> #include <spdlog/spdlog.h> namespace spd = spdlog; int main() { int n; // Console logger with color spd::set_level(spd::level::debug); auto console = spd::stdout_color_mt("logger"); console->info("Welcome to spdlog!"); console->error("Some error message with arg{}..", 1); console->debug("debug"); console->warn("warn"); // Create basic file logger (not rotated) auto my_logger = spd::basic_logger_mt("spdlog_test", "d:/logs/vs/spdlog_log.txt",false); my_logger->info("Some log message"); my_logger->debug("debug"); my_logger->warn("warning"); my_logger->error("error 现在c++的框架使用也很方便了,感谢开源。"); cout << endl; cout << "are you ok ?" << endl; cin >> n; return 0; }<file_sep>#include <vector> #include <cstdint> #include <iostream> using namespace std; int32_t getInt32(int32_t *p) { int32_t result = *p; be32toh(result); return result; } void writeInt32(int32_t *p, int32_t num) { *p=htobe32(num); } int main() { vector<char> test; test.reserve(100); const char* begin = test.data(); int32_t wtf = 1; int32_t *smg = &wtf; char* jb = (char*)smg; for(int i=0;i<4;i++) cout<<(int)jb[i]<<" "; writeInt32((int32_t*)begin,1); for(int i = 0;i < 4; i++) cout<<(int)test[i]<<" "; int32_t result = getInt32((int32_t*)begin); jb = (char*)&result; for(int i=0;i<4;i++) cout<<(int)jb[i]<<" "; cout<<result<<endl; }<file_sep>/* This file is part of Prometheus. */ #include "h256.h" #include "tools.h" using namespace std; using namespace Prometheus; int main() { Randomizer a; auto b = a.getRandom(); auto c = a.getRandom(); auto d = b ^ c; unsigned char e[65] = {0}; char2hex(e,(unsigned char*)b.data(),32); printf("%s\n",e); char2hex(e,(unsigned char*)c.data(),32); printf("%s\n",e); char2hex(e,(unsigned char*)d.data(),32); printf("%s\n",e); return 0; }<file_sep>#include <iostream> #include <fstream> #include <boost/asio.hpp> #include <functional> #include "kademlia/h256.h" #include "tools/ThreadPool.h" #include "kademlia/kademliaHost.h" #include "tools/BlockingQueue.h" #include "net/Connector.h" #include "console/server.h" #include <unistd.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace Prometheus; using namespace std; using namespace boost::asio; using namespace boost::property_tree; int main(int argc, char *argv[]) { boost::property_tree::ptree root; boost::property_tree::read_json<boost::property_tree::ptree>("config.json",root); string strmyid = root.get<string>("id"); string myip = root.get<string>("ip"); string myport = root.get<string>("port"); uint16_t UDPPort = atoi(myport.c_str()); NodeID myid = hex2char(strmyid); ip::udp::endpoint udpLocalEp(ip::udp::v4(),UDPPort); ip::tcp::endpoint tcpLocalEp(ip::tcp::v4(),UDPPort); io_service iosvc; io_service::work w(iosvc); BlockingQueue<UDPPacket> inq; BlockingQueue<UDPPacket> outq; Logger logger("host"); logger.SetLevel(LogLevel::debug); Prometheus::Randomizer r; NodeID nid = myid; NodeTable nt(nid,logger); shared_ptr<UDPConnector> uc(new UDPConnector(outq,inq,iosvc,logger,udpLocalEp)); uc->connect(); shared_ptr<KademliaHost> kh(new KademliaHost(nid,iosvc,outq,inq,nt,logger,tcpLocalEp)); shared_ptr<rpcHost> rh(new rpcHost(kh,logger)); uc->registerCallback(std::bind(&KademliaHost::muxer,kh.get())); ThreadPool tp("host"); tp.start(4); tp.run(std::bind(&KademliaHost::run,kh.get())); tp.run(std::bind(&rpcHost::run,rh.get())); tp.run(std::bind(&UDPConnector::run,uc.get())); tp.run(std::bind(&UDPConnector::recv,uc.get())); ptree network; ptree nodes; ptree nodeList; read_json<ptree>("network.json",network); nodes=network.get_child("nodes"); vector<shared_ptr<NodeInformation>> idlist; string inputidstr,inputaddr,inputport; for(ptree::iterator it = nodes.begin(); it != nodes.end(); ++it) { nodeList = it->second; inputidstr=nodeList.get<string>("id"); inputaddr=nodeList.get<string>("ip"); inputport=nodeList.get<string>("port"); NodeID inputid = hex2char(inputidstr); shared_ptr<NodeInformation> pNode(new NodeInformation(inputid,bi::address::from_string(inputaddr),atoi(inputport.data()))); idlist.emplace_back(pNode); } for(auto i: idlist) { kh->addNode(i); } iosvc.run(); }<file_sep>#include <boost/asio.hpp> #include <iostream> #include <memory> #include <functional> #include "tools/ThreadPool.h" #include "tools/BlockingQueue.h" #include <mutex> using namespace std; using namespace boost::asio; using namespace Prometheus; class MockProducer: boost::noncopyable{ public: MockProducer(BlockingQueue<string>& bqout,BlockingQueue<string>& bqin) :outQueue(bqout),inQueue(bqin) {} void run() { outQueue.put("test"); sleep(1); run(); } void callBack() { cout<<"Something came"<<endl; } private: BlockingQueue<string>& outQueue; BlockingQueue<string>& inQueue; }; class MockServer: boost::noncopyable{ public: MockServer(BlockingQueue<string>& bqin, BlockingQueue<string>& bqout,io_service& is,ip::udp::endpoint ep) :inputQueue(bqin),outputQueue(bqout),lep(ep),s(is) { } void connect() { s.open(ip::udp::v4()); s.bind(lep); } void registerCallback(function<void()> callback) { onReceivingCallback = callback; } void recv() { //lock_guard<mutex> lock(x_buf); s.async_receive_from(buffer(buf,512),lep,[this](boost::system::error_code ec, size_t len){ if(len) { string str(buf.data()); outputQueue.put(str); onReceivingCallback(); } recv(); }); } void run(ip::udp::endpoint rep) { string str = inputQueue.take(); send(str,rep); sleep(1); run(rep); } void send(const string& str,ip::udp::endpoint rep) { lock_guard<mutex> lock(x_buf); s.async_send_to(buffer(str),rep,[this](boost::system::error_code ec, size_t len){ }); } private: std::array<char,512> buf; mutex x_buf; function<void()> onReceivingCallback; BlockingQueue<string>& inputQueue; BlockingQueue<string>& outputQueue; ip::udp::endpoint lep; ip::udp::socket s; }; int main(int argc, char *argv[]) { ip::udp::endpoint ep(ip::udp::v4(),atoi(argv[1])); BlockingQueue<string> bqin; BlockingQueue<string> bqout; string fullep(argv[2]); ip::udp::endpoint rep(ip::address_v4::from_string(fullep.substr(0,fullep.find_first_of(':'))),atoi(fullep.substr(fullep.find_first_of(':')+1).c_str())); io_service iosvc; io_service::work w(iosvc); ThreadPool tp("mockserver"); shared_ptr<MockProducer> mp(new MockProducer(bqout,bqin)); tp.start(3); shared_ptr<MockServer> mc(new MockServer(bqout,bqin,iosvc,ep)); mc->registerCallback(bind(&MockProducer::callBack,mp.get())); mc->connect(); tp.run(bind(&MockProducer::run,mp.get())); tp.run(bind(&MockServer::recv,mc.get())); tp.run(bind(&MockServer::run,mc.get(),rep)); iosvc.run(); return 0; }<file_sep>/* This file is part of Prometheus. */ #include "tools.h" #include <cstdio> using namespace std; using namespace Prometheus; int main() { unsigned char a[256] = {0}; for(int i = 0;i < 256; i++) a[i] = i; printf("%s\n",a); unsigned char b[513] = {0}; char2hex(b,a,255); printf("%s\n",b); return 0; }<file_sep>#include "nodeTable.h" #include "tools.h" #include <vector> #include <iostream> using namespace std; namespace Prometheus { /** * @brief 查找离目标节点最近的k个节点. * * @param id 目标节点的id * @return vector<shared_ptr<NodeInformation>> 距离目标节点最近的k个节点的信息。 */ bool NodeTable::isBucketFull(const NodeID& id) { return kBucket[xordistance(id,MyNodeID)].size() >= MaxBucketSize; } vector<shared_ptr<NodeInformation>> NodeTable::LookUpKNearestNodes(const NodeID &id) { size_t distance = xordistance(id,MyNodeID); cout<<"distance="<<distance<<endl; size_t head = distance; int last = distance == 0?NumBuckets - 1:(distance - 1)%NumBuckets; cout<<"head="<<head<<"last="<<last<<endl; int count = k; vector<shared_ptr<NodeInformation>> result; if(distance > 1 && last != NumBuckets - 1) { int i = 0; while(count>0) { i=0; while(i<kBucket[head].size() && head != NumBuckets - 1) { result.push_back(kBucket[head][i]); i++; count--; if(count == 0)break; } if(count>0) { i=0; head++; while(i<kBucket[last].size()&& last) { result.push_back(kBucket[last][i]); i++; count--; if(count == 0)break; } if(count>0) last--; } } } else if(distance<2) { cout<<"here!"<<endl; int i = 0; while(count>0) { i=0; if(head == NumBuckets - 1) break; while(i<kBucket[head].size()) { result.push_back(kBucket[head][i]); i++; count--; if(count == 0) break; } if(count>0) head++; } } else if(last == NumBuckets - 1) { while(count>0) { int i = 0; if(last == 0) break; while(i<kBucket[last].size()) { result.push_back(kBucket[last][i]); i++; count--; if(count == 0)break; } if(count>0) last--; } } return result; } /** * @brief 查询一个节点。如果存在,返回该节点的节点信息的智能指针。如果不存在,返回空的智能指针。 * * @param id 待查询的节点信息 * @return shared_ptr<NodeInformation> 被查询的节点信息的智能指针。 */ shared_ptr<NodeInformation> NodeTable::LookUpNodeInformation(const NodeID &id) { shared_ptr<NodeInformation> result = nullptr; for(auto i:kBucket[xordistance(id,MyNodeID)]) if(i->nodeID == id) result = i; return result; } /** * @brief 向表中添加一个新的节点。如果节点已经存在,就把它移到最后面。 * * @param newNode 待加入的节点 */ void NodeTable::addNode(shared_ptr<NodeInformation> newNode) { size_t dist = xordistance(newNode->nodeID,MyNodeID); auto it = find_if(kBucket[dist].begin(),kBucket[dist].end(),[newNode](const shared_ptr<NodeInformation> item){ return item->nodeID == newNode->nodeID; }); if(it != kBucket[dist].end()) { //logger.Log(LogLevel::debug,"adding existing nodes"+char2hex(newNode->nodeID.data(),32)+", so move it to the end."); auto ni = *it; it = kBucket[dist].erase(it); kBucket[dist].push_back(ni); return; } else { kBucket[dist].push_back(newNode); } } } // namespace Prometheus<file_sep>#include <fstream> #include <iostream> #include <string> #include <kademlia/h256.h> #include <kademlia/tools.h> using namespace std; using namespace Prometheus; int main() { fstream s; s.open("Test.txt",ios::out); Randomizer r; string addr = "127.0.0.1"; NodeID id = r.getRandomSHA256(); string strid = char2hex(id.data(),32); int16_t port = rand() % 4096 + 1000; string strport = to_string(port); s<<strid<<" "<<addr<<" "<<strport<<endl; for(int i = 0;i<8;i++) { NodeID newID = id; newID[25]^=1<<2; newID[30]^=1<<i; strid = char2hex(newID.data(),32); port = rand() % 4096 + 1000; strport = to_string(port); s<<strid<<" "<<addr<<" "<<strport<<endl; } s.close(); return 0; }<file_sep>/** @file ThreadPool.h * @author 郑聪 * @date 2020/03/29 * * This file is part of Prometheus. */ #ifndef _THREADPOOL_H_ #define _THREADPOOL_H_ #include "noncopyable.h" #include <thread> #include <memory> #include <vector> #include <mutex> #include <condition_variable> #include <functional> #include <string> #include <future> #include <deque> #include <iostream> namespace Prometheus { /** @brief 实现了一个基本的线程池。 */ class ThreadPool : public noncopyable { public: explicit ThreadPool(const std::string& name = std::string("ThreadPool")); ~ThreadPool(); void setMaxQueueSize(int maxSize) { maxQueueSize = maxSize; } void setThreadInitCallback(const std::function<void()> cb) {threadInitCallback = cb; } void start(int numThreads); void stop(); const std::string& name() const {return name_; } size_t queueSize() const; /* template<class T, class... Args> void run(T&& f, Args&&... args) { std::cout<<"Thread pool tries to run a thread.\n"; using ReturnType = decltype(f(args...)); auto task = std::make_shared<std::packaged_task<ReturnType()>>( std::bind(std::forward<T>(f), std::forward<Args>(args)...) ); { std::cout<<"Thread Pool is trying to push a task into Queue.\n"; std::lock_guard<std::mutex> lock{mutex_}; _run( [task]() { (*task)(); } ); } } */ void run(std::function<void()> f); private: bool isFull() const; void runInThread(); std::function<void()> take(); //一个拥有所有指向线程的指针的数组。用来直接操作线程。 std::vector<std::unique_ptr<std::thread>> threads; //操作本线程池的mutex mutable std::mutex mutex_; //通知所有线程任务队列非空 mutable std::condition_variable notEmpty; //通知所有线程任务队列非满 mutable std::condition_variable notFull; //进程初始化后的回调函数 std::function<void()> threadInitCallback; //任务队列。其中的任务要求没有参数,没有返回值。如果有其他需求将会更改。 std::deque<std::function<void()>> taskQueue; //线程池的名字 std::string name_; //任务队列的最大长度 size_t maxQueueSize; //当前是否有线程在运行。 bool isRunning; }; } // namespace Prometheus #endif<file_sep>/* This file is part of Prometheus. */ /** @author 郑聪 * @date 2020/04/20 */ #ifndef _KADEMLIAHOST_H_ #define _KADEMLIAHOST_H_ #include <kademlia/kademlia.pb.h> #include "h256.h" #include "common.h" #include "nodeTable.h" #include "session.h" #include "tools/BlockingQueue.h" #include "net/MessageDispacher.h" #include <net/Connector.h> #include <tools/Logger.h> #include <boost/asio.hpp> #include <vector> #include <functional> #include <chrono> #include <iostream> #include <list> #include <map> #include <set> #include <memory> #include <memory.h> namespace Prometheus { /** @brief 负责处理kademlia网络的事务的类 * kademlia算法主要的部分就在这里。 * 这个类负责主动发起以下的四个操作: * Ping(),FindNode(),同时可以自己发现更多的peer * 及处理接收的来自外部节点的FindValue()和FindNode()的回复。 */ class KademliaHost { public: KademliaHost(const NodeID& _mynodeid,ba::io_service& iosvc, BlockingQueue<UDPPacket>& _outqueue,BlockingQueue<UDPPacket>& _inqueue, NodeTable& _peerTable,Logger& _logger, bi::tcp::endpoint localep): MyNodeID(_mynodeid),_iosvc(iosvc),TCPconn(iosvc,bi::tcp::endpoint(bi::tcp::v4(),localep.port())),outQueue(_outqueue),inQueue(_inqueue), dispacher(std::bind(&KademliaHost::defaultDispacherCallback,this,std::placeholders::_1,std::placeholders::_2)),logger(_logger), onPingingCallback(std::bind(&KademliaHost::onPinging,this,std::placeholders::_1,std::placeholders::_2)) { m_timer.reset(new boost::asio::deadline_timer(iosvc)); peerTable = std::make_shared<NodeTable>(_peerTable); dispacher.registerCallback(onPingingCallback); std::function<void(const std::shared_ptr<PingReplyPacket>&,const boost::asio::ip::udp::endpoint&)> onPingingReplyCallback (std::bind(&KademliaHost::onPingingReply,this,std::placeholders::_1,std::placeholders::_2)); dispacher.registerCallback(onPingingReplyCallback); std::function<void(const std::shared_ptr<FindNodePacket>&,const boost::asio::ip::udp::endpoint&)> onFindNodeCallback (std::bind(&KademliaHost::onFindNode,this,std::placeholders::_1,std::placeholders::_2)); std::function<void(const std::shared_ptr<FindNodeReplyPacket>&,const boost::asio::ip::udp::endpoint&)> onFindNodeReplyCallback (std::bind(&KademliaHost::onFindNodeReply,this,std::placeholders::_1,std::placeholders::_2)); dispacher.registerCallback(onFindNodeReplyCallback); ReceiveFile(); } //向列表中的一个节点发出ping包,来探测那个节点是否在线 void Ping(std::shared_ptr<NodeInformation> dest); //将一个值存放在网络中 void Store(const ValueID& Key,const bytes Value); //查询网络中是否存在NodeID为node的节点,并接收最靠近被查找节点的K个节点的三元组 void FindNode(std::shared_ptr<NodeInformation> node); //处理外部节点发来的节点查询请求 void onFindNode(const std::shared_ptr<FindNodePacket>& fnp, const bi::udp::endpoint& ep); //处理外部节点发来的FindNodePacket的回复 void onFindNodeReply(const std::shared_ptr<FindNodeReplyPacket>& fnrp, const bi::udp::endpoint& ep); //处理外部节点发来的PingPacket的回复 void onPinging(const std::shared_ptr<PingPacket>& pp,const bi::udp::endpoint& ep); //处理外部节点发来的PingReplyPacket的回复 void onPingingReply(const std::shared_ptr<PingReplyPacket>& prp,const bi::udp::endpoint& ep); void ReceiveFile(); bool SendFile(const std::shared_ptr<NodeInformation> node, const std::string& filepath); std::shared_ptr<NodeInformation> LookUpNodeInformation(const NodeID &id) { return peerTable->LookUpNodeInformation(id); } void run() { while(true) { for(auto i:AlivePeers) Ping(i); sleep(15); } } void muxer() { auto p = inQueue.take(); dispacher.onMessage(p.content,p._endpoint); } void defaultDispacherCallback(const std::shared_ptr<google::protobuf::Message>& message,const boost::asio::ip::udp::endpoint& ep) { std::cout<<"not Kademlia Message.TODO:Forwarding to upper layer."<<std::endl; } //添加新节点,并尝试ping这个节点,判断是否存活。 void addNode(std::shared_ptr<NodeInformation> newNode, bool isActive = true); private: //添加定时任务 void schedule(unsigned interval, std::function<void(boost::system::error_code const&)> f); //定时任务,检查是否有等待被驱逐而且计时器到期的节点,如果有则清除。 void checkEvictions(); void acceptHandler(std::shared_ptr<Session> session,boost::system::error_code e); void headerHandler(boost::system::error_code e,size_t len); void contentHandler(boost::system::error_code e,size_t len); NodeID MyNodeID; //本机的NodeID ba::io_service& _iosvc; bi::tcp::acceptor TCPconn; //bi::tcp::socket TCPSocket; BlockingQueue<UDPPacket>& outQueue; BlockingQueue<UDPPacket>& inQueue; std::shared_ptr<NodeTable> peerTable; //节点列表,处理网络中节点信息CRUD的工作 MessageDispacher dispacher; Logger logger; std::unique_ptr<boost::asio::deadline_timer> m_timer; std::set<std::shared_ptr<NodeInformation>> AlivePeers; //记录了最长时间未联系节点被ping的时间,用来计算超时 std::map<std::shared_ptr<NodeInformation>,std::chrono::steady_clock::time_point> NodeToBeEvicted; //记录了向这些节点发送findNode消息的时间 std::map<std::shared_ptr<NodeInformation>,std::chrono::steady_clock::time_point> FindingNode; std::vector<std::shared_ptr<NodeInformation>> FindNodeReply; std::map<std::shared_ptr<NodeInformation>,bool> FindNodeVisited; std::set<std::shared_ptr<NodeInformation>> PendingNodes; std::chrono::milliseconds const EvictionInterval = std::chrono::milliseconds(75); std::chrono::milliseconds const FindNodeInterval = std::chrono::milliseconds(300); std::chrono::milliseconds const PendingInterval = std::chrono::milliseconds(300); const unsigned int c_keepAliveInterval = 1000; std::function<void(const std::shared_ptr<PingPacket>&,const boost::asio::ip::udp::endpoint&)> onPingingCallback; std::vector<char> sendbuffer; std::vector<std::unique_ptr<boost::asio::deadline_timer>> timers; //记录收到的FindNode的数量 unsigned int FindNodeReceiveCount; std::set<std::shared_ptr<NodeInformation>> triedNodes; //FindNode请求中已经发送过请求的节点 unsigned CurrentFindNodeRound = 0; unsigned MaxFindNodeRound = 5; //FindNode请求的最大轮数 int alpha = 3; // findNode时发送消息的节点的数量 FILE *fp; //被传送的文件 }; } // namespace Prometheus #endif<file_sep>#include "net/MessageDispacher.h" #include "kademlia/kademlia.pb.h" #include <functional> #include "kademlia/h256.h" #include <memory> #include <vector> #include <iostream> using namespace Prometheus; using namespace std; int main() { function<void(const shared_ptr<google::protobuf::Message>&)> deff = [](const shared_ptr<google::protobuf::Message> &msg){cout<<"default message"<<endl;}; function<void(const shared_ptr<PingPacket>&)> f = [](const shared_ptr<PingPacket>& _p){cout<<_p->random();}; MessageDispacher md(deff); PingPacket p; Randomizer r; p.set_random(r.getRandomInt32()); cout<<"random="<<p.random()<<endl; vector<char> buffer; md.makeMessage(p,buffer); md.registerCallback<PingPacket>(f); md.onMessage(buffer); }<file_sep>/* This file is part of Prometheus. */ #include "common.h" #include <string> #ifndef _TOOLS_H_ #define _TOOLS_H_ namespace Prometheus { //将字节流转换为人类可读的十六进制序列 std::string char2hex(const unsigned char *input, int length); //将人类可读的十六进制序列转换为字节流 NodeID hex2char(const std::string& input); size_t xordistance(const NodeID& a,const NodeID& b); } // namespace Prometheus #endif<file_sep>/* This file is part of Prometheus. */ #include "h256.h" using namespace std; using namespace Prometheus; int main() { ShaProducer sp; sp.GetRandomSHA256(); return 0; }<file_sep>/* This file is part of Prometheus. */ #ifndef _NODETABLE_H_ #define _NODETABLE_H_ #include "common.h" #include <list> #include <array> #include <vector> #include <chrono> #include "tools/Logger.h" #include "tools.h" namespace Prometheus { /** @brief 管理k-bucket的类。主要进行k-bucket的增改删查,以及定时ping操作的通知。 */ class NodeTable { public: NodeTable(NodeID& _MyNodeID,Logger _logger): MyNodeID(_MyNodeID),logger(_logger){} //查询XOR距离最接近输入节点的K个节点。返回一个vector<NodeInformation>。 std::vector<std::shared_ptr<NodeInformation>> LookUpKNearestNodes(const NodeID &id); //查询k-bucket中一个节点的信息。 std::shared_ptr<NodeInformation> LookUpNodeInformation(const NodeID &id); //向Kbucket中添加一个新节点。 void addNode(std::shared_ptr<NodeInformation> newNode); void deleteNode(std::shared_ptr<NodeInformation> node) { auto& bucket = kBucket[xordistance(node->nodeID,MyNodeID)]; for(auto i = bucket.begin();i != bucket.end();i++) if(*i == node) { i=bucket.erase(i); } } bool isBucketFull(const NodeID& id); //查询一个NodeID对应的bucket中最久未联系节点 std::shared_ptr<NodeInformation> getLeastRecentNode(const NodeID& id) { return kBucket[xordistance(id,MyNodeID)].front(); } //仅供调试使用,不可在别的地方调用 const std::array<std::vector<std::shared_ptr<NodeInformation>>,257>& getBucket(){return kBucket; } private: //删除Kbucket中的一个节点。 void deleteNode(NodeID node); //定时任务,检查待驱逐节点回复是否超时。如果超时则删除。 void checkNodeToBeEvicted(); //存储节点信息的桶,每个桶中的元素离本机的异或距离相同。 std::array<std::vector<std::shared_ptr<NodeInformation>>,257> kBucket; uint32_t NumBuckets = 256; uint32_t MaxBucketSize=3; uint32_t PropagationCoefficient = 3; // 论文中执行递归寻址操作时每次请求的节点数量。 uint32_t k = 3; //论文中每次寻找节点操作返回的节点数量。 NodeID MyNodeID; Logger logger; }; } //namespace Prometheus #endif<file_sep># PrometheusMain 该项目为 西安电子科技大学学生自发发起的 “ProjectPrometheus(普罗米修斯计划)” 项目主程序 <a href="https://github.com/iodinetech/PrometheusMain/blob/master/introduction.pdf">简介 PPT</a><br> 若无法查看,请改善您的网络环境。 或,可尝试将本仓库代码整体下载到本地后进行查看。 由于最近实在太忙,该简介比较简略,稍后会更新详细版本,敬请关注! | Operating system & Architecture | Status | | ------------------------------- | ---------- | | Ubuntu 18.04 x86-64 | Build Pass | | Debian 10 AArch64 | Build Pass | 使用时需要配置两个文件:config.json和network.json.文件格式示例在代码的根目录. config.json 设置本节点的属性,network.json设置网络中其他节点的属性。 # 编译指引: 开启终端,执行下述命令,进行环境搭建和项目编译。 ```shell sudo apt-get install libspdlog-dev sudo apt-get install libcrypto++-dev sudo apt-get install libboost-all-dev sudo apt-get install libprotobuf-dev sudo apt-get install protobuf-compiler sudo apt-get install cmake mkdir build # 从这行开始,在该代码所在目录执行 cd build cmake .. make ``` 主程序为build/kadfiletranporter,控制台为build/console/rpcclient testenv里是demo用的三个节点。编译成功后将生成的两个可执行文件放在三个目录中,每个目录中一份。然后启动三个程序就可以观察到节点之间互相通信。 使用控制台可以通过AddPeer命令添加节点,通过SendFile命令向想要的节点发送文件。执行这两个命令后按照提示操作即可。 # 关于体验版 要体验 0.8.1 的功能,只需要将编译后 ./build/kadfiletransporter 和 ./build/console/rpcclient 文件夹中的两个二进制文件分别放入 testEnv 文件夹中的三个 test 文件夹,再分别在三个文件夹中打开终端,启动 kadfiletransporter 即可看到三个节点已经开始相互通信了。 各个 test 文件夹中的两个 json 文件均是用于建立测试环境的。三个文件夹就相当于三个节点,我们称这种运作模式为“伪分布式” 其中: 1. config.json 描述了当前的节点信息: - id:id 是一个 256 位的字符串,它唯一标识了一个 Prometheus 网络中的节点。您可以自己使用 SHA256 来生成自己喜欢的串,但我们建议使用随机生成的值来作为 id,防止碰撞; - ip:运行该节点的硬件(物理硬件或逻辑硬件)的 ip 地址。由于该测试环境中均是本机运行,所以填写本地地址即可; - port:Prometheus p2p 模块所监听的端口地址。由于我们要建立伪分布式网络,所有节点运行在同一物理机上,所以三个文件夹内 config 中的该字段均不同。 2. network.json 用于为我们的测试节点提供节点列表——每个节点在自己的该文件中填写想要连接到的其他节点即可。这里面的三个值的含义与 config.json 中的同名字段完全相同。 如果想要使用控制台,请在节点启动后,启动对应节点文件夹内的 rpcclient 即可运行控制台。控制台会自动连接处于同一个文件夹内的 kadfiletransporter。 当看到连接成功的提示后,您可以键入“SendFile”并按下回车来启动该示例程序的文件传输功能,接下来的操作跟随提示即可,控制台要求输入的节点 id,即是上文介绍过的节点 id。填写哪个节点,文件就会被发送到哪个节点。 使用完毕后,输入 exit 即可退出控制台 如果您在使用中遇到问题,欢迎在 issue 中提出来,我们会尽快回答并解决 <file_sep>#include <memory> #include <boost/asio.hpp> #include <string> #include <cstdlib> #include <iostream> #include <tools/Logger.h> #include "common.h" #ifndef _SESSION_H_ #define _SESSION_H_ namespace Prometheus { class Session : public std::enable_shared_from_this<Session> { public: typedef bi::tcp TCP; typedef boost::system::error_code Error; typedef std::shared_ptr<Session> Pointer; typedef File_info::Size_type Size_type; static void print_asio_error(const Error& error) { std::cerr << error.message() << "\n";} static Pointer create(ba::io_service& io) { return Pointer(new Session(io));} TCP::socket& socket() { return socket_; } ~Session() { if (fp_) fclose(fp_); clock_ = clock() - clock_; Size_type bytes_writen = total_bytes_writen_; if (clock_ == 0) clock_ = 1; double speed = bytes_writen * (CLOCKS_PER_SEC / 1024.0 / 1024.0) / clock_ ; std::cout << "cost time: " << clock_ / (double) CLOCKS_PER_SEC << " s " << "bytes_writen: " << bytes_writen << " bytes\n" << "speed: " << speed << " MB/s\n\n"; } void start() { clock_ = clock(); socket_.async_receive( ba::buffer(reinterpret_cast<char*>(&file_info_), sizeof(file_info_)), std::bind(&Session::handle_header, shared_from_this(),std::placeholders::_1,std::placeholders::_2)); } private: Session(ba::io_service& io) : socket_(io), fp_(NULL), total_bytes_writen_(0) { } void handle_header(const Error& error,size_t len) { if (error) return print_asio_error(error); size_t filename_size = file_info_.filename_size; if (filename_size > k_buffer_size) { std::cerr << "Path name is too long!\n"; return; } //得用async_read, 不能用async_read_some,防止路径名超长时,一次接收不完 ba::async_read(socket_, ba::buffer(buffer_, file_info_.filename_size), std::bind(&Session::handle_file, shared_from_this(), std::placeholders::_1,std::placeholders::_2)); } void handle_file(const Error& error, size_t len) { if (error) return print_asio_error(error); const char *basename = buffer_ + file_info_.filename_size - 1; while (basename >= buffer_ && (*basename != '\\' && *basename != '/')) --basename; ++basename; std::cout << "Open file: " << basename << " (" << buffer_ << ")\n"; fp_ = fopen(basename, "wb"); if (fp_ == NULL) { std::cerr << "Failed to open file to write\n"; return; } receive_file_content(); } void receive_file_content() { socket_.async_receive(ba::buffer(buffer_, k_buffer_size), std::bind(&Session::handle_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void handle_write(const Error& error, size_t bytes_transferred) { if (error) { if (error != boost::asio::error::eof) return print_asio_error(error); Size_type filesize = file_info_.filesize; if (total_bytes_writen_ != filesize) std::cerr << "Filesize not match! " << total_bytes_writen_ << "/" << filesize << "\n"; return; } total_bytes_writen_ += fwrite(buffer_, 1, bytes_transferred, fp_); receive_file_content(); } clock_t clock_; bi::tcp::socket socket_; FILE *fp_; File_info file_info_; Size_type total_bytes_writen_; static const unsigned k_buffer_size = 1024 * 32; char buffer_[k_buffer_size]; }; } // namespace Prometheus #endif<file_sep>#include <boost/asio.hpp> #include <iostream> using namespace std; using namespace boost::asio; int main() { ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"),1234); io_service iosvc; ip::udp::socket s(iosvc); s.connect(ep); string str = "test"; s.send_to(buffer(str),ep); return 0; }<file_sep>#include "kademliaHost.h" #include "kademlia/kademlia.pb.h" #include "net/Connector.h" #include "tools.h" #include "common.h" #include "session.h" #include <memory> #include <chrono> #include <vector> #include <boost/asio.hpp> using namespace std; namespace Prometheus { /** * @brief 向一个指定的IP地址发送Kademlia的PingPacket,只有一个节点要被踢出列表时才会使用 * @param addr 指定的IP地址 * @param port 指定的端口 */ void KademliaHost::Ping(shared_ptr<NodeInformation> dest) { AlivePeers.emplace(dest); logger.Log(LogLevel::debug,"pinging "+dest->NodeAddress.to_string()+":"+to_string(dest->UDPPort)); PingPacket p; Randomizer r; p.set_random(r.getRandomInt32()); if(shared_ptr<NodeInformation> item = peerTable->LookUpNodeInformation(dest->nodeID); item == nullptr) { dest->Pending = true; PendingNodes.insert(dest); } p.set_nodeid(reinterpret_cast<char*>(MyNodeID.data())); sendbuffer.reserve(512); sendbuffer.clear(); dispacher.makeMessage(p,sendbuffer); bi::udp::endpoint ep(dest->NodeAddress,dest->UDPPort); UDPPacket up(sendbuffer,ep); outQueue.put(up); } /** * @brief 收到PingPacket时的处理函数。 * * @param pp 收到的PingPacket * @param ep 发送方的端点 */ void KademliaHost::onPinging(const shared_ptr<PingPacket>& pp,const bi::udp::endpoint& ep) { string id = char2hex(reinterpret_cast<const unsigned char*>(pp->nodeid().data()),32); logger.Log(LogLevel::debug,"ping packet from"+id+" "+ep.address().to_string()+":"+to_string(ep.port())); //将对方添加进自己的节点列表 NodeID newNodeID = hex2char(id); shared_ptr<NodeInformation> newnode(new NodeInformation(newNodeID,ep.address(),ep.port())); addNode(newnode,false); logger.Log(LogLevel::debug,"sending pingreplypacket to "+ep.address().to_string()+":"+to_string(ep.port())+"\n"); PingReplyPacket p; p.set_random(pp->random()); p.set_nodeid(reinterpret_cast<char*>(MyNodeID.data())); sendbuffer.reserve(512); sendbuffer.clear(); dispacher.makeMessage(p,sendbuffer); UDPPacket up(sendbuffer,ep); outQueue.put(up); } void KademliaHost::onPingingReply(const shared_ptr<PingReplyPacket>& prp, const bi::udp::endpoint& ep) { string id = char2hex(reinterpret_cast<const unsigned char*>(prp->nodeid().data()),32); logger.Log(LogLevel::debug,"pingreply packet from "+id+" "+ep.address().to_string()+":"+to_string(ep.port())); NodeID inconmingID; auto temp = prp->nodeid(); for(int j = 0;j<32;j++) inconmingID[j] = temp[j]; //判断节点是否处于待驱逐列表中 auto iter = NodeToBeEvicted.find(peerTable->LookUpNodeInformation(inconmingID)); if(iter != NodeToBeEvicted.end()) { NodeToBeEvicted.erase(iter); peerTable->addNode(iter->first); } //判断节点是否属于新添加的,还未确认连通的节点列表 for(auto i = PendingNodes.begin();i != PendingNodes.end(); i++) if((*i)->nodeID == inconmingID) { (*i)->Pending = false; peerTable->addNode(*i); i = PendingNodes.erase(i); if(PendingNodes.empty() || i == PendingNodes.end())break; } } //此函数只能在第一轮时调用! void KademliaHost::FindNode(shared_ptr<NodeInformation> node) { auto SendSet = peerTable->LookUpKNearestNodes(node->nodeID); Randomizer r; for(auto i:SendSet) { triedNodes.insert(i); FindNodePacket p; p.set_nodeid(reinterpret_cast<char*>(i->nodeID.data())); p.set_random(r.getRandomInt32()); FindingNode[i]=chrono::steady_clock::now(); vector<char> buffer; buffer.reserve(512); dispacher.makeMessage(p,buffer); bi::udp::endpoint ep(i->NodeAddress,i->UDPPort); UDPPacket packet(buffer,ep); outQueue.put(packet); } } void KademliaHost::onFindNode(const shared_ptr<FindNodePacket>& prp, const bi::udp::endpoint& ep) { string id = prp->nodeid().data(); NodeID nid; Randomizer r; for(int i = 0;i<32;i++) nid[i]=id[i]; vector<shared_ptr<NodeInformation>> result = peerTable->LookUpKNearestNodes(nid); FindNodeReplyPacket p; for(auto i:result) { string tempid = reinterpret_cast<const char*>(i->nodeID.data()); NodeInfo* nodeinfo = p.add_nodelist(); nodeinfo->set_ip(ep.address().to_string()); nodeinfo->set_random(r.getRandomInt32()); nodeinfo->set_port(ep.port()); nodeinfo->set_nodeid(reinterpret_cast<const char*>(i->nodeID.data())); } p.set_random(r.getRandomInt32()); vector<char> buffer; buffer.reserve(512); dispacher.makeMessage(p,buffer); UDPPacket packet(buffer,ep); outQueue.put(packet); } void KademliaHost::onFindNodeReply(const shared_ptr<FindNodeReplyPacket>& fnrp, const bi::udp::endpoint& ep) { //todo:检查这个包的目标节点是不是我们想要的目标节点 Randomizer r; auto nodes = fnrp->nodelist(); NodeID targetid = hex2char(fnrp->target().nodeid()); for(auto i: nodes) { NodeID id = hex2char(i.nodeid().data()); shared_ptr<NodeInformation> newnode(new NodeInformation(id,bi::address::from_string(i.ip()),i.port())); addNode(newnode,true); } CurrentFindNodeRound++; if(CurrentFindNodeRound < MaxFindNodeRound) { int i=0; auto nearests =peerTable->LookUpKNearestNodes(targetid); while(i<alpha) { if(!triedNodes.count(nearests[i])) { FindNodePacket p; p.set_nodeid(char2hex(nearests[i]->nodeID.data(),NodeIDSize)); p.set_random(r.getRandomInt32()); bytes buffer; dispacher.makeMessage(p,buffer); bi::udp::endpoint ep(nearests[i]->NodeAddress,nearests[i]->UDPPort); UDPPacket packet(buffer,ep); outQueue.put(packet); } triedNodes.insert(nearests[i]); } } else { CurrentFindNodeRound = 0; triedNodes.clear(); } } void KademliaHost::checkEvictions() { schedule(EvictionInterval.count(),[this](boost::system::error_code ec){ vector<shared_ptr<NodeInformation>> onEviction; unsigned remainingToEvict = 0; for(auto i: NodeToBeEvicted) { if(chrono::steady_clock::now()-i.second > PendingInterval) { onEviction.push_back(i.first); } } for(auto i:onEviction) { peerTable->deleteNode(i); AlivePeers.erase(i); } remainingToEvict = NodeToBeEvicted.size()-onEviction.size(); if(remainingToEvict) checkEvictions(); }); } void KademliaHost::addNode(std::shared_ptr<NodeInformation> newNode, bool isActive) { //如果已经加入过,那么就只要将它移动到最后面. auto& bucket = peerTable->getBucket(); if(peerTable->LookUpNodeInformation(newNode->nodeID) != nullptr) { peerTable->addNode(newNode); } else { logger.Log(LogLevel::debug,"new node!"); //否则就要加入了 bool isFull = peerTable->isBucketFull(newNode->nodeID); if(isFull) { logger.Log(LogLevel::debug,"bucket full!"); shared_ptr<NodeInformation> leastRecent = peerTable->getLeastRecentNode(newNode->nodeID); Ping(leastRecent); NodeToBeEvicted[leastRecent] = chrono::steady_clock::now(); int evictSize = NodeToBeEvicted.size(); if(evictSize == 1) checkEvictions(); } else{ newNode->Pending=true; //peerTable->addNode(newNode); if(isActive) //如果是传入的包来自新节点,就不需要主动ping了 Ping(newNode); else peerTable->addNode(newNode); } } } void KademliaHost::schedule(unsigned interval, std::function<void(boost::system::error_code const&)> f) { unique_ptr<ba::deadline_timer> t(new ba::deadline_timer(_iosvc)); t->expires_from_now(boost::posix_time::milliseconds(interval)); t->async_wait(f); timers.emplace_back(move(t)); } void KademliaHost::ReceiveFile() { shared_ptr<Session> session = Session::create(TCPconn.get_io_service()); TCPconn.async_accept(session->socket(),std::bind(&KademliaHost::acceptHandler,this,session,std::placeholders::_1)); } void KademliaHost::acceptHandler(shared_ptr<Session> session,boost::system::error_code e) { session->start(); ReceiveFile(); } bool KademliaHost::SendFile(const shared_ptr<NodeInformation> targetnode, const string& filename) { FILE *fp = fopen(filename.c_str(), "rb"); if (fp == NULL) { std::cerr << "cannot open file\n"; return false; } boost::shared_ptr<FILE> file_ptr(fp, fclose); const size_t k_buffer_size = 32 * 1024; char buffer[k_buffer_size]; File_info file_info; int filename_size = filename.length() + 1; size_t file_info_size = sizeof(file_info); size_t total_size = file_info_size + filename_size; if (total_size > k_buffer_size) { std::cerr << "File name is too long"; return false; } file_info.filename_size = filename_size; fseek(fp, 0, SEEK_END); file_info.filesize = ftell(fp); rewind(fp); memcpy(buffer, &file_info, file_info_size); memcpy(buffer + file_info_size, filename.c_str(), filename_size); bi::tcp::socket sock(_iosvc); sock.connect(bi::tcp::endpoint(targetnode->NodeAddress, targetnode->UDPPort)); logger.Log(LogLevel::info,"Sending file: "+filename); size_t len = total_size; unsigned long long total_bytes_read = 0; while (true) { sock.send(ba::buffer(buffer, len), 0); if (feof(fp)) break; len = fread(buffer, 1, k_buffer_size, fp); total_bytes_read += len; logger.Log(LogLevel::info,"percentage: "+to_string(total_bytes_read/total_size)); } return true; } } // namespace Prometheus<file_sep>/** @file Connector.h * @author 郑聪 * @date 2020/04/04 * * This file is part of Prometheus. */ #ifndef _CONNECTOR_H_ #define _CONNECTOR_H_ #include "../tools/Logger.h" #include <boost/asio.hpp> #include <boost/system/error_code.hpp> #include <memory> #include <memory.h> #include "../tools/BlockingQueue.h" #include "../net/MessageDispacher.h" #include <string> #include <array> #include <functional> #include <mutex> #include <kademlia/common.h> namespace Prometheus { /** @brief 对TCP socket的shared_ptr包装 */ /* class TCPConnector : public std::enable_shared_from_this<TCPConnector> { public: TCPConnector(ba::io_service& service): socket_(service),logger() {} ~TCPConnector() { socket_.shutdown(bi::tcp::socket::shutdown_both); if(socket_.is_open()) socket_.close(); } bi::tcp::endpoint getEndpoint(){ boost::system::error_code ec; return socket_.remote_endpoint(ec); } void fileInfoHandler(boost::system::error_code ec, size_t len) { } bi::tcp::socket& get(){ return socket_; } void recv() { socket_.async_receive(ba::buffer(buf),fileInfoHandler); } std::function<void()> onReceiving; private: bi::tcp::socket socket_; std::vector<char> sendbuf; std::mutex x_buf; bi::tcp::endpoint lep; std::array<char,2048> buf; Logger logger_; }; */ struct UDPPacket { UDPPacket(std::vector<char>& content_, const bi::udp::endpoint& endpoint_) :content(content_),_endpoint(endpoint_) { } std::vector<char> content; bi::udp::endpoint _endpoint; }; /** @brief 对UDP的包装,内部有一个接收队列和一个发送队列。 */ class UDPConnector: boost::noncopyable{ public: UDPConnector(BlockingQueue<UDPPacket>& bqin, BlockingQueue<UDPPacket>& bqout,ba::io_service& is,Logger logger,bi::udp::endpoint ep) :inputQueue(bqin),outputQueue(bqout),lep(ep),logger_(logger),s(is) { } void connect() { logger_.Log(LogLevel::trace,"UDPConnector connecting"); s.open(bi::udp::v4()); s.bind(lep); } void registerCallback(std::function<void()> callback) { onReceivingCallback = callback; } void recv() { logger_.Log(LogLevel::trace,"UDPConnector Receiving"); //std::lock_guard<std::mutex> lock(x_buf); s.async_receive_from(ba::buffer(buf,512),lep,[this](boost::system::error_code ec, size_t len){ if(len) { std::vector<char> content(512); ::memcpy(content.data(),buf.data(),512); UDPPacket p(content,lep); outputQueue.put(p); onReceivingCallback(); } recv(); }); } void run() { while(true) { logger_.Log(LogLevel::trace,"UDPConnector running"); UDPPacket p = inputQueue.take(); send(p.content,p._endpoint); } } void send(const std::vector<char>& str,bi::udp::endpoint rep) { logger_.Log(LogLevel::trace,"UDPConnector Sending to"+std::to_string(rep.port())); s.async_send_to(ba::buffer(str),rep,[this](boost::system::error_code ec, size_t len){ }); } private: std::array<char,512> buf; std::vector<char> sendbuf; std::mutex x_buf; std::function<void()> onReceivingCallback; BlockingQueue<UDPPacket>& inputQueue; BlockingQueue<UDPPacket>& outputQueue; bi::udp::endpoint lep; Logger logger_; bi::udp::socket s; }; } // namespace Prometheus #endif<file_sep>cmake_minimum_required(VERSION 3.4.0) INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}") set(CXX_FLAGS -O2 --std=c++17 ) string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CXX_FLAGS}") find_package(Protobuf REQUIRED) if(PROTOBUF_FOUND) message(STATUS "protobuf found.") endif() include_directories(${Protobuf_INCLUDE_DIRS}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(kademlia) add_subdirectory(net) add_subdirectory(tools) add_subdirectory(console) add_executable(kadfiletransporter main.cpp) target_link_libraries( kadfiletransporter PRIVATE kademlia net tools boost_system) <file_sep>/** @file noncopyable.h * @author 郑聪 * @date 2020/3/29 * * This file is part of Prometheus. */ #ifndef _NONCOPYABLE_H_ #define _NONCOPYABLE_H_ namespace Prometheus { /** @brief 实现了不可拷贝的类。所有不允许拷贝的类都应该继承这个类。 */ class noncopyable { public: noncopyable(const noncopyable&) = delete; void operator=(const noncopyable&) = delete; protected: noncopyable() = default; ~noncopyable() = default; }; } // namespace Prometheus #endif<file_sep>#ifndef _H256_H_ #define _H256_H_ #include <crypto++/sha.h> #include <cstdint> #include <algorithm> #include <random> #include <cstdio> #include "tools.h" namespace Prometheus { /** @brief generate random number for SHA256 * **/ class Randomizer{ public: //生成随机的32位正整数 uint32_t getRandomInt32() { std::random_device engine; return (uint32_t)std::uniform_int_distribution<uint32_t>(0,INT_MAX)(engine); } //生成随机的SHA256 std::array<unsigned char,32> getRandomSHA256() { std::random_device engine; std::mt19937 gen(engine()); GenerateRandom(gen); return randomData; } private: std::array<unsigned char,32> randomData; template <class Engine> void GenerateRandom(Engine& _eng) { for(auto& i:randomData) i = (uint8_t)std::uniform_int_distribution<uint16_t>(0, 255)(_eng); //distribution has operator() } }; /** @brief produce random SHA256 for NodeID. * */ class ShaProducer{ public: std::array<unsigned char,32> GetRandomSHA256() { Randomizer r; std::array<unsigned char,32> input = r.getRandomSHA256(); unsigned char output[32]; ctx.CalculateDigest(output,(const byte *)input.data(),input.size()); std::array<unsigned char,32> result; for(int i = 0; i < 31; i++) result[i] = output[i]; return result; } private: CryptoPP::SHA256 ctx; }; std::array<unsigned char,32> operator^(const std::array<unsigned char,32>& lhs,const std::array<unsigned char,32>& rhs); bool operator<(const std::array<unsigned char,32>& lhs,const std::array<unsigned char,32>& rhs); } //namespace Prometheus #endif<file_sep>file(GLOB sources "*.cpp" "*.h") PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS kademlia.proto) add_library(kademlia ${sources} ${PROTO_SRCS} ${PROTO_HDRS}) target_link_libraries(kademlia PUBLIC net tools protobuf pthread) target_include_directories(kademlia SYSTEM PRIVATE ${CRYPTOPP_INCLUDE_DIR})<file_sep>file(GLOB sources "*.cpp" "*.h") add_library(tools ${sources}) target_link_libraries(tools -lpthread)<file_sep>/* This file is part of Prometheus. */ #include "tools.h" #include "h256.h" #include <iostream> namespace Prometheus { /** @brief 将字节流转换为人类可读的十六进制序列 * @param input 指向输入的字节流的字节指针 * @param length 输入的字节流的长度 * @retval 一个字符串,为化为十六进制字符串的字符序列 **/ std::string char2hex(const unsigned char *input, int length) { std::string result; result.reserve(2 * length + 1); int i = 0; unsigned char temp; while(i < length) { temp = input[i] / 16; if(temp < 10) { result.push_back(temp + '0'); } else { result.push_back(temp + 'a' - 10); } temp = input[i] % 16; if(temp < 10) { result.push_back(temp + '0'); } else { result.push_back(temp + 'a' - 10); } i++; } return result; } //输入的十六进制序列的长度必须为64位 NodeID hex2char(const std::string& input) { unsigned length = input.size(); NodeID result; for(int i=0;i<32;i++) { if(input[2*i]>='0' && input[2*i]<='9') result[i] = input[2*i]-'0'; else if(input[2*i]>='a' && input[2*i]<='f') result[i] = input[2*i]-'a'+10; result[i]*=16; if(input[2*i+1]>='0' && input[2*i+1]<='9') result[i] += input[2*i+1]-'0'; else if(input[2*i+1]>='a' && input[2*i+1]<='f') result[i] += input[2*i+1]-'a'+10; } return result; } /** @brief 计算两个NodeID的异或距离,即单个NodeID的位数减去两个NodeID的异或值的前导零的个数。 * @param a 一个NodeID * @param b 另一个NodeID */ size_t xordistance(const NodeID& a,const NodeID& b) { const size_t distanceTable[]={ 8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; NodeID c = a ^ b; size_t result = 256; int i = 0; while(c[i] == 0) { result -= 8; i++; } if (i != 32) result -= distanceTable[c[i]]; return result; } } //namespace Prometheus<file_sep>/** @file ThreadPool.cpp * @author 郑聪 * @date 2020/3/30 * * This file is part of Prometheus. */ #include "ThreadPool.h" #include <string> #include <cstdio> #include <iostream> using namespace std; namespace Prometheus { ThreadPool::ThreadPool(const string& nameArg) : mutex_(), notEmpty(), notFull(), name_(nameArg), maxQueueSize(0), isRunning(false) {} ThreadPool::~ThreadPool() { if(isRunning) { stop(); } } void ThreadPool::start(int numThreads) { isRunning = true; threads.reserve(numThreads); for(int i = 0; i< numThreads; i++) { threads.emplace_back(new thread(std::bind(&ThreadPool::runInThread, this),i)); } if(numThreads == 0 && threadInitCallback) { threadInitCallback(); } } void ThreadPool::stop() { { lock_guard<mutex> lock(mutex_); isRunning = false; notEmpty.notify_all(); } for(auto& t : threads) t->join(); } size_t ThreadPool::queueSize() const { lock_guard<mutex> lock(mutex_); return taskQueue.size(); } void ThreadPool::run(std::function<void()> task) { if(threads.empty()) { task(); } else { unique_lock<mutex> lock(mutex_); while(isFull()) { notFull.wait(lock); } taskQueue.push_back(std::move(task)); notEmpty.notify_one(); } } function<void()> ThreadPool::take() { unique_lock<mutex> lock(mutex_); while(taskQueue.empty() && isRunning) { notEmpty.wait(lock); } function<void()> task; if(!taskQueue.empty()) { task = taskQueue.front(); taskQueue.pop_front(); if(maxQueueSize > 0) { notFull.notify_one(); } } return task; } bool ThreadPool::isFull() const { return maxQueueSize > 0 && taskQueue.size() >= maxQueueSize; } void ThreadPool::runInThread() { try { if(threadInitCallback) { threadInitCallback(); } while(isRunning) { function<void()> task(take()); if(task) { task(); } } } catch(std::exception& e) { fprintf(stderr,"Exception caught in thread pool %s\n reason:%s\n",name_.c_str(),e.what()); } } } // namespace Prometheus <file_sep>/** @file BlockingQueue.h * @author 郑聪 * @date 2020/03/26 * 实现了基本的阻塞队列。 */ #ifndef _BLOCKING_QUEUE_H_ #define _BLOCKING_QUEUE_H_ #include <condition_variable> #include <mutex> #include <deque> #include "noncopyable.h" namespace Prometheus { /** @brief 实现了基本的阻塞队列。 * 有以下的一些操作: * put(T&)和put(T&&):向队列中添加一个元素。 * take():取出队列中的一个元素。 * size():获得队列的元素个数。 */ template<class T> class BlockingQueue : public noncopyable { public: BlockingQueue() : mutex_(),notEmpty_(),queue() {} ///<向队列中原子地添加一个元素。 void put(const T& x) { std::lock_guard<std::mutex> lock(mutex_); queue.push_back(x); notEmpty_.notify_one(); } ///<向队列中原子地添加一个元素。 void put(T&& x) { std::scoped_lock lock(mutex_); queue.push_back(std::move(x)); notEmpty_.notify_one(); } ///<从队列中原子地取一个元素。如果队列为空则阻塞。 T take() { std::unique_lock<std::mutex> lock(mutex_); while(queue.empty()) { notEmpty_.wait(lock); } T front(std::move(queue.front())); queue.pop_front(); return front; } ///<获得队列的长度。 size_t size() const { std::lock_guard<std::mutex> lock(mutex_); return queue.size(); } private: mutable std::mutex mutex_; std::condition_variable notEmpty_; std::deque<T> queue; }; } //namespace Prometheus #endif<file_sep>/** @file MessageDispacher.h * @author 郑聪 * @date 2020/04/12 * * This file is part of Prometheus. */ #ifndef _MESSAGE_DISPACHER_H_ #define _MESSAGE_DISPACHER_H_ #include <google/protobuf/message.h> #include "tools/noncopyable.h" #include <boost/asio.hpp> #include <memory> #include <map> #include <functional> #include <string> #include <vector> #include <type_traits> #include <iostream> namespace Prometheus{ /** @brief 从一个地址读入32位数据,并且将字节序从网络字节序转换为本机字节序 * @param p 指向32位数据的指针 */ inline int32_t getInt32(int32_t *p) { return be32toh(*p); } /** @brief 向指定的地址写入一个网络字节序的32位数据 * @param p 写入数据的地址 * @param num 想要写入的数 */ inline void writeInt32(int32_t *p, int32_t num) { *p=htobe32(num); } //为了实现针对不同类型的消息调用不同的回调,设置的接口 class BaseCallback:noncopyable { public: virtual void onMessage(const std::shared_ptr<google::protobuf::Message>& message, const boost::asio::ip::udp::endpoint& ep) const = 0; virtual ~BaseCallback() = default; }; template<class T> class ConcreteCallback:public BaseCallback { public: ConcreteCallback(std::function<void(const std::shared_ptr<T>&, const boost::asio::ip::udp::endpoint&)> _callback) :callback(_callback) {} void onMessage(const std::shared_ptr<google::protobuf::Message>& message, const boost::asio::ip::udp::endpoint& ep) const { std::shared_ptr<T> concreteMessage = std::dynamic_pointer_cast<T>(message); callback(concreteMessage,ep); } private: std::function<void(const std::shared_ptr<T>& message,const boost::asio::ip::udp::endpoint&)> callback; }; /** @brief protobuf消息分发器 * 将从网络上收到的protobuf格式消息根据头部的消息类型构造对象,并发送给对应的回调函数。 * 原理:protobuf生成的消息类中,有一个全局唯一的descriptor.将其和对应的回调函数绑定,组成一个map, * 就可以动态地分发消息了。 * * 消息格式:0~3字节:消息总长度lenm * 4~7字节:消息类型长度lent * 8~lent+7字节:消息类型 * lent+8~lenm-1字节:消息内容 * */ class MessageDispacher{ public: //构造函数,传入的函数用来处理找不到消息的缺省情况 MessageDispacher(std::function<void(const std::shared_ptr<google::protobuf::Message>&,const boost::asio::ip::udp::endpoint&) >& _default) :defaultCallback(_default) {} MessageDispacher(std::function<void(const std::shared_ptr<google::protobuf::Message>&, const boost::asio::ip::udp::endpoint&)>&& _default) :defaultCallback(_default) {} /** @brief 当收到消息时调用,将会把字节流对象通过protobuf自带的反射机制变为一个对应类型的message对象,并调用消息类型对应的回调函数。 * @param m 传入的字节流 * @param ep 消息发送方的端点 */ void onMessage(const std::vector<char>& m,const boost::asio::ip::udp::endpoint& ep) { std::shared_ptr<google::protobuf::Message> messagePtr; const char *begin = m.data(); int32_t namelen = getInt32((int32_t*)begin); int32_t len = getInt32((int32_t*)(begin+4)); std::string name(begin+8,begin+8+namelen-1); //8指len和namelen所占的字节数 //从protobuf的类型名构造一个该类型对应的消息 google::protobuf::Message* message = nullptr; const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(name); if(descriptor) { const google::protobuf::Message* prototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor); if(prototype) { message = prototype->New(); } } messagePtr.reset(message); //向构造的消息中填充内容并调用对应的回调函数 if(message) { message->ParseFromArray(begin+8+namelen,len-namelen-8); auto callbackiter = callbackMap.find(message->GetDescriptor()); if(callbackiter != callbackMap.end()) callbackiter->second->onMessage(messagePtr,ep); else this->defaultCallback(messagePtr,ep); } } /** @brief 将一个message对象序列化后进行必要的类型说明和打包,并生成字节流。 * @param message 待序列化的message对象 * @param result 生成的字节流对象 */ void makeMessage(const google::protobuf::Message& message, std::vector<char>& result) { try{ const std::string& name = message.GetDescriptor()->full_name(); int32_t lent = static_cast<int32_t>(name.size()+1); int32_t lenm = lent+static_cast<int32_t>(message.ByteSize())+2*sizeof(lent); result.reserve(lenm); char *begin = new char[lenm+1]; memset(begin,0,sizeof(begin)); writeInt32((int32_t*)begin,lent); writeInt32((int32_t*)(begin+4),lenm); memcpy(begin+8,name.c_str(),name.length()+1); message.SerializeWithCachedSizesToArray((uint8_t*)begin+8+lent); for(int i = 0;i<lenm;i++) result.push_back(begin[i]); delete[] begin; }catch(std::exception &e){ std::cout<<e.what()<<std::endl; } } /** @brief 注册一个消息类型对应的回调函数。 * @param _callback 一个类型消息的回调函数。 * 输入的回调函数要求具有以下的两个参数: * 一个指向消息的shared_ptr,和消息发送方的端点。 */ template <class T> void registerCallback(std::function<void(const std::shared_ptr<T>&,const boost::asio::ip::udp::endpoint&)>& _callback) { std::shared_ptr<ConcreteCallback<T>> cb(new ConcreteCallback<T>(_callback)); callbackMap[T::descriptor()] = cb; } private: //消息类型的描述符及对应回调函数的映射 std::map<const google::protobuf::Descriptor*,std::shared_ptr<BaseCallback>> callbackMap; //默认的回调函数,处理找不到对应类型消息的情况 std::function<void(const std::shared_ptr<google::protobuf::Message>&,const boost::asio::ip::udp::endpoint&)> defaultCallback; }; } //namespace Prometheus #endif<file_sep>#include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/un.h> #include <unistd.h> #include <memory> #include <vector> #include <kademlia/common.h> #include <kademlia/kademliaHost.h> #include <boost/asio.hpp> #include <tools/Logger.h> #define SERV_PORT 3000 #define MAXLINE 4096 namespace Prometheus { class rpcHost { public: rpcHost(std::shared_ptr<KademliaHost> host, Logger &l) : kadhost(host), logger(l) {} void run() { int socket_fd, connect_fd; pid_t pid; char *path = "console.ipc"; struct sockaddr_un servaddr; /* 服务器端网络地址结构体 */ char buf[MAXLINE], sendbuf[MAXLINE]; memset(buf, 0, sizeof(buf)); int len; /*创建服务器端套接字--IPv4协议,面向连接通信,TCP协议*/ if ((socket_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { printf("create socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } /*初始化*/ memset(&servaddr, 0, sizeof(servaddr)); /*数据初始化-清零 */ servaddr.sun_family = AF_UNIX; /*设置IPv4通信*/ strcpy(servaddr.sun_path, path); /*设置unix域文件名*/ /*将本地地址绑定到所创建的套接字上*/ if (bind(socket_fd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } /*开始监听是否有客户端连接*/ if (listen(socket_fd, 10) < 0) { printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } printf("waiting for client's connection......\n"); while (true) { /*阻塞直到有客户端连接,不然多浪费CPU资源*/ if ((connect_fd = accept(socket_fd, (struct sockaddr *)NULL, NULL)) < 0) { printf("accept socket error: %s(errno: %d)", strerror(errno), errno); exit(1); } pid = fork(); if (pid == 0) { /*接受客户端传过来的数据*/ while (1) { if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len] = '\0'; /*向客户端发送回应数据*/ //printf("receive message from client: %s\n", buf); std::string choice(buf); std::string nodeID; std::string nodeAddress; uint16_t udpPort; choice.pop_back(); //printf("send message to client: \n"); if (choice == "SendFile") { std::string filePath; printf("SendFile processed\n"); //向客户端请求NodeId sprintf(sendbuf, "Please input NodeId:"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len] = '\0'; printf("NodeId:%s", buf); nodeID = std::string(buf); memset(buf, 0, sizeof(buf)); } sprintf(sendbuf, "Please input filepath:"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len - 1] = '\0'; printf("filePath:%s", buf); } filePath = std::string(buf); memset(buf, 0, sizeof(buf)); NodeID id = hex2char(nodeID); std::shared_ptr<NodeInformation> tmp = kadhost->LookUpNodeInformation(id); if (tmp == nullptr) { sprintf(sendbuf, "Node doesn't exist!\n"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } } else { bool result = kadhost->SendFile(tmp, filePath); if (result == true) { sprintf(sendbuf, "File sent successfully.\n"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } } } } else if (choice == "addNode") { //向客户端请求NodeId sprintf(sendbuf, "Please input NodeId:"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len] = '\0'; printf("NodeId:%s", buf); nodeID = std::string(buf); memset(buf, 0, sizeof(buf)); } //向客户端请求NodeAddress sprintf(sendbuf, "Please input nodeAddress:"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len] = '\0'; printf("NodeAddress:%s", buf); nodeAddress = std::string(buf); memset(buf, 0, sizeof(buf)); } //向客户端请求UDPPort sprintf(sendbuf, "Please input UDPPort:"); if (send(connect_fd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send messaeg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if ((len = recv(connect_fd, buf, MAXLINE, 0)) > 0) { buf[len] = '\0'; printf("UDPPort:%s", buf); udpPort = std::stoi(std::string(buf)); memset(buf, 0, sizeof(buf)); } printf("addNode processed\n"); NodeID id = hex2char(nodeID); NodeInformation *tmp = new NodeInformation(id, bi::address::from_string(nodeAddress), udpPort); kadhost->addNode(std::make_shared<NodeInformation>(*tmp)); } else { printf("wrong choice\n"); //printf("%s", choice.c_str()); } } sprintf(sendbuf, "Please input your choice:\n"); send(connect_fd, sendbuf, strlen(sendbuf), 0); } close(connect_fd); close(socket_fd); return; } } } private: std::shared_ptr<KademliaHost> kadhost; Logger logger; }; // namespace Prometheus } //namespace Prometheus <file_sep>file(GLOB sources "*.cpp" "*.h") add_executable(rpcclient ${sources})<file_sep>#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/un.h> #include <unistd.h> #include <netinet/in.h> #include <errno.h> #include <stdlib.h> #define MAXLINE 1024 int main(int argc, char *argv[]) { char sendbuf[MAXLINE], receivebuf[MAXLINE]; char *path = "console.ipc"; struct sockaddr_un servaddr; int client_sockfd; int rec_len; int exit_flag = 0; /* 创建客户端套接字--UNIX域套接字,面向连接通信*/ if ((client_sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(0); } /* 初始化 */ memset(&servaddr, 0, sizeof(servaddr)); /* 数据初始化-清零 */ servaddr.sun_family = AF_UNIX; /* 设置UNIX域通信 */ strcpy(servaddr.sun_path,path); /* 设置套接字文件名 */ /* 将套接字绑定到服务器的网络地址上*/ if (connect(client_sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("connected failed"); exit(0); } /* 循环发送接收数据,send发送数据,recv接收数据 */ printf("Please input your choice\n>>"); while (1) { memset(sendbuf,0,sizeof(sendbuf)); fgets(sendbuf, 1024, stdin); /* 向服务器端发送数据 */ if(!strcmp(sendbuf,"exit\n")) { close(client_sockfd); return 0; } if (send(client_sockfd, sendbuf, strlen(sendbuf), 0) < 0) { printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } if(exit_flag == 1) { } /* 接受服务器端传过来的数据 */ if ((rec_len = recv(client_sockfd, receivebuf, MAXLINE, 0)) == -1) { perror("recv error"); exit(1); } receivebuf[rec_len] = '\0'; printf("%s\n>>", receivebuf); } /* 关闭套接字 */ close(client_sockfd); return 0; } <file_sep>#include "h256.h" #include <array> namespace Prometheus { std::array<unsigned char,32> operator^(const std::array<unsigned char,32>& lhs, const std::array<unsigned char,32>& rhs) { std::array<unsigned char,32> result; for(int i = 0; i < 32; i++) result[i] = lhs[i] ^ rhs[i]; return result; } bool operator<(const std::array<unsigned char,32>& lhs,const std::array<unsigned char,32>& rhs) { bool flag = false; for(int i=0;i<32;i++) { if(lhs[i]<rhs[i]) { flag = true; break; } } return flag; } } //namespace Prometheus<file_sep>#include "tools/Logger.h" #include <string> #include "tools/ThreadPool.h" #include <functional> #include <iostream> using namespace Prometheus; using namespace std; class LoggerTest { public: LoggerTest(const string& name): _name(name),logger(name) {} void run() { cout<<"LoggerTest is being run\n"; log(); } void log() { logger.SetLevel(LogLevel::trace); while(true){ logger.Log(LogLevel::trace,"this is a debug message from " + _name); logger.Log(LogLevel::debug,"this is a debug message from " + _name); logger.Log(LogLevel::warn,"this is a warn message from " + _name); logger.Log(LogLevel::error,"this is a error message from " + _name); logger.Log(LogLevel::critical,"this is a critical message from " + _name); logger.Log(LogLevel::info,"this is a info message from " + _name); sleep(1); } } private: string _name; Logger logger; }; int main() { ThreadPool tp("this is a thread poooooool"); LoggerTest lg1("thread1"); LoggerTest lg2("thread2"); LoggerTest lg3("thread3"); LoggerTest lg4("thread4"); LoggerTest lg5("thread5"); LoggerTest lg6("thread6"); tp.start(6); tp.run(std::bind(&LoggerTest::run,&lg1)); tp.run(std::bind(&LoggerTest::run,&lg2)); tp.run(std::bind(&LoggerTest::run,&lg3)); tp.run(std::bind(&LoggerTest::run,&lg4)); tp.run(std::bind(&LoggerTest::run,&lg5)); tp.run(std::bind(&LoggerTest::run,&lg6)); }
844994ceec8d46243929dcec2135505469800bc9
[ "Markdown", "CMake", "C++" ]
40
C++
iodinetech/PrometheusMain
e4abf5e57a967a2ce7fc4043da01ad11836bd5d3
691957e3a2935b1abeb760e606a06fbc08ab151b
refs/heads/master
<repo_name>SenhorPavan/CadastroBanco<file_sep>/src/View/TelaCadastro.java package View; import DAO.UsuarioDAO; import Models.Usuario; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import projetobanco.ProjetoBanco; public class TelaCadastro extends javax.swing.JFrame { /** * Creates new form TelaCadastro */ public TelaCadastro() { initComponents(); carregarCampos(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); tfdNome = new javax.swing.JTextField(); tfdData = new javax.swing.JTextField(); cbxGenero = new javax.swing.JComboBox<>(); tfdEmail = new javax.swing.JTextField(); tfdSenha = new javax.swing.JPasswordField(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); tabela = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); tfdConfirmarSenha = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cadastro de Usuários"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("Cadastro de Usuário"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Nome:"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("E-mail:"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Senha:"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel6.setText("Data Nascimento"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel7.setText("Gênero"); tfdNome.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N tfdData.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N cbxGenero.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N cbxGenero.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Masculino", "Feminino" })); tfdEmail.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N tfdSenha.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N tabela.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Nome", "E-mail", "Gênero", "Data Nascimento" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tabela); if (tabela.getColumnModel().getColumnCount() > 0) { tabela.getColumnModel().getColumn(1).setResizable(false); } jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("CADASTRAR"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); tfdConfirmarSenha.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Confirmar Senha: "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfdNome, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfdData, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(cbxGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfdEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(tfdConfirmarSenha, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfdSenha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel3))))) .addGroup(layout.createSequentialGroup() .addGap(185, 185, 185) .addComponent(jLabel1))) .addContainerGap(37, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cbxGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfdNome, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfdData, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfdEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfdSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addGap(4, 4, 4) .addComponent(tfdConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(54, 54, 54)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String nome = tfdNome.getText(); String email = tfdEmail.getText(); String data = tfdData.getText(); String senha = tfdSenha.getText(); String confirmaSenha = tfdConfirmarSenha.getText(); String genero = cbxGenero.getSelectedItem().toString(); Date dataNasci = null; try { dataNasci = new SimpleDateFormat("dd/MM/yyyy").parse(data); } catch (ParseException erro) { System.out.println("NÃO FOI POSSÍVEL CONVERTER DATA"); } if (senha.equals(confirmaSenha)) { Usuario p1 = new Usuario(nome, email, senha, genero, dataNasci); int codigo = UsuarioDAO.InserirUsuarioDB(p1); if (codigo == 0) { JOptionPane.showMessageDialog(null, "NÃO FOI POSSÍVEL CADASTRAR O USUÁRIO"); } else { JOptionPane.showMessageDialog(null, "USUÁRIO CADASTRADO COM SUCESSO"); AdicionarLinhaTabela(p1); LimparCampos(); } } else { JOptionPane.showMessageDialog(null, "SENHA INCORRETA"); } }//GEN-LAST:event_jButton1ActionPerformed public void LimparCampos() { tfdNome.setText(""); tfdEmail.setText(""); tfdData.setText(""); tfdSenha.setText(""); tfdConfirmarSenha.setText(""); } public void carregarCampos() { ProjetoBanco.listaUsuario = UsuarioDAO.BuscarUsuarios(); DefaultTableModel tabela = (DefaultTableModel) this.tabela.getModel(); for (int i = 0; i < ProjetoBanco.listaUsuario.size(); i++) { Object[] dado = { ProjetoBanco.listaUsuario.get(i).getCodigo(), ProjetoBanco.listaUsuario.get(i).getNome(), ProjetoBanco.listaUsuario.get(i).getEmail(), ProjetoBanco.listaUsuario.get(i).getGenero(), ProjetoBanco.listaUsuario.get(i).getData_nascimento(),}; tabela.addRow(dado); } } public void AdicionarLinhaTabela(Usuario usuario) { DefaultTableModel tabela = (DefaultTableModel) this.tabela.getModel(); java.sql.Date dataFormatada = new java.sql.Date(usuario.getData_nascimento().getTime()); Object[] dado = { usuario.getCodigo(), usuario.getNome(), usuario.getEmail(), usuario.getGenero(), dataFormatada}; tabela.addRow(dado); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaCadastro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cbxGenero; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTable tabela; private javax.swing.JPasswordField tfdConfirmarSenha; private javax.swing.JTextField tfdData; private javax.swing.JTextField tfdEmail; private javax.swing.JTextField tfdNome; private javax.swing.JPasswordField tfdSenha; // End of variables declaration//GEN-END:variables }
bf3d6b8600faccd89c9b1e1d55773d872147e4ba
[ "Java" ]
1
Java
SenhorPavan/CadastroBanco
1468ad814d2d330503e5de13285592a988a2e7f5
4a503b9d99e0a52850f9c972d3363fb2c6a97693
refs/heads/master
<file_sep>tutorial_osx ============ Hello swift <file_sep>// // AppDelegate.swift // Lession 62 // // Created by Astin on 12/23/14. // Copyright (c) 2014 Astin. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
22dd629c8c0a804cba005a7bbc5862e294c37ec2
[ "Markdown", "Swift" ]
2
Markdown
AstinCHOI/tutorial_osx
d3d1cb72ed45cb3d92c528fd70b8b72d07158129
e73596b6e08557150f93be2f0951f99ce9c12a96
refs/heads/master
<repo_name>erinabbey/techshop<file_sep>/src/component/Cart/Cart.jsx import React from 'react' import {Container, Typography, Button, Grid} from '@material-ui/core' import useStyles from './style' import CartItem from './CartItem/CartItem' import {Link} from 'react-router-dom' const Cart = ({cart, handleUpdateCartQty, handleRemove, onEmptyCart }) => { const classes = useStyles() // const isEmpty = !cart.line_items.length const handleEmptyCart = () => onEmptyCart(); const renderEmptyCart = () =>{ <Typography variant = "subtitle1">You have no items in your shopping cart, start adding some <Link to = "/" className = {classes.link}>start adding some</Link> </Typography> } const FilledCart = () =>{ return( <> <Grid container spacing = {3}> {cart.line_items.map((item) =>( <Grid item xs={12} sm = {4} key = {item.id}> <CartItem item = {item} onUpdateCartQty = {handleUpdateCartQty} onRemoveFromCart = {handleRemove}></CartItem> </Grid> ))} </Grid> <div className = {classes.cartDetails}> <Typography variant = "h4"> Subtotal : {cart.subtotal.formatted_with_symbol}</Typography> <div> <Button className = {classes.emptyButton} size = "large" type = "button" variant = "container" color = "secondary" onClick = {handleEmptyCart}> Empty cart </Button> <Button component = {Link} to = "/checkout" className = {classes.checkoutButton} size = "large" type = "button" variant = "container" color = "primary"> Check out </Button> </div> </div> </>) } if(!cart.line_items) return 'Loading...' return ( <Container > <div className = {classes.toolbar}> </div> <Typography className = {classes.title} variant = 'h4'>Shopping cart</Typography> {!cart.line_items.length ? renderEmptyCart():FilledCart()} </Container> ) } export default Cart <file_sep>/src/component/Products/Products.jsx import {Grid} from '@material-ui/core' import React from 'react' import Product from './Product/Product' import useStyle from './style' // const products = [ // {id: 1, name: 'Headphone', description: 'High quality' , price :'$19.99', image: 'https://unsplash.com/photos/NehdOHCXsjs',}, // {id: 2, name: 'Ipod', description: 'High quality', price :'$39.99' , image:'https://unsplash.com/photos/UI0KhU_Khhw',}, // {id: 3, name: 'Speaker', description: 'High quality', price :'$29.99', image:'https://unsplash.com/photos/eMw1fBx4_Wk', }, // ] const Products = ({products, onAddToCart}) =>{ const classes = useStyle() if (!products.length) return <p>Loading...</p>; return( <main className = {classes.content}> <div className = {classes.toolbar}/> <Grid container justify = 'center' spacing = {4}> {products.map((product)=>( <Grid key ={product.id} xs = {12} sm ={6} md = {4} lg = {3}> <Product product = {product} onAddToCart = {onAddToCart}/> </Grid> ))} </Grid> </main> ) } export default Products<file_sep>/src/component/CheckoutForm/AddressForm.jsx import React, {useState, useEffect} from 'react' import {InputLabel, MenuItem, Select, Button, Typography, Grid} from '@material-ui/core' import {useForm, FormProvider} from 'react-hook-form' import FormInput from "./CustomTextField" import {commerce} from '../../lib/commerce' import {Link} from 'react-router-dom' import './AddressFormStyle.css' const AddressForm = ({checkoutToken, next}) => { const methods = useForm() const [shippingCountries, setShippingCountries] = useState([]) const [shippingCountry, setShippingCountry] = useState('') const [shippingSubdivisions, setShippingSubdivisions] = useState([]) const [shippingSubdivision, setShippingSubdivision] = useState('') const [shippingOptions, setShippingOptions] = useState([]) const [shippingOption, setShippingOption] = useState('') const fetchShippingCountries = async(checkoutTokenID)=>{ const {countries} = await commerce.services.localeListShippingCountries(checkoutTokenID) // console.log(countries) setShippingCountries(countries) setShippingCountry(Object.keys(countries)[0]) } const countries = Object.entries(shippingCountries).map(([code, name]) =>({id: code, label: name})) const subdivisions = Object.entries(shippingSubdivisions).map(([code, name]) =>({id: code, label: name})) const options = shippingOptions.map((s0) => ({id: s0.id, label: `${s0.description} - (${s0.price.formatted_with_symbol})`})) const fetchSubdivisions = async(countryCode) =>{ const {subdivisions} = await commerce.services.localeListSubdivisions(countryCode) setShippingSubdivisions(subdivisions) setShippingSubdivision(Object.keys(subdivisions)[0]) } const fetchShippingOptions = async(checkoutTokenId, country, region = null) =>{ const options = await commerce.checkout.getShippingOptions(checkoutTokenId, {country, region} ) setShippingOptions(options) setShippingOption(options[0].id) } useEffect(() =>{ fetchShippingCountries(checkoutToken.id) }, []) // when country change useEffect(() =>{ if(shippingCountry) fetchSubdivisions(shippingCountry) }, [shippingCountry]) useEffect(() =>{ if(shippingSubdivision) fetchShippingOptions(checkoutToken.id, shippingCountry, shippingSubdivision) }, [shippingSubdivision]) return ( <> <Typography variant = "h6" gutterBottom>Shipping Address</Typography> <FormProvider {...methods}> <div className ="container"> <form onSubmit = {methods.handleSubmit((data) => next({...data, shippingCountry, shippingSubdivision, shippingOption}))} > <Grid item container spacing = {3}> <div className = 'omrs-input-group'> <label for="name" className="omrs-input-underlined"/> <input name = "firstName" label = "First Name" required/> <span className="omrs-input-label">First name</span> <label for="name" className="omrs-input-underlined"/> <input name = "lastName" label = "Last Name" required/> <span className="omrs-input-label">Last name</span> <label for="name" className="omrs-input-underlined"/> <input name = "address1" label = "Address" required/> <span className="omrs-input-label">Address</span> <label for="name" className="omrs-input-underlined"/> <input name = "email" label = "Email" required/> <span className="omrs-input-label">Email</span> <label for="name" className="omrs-input-underlined"/> <input name = "city" label = "City" required/> <span className="omrs-input-label">City</span> <label for="name" className="omrs-input-underlined"/> <input name = "zip" label = "ZIP/Postal code" required/> <span className="omrs-input-label">ZIP/Postal code</span> </div> <Grid item xs = {12} sm = {6}> <InputLabel>Shipping Address </InputLabel> <Select value = {shippingCountry} fullWidth onChange = {(e) => setShippingCountry(e.target.value)}> {countries.map((country) =>( <MenuItem key = {country.id} value = {country.id}> {country.label} </MenuItem> ))} </Select> </Grid> <Grid item xs = {12} sm = {6}> <InputLabel>Shipping Subdivision </InputLabel> <Select value = {shippingSubdivision} fullWidth onChange = {(e) => setShippingSubdivision(e.target.value)}> {subdivisions.map((subdivision) =>( <MenuItem key ={subdivision.id} value = {subdivision.id}> {subdivision.label} </MenuItem> ))} </Select> </Grid> <Grid item xs = {12} sm = {6}> <InputLabel>Shipping Options </InputLabel> <Select value = {shippingOption} fullWidth onChange = {(e) => setShippingOptions(e.target.value)}> {options.map((option) => ( <MenuItem key ={option.id} value = {option.id}> {option.label} </MenuItem> ))} </Select> </Grid> </Grid> <br/> <div style = {{display: 'flex', justifyContent: 'space-between'}}> <Button component = {Link} to ="/cart" variant = 'outlined'>Back to cart</Button> <Button type = 'submit' color = 'primary' variant = 'contained'>Next</Button> </div> </form> </div> </FormProvider> </> ) } export default AddressForm <file_sep>/src/component/Products/Product/Product.jsx import React from 'react' import {Card, CardMedia, CardContent, CardActions, Typography, IconButton} from '@material-ui/core' import {AddShoppingCart} from '@material-ui/icons' import useStyles from './style' const Product = ({product, onAddToCart}) => { const classes = useStyles() const handleAddToCart = () => onAddToCart(product.id, 1) // const url = product.media_url.replace(/^https?:/, ''); return ( <Card className = {classes.root}> <CardMedia className = {classes.media} image = {product.media.source} title = {product.name}/> <CardContent> <div className = {classes.cardContent}> <Typography variant = 'h5' gutterBottom component = "h2"> {product.name} </Typography> <Typography variant = 'h5' gutterBottom compoennt = "h2"> ${product.price.formatted} </Typography> </div> <Typography dangerouslySetInnerHTML = {{__html: product.description}} variant ='body2' color='textSecondary' component = "p"></Typography> </CardContent> <CardActions disableSpacing className = {classes.cardActions}> <IconButton arial-label = 'Add to cart' onClick = {handleAddToCart}> <AddShoppingCart/> </IconButton> </CardActions> </Card> ) } export default Product
698cdf46d78370f8720c89cfc0c0df1a87314484
[ "JavaScript" ]
4
JavaScript
erinabbey/techshop
a39309fa882997db577724a2f3555d4cac09f150
607b20dd56a694e305a2dfdff582eacbbc2b2027
refs/heads/master
<file_sep># recon by omethasan <file_sep>#!/bin/sh red="`tput setaf 1`" norm="`tput sgr0`" bold="`tput bold`" green="`tput setaf 2`" echo " ___ ___ __ _____ __ " echo " / _ \___ ___/ (_)______ ____/ /_ / __(_)__ ___/ /__ ____" echo "${red}${bold} / , _/ -_) _ / / __/ -_) __/ __/ / _// / _ \/ _ / -_) __/${norm}" echo "/_/|_|\__/\_,_/_/_/ \__/\__/\__/ /_/ /_/_//_/\_,_/\__/_/ " echo echo " [+] by ${bold}@Prial261${norm}" echo " [+] Usage:" echo " $ comb subdomains.txt payload.txt > urls.txt" echo " $./redirect.sh urls.txt" echo filename=$1 while read urls; do echo "${red}${bold}Testing ==>${green} $urls ${norm}" echo curl -I -s $urls | grep -i -E "http://google.com|https://google.com|http://www.google.com|https://www.google.com|https://https:/google.com|http://1572395042|https://1572395042|http://;@www.google.com|https://;@www.google.com|http://@google.com|https://@google.com|http://https:/www.google.com/|https://https:/www.google.com/|Location: //google.com|//google.com..|location: //" echo "${red}[+] Done [+]${norm}" done < $filename
cef0a58b0da2ce9947118288ad942e6e1e53f0e3
[ "Markdown", "Shell" ]
2
Markdown
donomethasan/recon
93548553f06cc716fd4ffc6730dbe3a37d1bcc63
34cec064cf3ee0a5909339644518a5a05b0f26b4
refs/heads/master
<file_sep>from rest_framework import serializers from like.models import Like from .models import Post from django.db.models import Sum class PostSerializer(serializers.ModelSerializer): like = serializers.SerializerMethodField() def get_like(self, obj): if type(obj) is Post: if obj._meta is Post._meta: liked = Like.objects.filter(post_id=obj.id, value=1).aggregate(Sum('value'))['value__sum'] dislike = Like.objects.filter(post_id=obj.id, value=-1).aggregate(Sum('value'))['value__sum'] liked = liked if liked else 0 dislike = dislike if dislike else 0 return {'liked': liked, 'disLiked': dislike} return {'liked': 0, 'disLiked': 0} def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.body = validated_data.get('body', instance.body) instance.save() return instance class Meta: model = Post fields = '__all__' <file_sep>from django.db.models import Q from accounts.models import User from accounts.serializers import UserSerializer from chanel.models import Chanel from django.http import JsonResponse from rest_framework.status import HTTP_200_OK from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from chanel.serializers import ChanelSerializer from posts.models import Post from posts.serializers import PostSerializer class Search(APIView): permission_classes = (IsAuthenticated,) def post(self, request): body = request.data.get('body') result = {} post_records = Post.objects.filter(Q(title__icontains=body) | Q(body__icontains=body)) result['post'] = PostSerializer(post_records, many=True).data chanel_records = Chanel.objects.filter(Q(description__icontains=body) | Q(identifier__icontains=body)) result['chanel'] = ChanelSerializer(chanel_records, many=True).data user_records = User.objects.filter(Q(first_name__icontains=body) | Q(last_name__icontains=body) | Q(email__icontains=body) | Q(username__icontains=body)) result['user'] = UserSerializer(user_records, many=True).data return JsonResponse(data={'data': result, 'success': True}, status=HTTP_200_OK) <file_sep>from rest_framework import serializers from .models import Chanel, Follow from accounts.serializers import UserSerializer class ChanelSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) author = UserSerializer(read_only=True, many=True) def update(self, instance, validated_data): instance.description = validated_data.get('description', instance.description) instance.identifier = validated_data.get('identifier', instance.identifier) instance.law = validated_data.get('law', instance.law) instance.title = validated_data.get('title', instance.title) instance.save() return instance class Meta: model = Chanel fields = '__all__' class FollowSerializer(serializers.ModelSerializer): def to_representation(self, instance): ret = super(FollowSerializer, self).to_representation(instance) ret['chanel'] = {'identifier': instance.chanel.identifier, 'id':instance.chanel.id} return ret class Meta: model = Follow fields = '__all__' <file_sep># Generated by Django 3.0.2 on 2020-02-03 20:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chanel', '0002_follow'), ] operations = [ migrations.AddField( model_name='chanel', name='law', field=models.TextField(max_length=2000, null=True), ), ] <file_sep>from django.urls import path from .views import Comments urlpatterns = [ path('', Comments.as_view()), path('update/<int:pk>', Comments.as_view()), path('delete/<int:pk>', Comments.as_view()), path('post/<int:post_id>', Comments.as_view()), ] <file_sep>from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self, first_name, last_name, phone_number, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.first_name = first_name user.username = username user.last_name = last_name user.phone_number = phone_number user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, phone_number, email, password): user = self.create_user( email=email, first_name=first_name, last_name=last_name, phone_number=phone_number, password=<PASSWORD>, ) user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( max_length=255, unique=True, ) username = models.CharField(max_length=200, unique=True) active = models.BooleanField(default=True) admin = models.BooleanField(default=False) # a superuser first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=13, unique=True) city = models.CharField(max_length=30, null=True) country = models.CharField(max_length=30, null=True) picture = models.ImageField(upload_to='profile/', max_length=1000, null=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number'] def get_full_name(self): return str(self.first_name) + ' ' + str(self.last_name) def get_username(self): return self.username def __str__(self): return self.get_full_name() # def has_perm(self, perm, obj=None): # """Does the user have a specific permission?""" # return True objects = UserManager() <file_sep># Generated by Django 3.0.2 on 2020-02-01 14:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('email', models.EmailField(max_length=255, unique=True)), ('active', models.BooleanField(default=True)), ('admin', models.BooleanField(default=False)), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=100)), ('point', models.IntegerField(default=0)), ('phone_number', models.CharField(max_length=13, unique=True)), ('city', models.CharField(max_length=30, null=True)), ('country', models.CharField(max_length=30, null=True)), ('picture', models.ImageField(max_length=1000, upload_to='')), ], options={ 'abstract': False, }, ), ] <file_sep># Generated by Django 3.0.2 on 2020-02-02 11:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0002_auto_20200202_0027'), ('comment', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='comment', name='is_post', ), migrations.AlterField( model_name='comment', name='comment', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='for_comment', to='comment.Comment'), ), migrations.AlterField( model_name='comment', name='post', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.Post'), ), ] <file_sep>from rest_framework import serializers from .models import Notify from accounts.serializers import UserSerializer class NotifySerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Notify fields = '__all__' <file_sep>from django.http import JsonResponse from rest_framework.parsers import FileUploadParser from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_404_NOT_FOUND ) from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from accounts.models import User from accounts.serializers import UserSerializer from chanel.models import Follow from chanel.serializers import FollowSerializer from posts.models import Post class UserAPI(APIView): permission_classes = (IsAuthenticated,) parser_class = (FileUploadParser,) def put(self, request): _request_perms = request.data try: _request_perms['title'] = str(_request_perms.get('picture').name) except Exception: pass user = request.user ser = UserSerializer(user, _request_perms, partial=True) if ser.is_valid(): ser.save() return JsonResponse(data={'msg': 'user update', 'success': True}, status=HTTP_200_OK) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def get(self, request, username=None): data = {} data['user_post_count'] = Post.objects.filter(author=request.user).count() if username: try: user = User.objects.get(username=username) except User.DoesNotExist: return JsonResponse(data={'msg': 'user not found', 'success': False}, status=HTTP_404_NOT_FOUND) follower = Follow.objects.filter(chanel__owner=user) following = Follow.objects.filter(user=user) data['follower'] = FollowSerializer(follower, many=True).data data['follower_count'] = follower.count() data['following'] = FollowSerializer(following, many=True).data data['following_count'] = following.count() data['user_data'] = UserSerializer(user).data return JsonResponse(data={'data': data, 'success': True}, status=HTTP_200_OK) else: data['user_data'] = UserSerializer(request.user).data follower = Follow.objects.filter(chanel__owner=request.user) following = Follow.objects.filter(user=request.user) data['follower'] = FollowSerializer(follower, many=True).data data['follower_count'] = follower.count() data['following'] = FollowSerializer(following, many=True).data data['following_count'] = following.count() return JsonResponse(data={'data': data, 'success': True}, status=HTTP_200_OK) <file_sep>from django.apps import AppConfig class ChanelConfig(AppConfig): name = 'chanel' <file_sep>from django.db import models class FileModel(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images/') class Meta: db_table = 'file' <file_sep>from notify.models import Notify from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK ) from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from Helper.permission import IsOwner from notify.serializers import NotifySerializer class Notifier(APIView): permission_classes = (IsAuthenticated, IsOwner) def get(self, request, pk=None): if pk: try: notify = Notify.objects.get(pk=pk) self.check_object_permissions(request, notify) data = NotifySerializer(notify).data notify.is_read = True notify.save() except Notify.DoesNotExist: return JsonResponse(data={'msg': 'notify id is incorrect', 'success': False}, status=HTTP_400_BAD_REQUEST) else: notify = Notify.objects.filter(user=request.user, is_read=False) data = NotifySerializer(notify, many=True).data return JsonResponse(data={'data': data, 'success': True}, status=HTTP_200_OK) <file_sep>from django.urls import path from .views import Likes urlpatterns = [ path('', Likes.as_view()), path('update/<int:pk>', Likes.as_view()), path('delete/<int:pk>', Likes.as_view()), path('get/<int:post_id>', Likes.as_view()), ] <file_sep>from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.phone_number = validated_data.get('phone_number', instance.phone_number) instance.city = validated_data.get('city', instance.city) instance.country = validated_data.get('country', instance.country) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.username = validated_data.get('username', instance.username) instance.picture = validated_data.get('picture', instance.picture) instance.save() return instance def to_representation(self, instance): ret = super(UserSerializer, self).to_representation(instance) ret.pop('phone_number') ret.pop('email') return ret class Meta: model = User fields = ['username', 'first_name', 'last_name', 'picture', 'city', 'country', 'id', 'email', 'phone_number'] <file_sep>from django.urls import path from rest_framework_simplejwt import views as jwt_views from .webService.signup import Signup from .webService.forgerPassword import ForgetPassword from .webService.changePassword import ChangePassword from .webService.userAPI import UserAPI urlpatterns = [ path('login', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('signup', Signup.as_view()), path('forgetPassword', ForgetPassword.as_view()), path('changePassword', ChangePassword.as_view()), path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('update', UserAPI.as_view()), path('get/<str:username>', UserAPI.as_view()), path('me', UserAPI.as_view()), ] <file_sep># Simple webserver for social webapp a project that users can share their posts and picture and comment for each other ## Installing 1-clone project 2-create virtual env 3-set virtual env in console or terminal or etc 4-pip install -r requirements.txt 5-python manage.py runserver ## Built With * [Django](https://www.djangoproject.com/) * [restFramWork](www.django-rest-framework.org) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details <file_sep># Generated by Django 3.0.2 on 2020-02-01 21:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Chanel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.TextField(max_length=2500)), ('identifier', models.CharField(max_length=100, unique=True)), ('author', models.ManyToManyField(related_name='author', to=settings.AUTH_USER_MODEL)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='owner', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'chanel', }, ), ] <file_sep>from comment.models import Comment from like.models import Like from like.serializers import LikeSerializer from posts.models import Post from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_201_CREATED ) from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated class Likes(APIView): permission_classes = (IsAuthenticated,) def post(self, request): _request_params = dict(request.data) _request_params['owner'] = request.user.id try: post = Post.objects.get(pk=_request_params.get('post')) try: like = Like.objects.get(post_id=post.id, owner=request.user) like.delete() if _request_params.get('value') == like.value: return JsonResponse(data={'msg': 'like or dislike deleted', 'success': True}, status=HTTP_200_OK) else: raise Like.DoesNotExist except Like.DoesNotExist: ser = LikeSerializer(data=_request_params) if ser.is_valid(): ser_data = ser.data ser_data['owner'] = request.user try: ser_data['post'] = post except Post.DoesNotExist: return JsonResponse(data={'msg': 'post not correctly send ', 'success': False}, status=HTTP_400_BAD_REQUEST) Like.objects.create(**ser_data) if ser_data.get('value') == 1: return JsonResponse(data={'msg': 'liked', 'success': True}, status=HTTP_201_CREATED) return JsonResponse(data={'msg': 'disLiked', 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) except Post.DoesNotExist: try: comment = Comment.objects.get(pk=_request_params.get('comment')) try: like = Like.objects.get(comment_id=comment.id, owner=request.user) like.delete() if _request_params.get('value') == like.value: return JsonResponse(data={'msg': 'like or dislike deleted', 'success': True}, status=HTTP_200_OK) else: raise Like.DoesNotExist except Like.DoesNotExist: ser = LikeSerializer(data=_request_params) if ser.is_valid(): ser_data = ser.data ser_data['owner'] = request.user try: ser_data['comment'] = comment except Comment.DoesNotExist: return JsonResponse(data={'msg': 'post not correctly send ', 'success': False}, status=HTTP_400_BAD_REQUEST) Like.objects.create(**ser_data) if ser_data.get('value') == 1: return JsonResponse(data={'msg': 'liked', 'success': True}, status=HTTP_201_CREATED) return JsonResponse(data={'msg': 'disLiked', 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) except Comment.DoesNotExist: return JsonResponse(data={'msg': 'post not correctly send ', 'success': False}, status=HTTP_400_BAD_REQUEST)<file_sep>from django.urls import path from .webservice.chanelAPI import Chanels from .webservice.followAPI import Following from .webservice.author import Author urlpatterns = [ path('', Chanels.as_view()), path('update/<str:identifier>', Chanels.as_view()), path('delete/<int:pk>', Chanels.as_view()), path('get/<str:identifier>', Chanels.as_view()), path('get/<int:id>', Chanels.as_view()), path('get', Chanels.as_view()), path('follow/<str:identifier>', Following.as_view()), path('author', Author.as_view()), path('author/delete/<str:author>', Author.as_view()), ] <file_sep>from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_201_CREATED ) from notify.models import Notify from ..serializers import FollowSerializer from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from chanel.models import Chanel, Follow class Following(APIView): permission_classes = (IsAuthenticated,) def post(self, request, identifier=None): _request_params = request.data _request_params['user'] = request.user.id try: chanel = Chanel.objects.get(identifier=identifier) _request_params['chanel'] = chanel.id except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel identifier not found', 'success': False}, status=HTTP_400_BAD_REQUEST) ser = FollowSerializer(data=_request_params) if ser.is_valid(): try: follow = Follow.objects.get(user=request.user, chanel=chanel) follow.delete() return JsonResponse(data={'msg': 'you unFollow {}'.format(follow.chanel.identifier), 'success': True}, status=HTTP_201_CREATED) except Follow.DoesNotExist: if chanel.owner == request.user: return JsonResponse(data={'msg': 'you cant follow your self', 'success': True}, status=HTTP_201_CREATED) follow = Follow.objects.create(**{'user': request.user, 'chanel': chanel}) Notify.objects.create(**{'user': follow.chanel.owner, 'body': 'you follow by {}'. format(request.user.get_username()), "link": "{}/api/chanel/get/".format(request.get_host()) + str(follow.chanel.identifier)}) return JsonResponse(data={'msg': 'you follow {}'.format(follow.chanel.identifier), 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) <file_sep>from django.db import models from accounts.models import User from chanel.models import Chanel class Post(models.Model): title = models.CharField(max_length=200, default='no title') body = models.TextField() chanel = models.ForeignKey(Chanel, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) create_time = models.DateTimeField(auto_now_add=True) class Meta: db_table = "post" <file_sep>from django.urls import path from .views import FileUpload urlpatterns = [ path('', FileUpload.as_view()), ] <file_sep>from rest_framework.permissions import BasePermission from chanel.models import Chanel from comment.models import Comment from notify.models import Notify from posts.models import Post class IsOwner(BasePermission): def has_object_permission(self, request, view, obj): if obj._meta is Chanel._meta or obj._meta is Comment._meta: return obj.owner.pk == request.user.pk elif obj._meta is Notify._meta: return request.user == obj.user class IsAuthorOwner(BasePermission): def has_object_permission(self, request, view, obj): if obj._meta is Post._meta: return obj.author == request.user or obj.owner == request.user elif obj._meta is Chanel._meta: return request.user in obj.author.all() or obj.owner == request.user class IsChanelOwner(BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user <file_sep>import datetime import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = <KEY>' DEBUG = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig', 'chanel.apps.ChanelConfig', 'comment.apps.CommentConfig', 'like.apps.LikeConfig', 'notify.apps.NotifyConfig', 'files.apps.FilesConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sosial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True WSGI_APPLICATION = 'sosial.wsgi.application' AUTH_USER_MODEL = 'accounts.User' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=360), 'ROTATE_REFRESH_TOKENS': True, 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=365), 'SLIDING_TOKEN_LIFETIME': datetime.timedelta(days=360), 'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=365), } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'social', # 'USER': 'root', # 'PASSWORD': '123', # 'HOST': '127.0.0.1', # 'PORT': '3306', # } # } MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # MEDIA_ROOT = os.path.join(BASE_DIR,'static','media') MEDIA_URL = '/media/' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>'<file_sep>from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_201_CREATED ) from ..serializers import ChanelSerializer from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from Helper.permission import IsOwner from chanel.models import Chanel class Chanels(APIView): permission_classes = (IsAuthenticated, IsOwner) def post(self, request): _request_params = dict(request.data) author = request.user owner = author _request_params['author'] = author.id _request_params['owner'] = owner.id if not _request_params.get('identifier'): _request_params['identifier'] = str(request.user.username) ser = ChanelSerializer(data=_request_params) if ser.is_valid(): chanel = Chanel.objects.create(**ser.data, owner=author) chanel.author.add(author) return JsonResponse(data={'msg': 'create chanel', 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def put(self, request, identifier=None): _request_params = dict(request.data) _request_params['owner'] = request.user.id _request_params['author'] = request.user.id _request_params['identifier'] = identifier try: chanel = Chanel.objects.get(identifier=identifier) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel Dose not exists', 'success': False}, status=HTTP_400_BAD_REQUEST) ser = ChanelSerializer(chanel, data=_request_params, partial=True) if ser.is_valid(): ser.save() return JsonResponse(data={'msg': 'update chanel', 'success': True}, status=HTTP_200_OK) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def delete(self, request, pk=None): try: chanel = Chanel.objects.get(id=pk) self.check_object_permissions(request, chanel) chanel.delete() return JsonResponse(data={'msg': 'delete chanel', 'success': True}, status=HTTP_201_CREATED) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel Dose not exists', 'success': False}, status=HTTP_400_BAD_REQUEST) def get(self, request, identifier=None, id=None): if not identifier: chanel = Chanel.objects.filter(author=request.user) return JsonResponse( data={'data': ChanelSerializer(chanel, many=True, read_only=True).data, 'success': True}, status=HTTP_201_CREATED) else: try: if id: chanel = Chanel.objects.get(id=id) else: chanel = Chanel.objects.get(identifier=identifier) return JsonResponse(data={'data': ChanelSerializer(chanel, read_only=True).data, 'success': True}, status=HTTP_200_OK) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel Dose not exists', 'success': False}, status=HTTP_400_BAD_REQUEST) <file_sep># Generated by Django 3.0.2 on 2020-02-03 20:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0005_auto_20200203_0957'), ('comment', '0002_auto_20200202_1151'), ('like', '0002_auto_20200202_1258'), ] operations = [ migrations.AddField( model_name='like', name='comment', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='comment.Comment'), ), migrations.AlterField( model_name='like', name='post', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='posts.Post'), ), ] <file_sep>from rest_framework import serializers from .models import Like from accounts.serializers import UserSerializer class LikeSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) class Meta: model = Like fields = '__all__' <file_sep>from notify.models import Notify from posts.models import Post from .models import Comment from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_201_CREATED ) from .serializers import CommentSerializer from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from Helper.permission import IsOwner class Comments(APIView): permission_classes = (IsAuthenticated, IsOwner) def post(self, request): _request_params = dict(request.data) _request_params['owner'] = request.user.id try: comment = '' post = Post.objects.get(pk=_request_params.get('post')) if _request_params.get('comment'): comment = Comment.objects.get(pk=_request_params['comment']) except (Post.DoesNotExist, Comment.DoesNotExist): return JsonResponse(data={'msg': 'post or comment id is not correct', 'success': False}, status=HTTP_400_BAD_REQUEST) ser = CommentSerializer(data=_request_params) if ser.is_valid(): ser_data = ser.data ser_data['owner'] = request.user ser_data['post'] = post ser_data['comment'] = comment if not comment: ser_data.pop('comment') comment = Comment.objects.create(**ser_data) Notify.objects.create(**{'user': post.author, 'body': 'you have a comment of {}'. format(request.user.get_username()), "link": "{}/api/comment/get/".format(request.get_host()) + str(comment.id)}) return JsonResponse(data={'msg': 'comment create', 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def put(self, request, pk): _request_params = dict(request.data) try: comment = Comment.objects.get(pk=pk) self.check_object_permissions(request, comment) except Comment.DoesNotExist: return JsonResponse(data={'msg': 'comment id is not correct', 'success': False}, status=HTTP_400_BAD_REQUEST) ser = CommentSerializer(comment, _request_params, partial=True) if ser.is_valid(): ser.save() return JsonResponse(data={'msg': 'comment is update', 'success': True}, status=HTTP_200_OK) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def get(self, request, post_id=None): comment = Comment.objects.filter(post_id=post_id) data = CommentSerializer(comment, many=True).data return JsonResponse(data={'data': data, 'success': True}, status=HTTP_200_OK) def delete(self, request, pk=None): try: comment = Comment.objects.get(pk=pk) self.check_object_permissions(request, comment) comment.delete() return JsonResponse(data={'msg': 'comment delete', 'success': True}, status=HTTP_200_OK) except Comment.DoesNotExist: return JsonResponse(data={'msg': 'comment id is not correct', 'success': False}, status=HTTP_400_BAD_REQUEST) <file_sep>from django.http import JsonResponse from rest_framework.status import ( HTTP_201_CREATED, HTTP_400_BAD_REQUEST ) from rest_framework.views import APIView from ..serializers import UserSerializer from chanel.models import Chanel import random from django.db.utils import IntegrityError from rest_framework.parsers import FileUploadParser class Signup(APIView): parser_class = (FileUploadParser,) def post(self, request): _request_params = request.data try: _request_params['title'] = str(_request_params.get('picture').name) except Exception: pass ser = UserSerializer(data=_request_params) if ser.is_valid(): try: user = ser.save() validated_data = ser.data except IntegrityError as e: return JsonResponse({'data': e.args, 'success': False}, status=HTTP_400_BAD_REQUEST) user.set_password(_request_params['<PASSWORD>']) user.save() chanel_identifier = user.username owner_id = user.id description = 'main page of {}'.format(chanel_identifier) try: chanel = Chanel.objects.create(identifier=chanel_identifier, owner_id=owner_id, description=description) except IntegrityError: chanel = Chanel.objects.create(identifier=chanel_identifier + int(random.random * 10), owner_id=owner_id, description=description) chanel.author.add(user) return JsonResponse({'data': validated_data, 'success': True}, status=HTTP_201_CREATED) else: data = ser.errors return JsonResponse(data, status=HTTP_400_BAD_REQUEST) <file_sep>from django.urls import path from .views import Notifier urlpatterns = [ path('get/<int:pk>', Notifier.as_view()), path('get', Notifier.as_view()), ] <file_sep># Generated by Django 3.0.2 on 2020-02-01 14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='picture', field=models.ImageField(max_length=1000, null=True, upload_to=''), ), ] <file_sep>from django.db.models import Sum from rest_framework import serializers from like.models import Like from .models import Comment from accounts.serializers import UserSerializer class CommentSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) like = serializers.SerializerMethodField() def get_like(self, obj): if type(obj) is Comment: if obj._meta is Comment._meta: liked = Like.objects.filter(comment_id=obj.id, value=1).aggregate(Sum('value'))['value__sum'] dislike = Like.objects.filter(comment_id=obj.id, value=-1).aggregate(Sum('value'))['value__sum'] liked = liked if liked else 0 dislike = dislike if dislike else 0 return {'liked': liked, 'disLiked': dislike} return {'liked': 0, 'disLiked': 0} def validate_post(self, attrs): if not attrs: raise serializers.ValidationError('post not send ') def validate_comment(self, attrs): if not dict(self.initial_data).get('post'): if not attrs: raise serializers.ValidationError('comment not send ') def update(self, instance, validated_data): instance.body = validated_data.get('body', instance.body) instance.save() return instance class Meta: model = Comment fields = '__all__' <file_sep>asgiref==3.2.3 Django==3.0.2 django-cors-headers==3.2.1 django-filter==2.2.0 django-mysql==3.3.0 djangorestframework==3.11.0 djangorestframework-simplejwt==4.4.0 Markdown==3.1.1 mysqlclient==1.4.6 Pillow==7.0.0 pkg-resources==0.0.0 PyJWT==1.7.1 pytz==2019.3 sqlparse==0.3.0 <file_sep>from django.http import JsonResponse from rest_framework.status import ( HTTP_201_CREATED, HTTP_404_NOT_FOUND, HTTP_400_BAD_REQUEST ) from accounts.models import User from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from Helper.permission import IsChanelOwner from chanel.models import Chanel class Author(APIView): permission_classes = (IsAuthenticated, IsChanelOwner) def post(self, request): _request_params = request.data try: chanel = Chanel.objects.get(identifier=_request_params.get('identifier')) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel Dose not exists', 'success': False}, status=HTTP_404_NOT_FOUND) self.check_object_permissions(request, chanel) try: author = User.objects.get(username=_request_params.get('username')) except User.DoesNotExist: return JsonResponse(data={'msg': 'user not found', 'success': False}, status=HTTP_400_BAD_REQUEST) try: Chanel.objects.get(identifier=_request_params.get('identifier'), author=author) return JsonResponse(data={'msg': 'user is already your author ', 'success': False}, status=HTTP_400_BAD_REQUEST) except Chanel.DoesNotExist: chanel.author.add(author) return JsonResponse(data={'msg': 'user add to your chanel author ', 'success': True}, status=HTTP_201_CREATED) def delete(self, request, author): _request_params = request.data try: chanel = Chanel.objects.get(identifier=_request_params.get('identifier'), owner=request.user) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel Dose not exists', 'success': False}, status=HTTP_404_NOT_FOUND) self.check_object_permissions(request, chanel) try: author = User.objects.get(username=author) except User.DoesNotExist: return JsonResponse(data={'msg': 'Author Dose not exists', 'success': False}, status=HTTP_404_NOT_FOUND) try: chanel = Chanel.objects.get(identifier=_request_params.get('identifier'), owner=request.user, author=author) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'Author Dose not exists', 'success': False}, status=HTTP_404_NOT_FOUND) chanel.author.remove(author) return JsonResponse(data={'msg': 'Author {} removed'.format(author.username), 'success': True}, status=HTTP_404_NOT_FOUND) <file_sep>from django.urls import path from .views import Posts, GetPost urlpatterns = [ path('', Posts.as_view()), path('get', GetPost.as_view()), path('<int:pk>', Posts.as_view()), path('chanel/<str:identifier>', Posts.as_view()), path('update/<int:pk>', Posts.as_view()), path('delete/<int:pk>', Posts.as_view()), ] <file_sep>from django.db import models from accounts.models import User from comment.models import Comment from posts.models import Post class Like(models.Model): like_choice = ((1, 'LIKE'), (-1, 'DISLIKE')) owner = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True) value = models.IntegerField(choices=like_choice, default=1) class Meta: db_table = 'like' <file_sep>from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import FileSerializer from rest_framework.permissions import IsAuthenticated class FileUpload(APIView): permission_classes = (IsAuthenticated,) parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): _request_perms = request.data _request_perms['title'] = str(_request_perms['image'].name) ser = FileSerializer(data=_request_perms) if ser.is_valid(): ser.save() return Response(ser.data, status=status.HTTP_201_CREATED) else: return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST) <file_sep># Generated by Django 3.0.2 on 2020-02-02 12:36 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('posts', '0002_auto_20200202_0027'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Like', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.IntegerField(choices=[(1, 'LIKE'), (-1, 'DISLIKE')], default=1)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.Post')), ], ), ] <file_sep>from ..models import User from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST ) from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated class ChangePassword(APIView): permission_classes = (IsAuthenticated,) def post(self, request): _request_params = request.data password = _request_params.get('password') if not password: return JsonResponse({'msg': 'password is required', 'success': False}, status=HTTP_400_BAD_REQUEST) try: user = request.user user.set_password(_request_params.get('password')) user.save() return JsonResponse({'msg': 'password change', 'success': True}) except User.DoesNotExist: return JsonResponse({'msg': 'user not found . params: email:""', 'success': False}, status=HTTP_400_BAD_REQUEST)<file_sep>from ..models import User from django.http import JsonResponse from rest_framework import status from rest_framework.views import APIView from django.core.mail import send_mail from django.conf import settings class ForgetPassword(APIView): def post(self, request): _request_params = request.data try: user = User.objects.get(email=_request_params.get('email')) password = <PASSWORD>.objects.make_<PASSWORD>_<PASSWORD>() subject = 'recover password' message = 'your password is {}'.format(password) email_from = settings.EMAIL_HOST_USER recipient_list = [user.email, '<EMAIL>', ] try: send_mail(subject, message, email_from, recipient_list) except: return JsonResponse({'msg': 'cant send mail try again', 'success': False}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) user.set_password(<PASSWORD>) user.save() return JsonResponse({'msg': 'user password change and send to your email ', 'success': True}, status=status.HTTP_200_OK) except User.DoesNotExist: return JsonResponse({'msg': 'user not found . params: email:""', 'success': False}, status=status.HTTP_404_NOT_FOUND) <file_sep>from django.db import models from accounts.models import User class Notify(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_read = models.BooleanField(default=False) body = models.TextField(max_length=1000) link = models.CharField(max_length=255) class Meta: db_table = 'notify' <file_sep># Generated by Django 3.0.2 on 2020-02-03 06:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('files', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='filemodel', table='file', ), ] <file_sep>import datetime from pickle import FALSE from django.core.paginator import Paginator from django.db.models import Q, Sum, Case, When, IntegerField, Count from django.db.models.functions import Coalesce from .models import Post from django.http import JsonResponse from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_201_CREATED ) from .serializers import PostSerializer from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from Helper.permission import IsAuthorOwner from chanel.models import Chanel class Posts(APIView): permission_classes = (IsAuthenticated, IsAuthorOwner) def post(self, request): _request_params = dict(request.data) if not _request_params.get('chanelIdentifier'): return JsonResponse(data={'msg': 'chanelIdentifier Does not SEND', 'success': False}, status=HTTP_400_BAD_REQUEST) try: chanel = Chanel.objects.get(identifier=_request_params.get('chanelIdentifier')) self.check_object_permissions(request, chanel) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'chanel DosNotExist', 'success': False}, status=HTTP_400_BAD_REQUEST) _request_params['chanel'] = chanel.id _request_params['author'] = request.user.id ser = PostSerializer(data=_request_params) if ser.is_valid(): ser_data = ser.data ser_data['chanel'] = chanel ser_data['author'] = request.user Post.objects.create(**ser_data) return JsonResponse(data={'msg': 'create post', 'success': True}, status=HTTP_201_CREATED) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def get(self, request, pk=None, identifier=None): if pk: try: data = PostSerializer(Post.objects.get(pk=pk)).data except Post.DoesNotExist: return JsonResponse(data={'msg': 'post DosNotExist', 'success': False}, status=HTTP_400_BAD_REQUEST) elif identifier: data = PostSerializer(Post.objects.filter(chanel__identifier=identifier), many=True).data return JsonResponse(data={'msg': data, 'success': True}, status=HTTP_200_OK) def put(self, request, pk): _request_params = dict(request.data) try: post = Post.objects.get(pk=pk) self.check_object_permissions(request, post) _request_params['chanel'] = post.chanel_id _request_params['author'] = post.author_id except Post.DoesNotExist: return JsonResponse(data={'msg': 'post DosNotExist', 'success': False}, status=HTTP_400_BAD_REQUEST) ser = PostSerializer(post, _request_params, partial=True) if ser.is_valid(): ser.save() return JsonResponse(data={'msg': 'update post', 'success': True}, status=HTTP_200_OK) else: return JsonResponse(data={'msg': ser.errors, 'success': False}, status=HTTP_400_BAD_REQUEST) def delete(self, request, pk=None): try: post = Post.objects.get(id=pk) self.check_object_permissions(request, post) post.delete() return JsonResponse(data={'msg': 'delete post', 'success': True}, status=HTTP_200_OK) except Chanel.DoesNotExist: return JsonResponse(data={'msg': 'post Dose not exists', 'success': False}, status=HTTP_400_BAD_REQUEST) class GetPost(APIView): permission_classes = (IsAuthenticated,) def post(self, request): _request_params = request.data page_number = _request_params.get('page_number', 1) if _request_params.get('newestSort'): post = Post.objects.filter(create_time__gte=datetime.date.today() - datetime.timedelta(days=7)).order_by('-create_time') elif _request_params.get('hotSort'): post = Post.objects.annotate(total=Coalesce(Sum('like__value'), 0)).order_by('-total') elif _request_params.get('followed'): post = Post.objects.filter(chanel__follow__user=request.user) else: post = Post.objects.filter(Q(author=request.user) | Q(comment__owner=request.user)) paginator = Paginator(post, 10) post = paginator.get_page(page_number) data = PostSerializer(many=True, instance=post).data return JsonResponse(data={'data': data, 'success': True, "page_number": page_number, 'count': paginator.count, 'last_page': paginator.num_pages}, status=HTTP_200_OK) <file_sep># Generated by Django 3.0.2 on 2020-02-04 17:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chanel', '0004_chanel_title'), ] operations = [ migrations.AlterField( model_name='chanel', name='title', field=models.CharField(max_length=150), ), ] <file_sep># Generated by Django 3.0.2 on 2020-02-04 17:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chanel', '0003_chanel_law'), ] operations = [ migrations.AddField( model_name='chanel', name='title', field=models.CharField(default='test', max_length=150), ), ] <file_sep># Generated by Django 3.0.2 on 2020-02-03 09:30 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('posts', '0002_auto_20200202_0027'), ] operations = [ migrations.AddField( model_name='post', name='create_time', field=models.DateTimeField(default=datetime.datetime(2020, 2, 3, 9, 30, 44, 412117, tzinfo=utc)), ), ] <file_sep># Generated by Django 3.0.2 on 2020-02-04 17:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chanel', '0005_auto_20200204_1727'), ] operations = [ migrations.AlterField( model_name='chanel', name='law', field=models.TextField(max_length=2000), ), ] <file_sep>from django.db import models # Create your models here. from accounts.models import User from posts.models import Post class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='for_comment') body = models.TextField(max_length=2500) class Meta: db_table = 'comment' <file_sep>from statistics import mode from django.db import models from accounts.models import User class Chanel(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') author = models.ManyToManyField(User, related_name='author') description = models.TextField(max_length=2500) identifier = models.CharField(unique=True, max_length=100) law = models.TextField(max_length=2000) title = models.CharField(max_length=150) class Meta: db_table = "chanel" class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) chanel = models.ForeignKey(Chanel, on_delete=models.CASCADE) class Meta: db_table = "follow"
6597a0bf62c0c51a766c2a94094c3cba86f87f1b
[ "Markdown", "Python", "Text" ]
50
Python
vahidtwo/simpleSocialSite
40d971f04b7127811b7e277ddb3068fb451e9574
cc803917989855cc9c101be97aeee0fc833d547c
refs/heads/master
<repo_name>swimson/Automaton<file_sep>/src/Swimson/Automaton/Transition/Transition.php <?php namespace Swimson\Automaton\Transition; use Swimson\Automaton\State\StateInterface; class Transition implements TransitionInterface { /** * @var StateInterface */ private $source; /** * @var string */ private $event; /** * @var StateInterface */ private $target; /** * @inheritDoc */ public function __construct(StateInterface $source, $event, StateInterface $target) { $this->source = $source; $this->event = $event; $this->target = $target; } /** * @inheritDoc */ public function getSource() { return $this->source; } /** * @inheritDoc */ public function getTarget() { return $this->target; } /** * @inheritDoc */ public function getEvent() { return $this->event; } }<file_sep>/src/Swimson/Automaton/StateMachine/StateMachineInterface.php <?php namespace Swimson\Automaton\StateMachine; use Swimson\Automaton\State\StateInterface; interface StateMachineInterface { const STATE_MACHINE_OFF = 0; const STATE_MACHINE_BOOTED = 1; /************************************************************** * Initialization **************************************************************/ /** * Add a state to the Machine * @param StateInterface $state * @return StateMachine * @throws \Swimson\Automaton\Exception\AlterStateMachineException */ public function addState(StateInterface $state); /** * Removes a state from the Machine * @param StateInterface $state * @return StateMachine * @throws \Swimson\Automaton\Exception\AlterStateMachineException */ public function removeState(StateInterface $state); /** * Get all the states loaded into the machine * @return array */ public function getAllStates(); /************************************************************** * Based on Current State **************************************************************/ /** * Returns the current state * @return \Swimson\Automaton\State\State * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function getState(); /** * Gets the available target states * @return array */ public function getAvailableStates(); /** * Checks if the Machine is in a given state * @param StateInterface $state * @return bool * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function isCurrently(StateInterface $state); /** * Returns whether the state is available to transition to * @param StateInterface $state * @return bool * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function isAvailable(StateInterface $state); /************************************************************** * Events **************************************************************/ /** * Get all possible events * @return array */ public function getAllEvents(); /** * Get the list of active event - those that will trigger a state change * @return array * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function getActiveEvents(); /** * Will the event trigger a state change? * @param string $event * @return boolean * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function isActive($event); /** * Triggers an Event within the Machine * @param string $event * @return StateMachine * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function trigger($event); /************************************************************** * StateMachine Boot **************************************************************/ /** * Boots the finite state machine * @param StateInterface $startingState * @return StateMachine * @throws \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function boot(StateInterface $startingState); /** * Turns off the finite state machine * @return StateMachine */ public function stop(); /** * Returns whether the state machine is booted * @return boolean */ public function isBooted(); }<file_sep>/src/Swimson/Automaton/Tests/StateMachineTest.php <?php namespace Swimson\Automaton\Tests; use Swimson\Automaton\State\State; use Swimson\Automaton\StateMachine\StateMachine; use Swimson\Automaton\Transition\Transition; class StateMachineTest extends \PHPUnit_Framework_TestCase { /** * @var StateMachine */ protected $stateMachine; /** * @var State */ protected $state1; /** * @var State */ protected $state2; /** * @var Transition */ protected $transition1; /** * @var Transition */ protected $transition2; /** * @var Transition */ protected $transition3; /** * @var State */ protected $state3; public function setup() { $this->stateMachine = new StateMachine(); $this->state1 = new State('state1'); $this->state2 = new State('state2'); $this->state3 = new State('state3'); } public function setupMachine1() { /** * Transitions * 1 :=> 2 * 2 := 1, 3 * 3: => No transitions */ $this->state1->addTransition('event1-2', $this->state2); $this->state2->addTransition('event2-1', $this->state1); $this->state2->addTransition('event2-3', $this->state3); $this->stateMachine->addState($this->state1); $this->stateMachine->addState($this->state2); $this->stateMachine->addState($this->state3); } public function testInterface() { $this->assertInstanceOf('Swimson\Automaton\StateMachine\StateMachineInterface', $this->stateMachine); } public function testAddState() { $state1 = $this->state1; $stateMachine = $this->stateMachine; $stateMachine->addState($state1); $this->assertEquals(array($state1->getName() => $state1), $stateMachine->getAllStates()); } /** * @expectedException \Swimson\Automaton\Exception\AlterStateMachineException */ public function testExceptionOnAddingState() { $state1 = $this->state1; $state2 = $this->state2; $stateMachine = $this->stateMachine; $stateMachine->addState($state1); $stateMachine->boot($state1); $stateMachine->addState($state2); // exception thrown } public function testRemoveState() { $state1 = $this->state1; $stateMachine = $this->stateMachine; $stateMachine->addState($state1); $this->assertEquals(array($state1->getName() => $state1), $stateMachine->getAllStates()); $stateMachine->removeState($state1); $this->assertEquals(array(), $stateMachine->getAllStates()); } /** * @expectedException \Swimson\Automaton\Exception\AlterStateMachineException */ public function testExceptionOnRemovingState() { $this->stateMachine->addState($this->state1); $this->stateMachine->boot($this->state1); $this->stateMachine->removeState($this->state1); } public function testGetAllStates() { $this->assertEquals(array(), $this->stateMachine->getAllStates()); $this->stateMachine->addState($this->state1); $this->stateMachine->addState($this->state2); $this->assertEquals( array( $this->state1->getName() => $this->state1, $this->state2->getName() => $this->state2 ), $this->stateMachine->getAllStates() ); } public function testGetState() { $this->stateMachine->addState($this->state1); $this->stateMachine->addState($this->state2); $this->stateMachine->boot($this->state1); $this->assertEquals($this->state1, $this->stateMachine->getState()); $this->stateMachine->stop(); $this->stateMachine->boot($this->state2); $this->assertEquals($this->state2, $this->stateMachine->getState()); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testGetStateException() { $this->stateMachine->getState(); } public function testGetAvailableStates() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertEquals(array($this->state2), $this->stateMachine->getAvailableStates()); $this->stateMachine->stop(); $this->stateMachine->boot($this->state2); $this->assertEquals(array($this->state1, $this->state3), $this->stateMachine->getAvailableStates()); $this->stateMachine->stop(); $this->stateMachine->boot($this->state3); $this->assertEquals(array(), $this->stateMachine->getAvailableStates()); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testGetAvailableStatesException() { $this->setupMachine1(); $this->stateMachine->getAvailableStates(); } public function testIsCurrently() { $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isCurrently($this->state1)); $this->assertFalse($this->stateMachine->isCurrently($this->state2)); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testIsCurrentlyException() { $this->stateMachine->isCurrently($this->state1); } public function testIsAvailable() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isAvailable($this->state2)); $this->assertFalse($this->stateMachine->isAvailable($this->state3)); $this->stateMachine->stop(); $this->stateMachine->boot($this->state2); $this->assertTrue($this->stateMachine->isAvailable($this->state1)); $this->assertTrue($this->stateMachine->isAvailable($this->state3)); $this->stateMachine->stop(); $this->stateMachine->boot($this->state3); $this->assertFalse($this->stateMachine->isAvailable($this->state1)); $this->assertFalse($this->stateMachine->isAvailable($this->state3)); $this->stateMachine->stop(); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testIsAvailableException() { $this->setupMachine1(); $this->stateMachine->isAvailable($this->state1); } public function testGetAllEvents() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertEquals(array('event1-2', 'event2-1', 'event2-3'), $this->stateMachine->getAllEvents()); } public function testGetActiveEvents() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertEquals(array('event1-2'), $this->stateMachine->getActiveEvents()); $this->stateMachine->stop(); $this->stateMachine->boot($this->state2); $this->assertEquals(array('event2-1', 'event2-3'), $this->stateMachine->getActiveEvents()); $this->stateMachine->stop(); $this->stateMachine->boot($this->state3); $this->assertEquals(array(), $this->stateMachine->getActiveEvents()); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testGetActiveEventsException() { $this->setupMachine1(); $this->stateMachine->getActiveEvents(); } public function testIsActive() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isActive('event1-2')); $this->assertFalse($this->stateMachine->isActive('event2-1')); $this->assertFalse($this->stateMachine->isActive('event2-3')); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testIsActiveException() { $this->setupMachine1(); $this->stateMachine->isActive('event1-2'); } public function testTrigger() { $this->setupMachine1(); $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isCurrently($this->state1)); $this->stateMachine->trigger('event1-2'); $this->assertTrue($this->stateMachine->isCurrently($this->state2)); $this->stateMachine->trigger('event2-3'); $this->assertTrue($this->stateMachine->isCurrently($this->state3)); } /** * @expectedException \Swimson\Automaton\Exception\StateMachineUnavailableException */ public function testTriggerUnavailableException() { $this->setupMachine1(); $this->stateMachine->trigger('event1-2'); } public function testBoot() { $this->assertFalse($this->stateMachine->isBooted()); $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isBooted()); } /** * @expectedException \Swimson\Automaton\Exception\AlterStateMachineException */ public function testBootException() { $this->stateMachine->boot($this->state1); $this->stateMachine->boot($this->state1); } public function testStop() { $this->assertFalse($this->stateMachine->isBooted()); $this->stateMachine->boot($this->state1); $this->assertTrue($this->stateMachine->isBooted()); $this->stateMachine->stop(); $this->assertFalse($this->stateMachine->isBooted()); } } <file_sep>/src/Swimson/Automaton/State/State.php <?php namespace Swimson\Automaton\State; use Swimson\Automaton\Transition\Transition; class State implements StateInterface { /** * @var string */ private $name; /** * @var array */ private $transitions = array(); /** * @inheritDoc */ public function __construct($name) { $this->name = $name; } /** * @inheritDoc */ public function addTransition($event, StateInterface $target) { $transition = new Transition($this, $event, $target); $this->transitions[$transition->getEvent()] = $transition; } /** * @inheritDoc */ public function getTransitions() { return $this->transitions; } /** * @inheritDoc */ public function getName() { return $this->name; } /** * @inheritDoc */ public function getEvents() { $return = array(); $transitions = $this->getTransitions(); foreach ($transitions as $transition) { /** @var $transition Transition */ $event = $transition->getEvent(); if (!in_array($event, $return)) { $return[] = $event; } } return $return; } public function getActiveEvents() { $return = array(); $transitions = $this->getTransitions(); foreach ($transitions as $transition) { /** @var $transition Transition */ $event = $transition->getEvent(); if (!in_array($event, $return)) { $return[] = $event; } } return $return; } public function __toString() { return $this->name; } } <file_sep>/test.php <?php include(__DIR__ . '/src/StateMachine/StateMachineInterface.php'); include(__DIR__ . '/src/StateMachine/StateInterface.php'); include(__DIR__ . '/src/StateMachine/TransitionInterface.php'); include(__DIR__ . '/src/StateMachine/State.php'); include(__DIR__ . '/src/StateMachine/StateMachine.php'); include(__DIR__ . '/src/StateMachine/Transition.php'); use StateMachine\State; use StateMachine\StateMachine; // States Available $child = new State('child'); $adult = new State('adult'); $engaged = new State('engaged'); $married = new State('married'); $divorced = new State('divorced'); $widowed = new State('widowed'); $dead = new State('dead'); // Transitions Available $child->addTransition('grows-up', $adult); $child->addTransition('death', $dead); $adult->addTransition('engagement', $engaged); $adult->addTransition('death', $dead); $engaged->addTransition('wedding-canceled', $adult); $engaged->addTransition('wedding', $married); $engaged->addTransition('death', $dead); $married->addTransition('divorce', $divorced); $married->addTransition('death', $dead); $married->addTransition('spouse-dies', $widowed); $widowed->addTransition('engagement', $engaged); $widowed->addTransition('death', $dead); $divorced->addTransition('engagement', $engaged); $divorced->addTransition('death', $dead); // Boot up State Machine $fsm = new StateMachine($child); $fsm->addState($adult); $fsm->addState($engaged); $fsm->addState($married); $fsm->addState($divorced); $fsm->addState($widowed); $fsm->addState($dead); $fsm->boot($child); ?> <h2>Initial State: </h2> <?php echo $fsm->getState(); ?> <h2>Process Event <em>grows-up</em></h2> <?php echo $fsm->trigger('grows-up')->getState(); ?> <h2>Process Event <em>engagement</em></h2> <?php echo $fsm->trigger('engagement')->getState(); ?> <h2>Wedding Canceled</h2> <?php echo $fsm->trigger('wedding-canceled')->getState(); ?> <h2>Try to Skip To <em>Married</em></h2> <?php echo $fsm->trigger('wedding')->getState(); ?> <h2>Get Engaged a Second Time and Get Married</h2> <?php echo $fsm->trigger('engagement')->trigger('wedding')->getState(); ?> <h2>Person Dies</h2> <?php echo $fsm->trigger('death')->getState(); ?> <file_sep>/src/Swimson/Automaton/Tests/StateTest.php <?php namespace Swimson\StateMachine\Tests; use Swimson\Automaton\State\State; class StateTest extends \PHPUnit_Framework_TestCase { public function testInterface() { $this->assertInstanceOf('Swimson\Automaton\State\StateInterface', new State('test')); } public function testGetName() { $state = new State('test'); $this->assertEquals('test', $state->getName()); } public function testAddTransition() { $state1 = new State('test1'); $state2 = new State('test2'); $state1->addTransition('event1', $state2); $this->assertEquals(1, count($state1->getTransitions())); } } <file_sep>/readme.md Ideas -- Unable to add/remove states once booted -- Unable to get current state if not booted; -- Able to add transitions after booted; <file_sep>/src/Swimson/Automaton/Exception/StateMachineUnavailableException.php <?php namespace Swimson\Automaton\Exception; class StateMachineUnavailableException extends \Exception { const MSG = 'Unable to access StateMachine before machine has been booted.'; public function __toString() { return self::MSG; } } <file_sep>/src/Swimson/Automaton/Tests/TransitionTest.php <?php namespace Swimson\Automaton\Tests; use Swimson\Automaton\State\State; use Swimson\Automaton\Transition\Transition; class TransitionTest extends \PHPUnit_Framework_TestCase { /** * @var State */ protected $state1; /** * @var State */ protected $state2; /** * @var Transition */ protected $transition; public function setup() { $this->state1 = new State('state1'); $this->state2 = new State('state2'); $this->transition = new Transition($this->state1, 'event', $this->state2); } public function testInterface() { $this->assertInstanceOf('Swimson\Automaton\Transition\TransitionInterface', $this->transition); } public function testGetSource() { $this->assertInstanceOf('Swimson\Automaton\State\StateInterface', $this->transition->getSource()); $this->assertEquals($this->state1, $this->transition->getSource()); } public function testGetTarget() { $this->assertInstanceOf('Swimson\Automaton\State\StateInterface', $this->transition->getTarget()); $this->assertEquals($this->state2, $this->transition->getTarget()); } } <file_sep>/src/Swimson/Automaton/State/StateInterface.php <?php namespace Swimson\Automaton\State; interface StateInterface { /** * Get Name * @return string */ public function getName(); /** * Add Transition * @param $event * @param StateInterface $target * @return $this */ public function addTransition($event, StateInterface $target); /** * Returns an array of Transition objects * @return array */ public function getTransitions(); /** * Returns an array of events that are available for this state * @return array */ public function getEvents(); /** * Returns an array of events that are available from this state * @return array */ public function getActiveEvents(); }<file_sep>/src/Swimson/Automaton/Exception/AlterStateMachineException.php <?php namespace Swimson\Automaton\Exception; class AlterStateMachineException extends \Exception { const MSG = 'Unable to alter StateMachine after machine has been booted. To make changes, turn StateMachine off.'; public function __toString() { return self::MSG; } } <file_sep>/src/Swimson/Automaton/StateMachine/StateMachine.php <?php namespace Swimson\Automaton\StateMachine; use Swimson\Automaton\Exception\AlterStateMachineException; use Swimson\Automaton\Exception\StateMachineUnavailableException; use Swimson\Automaton\State\StateInterface; class StateMachine implements StateMachineInterface { /** * @var array */ private $states = array(); /** * @var \Swimson\Automaton\State\StateInterface */ private $currentState; /** * @var int */ private $machineStatus; public function __construct() { $this->machineStatus = self::STATE_MACHINE_OFF; } /** * @inheritDoc */ public function addState(StateInterface $state) { if($this->isBooted()){ throw new AlterStateMachineException(); } $this->states[$state->getName()] = $state; return $this; } /** * @inheritDoc */ public function removeState(StateInterface $state) { if($this->isBooted()){ throw new AlterStateMachineException(); } if (array_key_exists($state->getName(), $this->states)) { unset($this->states[$state->getName()]); } return $this; } /** * @inheritDoc */ public function getAllStates() { return $this->states; } /** * @inheritDoc */ public function getState() { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } return $this->currentState; } /** * @inheritDoc */ public function getAvailableStates() { $return = array(); if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } foreach ($this->currentState->getTransitions() as $transition) { /** @var \Swimson\Automaton\Transition\Transition $transition */ $targetName = $transition->getTarget()->getName(); if (!array_key_exists($targetName, $return)) { $return[] = $transition->getTarget(); } } return $return; } /** * @inheritDoc */ public function isCurrently(StateInterface $state) { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } return $this->currentState->getName() == $state->getName(); } /** * @inheritDoc */ public function isAvailable(StateInterface $state) { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } $return = false; $transitions = $this->currentState->getTransitions(); foreach ($transitions as $transition) { /** @var \Swimson\Automaton\Transition\Transition $transition */ if ($state->getName() == $transition->getTarget()->getName()) { $return = true; } } return $return; } /** * @inheritDoc */ public function getAllEvents() { $return = array(); foreach ($this->states as $state) { /** @var \Swimson\Automaton\State\State $state */ $events = $state->getEvents(); foreach ($events as $event) { if (!in_array($event, $return)) { $return[] = $event; } } } return $return; } /** * @inheritDoc */ public function getActiveEvents() { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } return $this->currentState->getActiveEvents(); } /** * @inheritDoc */ public function isActive($event) { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } return in_array($event, $this->getActiveEvents()); } /** * @inheritDoc */ public function trigger($event) { if(!$this->isBooted()){ throw new StateMachineUnavailableException(); } if ($this->isActive($event)) { $transitions = $this->currentState->getTransitions(); /** @var \Swimson\Automaton\Transition\Transition $transition */ $transition = $transitions[$event]; $targetState = $transition->getTarget(); $this->transitionTo($targetState); } return $this; } /** * @inheritDoc */ public function boot(StateInterface $startingState) { if ($this->machineStatus == self::STATE_MACHINE_BOOTED) { throw new AlterStateMachineException(); } $this->currentState = $startingState; $this->machineStatus = self::STATE_MACHINE_BOOTED; return $this; } /** * @inheritDoc */ public function stop() { $this->currentState = null; $this->machineStatus = self::STATE_MACHINE_OFF; return $this; } /** * @inheritDoc */ public function isBooted() { return $this->machineStatus == self::STATE_MACHINE_BOOTED; } private function transitionTo(StateInterface $targetState) { if ($this->currentState->getName() != $targetState->getName()) { $this->currentState = $targetState; } } }<file_sep>/src/Swimson/Automaton/Transition/TransitionInterface.php <?php namespace Swimson\Automaton\Transition; interface TransitionInterface { /** * Get Source State * @return \Swimson\Automaton\State\State */ public function getSource(); /** * Get Target State * @return \Swimson\Automaton\State\ */ public function getTarget(); /** * @return string */ public function getEvent(); }
3b3d6813644341abbb496984857e29600b0bd57c
[ "Markdown", "PHP" ]
13
PHP
swimson/Automaton
4c1447214fe574ef4437c5eda3f1c27cf2af11b5
d990dc53b55732cf9f6ca5608e249a58f39b2ada
refs/heads/master
<file_sep>logging.level.org.springframework=ERROR logging.level.com.tenpin=ERROR spring.main.banner-mode=off game.path=src/test/resources/game.txt<file_sep>package com.tenpin.model; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class FramesFactoryTest { @InjectMocks private FramesFactory factory; List<Roll> rollList; @Test public void testShouldDifferentiateBetweenThrows(){ rollList = new ArrayList<>(); rollList.add(new Roll("a", "0")); rollList.add(new Roll("a", "5")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "F")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "4")); Frame frame1 = new Regular(new Roll("a", "0"), new Roll("a", "5"), null); Frame frame2 = new Strike(new Roll("a", "10"), null); Frame frame3 = new Spare(new Roll("a", "F"), new Roll("a", "10"), null); Frame frame4 = new Incomplete(new Roll("a", "4")); frame1.setNext(frame2); frame2.setNext(frame3); frame3.setNext(frame4); List<Frame> frames = new ArrayList<>(Arrays.asList(frame1,frame2,frame3,frame4)); Assert.assertEquals(frames.get(0).mark(),factory.build(rollList).get(0).mark()); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); } @Test public void testShouldCreateLastFrameForXXX(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Strike(new Roll("a", "10"), null); Frame frame3 = new Strike(new Roll("a", "10"), null); Frame terminal = Terminal.builder().one(frame1).two(frame2).three(frame3).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); frame2.setNext(frame3); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForXS(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "1")); rollList.add(new Roll("a", "9")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Spare(new Roll("a", "1"),new Roll("a", "9"), null); Frame terminal = Terminal.builder().one(frame1).two(frame2).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForXXI(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "9")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Strike(new Roll("a", "10"), null); Frame frame3 = new Incomplete(new Roll("a", "9")); Frame terminal = Terminal.builder().one(frame1).two(frame2).three(frame3).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); frame2.setNext(frame3); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForXR(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "1")); rollList.add(new Roll("a", "8")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Regular(new Roll("a", "1"),new Roll("a", "8"), null); Frame terminal = Terminal.builder().one(frame1).two(frame2).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForSI(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "1")); rollList.add(new Roll("a", "9")); rollList.add(new Roll("a", "2")); Frame frame1 = new Spare(new Roll("a", "1"),new Roll("a", "9"), null); Frame frame2 = new Incomplete(new Roll("a", "2")); Frame terminal = Terminal.builder().one(frame1).two(frame2).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForXI(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "9")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Incomplete(new Roll("a", "9")); Frame terminal = Terminal.builder().one(frame1).two(frame2).build(); frames.get(8).setNext(terminal); frame1.setNext(frame2); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForX(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "10")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame terminal = Terminal.builder().one(frame1).build(); frames.get(8).setNext(terminal); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForS(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "9")); rollList.add(new Roll("a", "1")); Frame frame1 = new Spare(new Roll("a", "9"),new Roll("a", "1"), null); Frame terminal = Terminal.builder().one(frame1).build(); frames.get(8).setNext(terminal); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } @Test public void testShouldCreateLastFrameForR(){ List<Frame> frames = createTillTerminal(); rollList.add(new Roll("a", "2")); rollList.add(new Roll("a", "1")); Frame frame1 = new Regular(new Roll("a", "2"),new Roll("a", "1"), null); Frame terminal = Terminal.builder().one(frame1).build(); frames.get(8).setNext(terminal); Assert.assertEquals(frames.get(0).score(),factory.build(rollList).get(0).score()); Assert.assertEquals(frames.get(8).mark(),factory.build(rollList).get(8).mark()); } private List<Frame> createTillTerminal() { rollList = new ArrayList<>(); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); rollList.add(new Roll("a", "10")); Frame frame1 = new Strike(new Roll("a", "10"), null); Frame frame2 = new Strike(new Roll("a", "10"), null); Frame frame3 = new Strike(new Roll("a", "10"), null); Frame frame4 = new Strike(new Roll("a", "10"), null); Frame frame5 = new Strike(new Roll("a", "10"), null); Frame frame6 = new Strike(new Roll("a", "10"), null); Frame frame7 = new Strike(new Roll("a", "10"), null); Frame frame8 = new Strike(new Roll("a", "10"), null); Frame frame9 = new Strike(new Roll("a", "10"), null); frame1.setNext(frame2); frame2.setNext(frame3); frame3.setNext(frame4); frame4.setNext(frame5); frame5.setNext(frame6); frame6.setNext(frame7); frame7.setNext(frame8); frame8.setNext(frame9); frame9.setNext(null); return new ArrayList<>(Arrays.asList(frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8,frame9)); } }<file_sep>package com.tenpin.model; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; @ToString @EqualsAndHashCode(callSuper = true) public class Regular extends Frame{ public Regular(@NonNull Roll first, @NonNull Roll second, Frame next) { super(first, second, next); if (first.getScore() + second.getScore() > 9){ throw new IllegalStateException("You can't sum more than 10 points in single frame!"); } } @Override public Integer score() { return super.first.getScore() + super.second.getScore(); } @Override public Integer scoreForSpare() { return first.getScore(); } @Override public Integer scoreForStrike() { return score(); } @Override public String mark() { return "\t" + (first.isF() ? "F": first.getScore()) + "\t" + (second.isF() ? "F": second.getScore()) + (hasNext() ? next.mark() : ""); } } <file_sep>package features; import com.tenpin.ApplicationStart; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.junit.Assert; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class ScoreboardSteps { private static final String EXPECTED_AVERAGE_SCOREBOARD = "src/test/resources/scoreboard-average.txt"; private static final String EXPECTED_PERFECT_SCOREBOARD = "src/test/resources/scoreboard-perfect.txt"; private static final String EXPECTED_AWFUL_SCOREBOARD = "src/test/resources/scoreboard-bust.txt"; private static final String EXPECTED_FRAMES = "src/test/resources/scoreboard-frames.txt"; private static final ByteArrayOutputStream SOUT_CAPTOR = new ByteArrayOutputStream(); private final ApplicationStart app; private String scoreboard; private String frames; public ScoreboardSteps(ApplicationStart app) { this.app = app; } public String loadFile(String path) throws IOException { StringBuilder builder = new StringBuilder(); Stream<String> stream = Files.lines( Paths.get(path), StandardCharsets.UTF_8); stream.forEach(s -> builder.append(s).append("\n")); System.setOut(new PrintStream(SOUT_CAPTOR)); return builder.toString(); } @When("I input my throws") public void iShowMyScoreboard() { app.run(); } @Then("I'm shown my scoreboard") public void iMShownMyScoreboard() { Assert.assertTrue(SOUT_CAPTOR.toString().trim().contains(scoreboard.trim())); Assert.assertTrue(SOUT_CAPTOR.toString().trim().contains(frames)); } @Given("I have an average game") public void iHaveAnAverageGame() throws IOException { scoreboard = loadFile(EXPECTED_AVERAGE_SCOREBOARD); frames = loadFile(EXPECTED_FRAMES); } @Given("I have a perfect game") public void iHaveAPerfectGame() throws IOException { scoreboard = loadFile(EXPECTED_PERFECT_SCOREBOARD); frames = loadFile(EXPECTED_FRAMES); } @Given("I have an awful game") public void iHaveAnAwfulGame() throws IOException { scoreboard = loadFile(EXPECTED_AWFUL_SCOREBOARD); frames = loadFile(EXPECTED_FRAMES); } } <file_sep>logging.level.org.springframework=ERROR logging.level.com.tenpin=ERROR spring.main.banner-mode=off game.path=${SCOREBOARD_PATH}<file_sep><h1>Ten pin bowling scoreboard</h1> <h2>Tech stack</h2> <ul> <li>Java 8</li> <li>Maven 3.6</li> <li>Spring boot 2.4</li> <li>Jackson 2.6</li> <li>Cucumber</li> <li>Docker</li> <li>Makefiles</li> </ul> <h2>How to run</h2> <p>In order to run, first localize your game.txt file with all the throws for the players. The path to this file can either be relative, if it resides within this projects directory, or absolute.</p> <p>With all this info retrieved, you may begin with the next step, running the application. You may choose to do it with docker or without it</p> <h3>1- Docker</h3> -- Working with version 19.03.12 - Other will most likely also work but no guarantees -- <p>Run these commands from the root replacing placeholders where necessary</p> <ul> <li>make build (this will take a while)</li> <li>make run SCOREBOARD_PATH={Path to game.txt file}</li> </ul> <p>For Windows you either have to download Ubuntu's subsystems plugin or adapt and run docker's commands manually from the Makefile file adapting syntax where necessary</p> <p><b>A note on docker executable:</b> Docker automatically converts all tabs separators to spaces. You may need to run this project natively on your machine in order to see the intended identation</p> <h3>2- Native</h3> <p>Run these commands from the root replacing placeholders where necessary</p> <ul> <li>make package</li> <li>make package native SCOREBOARD_PATH={Path to game.txt file}</li> </ul> <p>For windows follow advice in the docker section.</p> <h2>How to use</h2> <p>This is a CLI app without GUI. This project provides an example for games one player might encounter such as:.</p> perfect game, the worst outcome possible, and an average game with misses, strikes and spares. <p>Have fun!</p><file_sep>build: docker build -t ten-pin-scoreboard -f ten-pin-scoreboard/src/docker/Dockerfile . run: docker run --rm -itv ${SCOREBOARD_PATH}:/home/app/game.txt ten-pin-scoreboard:latest ten-pin-scoreboard package: mvn clean package native: java -D${SCOREBOARD_PATH} -jar ten-pin-scoreboard/target/ten-pin-scoreboard-1.0-SNAPSHOT.jar<file_sep>FROM maven:3.6-jdk-8 AS build COPY ten-pin-scoreboard/src /home/app/ten-pin-scoreboard/src COPY ten-pin-scoreboard/pom.xml /home/app/ten-pin-scoreboard COPY pom.xml /home/app RUN mvn -f /home/app/pom.xml package FROM openjdk:8 COPY --from=build /home/app/ten-pin-scoreboard/target/ten-pin-scoreboard-1.0-SNAPSHOT.jar /usr/local/lib/ten-pin-scoreboard.jar ENV SCOREBOARD_PATH=/home/app/game.txt ENTRYPOINT ["java","-jar","/usr/local/lib/ten-pin-scoreboard.jar"]<file_sep>package com.tenpin.model; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; @ToString @EqualsAndHashCode(callSuper = true) public class Spare extends Frame { public Spare(@NonNull Roll first, @NonNull Roll second, Frame next) { super(first, second, next); } @Override public Integer score() { return hasNext() && next.scoreForSpare() != null ? 10 + next.scoreForSpare() : null; } @Override public Integer scoreForSpare() { return first.getScore(); } @Override public Integer scoreForStrike() { return 10; } @Override public String mark() { return "\t" + (first.isF() ? "F": first.getScore()) + "\t/" + (hasNext() ? next.mark() : ""); } }
faa31964f8272bb307843196cf942dc0e688a643
[ "Markdown", "Makefile", "INI", "Java", "Dockerfile" ]
9
INI
JoseGC789/Bowling-Scoreboard
0bc8205c811d46fe4a24a768bd1c96aed4e8d77f
8e332f31a315c855af4f9a1b101c597a1da1dd50
refs/heads/master
<repo_name>86okimasa/furima-31128<file_sep>/spec/factories/item_purchases.rb FactoryBot.define do factory :item_purchase do token {"tok_<PASSWORD>"} postal_code {'123-4567'} prefecture_id {'1'} municipalities {'大阪市'} address {'1-1'} building {'ビル'} phone_number {'09000000000'} end end<file_sep>/spec/models/item_spec.rb require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '商品出品'do context '出品がうまくいくとき' do it '商品情報が全て存在していれば出品できる' do expect(@item).to be_valid end end context '出品がうまくいかないとき' do it '出品画像がないと出品できない' do @item.image = nil @item.valid? expect(@item.errors.full_messages).to include("Image can't be blank") end it '商品名がないと出品できない' do @item.name = nil @item.valid? expect(@item.errors.full_messages).to include("Name can't be blank") end it '説明がないと出品できない' do @item.explanation = nil @item.valid? expect(@item.errors.full_messages).to include("Explanation can't be blank") end it 'カテゴリーが選択されていないと出品できない' do @item.category_id = nil @item.valid? expect(@item.errors.full_messages).to include("Category can't be blank") end it 'カテゴリーが[--]では出品できない' do @item.category_id = 0 @item.valid? expect(@item.errors.full_messages).to include("Category must be other than 0") end it '状態が選択されていないと出品できない' do @item.condition_id = nil @item.valid? expect(@item.errors.full_messages).to include("Condition can't be blank") end it '配送料について選択されていないと出品できない' do @item.shipping_id = nil @item.valid? expect(@item.errors.full_messages).to include("Shipping can't be blank") end it '発送元について選択されていないと出品できない' do @item.prefecture_id = nil @item.valid? expect(@item.errors.full_messages).to include("Prefecture can't be blank") end it '発送日について選択されていないと出品できない' do @item.dispatch_id = nil @item.valid? expect(@item.errors.full_messages).to include("Dispatch can't be blank") end it '価格について選択されていないと出品できない' do @item.price = nil @item.valid? expect(@item.errors.full_messages).to include("Price can't be blank") end it '価格設定が範囲外だと出品できない(300円未満の時)' do @item.price = 1 @item.valid? expect(@item.errors.full_messages).to include("Price 半角数字で入力!¥300~¥9999999の範囲で入力") end it '価格設定が範囲外だと出品できない(9999999円超過の時)' do @item.price = 10000000 @item.valid? expect(@item.errors.full_messages).to include("Price 半角数字で入力!¥300~¥9999999の範囲で入力") end end end end <file_sep>/app/javascript/price.js function price () { const input = document.getElementById("item-price"); input.addEventListener("input", () => { const value = input.value; const tax = document.getElementById("add-tax-price"); tax.innerHTML = Math.floor(value * 0.1); const profit = document.getElementById("profit"); profit.innerHTML = Math.floor(value - value * 0.1); }) } window.addEventListener('load', price); <file_sep>/spec/factories/users.rb FactoryBot.define do factory :user do nickname {Faker::Name.initials(number: 2)} email {Faker::Internet.free_email} password {Faker::Internet.password(min_length: 4)+"1a"} password_confirmation {<PASSWORD>} family_name {"沖元"} first_name {"正明"} family_kana {"オキモト"} first_kana {"マサアキ"} birthday {Faker::Date.birthday(min_age: 5, max_age: 90)} end end <file_sep>/app/models/item.rb class Item < ApplicationRecord with_options presence: true do validates :image validates :name validates :explanation validates :category_id validates :condition_id validates :shipping_id validates :prefecture_id validates :dispatch_id validates :price, numericality: { with: /\A[0-9]+\z/, greater_than_or_equal_to: 300, less_than_or_equal_to: 9999999, message: "半角数字で入力!¥300~¥9999999の範囲で入力"} end belongs_to :user has_one_attached :image has_one :purchase extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :category belongs_to :condition belongs_to :shipping belongs_to :prefecture belongs_to :dispatch with_options numericality: { other_than: 0 } do validates :category_id validates :condition_id validates :shipping_id validates :prefecture_id validates :dispatch_id end end <file_sep>/app/models/item_purchase.rb class ItemPurchase include ActiveModel::Model attr_accessor :item_id, :user_id, :price, :postal_code, :prefecture_id, :municipalities, :address, :building, :phone_number, :token, :purchase_id, :token with_options presence: true do validates :postal_code, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: "郵便番号は半角数字でハイフンを含めてください"} validates :prefecture_id, numericality: { other_than: 0, message: "お届け先の都道府県を選択してください" } validates :municipalities validates :address validates :phone_number, numericality: { only_integer: true, message: "電話番号はハイフン無しで入力" } validates :token validates :user_id validates :item_id end def save @purchase = Purchase.create(item_id: item_id, user_id: user_id) Purchaser.create(postal_code: postal_code, prefecture_id: prefecture_id, municipalities: municipalities, address: address, building: building, phone_number: phone_number, purchase_id: @purchase.id) end end <file_sep>/spec/models/item_purchase_spec.rb require 'rails_helper' RSpec.describe ItemPurchase, type: :model do before do @item_purchase = FactoryBot.build(:item_purchase) end describe '商品購入'do context '購入がうまくいくとき' do it '情報全てが存在するとき' do expect(@item_purchase).to be_valid end it '建物名の情報がなくても購入できる'do @item_purchase.building = nil expect(@item_purchase).to be_valid end end context '購入ができないとき' do it 'クレジットカードの情報が空では購入できない' do @item_purchase.token = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Token can't be blank") end it '郵便番号が空では購入できない' do @item_purchase.postal_code = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Postal code can't be blank") end it '都道府県が空では購入できない' do @item_purchase.prefecture_id = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Prefecture お届け先の都道府県を選択してください") end it '市区町村が空では購入できない' do @item_purchase.municipalities = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Municipalities can't be blank") end it '番地が空では購入できない' do @item_purchase.address = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Address can't be blank") end it '電話番号が空では購入できない' do @item_purchase.phone_number = nil @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Phone number can't be blank") end it '郵便番号に[-]がなければ購入できない' do @item_purchase.postal_code = 1234567 @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Postal code 郵便番号は半角数字でハイフンを含めてください") end it '郵便番号は半角数字でなければ購入できない' do @item_purchase.postal_code = '1234567' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Postal code 郵便番号は半角数字でハイフンを含めてください") end it '都道府県が[--]では購入できない' do @item_purchase.prefecture_id = 0 @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Prefecture お届け先の都道府県を選択してください") end it '電話番号に[-]があると購入できない' do @item_purchase.phone_number = '123-4567' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Phone number 電話番号はハイフン無しで入力") end end end end <file_sep>/spec/models/user_spec.rb require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe '新規登録' do context '新規登録がうまくいくとき' do it "ユーザー情報及び本人確認の項目が全て存在すれば登録できる" do expect(@user).to be_valid end end context '新規登録がうまくいかないとき' do it "ニックネームが空だと登録できない" do @user.nickname = nil @user.valid? expect(@user.errors.full_messages).to include("Nickname can't be blank") end it "emailが空だと登録できない" do @user.email = nil @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it "パスワードが空だと登録できない" do @user.password = nil @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it "苗字が空だと登録できない" do @user.family_name = nil @user.valid? expect(@user.errors.full_messages).to include("Family name can't be blank") end it "名前が空だと登録できない" do @user.first_name = nil @user.valid? expect(@user.errors.full_messages).to include("First name can't be blank") end it "苗字のフリガナが空だと登録できない" do @user.family_kana = nil @user.valid? expect(@user.errors.full_messages).to include("Family kana can't be blank") end it "名前のフリガナが空だと登録できない" do @user.first_kana = nil @user.valid? expect(@user.errors.full_messages).to include("First kana can't be blank") end it "誕生日が空だと登録できない" do @user.birthday = nil @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end it "emailに一意性がないと登録できない" do @user.save another_user = FactoryBot.build(:user, email: @user.email) another_user.valid? expect(another_user.errors.full_messages).to include("Email has already been taken") end it "アドレスに@が含まれていないと登録できない" do @user.email = "aaa<EMAIL>" @user.valid? expect(@user.errors.full_messages).to include("Email is invalid") end it "パスワードが5文字以下だと登録できない" do @user.password = "<PASSWORD>" @user.password_confirmation = "<PASSWORD>" @user.valid? expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it "パスワードが半角英数混合でないと登録できない(半角英語のみの場合)" do @user.password = "<PASSWORD>" @user.valid? expect(@user.errors.full_messages).to include("Password には英字と数字の両方を含めて設定してください") end it "パスワードが半角英数混合でないと登録できない(半角数字のみの場合)" do @user.password = "<PASSWORD>" @user.valid? expect(@user.errors.full_messages).to include("Password には英字と数字の両方を含めて設定してください") end it "パスワードと確認用パスワードの値が一致していないと登録できない" do @user.password = "<PASSWORD>" @user.password_confirmation = "<PASSWORD>" @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it "苗字が全角(漢字、カタカナ、ひらがな)以外での入力だと登録できない" do @user.family_name = "aaaaa" @user.valid? expect(@user.errors.full_messages).to include("Family name 全角(漢字、カタカナ、ひらがな)を使用してください") end it "名前が全角(漢字、カタカナ、ひらがな)以外での入力だと登録できない" do @user.first_name = "aaaaa" @user.valid? expect(@user.errors.full_messages).to include("First name 全角(漢字、カタカナ、ひらがな)を使用してください") end it "苗字のフリガナが全角カタカナ以外での入力だと登録できない" do @user.family_kana = "あああああ" @user.valid? expect(@user.errors.full_messages).to include("Family kana 全角カタカナを使用してください") end it "名前のフリガナが全角カタカナ以外での入力だと登録できない" do @user.first_kana = "あああああ" @user.valid? expect(@user.errors.full_messages).to include("First kana 全角カタカナを使用してください") end end end end
2bb86f481506dc349d95e2189067ad7ee74acab8
[ "JavaScript", "Ruby" ]
8
Ruby
86okimasa/furima-31128
ddb3fb4b64b407c221c923b9f409d9ffbc38cc0f
e828c3a7fa653783b60a778a40e8e0af9ed650b7
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.baeldung</groupId> <artifactId>spring-jasper</artifactId> <version>1.0.1-SNAPSHOT</version> <name>spring-jasper</name> <packaging>war</packaging> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <!-- Spring Data JPA dependencies --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>${spring-data-jpa.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <!-- logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${org.slf4j.version}</version> </dependency> <!-- test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>${org.hamcrest.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>${org.hamcrest.version}</version> <scope>test</scope> </dependency> <!-- Jasper Report --> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>${jasperReport.version}</version> </dependency> </dependencies> <build> <finalName>spring-jasper</finalName> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>${maven-war-plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin.version}</version> <configuration> <excludes> <!-- <exclude>**/*ProductionTest.java</exclude> --> </excludes> <systemPropertyVariables> <!-- <provPersistenceTarget>h2</provPersistenceTarget> --> </systemPropertyVariables> </configuration> </plugin> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>${cargo-maven2-plugin.version}</version> <configuration> <wait>true</wait> <container> <containerId>jetty8x</containerId> <type>embedded</type> <systemProperties> <!-- <provPersistenceTarget>cargo</provPersistenceTarget> --> </systemProperties> </container> <configuration> <properties> <cargo.servlet.port>8082</cargo.servlet.port> </properties> </configuration> </configuration> </plugin> </plugins> </build> <properties> <java-version>1.7</java-version> <!-- spring --> <org.springframework.version>4.2.4.RELEASE</org.springframework.version> <!-- persistence --> <hibernate.version>4.3.11.Final</hibernate.version> <hibernate-validator.version>5.2.2.Final</hibernate-validator.version> <mysql-connector-java.version>5.1.37</mysql-connector-java.version> <spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version> <!-- logging --> <org.slf4j.version>1.7.13</org.slf4j.version> <logback.version>1.1.3</logback.version> <!-- javax jsp --> <javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version> <javax.servlet.version>3.0.1</javax.servlet.version> <jstl.version>1.2</jstl.version> <!-- Inject --> <javax.inject.version>1</javax.inject.version> <org.hamcrest.version>1.3</org.hamcrest.version> <junit.version>4.12</junit.version> <javax.mail.version>1.4.7</javax.mail.version> <jackson.version>2.6.4</jackson.version> <commons-dbcp.version>1.4</commons-dbcp.version> <!-- Maven plugins --> <cargo-maven2-plugin.version>1.4.17</cargo-maven2-plugin.version> <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version> <maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version> <!-- Jasper Report --> <jasperReport.version>6.2.0</jasperReport.version> </properties> <repositories> <repository> <id>jasperreports</id> <url>http://jasperreports.sourceforge.net/maven2</url> </repository> </repositories> </project><file_sep>package org.baeldung.persistence.model; public class Technology { private String techonologyName; public String getTechonologyName() { return techonologyName; } public void setTechonologyName(String techonologyName) { this.techonologyName = techonologyName; } }
e9f28626eda0c8f49963ccaa65ddfef8b47b02ca
[ "Java", "Maven POM" ]
2
Maven POM
dasvipin5585/tutorials
b14575f367feb1728d4fe511380de382dc666ee5
b6818ac40e9f30b09837c0754e3442a7daa3a928
refs/heads/master
<file_sep>import pandas as pd import matplotlib.pyplot as plt from Carro import Carro def read1(nome): arq = open(nome, "r") l = arq.readlines() modelo = l[0] ano = l[3] km = l[5] cor = l[7] # print(l[8]) if l[8][:6] == "PORTAS": val = l[10] # print(val) aux = l[11].split() comb = aux[3] motor = aux[9] camb = aux[11] else: val = l[8] # print(val) aux = l[9].split() comb = aux[3] motor = aux[9] camb = aux[11] arq.close() if nome == "data/test2.txt": aux = ano ano = km km = aux modelo = modelo.strip('\n') marca = modelo.split()[0] marca = marca.lower() cor = cor.strip('\n') ano = ano.strip('\n') motor = motor.strip('\n') motor = float(motor) comb = comb.strip('\n') val = val.strip('\n') val = val.strip("R$ ") val = val[:-3] val = val.replace(".", "") val = int(val) km = km.strip('\n') km = int(km) camb = camb.strip('\n') carro = Carro(modelo, marca, ano, km, val, motor, camb, comb, cor) return carro def read2(nome): arq = open(nome, "r") l = arq.readlines() for i in range(len(l)): if l[i][:6] == 'Modelo': modelo = l[i + 1] elif l[i][:5] == 'Marca': marca = l[i + 1] elif l[i][:3] == 'Ano': ano = l[i + 1] elif l[i][:13] == 'Quilometragem': km = l[i + 1] elif l[i][:3] == 'Cor': cor = l[i + 1] elif l[i][:6] == 'Câmbio': camb = l[i + 1] elif l[i][:11] == 'Combustível': comb = l[i + 1] elif l[i][:8] == 'Potência': motor = l[i + 1] arq.close() modelo = modelo.strip('\n') modelo = modelo.replace("GM - CHEVROLET", "Chevrolet") marca = marca.strip('\n') marca = marca.replace("GM - CHEVROLET", "Chevrolet") marca = marca.lower() cor = cor.strip('\n') ano = ano.strip('\n') motor = motor.strip('\n') motor = float(motor) comb = comb.strip('\n') km = km.strip('\n') km = int(km) camb = camb.strip('\n') carro = Carro(modelo, marca, ano, km, "nan", motor, camb, comb, cor) return carro arquivos1 = ["test1.txt", "test2.txt", "test3.txt", "test4.txt", "test5.txt", "test13.txt", "test14.txt", "test15.txt"] arquivos2 = ["test6.txt", "test7.txt", "test8.txt", "test9.txt", "test10.txt", "test11.txt", "test12.txt"] carros = [] for i in arquivos1: aux = "data/" + i carros.append(read1(aux)) for i in arquivos2: aux = "data/" + i carros.append(read2(aux)) df = pd.DataFrame({"Marca": [], "Modelo": [], "Ano": [], "Kilometragem": [], "Valor": [], "Potencia do motor": [], "Transmissão": [], "Combustivel": [], "Cor": []}) for i in carros: df = df.append(i.creat_serie(), ignore_index=True) # -------------------------------------------------------------------------- # Grafico pizza - cor do carro qnt_cor = df["Cor"].value_counts().values nome_cor = df["Cor"].value_counts().index explode = (0.1, 0, 0, 0) plt.title("Cor por carro") plt.pie(qnt_cor, labels=list(nome_cor), explode=explode, shadow=True, autopct="%1.1f%%") plt.show() # -------------------------------------------------------------------------- # Grafico de barra - Potencia por veiculo x = list(df["Modelo"]) aux2 = 0 for i in range(len(x)): aux = x[i].split()[1] if aux in x: aux = aux + str(aux2) aux2 = aux2 + 1 x[i] = aux y = df["Potencia do motor"] plt.xticks(rotation=90) plt.title("Potencia do motor por veiculo") plt.bar(x, y) plt.show() # -------------------------------------------------------------------------- # Grafico de disperção - Valor por veiculo x = list(df["Modelo"][df["Valor"] != "nan"]) aux2 = 0 for i in range(len(x)): aux = x[i].split()[1] if aux in x: aux = aux + str(aux2) aux2 = aux2 + 1 x[i] = aux y = df["Valor"][df["Valor"] != "nan"] plt.xticks(rotation=45) plt.title("Disperção dos preços") plt.scatter(x, y, marker='x', ) plt.show() # -------------------------------------------------------------------------- # Histograma - frequencia das kilometragens df.hist(column="Kilometragem") plt.title("Histograma - Kilometragem") plt.show() # -------------------------------------------------------------------------- # Grafico ed barra - numero de carros por montadora x = df["Marca"].value_counts().index y = df["Marca"].value_counts().values plt.title("Numero de veiculos por montadora") plt.barh(x, y) plt.show() <file_sep>import pandas as pd class Carro: def __init__(self, modelo, marca, ano, kilometragem, valor, motor, transmissao, combustivel, cor): self.modelo = modelo self.marca = marca self.ano = ano self.kilometragem = kilometragem self.valor = valor self.motor = motor self.transmissao = transmissao self.combustivel = combustivel self.cor = cor def print_carro(self): print(self.marca) print(self.modelo) print(self.ano) print(self.kilometragem) print(self.valor) print(self.motor) print(self.transmissao) print(self.combustivel) print(self.cor) def creat_serie(self): s = pd.Series([self.marca, self.modelo, self.ano, self.kilometragem, self.valor, self.motor, self.transmissao, self.combustivel, self.cor], ["Marca", "Modelo", "Ano", "Kilometragem", "Valor", "Potencia do motor", "Transmissão", "Combustivel", "Cor"]) return s
b555099d9fbf152a95d982461f19b30abdd661b9
[ "Python" ]
2
Python
danielpachec0/projetoMonitoriaIp
7575dfbec3c9ef73b7c1827d82069109faa347ee
bb9daef9d2a4fe29c0cba4060b2b521b97e74c8d
refs/heads/master
<file_sep>export const BASEURL = 'http://localhost:8443/' export const URL_PRODUCT_LIST = BASEURL + "productlist"<file_sep>import { connect } from 'react-redux' import App from '../components/App'; import { fetchProduct } from '../modules/products'; export default connect( (state) => ({ }), (dispatch) => ({ fetchProduct: () => dispatch(fetchProduct()), }) )(App)<file_sep>import React from 'react' import {MuiThemeProvider} from '@material-ui/core/styles' import {BrowserRouter,Route} from 'react-router-dom' import PropTypes from 'prop-types' import { CssBaseline,Box } from '@material-ui/core'; import ProductList from '../containers/ProductList'; const App = ({fetchProduct})=>{ const isFirstRef = React.useRef(true); React.useEffect(()=>{ if(isFirstRef.current){ isFirstRef.current = false; } fetchProduct() }) const contents = ( <BrowserRouter> <CssBaseline/> <Box display="flex"> {/* <Header/> */} <Route exact path="/" render={()=>{ return <ProductList/>; }}/> </Box> </BrowserRouter> ) return ( <MuiThemeProvider> <BrowserRouter> <CssBaseline/> {contents} </BrowserRouter> </MuiThemeProvider> ) } App.prototype ={ fetchProduct : PropTypes.func } export default App<file_sep>import { connect } from 'react-redux'; import ProductList from '../components/ProductList'; import { } from '../modules/products'; export default connect( (state) => ({ products: state.products.rows, loading: state.products.loading, error: state.products.error }), (dispatch)=>({ }) )(ProductList)<file_sep>import React from 'react'; import { Container,Box } from '@material-ui/core'; import {withRouter} from 'react-router-dom' const ProductList = ({ products, loading, error }) => { return ( <React.Fragment> <Container maxWidth="lg"> { products.map((product, index) => ( <Box key={ index }> Product { index + 1 } </Box> )) } </Container> </React.Fragment> ) } export default withRouter(ProductList);<file_sep># my_product_frontend react js version (example app for basic react redux , redux-thunk)
9661e63f68c688d2797ab79ff699256dcdd7e05d
[ "JavaScript", "Markdown" ]
6
JavaScript
ThantsinAg19/my_product_frontend
6aad4a73440a1a46b7db0b988ce33cc92a816e75
d3792a05dd9f20cf99c72cf43f929ed54a1ac35b
refs/heads/master
<repo_name>inaka/katana-test<file_sep>/README.md # katana-test # ⚠ THIS REPO IS ARCHIVED ⚠️ Instead of using this tool, consider adding a `test` alias to your `rebar.config`, like this: ```erlang {alias, [{test, [compile, format, lint, hank, dialyzer, {ct, "--verbose"}, cover, edoc]}]}. ``` That way, you can run `rebar3 test` on your CI pipelines and get the code checked with all the desirable tools/plugins at once. <details><summary>Old Readme</summary> Katana Test is an Erlang library application containing modules useful for testing Erlang systems. It currently contains the module `ktn_meta_SUITE`, which is a Common Test suite to be included among your tests. Read below for more information. # Contact Us If you find any **bugs** or have a **problem** while using this library, please [open an issue](https://github.com/inaka/katana-test/issues/new) in this repo (or a pull request :)). And you can check all of our open-source projects at [inaka.github.io](http://inaka.github.io) ### `ktn_meta_SUITE` #### Goals The **meta** suite lets you check your code with `dialyzer`, `xref` and `elvis`. #### Usage To include the suite in your project, you only need to invoke its functions from a common_test suite. If you use [mixer](https://github.com/inaka/mixer) you can do… ```erlang -module(your_meta_SUITE). -include_lib("mixer/include/mixer.hrl"). -mixin([ktn_meta_SUITE]). -export([init_per_suite/1, end_per_suite/1]). init_per_suite(Config) -> [{application, your_app} | Config]. end_per_suite(_) -> ok. ``` Of course, you can choose what functions to include, for example if you want `dialyzer` but not `elvis` nor `xref` you can do… ```erlang -mixin([{ ktn_meta_SUITE , [ dialyzer/1 ] }]). -export([all/0]). all() -> [dialyzer]. ``` #### Configuration `ktn_meta_SUITE` uses the following configuration parameters that you can add to the common_test config for your test suite: | Parameter | Description | Default | |-----------|-------------|---------| | `base_dir` | The base_dir for your app | `code:lib_dir(App)` where `App` is what you define in `application` below | | `application` | The name of your app | **no default** | | `dialyzer_warnings` | The active warnings for _diaylzer_ | `[error_handling, race_conditions, unmatched_returns, unknown]` | | `plts` | The list of plt files for _dialyzer_ | `filelib:wildcard("your_app/*.plt")` | | `elvis_config` | Config file for _elvis_ | `"your_app/elvis.config"` | | `xref_config` | Config options for _xref_ | `#{dirs => [filename:join(BaseDir, "ebin"), filename:join(BaseDir, "test")], xref_defaults => [{verbose, true}, {recurse, true}, {builtins, true}]}` | | `xref_checks` | List of checks for _xref_ | `[ undefined_function_calls, locals_not_used, deprecated_function_calls]` | | `dirs` | List of folders to check with _xref_ and _dialyzer_ | `["ebin", "test"]` | </details> <file_sep>/test/cover.spec %% Specific modules to include in cover. { incl_mods, [ ktn_meta_SUITE ] }. <file_sep>/CHANGELOG.md # Change Log ## [1.0.1](https://github.com/inaka/katana-test/tree/1.0.1) (2018-07-12) [Full Changelog](https://github.com/inaka/katana-test/compare/1.0.0...1.0.1) **Implemented enhancements:** - Remove get\_warnings from ktn\_meta\_SUITE [\#29](https://github.com/inaka/katana-test/issues/29) **Closed issues:** - If there is a test PLT, katana-test should use that one [\#48](https://github.com/inaka/katana-test/issues/48) - Update elvis\_core dependency version to 0.3.9 [\#43](https://github.com/inaka/katana-test/issues/43) - Error when is set as dependency using rebar3 [\#30](https://github.com/inaka/katana-test/issues/30) - Fulfill the open-source checklist [\#2](https://github.com/inaka/katana-test/issues/2) **Merged pull requests:** - update deps [\#51](https://github.com/inaka/katana-test/pull/51) ([getong](https://github.com/getong)) - Tiny README fixes [\#50](https://github.com/inaka/katana-test/pull/50) ([vassilevsky](https://github.com/vassilevsky)) - Remove unknown from the list of dialyzer warnings [\#49](https://github.com/inaka/katana-test/pull/49) ([elbrujohalcon](https://github.com/elbrujohalcon)) - If it exists use `\_build/test/lib` instead of `\_build/default/lib` [\#38](https://github.com/inaka/katana-test/pull/38) ([amilkr](https://github.com/amilkr)) ## [1.0.0](https://github.com/inaka/katana-test/tree/1.0.0) (2017-12-05) [Full Changelog](https://github.com/inaka/katana-test/compare/0.1.1...1.0.0) **Closed issues:** - Bump Version to 1.0.0 [\#46](https://github.com/inaka/katana-test/issues/46) **Merged pull requests:** - Bump version to 1.0.0 [\#47](https://github.com/inaka/katana-test/pull/47) ([elbrujohalcon](https://github.com/elbrujohalcon)) - \[Fix \#34\] Upgrade deps [\#45](https://github.com/inaka/katana-test/pull/45) ([elbrujohalcon](https://github.com/elbrujohalcon)) - Remove dead hipchat link [\#44](https://github.com/inaka/katana-test/pull/44) ([elbrujohalcon](https://github.com/elbrujohalcon)) - Write end\_per\_suite following OTP doc on init\_per\_suite [\#41](https://github.com/inaka/katana-test/pull/41) ([lucafavatella](https://github.com/lucafavatella)) - Dialyzer warn unknown [\#39](https://github.com/inaka/katana-test/pull/39) ([lucafavatella](https://github.com/lucafavatella)) ## [0.1.1](https://github.com/inaka/katana-test/tree/0.1.1) (2016-08-11) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.6...0.1.1) **Closed issues:** - Version Bump to 0.1.1 [\#35](https://github.com/inaka/katana-test/issues/35) - Version Bump to 0.1.0 [\#32](https://github.com/inaka/katana-test/issues/32) - Move from erlang.mk to rebar3 [\#28](https://github.com/inaka/katana-test/issues/28) **Merged pull requests:** - \[Close \#35\] version bump 0.1.1 [\#36](https://github.com/inaka/katana-test/pull/36) ([Euen](https://github.com/Euen)) - update build\_tool [\#34](https://github.com/inaka/katana-test/pull/34) ([Euen](https://github.com/Euen)) - \[Close \#32\] version bump 0.1.0 [\#33](https://github.com/inaka/katana-test/pull/33) ([Euen](https://github.com/Euen)) - Euen.28.rebar3 [\#31](https://github.com/inaka/katana-test/pull/31) ([Euen](https://github.com/Euen)) - Add proper rebar.config [\#27](https://github.com/inaka/katana-test/pull/27) ([elbrujohalcon](https://github.com/elbrujohalcon)) ## [0.0.6](https://github.com/inaka/katana-test/tree/0.0.6) (2016-04-08) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.5...0.0.6) **Merged pull requests:** - Version Bump to 0.0.6 [\#26](https://github.com/inaka/katana-test/pull/26) ([elbrujohalcon](https://github.com/elbrujohalcon)) - Upgrade elvis\_core dep to 0.2.11 [\#25](https://github.com/inaka/katana-test/pull/25) ([elbrujohalcon](https://github.com/elbrujohalcon)) ## [0.0.5](https://github.com/inaka/katana-test/tree/0.0.5) (2016-03-22) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.4...0.0.5) **Closed issues:** - Bump version to 0.0.5 [\#22](https://github.com/inaka/katana-test/issues/22) - ktn\_meta\_SUITE fails to find the plt when using rebar3 [\#21](https://github.com/inaka/katana-test/issues/21) **Merged pull requests:** - \[Fix \#22\] Bump version to 0.0.5 [\#24](https://github.com/inaka/katana-test/pull/24) ([harenson](https://github.com/harenson)) - \[Fix \#21\] Add Rebar3 default support [\#23](https://github.com/inaka/katana-test/pull/23) ([harenson](https://github.com/harenson)) ## [0.0.4](https://github.com/inaka/katana-test/tree/0.0.4) (2016-03-18) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.3...0.0.4) **Fixed bugs:** - sync is not in SHELL\_DEPS [\#16](https://github.com/inaka/katana-test/pull/16) ([elbrujohalcon](https://github.com/elbrujohalcon)) **Closed issues:** - Bump version to 0.0.4 after merging pull\#18 [\#19](https://github.com/inaka/katana-test/issues/19) - Allow user to provide a list with folders to check for xref and dialyzer tests [\#17](https://github.com/inaka/katana-test/issues/17) **Merged pull requests:** - \[Fix \#19\] Bump version to 0.0.4 [\#20](https://github.com/inaka/katana-test/pull/20) ([harenson](https://github.com/harenson)) - \[Fix \#17\] Allow user to provide a list of folders to check with xref and dialyzer tests [\#18](https://github.com/inaka/katana-test/pull/18) ([harenson](https://github.com/harenson)) ## [0.0.3](https://github.com/inaka/katana-test/tree/0.0.3) (2016-03-10) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.2...0.0.3) **Closed issues:** - Bump version to 0.0.3 [\#13](https://github.com/inaka/katana-test/issues/13) - Add rebar.config file [\#12](https://github.com/inaka/katana-test/issues/12) **Merged pull requests:** - \[Fix \#13\] Bump version to 0.0.3 [\#15](https://github.com/inaka/katana-test/pull/15) ([harenson](https://github.com/harenson)) - \[Fix \#12\] Add rebar.config file [\#14](https://github.com/inaka/katana-test/pull/14) ([harenson](https://github.com/harenson)) ## [0.0.2](https://github.com/inaka/katana-test/tree/0.0.2) (2016-03-09) [Full Changelog](https://github.com/inaka/katana-test/compare/0.0.1...0.0.2) **Closed issues:** - Bump version to 0.0.2 [\#9](https://github.com/inaka/katana-test/issues/9) - Rename katana-test.app.src to katana\_test.app.src [\#8](https://github.com/inaka/katana-test/issues/8) - Update to the latest version of elvis\_core \(0.2.8-2\) [\#6](https://github.com/inaka/katana-test/issues/6) **Merged pull requests:** - \[Fix \#9\] Bump version to 0.0.2 [\#11](https://github.com/inaka/katana-test/pull/11) ([harenson](https://github.com/harenson)) - \[Fix \#8\] Rename katana-test.app.src to katana\_test.app.src [\#10](https://github.com/inaka/katana-test/pull/10) ([harenson](https://github.com/harenson)) - \[Fix \#6\] Update elvis\_core dependency version to 0.2.8-2 [\#7](https://github.com/inaka/katana-test/pull/7) ([harenson](https://github.com/harenson)) ## [0.0.1](https://github.com/inaka/katana-test/tree/0.0.1) (2016-03-01) **Merged pull requests:** - Igaray.version bump [\#5](https://github.com/inaka/katana-test/pull/5) ([igaray](https://github.com/igaray)) - Initial commit. [\#3](https://github.com/inaka/katana-test/pull/3) ([igaray](https://github.com/igaray)) - Update LICENSE [\#1](https://github.com/inaka/katana-test/pull/1) ([elbrujohalcon](https://github.com/elbrujohalcon)) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
c1c7138b5914d12592e44e277caca8f9d2d8217a
[ "Markdown", "Python" ]
3
Markdown
inaka/katana-test
4ec9be2202b2d0466f84f3ba96e9aedb9fb05bf5
cfd522334babdb05589ef79640fb8e022fbdcb11
refs/heads/master
<repo_name>casualarmsbeta/casualarmsbeta.github.io<file_sep>/data/support.js --- --- // Change this when the community administration enters/leaves DST! var communityObservesDST = true; // true or false // End DST change region var staticDataJSON = {% include_relative static.json %}; var eventGames = staticDataJSON["eventGames"]; var leaderboardTiers = staticDataJSON["leaderboardTiers"]; var patreonTiers = staticDataJSON["patreonTiers"]; var leaderboardTitles = staticDataJSON["leaderboardTitles"]; var eventTypes = staticDataJSON["eventTypes"]; var eventStages = staticDataJSON["eventStages"]; var eventItems = staticDataJSON["eventItems"]; var eventThemes = staticDataJSON["eventThemes"]; var stageSets = staticDataJSON["stageSets"]; var itemSets = staticDataJSON["itemSets"]; var eventSponsors = staticDataJSON["eventSponsors"]; var badgeList = staticDataJSON["badgeList"]; var eventTypesLeaderboards = staticDataJSON["eventTypesLeaderboards"]; for (var game in eventGames) { for (var i = 1; i < leaderboardTiers[game].length; ++i) { var tier = leaderboardTiers[game][i]; var badge = { "caption" : leaderboardTitles[game].prefix + tier.name + leaderboardTitles[game].suffix, "style" : "light", "criterion" : "Earn at least " + tier.start + " points in " + eventGames[game] + " events", }; badgeList[game + "_ldb" + (i - 1)] = badge; } } // Event database var eventDataJSON = {% include_relative events.json %}; for (var i = 0; i < eventDataJSON.length; i++) { var eventdata = eventDataJSON[i]; eventdata.date = new Date(eventdata.date); eventDataJSON[i] = eventdata; } eventDataJSON.sort(function(a, b) { return a.date - b.date; }); // Streams database var streamsDataJSON = {% include_relative streams.json %}; for (var s = 0; s < streamsDataJSON.length; s++) { var eventdata = streamsDataJSON[s]; eventdata.date = new Date(eventdata.date); streamsDataJSON[s] = eventdata; } streamsDataJSON.sort(function(a, b) { return a.date - b.date; }); // Leaderboards etc var leaderboardsJSON = {% include_relative leaderboards.json %}; var seasonHistoryJSON = {% include_relative season-history.json %}; var badgeDatabaseJSON = {% include_relative badges.json %}; var patronsJSON = {% include_relative patreon.json %}; leaderboardsJSON.variety = [] for (var game in eventGames) leaderboardsJSON[game].sort(function(a, b) { return b.coins - a.coins; }); // Tournament history var tournamentsLog = {% include_relative champions.json %}; // Host database var hostDatabase = [ { "tag" : "CC", "name" : "Rashiko", "code" : "6822-5055-2423", tier : 2}, { "tag" : "", "name" : "Literary", "code" : "4704-7597-7783", tier : 2}, //{ "tag" : "", "name" : "Mileve", "code" : "2795-2096-7893", tier : 3}, { "tag" : "", "name" : "Sora", "code" : "0499-4528-8293", tier : 3}, { "tag" : "", "name" : "Reis", "code" : "1753-6049-3315", tier : 3}, //{ "tag" : "CC", "name" : "Marie", "code" : "5693-4645-2698", tier : 3}, { "tag" : "", "name" : "Spenjo", "code" : "0725-4824-1895", tier : 2}, { "tag" : "", "name" : "Levi", "code" : "3256-0282-5625", tier : 1}, { "tag" : "", "name" : "Taste", "code" : "4535-5139-5505", tier : 1}, { "tag" : "", "name" : "<NAME>", "code" : "4303-5678-5601", tier : 0}, { "tag" : "", "name" : "<NAME>", "code" : "0656-1636-5890", tier : 0}, { "tag" : "CC", "name" : "Fang", "code" : "8434-0819-1597", tier : 0}, { "tag" : "", "name" : "DinosaurY", "code" : "2926-5224-3023", tier : 0}, { "tag" : "", "name" : "Jake", "code" : "7677-0583-7008", tier : 0}, { "tag" : "CC", "name" : "Era", "code" : "5972-7410-1228", tier : 0}, { "tag" : "CC", "name" : "Cocovet", "code" : "8037-4720-4522", tier : 0}, { "tag" : "", "name" : "Ombreverte", "code" : "3089-8564-5404", tier : 0}, { "tag" : "", "name" : "Udon", "code" : "3801-5397-8600", tier : 0}, { "tag" : "CC", "name" : "Tom", "code" : "3190-3514-8531", tier : 0}, ] var dst = communityObservesDST ? -60 : 0; var eventSlots = [ { "id" : "arms-tue", "slot_game" : "arms", "game" : "arms", "date" : getNextWeekday(3, 02, 00, dst), "duration" : 120, "tz" : "PST", "type" : "leaderboard", "title" : "Tidal Tuesday"}, { "id" : "arms-wed", "slot_game" : "arms", "game" : "arms", "date" : getNextWeekday(3, 23, 00, dst), "duration" : 120, "tz" : "EST", "type" : "leaderboard", "title" : "Wildcard Wednesday"}, { "id" : "arms-thu", "slot_game" : "arms", "game" : "arms", "date" : getNextWeekday(4, 19, 00, dst), "duration" : 120, "tz" : "GMT", "type" : "leaderboard", "title" : "Thumpin' Thursday"}, { "id" : "arms-sun", "slot_game" : "arms", "game" : "arms", "date" : getNextWeekday(0, 20, 45, dst), "duration" : 120, "tz" : "EST", "type" : "leaderboard", "title" : "Sunday Showdown"}, // { "id" : "kart-mon", "slot_game" : "flex", "game" : "kart", "date" : getNextWeekday(1, 18, 30), "duration" : 60, "tz" : "GMT", "type" : "race", "title" : "Monday Motorway", "stages" : "all-race", "theme" : "150cc", "hosts" : [{"name":"","code":"1077-9421-4443"}]}, // { "id" : "kart-wed", "slot_game" : "flex", "game" : "kart", "date" : getNextWeekday(3, 18, 30), "duration" : 60, "tz" : "GMT", "type" : "race", "title" : "Wonky Wednesday", "stages" : "all-race", "theme" : "mirror", "hosts" : [{"name":"","code":"4621-2901-6363"}]}, // { "id" : "kart-fri", "game" : "flex", "start" : getNextWeekday(5, 22, 30), "duration" : 60, "tz" : "EST", "type" : "battle", "title" : "Frantic Friday", "stages" : "all-battle", "theme" : "mk_battle"}, // { "id" : "kart-sat", "slot_game" : "flex", "game" : "kart", "date" : getNextWeekday(6, 23, 30), "duration" : 60, "tz" : "EDT", "type" : "race", "title" : "Saturday Speedway", "stages" : "all-race", "theme" : "200cc", "hosts" : [{"name":"","code":"4412-5645-5723"}]}, { "id" : "splat-mon", "slot_game" : "splat", "game" : "splat", "date" : getNextWeekday(1, 19, 30, dst), "duration" : 60, "tz" : "EST", "type" : "friends", "title" : "Messy Monday"}, { "id" : "splat-thu", "slot_game" : "splat", "game" : "splat", "date" : getNextWeekday(5, 02, 30, dst), "duration" : 60, "tz" : "PST", "type" : "friends", "title" : "Turfsday"}, { "id" : "splat-sat", "slot_game" : "splat", "game" : "splat", "date" : getNextWeekday(6, 17, 30, dst), "duration" : 60, "tz" : "GMT", "type" : "friends", "title" : "Splaturday"}, { "id" : "smash-mon", "slot_game" : "smash", "game" : "smash", "date" : getNextWeekday(1, 22, 30, dst), "duration" : 60, "tz" : "EST", "type" : "friends", "title" : "Marthday"}, { "id" : "smash-wed", "slot_game" : "smash", "game" : "smash", "date" : getNextWeekday(3, 19, 30, dst), "duration" : 60, "tz" : "GMT", "type" : "friends", "title" : "WedNessDay"}, { "id" : "smash-sat", "slot_game" : "smash", "game" : "smash", "date" : getNextWeekday(0, 00, 30, dst), "duration" : 60, "tz" : "PST", "type" : "friends", "title" : "Mr. Saturnday"}, ]; var streamSlots = [ // { "id" : "maker-mon", "slot_game" : "variety", "platform" : "mixer", "game" : "variety", "date" : getNextWeekday(1, 18, 30), "duration" : 60, "tz" : "EDT", "title" : "Maker Monday"}, // { "id" : "mine-tue", "slot_game" : "variety", "platform" : "twitch", "game" : "variety", "date" : getNextWeekday(3, 01, 00), "duration" : 120, "tz" : "EDT", "title" : "Tiled Tuesday"} ];
0aee8f8bb0315d28ac01655be3278c6cf187ff5d
[ "JavaScript" ]
1
JavaScript
casualarmsbeta/casualarmsbeta.github.io
7036c90d4abc41e6b1b76957a42bcc2b98af1806
e55c223b7da01980db84b6a70d07e6c154746fbd
refs/heads/master
<file_sep>import { ADD, CHANGE, DELETE } from './const'; import { ITodoState } from '../../interface'; const initState: ITodoState = { todoList: [] } export const Todo = (state = initState, action: any) => { const index = state.todoList.findIndex(item => item.id === action.id); switch (action.type) { case ADD: return Object.assign({}, state, { todoList: [...state.todoList, action.response] }); case DELETE: return Object.assign({}, state, { todoList: [ ...state.todoList.slice(0, index), ...state.todoList.slice(index + 1) ] }); case CHANGE: return Object.assign({}, state, { todoList: [ ...state.todoList.slice(0, index), Object.assign({}, state.todoList[index], { done: !state.todoList[index].done}), ...state.todoList.slice(index + 1) ] }); default: return state; } };<file_sep>import { ADD, DELETE, CHANGE } from './const'; // import { ITodoItem } from '../../interface'; export interface IAddTodoItem { type: ADD } export interface IDeleteTodoItem { type: DELETE; } export interface IChangeTodoItem { type: CHANGE; } export type TodoAction = IAddTodoItem | IDeleteTodoItem | IChangeTodoItem; export const AddTodoItem = (value: string) => { return { type: ADD, response: { contents: value, done: false, id: value + Math.random() } }; }; export const DeleteTodoItem = (id: string) => { return { type: DELETE, id }; } export const ChangeTodoItem = (id: string) => { return { type: CHANGE, id }; } <file_sep>export interface ITodoItem { contents: string, done: boolean, id: string } export interface ITodoProps { todoList: ITodoItem[] } export interface ITodoState { todoList: ITodoItem[] } export interface ITodoHandleEvent { handleDeleteItem(id: string): void, handlechangeItemStatus(id: string): void, } export interface ITodoHandleAddItem{ handleAddItem(value: string): any }<file_sep>export const ADD = 'ADD_TODO_ITEM'; export const DELETE = 'DELETE_TODO_ITEM'; export const CHANGE = 'CHANGE_TODO_ITEM'; export type ADD = typeof ADD; export type DELETE = typeof DELETE; export type CHANGE = typeof CHANGE;
3598af8a1c6896cb6a3aad7df406773a988ceca8
[ "TypeScript" ]
4
TypeScript
baokenan/ts-todo-bkn
a39211cef77cf2b5f84394bc73a20b86053269b4
1a9fa53d24079824ea6cdde07b3116f2957fdb90
refs/heads/master
<file_sep><?php $groupswithaccess="ALL"; require_once("slpw/sitelokpw.php"); require_once("slpw/slupdateform.php"); ?> <!doctype html> <html class="no-js" 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 rel="shortcut icon" href="/assets/icons/favicon.ico" type="image/x-icon"> <link rel="icon" href="/assets/icons/favicon.ico" type="image/x-icon"> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> <title>Creative Peaks</title> <?php if (function_exists('sl_loginformhead')) sl_loginformhead(5,false); ?> <?php if (function_exists('sl_updateformhead')) sl_updateformhead(4,false); ?> <meta name="description" content="Creative Peaks is a professional organization established to help arts graduates and arts educators develop their skills and start a rewarding career doing what they love."> <link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <body> <!-- ONLY VISIBLE IF NOT LOGGED IN --> <?php if ($slpublicaccess) { ?> <div style="padding-left: 40%"> <?php if (function_exists('sl_loginformbody')) sl_loginformbody(5,false,$msg); ?> <!-- Login Form --> <?php } // Hide ?> </div> <!-- ONLY VISIBLE IF LOGGED IN --> <?php if (!$slpublicaccess) { ?> <!--Responsive Top Menu --> <div class="grid-container"> <div class="grid-x"> <div class="small-6 cell"> <img src="assets/peakslogohorizontal.svg" alt="" style="width:60%; padding-top: 20px;"> </div> <div class="small-6 cell"> <ul class="menu align-right welcome_top"> <li>Welcome, <?php echo $slname_html; ?> | <a class="on-hover"href="slpw/sitelokpw.php?sitelokaction=logout">Logout</a></li> </ul> </div> </div> </div> <!-- Welcome Banner --> <div class="grid-x grid-padding-x align-bottom welcome_banner"> <div class="grid-container"> <div class="small-12 medium-4 cell"></div> <div class="small-12 medium-4 cell"> <h5 class="greeting">Welcome, <?php echo $slname_html; ?></h4> </div> <div class="small-12 medium-4 cell"></div> </div> </div> <!-- Member Boxes --> <div class="divbox grid-x grid-padding-x"> <!--News Announcements--> <div class="small-12 cell memberboxes" id="memberbox1" style="display: block;"> <ul class="menu align-center nav_menu"> <li class="is-active"><a href="#">News</a></li> <li><a href="javascript:showonlyone('memberbox2')">Blog</a></li> <li><a href="https://members.creativepeaks.org/community">Community</a></li> <li><a href="#">Get Trained</a></li> <li><a href="#">My Courses</a></li> <li><a href="#sl_account_area">My Account</a></li> </ul> <div class="grid-container"> <div class="grid-x"> <div class="small-12 medium-4 cell content_spaced"> <h5>Announcing Our Next Round of Trainings</h5> <h6>Starting October 1st, 2019</h6> <p>To apply you must fill out the application</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat recusandae voluptas accusamus corporis at veritatis voluptatem laborum, eligendi repellat porro beatae, dolorem molestias aperiam eaque provident, tempore necessitatibus temporibus in?</p> </div> <div class="small-12 medium-4 cell content_spaced"> <h5>Announcing Our Next Round of Trainings</h5> <h6>Starting October 1st, 2019</h6> <p>To apply you must fill out the application</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat recusandae voluptas accusamus corporis at veritatis voluptatem laborum, eligendi repellat porro beatae, dolorem molestias aperiam eaque provident, tempore necessitatibus temporibus in?</p> </div> <div class="small-12 medium-4 cell content_spaced"> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Praesentium ad, dolores labore illum qui sit doloribus nostrum ipsam ex dignissimos ratione ea veritatis assumenda officia architecto eum voluptatum excepturi facilis?</p> <?php if ((function_exists('sl_isactivememberof')) && (sl_isactivememberof("TEST"))) { ?> <p>Group only text</p> <?php } ?> </div> </div> </div> </div> <!-- Blog --> <div class="small-12 cell memberboxes" id="memberbox2" style="display: none;"> <ul class="menu align-center nav_menu"> <li><a href="javascript:showonlyone('memberbox1')">News</a></li> <li class="is-active"><a>Blog</a></li> <li><a href="https://members.creativepeaks.org/community">Community</a></li> <li><a href="#">Get Trained</a></li> <li><a href="#">My Courses</a></li> <li><a href="#sl_account_area">My Account</a></li> </ul> <div class="grid-container"> <div class="grid-x"> <div class="small-12 medium-6 cell"> <h5>Recent Blog Articles</h5> <h6>Starting October 1st, 2019</h6> <p>To apply you must fill out the application</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat recusandae voluptas accusamus corporis at veritatis voluptatem laborum, eligendi repellat porro beatae, dolorem molestias aperiam eaque provident, tempore necessitatibus temporibus in?</p> </div> <div class="small-12 medium-6 cell"> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Praesentium ad, dolores labore illum qui sit doloribus nostrum ipsam ex dignissimos ratione ea veritatis assumenda officia architecto eum voluptatum excepturi facilis?</p> </div> </div> </div> </div> <!-- Account Information --> <div class="small-12 cell memberboxes" id="memberbox3" style="display: none;"> <div class="grid-container"> <div class="grid-x"> <div class="small-6 cell reveal" id="update_form" data-reveal> <?php if (function_exists('sl_updateformbody')) sl_updateformbody(4,false); ?> <button class="close-button" data-close aria-label="Close modal" type="button"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> </div> <!-- Logout--> <div class="memberboxes" id="memberbox6" style="display:none;"> <p>click here to <a href="slpw/sitelokpw.php?sitelokaction=logout">Logout</a></p> <?php } ?> </div> </div> <!-- Account Area --> <div class="grid-container"> <div class="grid-x grid-padding-x" id="sl_account_area"> <div class="small-4 cell"> <h5 class="boarder_box">My Account</h5> <ul> <li>Username: <?php echo $slusername_html; ?></li> <li>Email: <?php echo $slemail_html; ?></li> </ul> <ul class="menu acct_edit"> <li class="edit_p"><a data-open="update_form">Edit Profile</a></li> <li><a href="#">Change Password</a></li> </ul> </div> <div class="small-8 cell"> <h5 class="boarder_box">My Membership</h5> </div> </div> </div> <!-- end content section --> <script src="node_modules/jquery/dist/jquery.js"></script> <script src="node_modules/what-input/dist/what-input.js"></script> <script src="node_modules/foundation-sites/dist/js/foundation.js"></script> <script src="node_modules/foundation-sites/js/foundation.core.js"></script> <script src="node_modules/foundation-sites/js/foundation.accordion.js"></script> <script src="node_modules/foundation-sites/js/foundation.reveal.js"></script> <script src="node_modules/foundation-sites/js/foundation.dropdownMenu.js"></script> <script src="node_modules/foundation-sites/js/foundation.accordionMenu.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.keyboard.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.box.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.nest.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.triggers.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.mediaQuery.js"></script> <script src="node_modules/foundation-sites/js/foundation.util.motion.js"></script> <script src="js/app.js"></script> </body> </head>
b47665163c7befea772a9b8bff5653bc83e6852d
[ "PHP" ]
1
PHP
adjustyourtone/cpMembers
f3275c1ba6fcd53b6f273a6fdd07262d2638d661
b582b5430f1ec7fcac287e4fbd9fbe3a810bc51d
refs/heads/master
<file_sep>let a = 9; let b = a*2; console.log(b);
fa4743ea2fb9ee3274fb9f6eca087533c4b7190f
[ "JavaScript" ]
1
JavaScript
gagansidhu09/4april
6dfa435beb8eee7b5d0aef150dcf28bead4f7450
59e072b928eadc8727f42e6d8be7c9a5dcd6f13e
refs/heads/master
<file_sep>rootProject.name = 'rabbit-publisher' <file_sep>package com.publisher.controller; import com.publisher.service.OrderService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @RequiredArgsConstructor public class OrderController { private final OrderService orderService; @GetMapping("order/{id}") public Map<String,String> order(@PathVariable Long id) { return orderService.order(id); } } <file_sep>rootProject.name = 'rabbit-consumer' <file_sep>package com.publisher.service; public interface EmailService { void sendEmail(String email); } <file_sep>package com.publisher.service.impl; import com.publisher.model.Order; import com.publisher.service.EmailService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.stream.function.StreamBridge; import org.springframework.stereotype.Service; @RequiredArgsConstructor @Service @Slf4j public class EmailServiceImpl implements EmailService { //private final Consumer<Integer> acceptOrderConsumer; private final StreamBridge streamBridge; @Override public void sendEmail(String email) { log.info("Sending email to {}",email); streamBridge.send("email", email); //acceptOrderConsumer.accept((int) id); } }
bc7fb3ac4a9fcba4972fdf48649982d354e2b62e
[ "Java", "Gradle" ]
5
Gradle
mdsagir/spring-cloud-stream-rabbimq
e7af877fe3ac581102cde36412b8fa8edacb7ab9
8e9ebb3c453bb5c53b4084847e3518a350d7f654
refs/heads/master
<file_sep>#ifndef H_HEADER_INCLUDED #define H_HEADER_INCLUDED #include <iostream> class Rational { public: bool nan; int numerator; int denumerator; //constructors Rational(); Rational(int); Rational(int, int); //functions int gcd(int, int); // to realization the function reduce Rational reduce(); Rational neg(); // negative, x*(-1) Rational inv(); // inverse, x^-1 Rational sum(Rational); Rational sub(Rational); Rational mul(Rational); Rational div(Rational); //comparison functions bool eq(Rational); // "==" bool neq(Rational); // "!=" bool l(Rational); // less than "<" bool leq(Rational); //// less or equal than "<=" bool g(Rational); // greater than ">" bool geq(Rational); // greater or equal than ">=" //functions of input and output void scan(); void print(); //operators Rational operator+(Rational); Rational operator-(Rational); Rational operator*(Rational); Rational operator/(Rational); bool operator==(Rational); bool operator!=(Rational); bool operator<(Rational); bool operator<=(Rational); bool operator>(Rational); bool operator>=(Rational); }; std::ostream& operator<<(std::ostream&, const Rational&); std::istream& operator>>(std::istream&, Rational&); #endif // H_HEADER_INCLUDED <file_sep>#include <iostream> #include "header.h" Rational::Rational() { numerator = 1; denumerator = 1; } Rational::Rational(int x) { numerator = x; denumerator = 1; } Rational::Rational(int x, int y) { numerator = x; denumerator = y; nan = (y == 0); } int Rational::gcd(int a, int b) { return b ? gcd(b, a % b) : a; } Rational Rational::reduce(){ int res = gcd(numerator, denumerator); return Rational(numerator / res, denumerator / res); } Rational Rational::neg() { return Rational((-1) * numerator, denumerator); } Rational Rational::inv() { return Rational(denumerator, numerator); } Rational Rational::sum(Rational r) { if (denumerator == r.denumerator) { return Rational(numerator + r.numerator, denumerator); } else { int newNumerator = numerator * r.denumerator + r.numerator * denumerator; int newDenumerator = denumerator * r.denumerator; return Rational(newNumerator, newDenumerator); } } Rational Rational::sub(Rational r) { return sum(r.neg()); } Rational Rational::mul(Rational r) { return Rational(numerator * r.numerator, denumerator * r.denumerator); } Rational Rational::div(Rational r) { return mul(r.inv()); } bool Rational::eq(Rational r) { return numerator == r.numerator && denumerator == r.denumerator; } bool Rational::neq(Rational r) { return !eq(r); } bool Rational::l(Rational r) { return numerator * r.denumerator < r.numerator * denumerator; } bool Rational::leq(Rational r) { return numerator * r.denumerator <= r.numerator * denumerator; } bool Rational::g(Rational r) { return numerator * r.denumerator > r.numerator * denumerator; } bool Rational::geq(Rational r) { return numerator * r.denumerator >= r.numerator * denumerator; } void Rational::print() { if (nan) { std::cout << "NAN" << std::endl; } else { std::cout << numerator << "/" << denumerator << std::endl; } } void Rational::scan() { std::cout << "Enter the numerator: "; std::cin >> numerator; std::cout << "Enter the denumerator: "; std::cin >> denumerator; nan = (denumerator == 0); } Rational Rational::operator+(Rational r) { return sum(r); } Rational Rational::operator-(Rational r) { return sub(r); } Rational Rational::operator*(Rational r) { return mul(r); } Rational Rational::operator/(Rational r) { return div(r); } bool Rational::operator==(Rational r) { return eq(r); } bool Rational::operator!=(Rational r) { return neq(r); } bool Rational::operator<(Rational r) { return l(r); } bool Rational::operator<=(Rational r) { return leq(r); } bool Rational::operator>(Rational r) { return g(r); } bool Rational::operator>=(Rational r) { return geq(r); } std::ostream& operator<<(std::ostream& output, const Rational& r) { if (r.nan) { output << "NAN"; } else { output << r.numerator << "/" << r.denumerator; } return output; } std::istream& operator>>(std::istream& input, Rational& r) { input >> r.numerator >> r.denumerator; r.nan = (r.denumerator == 0); return input; } <file_sep>#include "header.h" #include <iostream> int main() { Rational x; // 1/1 Rational y(10, 5); // 10/5 Rational z(7); std::cout << "x.eq(y): "; std::cout << x.eq(y) << std::endl; std::cout << "x.neq(y): "; std::cout << x.neq(y) << std::endl; std::cout << "z.neg(): "; z.neg().print(); Rational n(10, 0); n.mul(Rational(1)).print(); Rational(1).mul(n).print(); }
403db154b9b90cd1b0a42049b211ae5ae4bb4d63
[ "C++" ]
3
C++
natali1821/Rationals
e3ab55493182b91df0a7272c823dca4648aac30a
4ff650b5983f6d431c5629009ed2c5943c5d293d
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.CompoundBorder; import javax.swing.border.EtchedBorder; /** * * @author Magda */ public class Swing2 { Swing2(Zbior z1){ BufferedImage myImage = null; try{ myImage = ImageIO.read(new File("images\\img2.jpg")); } catch(IOException e) { } JFrame ramka = new JFrame("Rezerwacje"); ramka.setContentPane(new ImagePanel(myImage)); JButton powrot = new JButton("Powrót"); powrot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent event){ new Swing(z1); ramka.setVisible(false); ramka.dispose(); } }); powrot.setBounds(50,50,150,50); ramka.add(powrot); ramka.setSize(600,600); // stała szerokość okna aby nam dzięcioły nie psuły aplikacji :-) ramka.setResizable(false); ramka.setLayout(null); ramka.setVisible(true); ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ramka.setLocationRelativeTo(null); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.CompoundBorder; import javax.swing.border.EtchedBorder; /** * * @author Magda */ public class Swing5 { public boolean getWartosc(String i ){ if (i=="Tak"){ return true; } else{ return false; } } Swing5(Zbior z1){ BufferedImage myImage = null; try{ myImage = ImageIO.read(new File("images\\img2.jpg")); } catch(IOException e) { } JFrame ramka = new JFrame("Rezerwacje"); ramka.setContentPane(new ImagePanel(myImage)); JButton powrot = new JButton("Powrót"); powrot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent event){ new Swing(z1); ramka.setVisible(false); ramka.dispose(); } }); powrot.setBounds(50,50,150,50); ///////////////////////// JLabel naglowek = new JLabel(); naglowek.setText("<html><p>Dodaj budynek&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p><hr/>" + "<p>Nazwa</p><p></p><p>Winda</p><p></p><p>Wi-Fi</p>" + "<p></p><p>Gastronomia</p>" + "</html>"); naglowek.setBounds(50,150,450,400); naglowek.setFont(new Font("Serif", Font.PLAIN, 21)); naglowek.setForeground(Color.BLACK); naglowek.setOpaque(true); naglowek.setBackground(Color.white); naglowek.setBorder( new CompoundBorder( new CompoundBorder( BorderFactory.createLineBorder(Color.LIGHT_GRAY,10), BorderFactory.createLineBorder(Color.GRAY,6) ), BorderFactory.createLineBorder(Color.WHITE,10) ) ); naglowek.setVerticalAlignment(SwingConstants.TOP); ramka.add(naglowek); /////////////// JTextField tNazwaB = new JTextField("Podaj nazwę"); tNazwaB.setBounds(26, 95, 190, 25); naglowek.add(tNazwaB); //////////////// String windaTN[] = {"Tak","Nie"}; JComboBox winda = new JComboBox(windaTN); winda.setBounds(26,150,190,25); winda.setBackground(Color.WHITE); naglowek.add(winda); String wifiTN[] = {"Tak","Nie"}; JComboBox wifi = new JComboBox(wifiTN); wifi.setBounds(26,205,190,25); wifi.setBackground(Color.WHITE); naglowek.add(wifi); String gastronomiaTN[] = {"Tak","Nie"}; JComboBox gastronomia = new JComboBox(gastronomiaTN); gastronomia.setBounds(26,260,190,25); gastronomia.setBackground(Color.WHITE); naglowek.add(gastronomia); /** * * @param i * @return */ JButton dodaj = new JButton("Dodaj"); dodaj.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent event){ Budynek tmp = new Budynek(); tmp = new Budynek(tNazwaB.getText(),getWartosc(winda.getSelectedItem().toString()),getWartosc(gastronomia.getSelectedItem().toString()),getWartosc(wifi.getSelectedItem().toString())); tmp.IDbud = z1.getSpisBudynkow().size()+1; z1.DodajBudynek(tmp); System.out.println(tmp.toString()); new Swing6(z1); ramka.setVisible(false); ramka.dispose(); } }); dodaj.setBounds(26,300,150,50); ramka.add(powrot); naglowek.add(dodaj); //ramka.add(powrot); ramka.setSize(600,600); // stała szerokość okna aby nam dzięcioły nie psuły aplikacji :-) ramka.setResizable(false); ramka.setLayout(null); ramka.setVisible(true); ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ramka.setLocationRelativeTo(null); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.util.ArrayList; import java.util.Date; /** * * @author Admin */ public interface Rezerwowalny { void DodajRezerwację(Rezerwacja r); void UsuńRezerwację(Rezerwacja r, String pesel); Rezerwacja ZnajdźRezerwację(Date dzień1,String godzina_początkowa,String godzina_końcowa); //ZMIENIŁEM Z ARRAYLIST<rEZERWACJA> NA SAMO rEZERWACJA, BO NIE MOŻE BYĆ DO <NAME> W TYM SAMYM CZASIE WIECEJ NIŻ JEDNEJ REZERWACJI Rezerwacja ZnajdźRezerwację(int numer); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Admin */ enum Płcie { K,M}; public class Najemca extends Dodatki { public int idNajemcy; private String imię; private String nazwisko; private String pesel; private Płcie płeć; /** * @return the imię */ public String getImię() { return imię; } /** * @param imię the imię to set */ public void setImię(String imię) { if (SprawdźString(imię, Dodatki.getStringZnaki())){ this.imię = imię.toUpperCase();// Wszystko na duże litery aby nie bawić się w rozróżnienia (można usunąć) } else{ try { throw new KonstruktorException("Błędne imię najemcy"); } catch (KonstruktorException ex) { Logger.getLogger(Najemca.class.getName()).log(Level.SEVERE, null, ex); } } } /** * @return the nazwisko */ public String getNazwisko() { return nazwisko; } /** * @param nazwisko the nazwisko to set */ public void setNazwisko(String nazwisko) { if (SprawdźString(nazwisko, Dodatki.getStringZnaki())){ this.nazwisko = nazwisko.toUpperCase();// Wszystko na duże litery aby nie bawić się w rozróżnienia (można usunąć) } else{ try { throw new KonstruktorException("Błędne nazwisko najemcy"); } catch (KonstruktorException ex) { Logger.getLogger(Najemca.class.getName()).log(Level.SEVERE, null, ex); } } } /** * @return the pesel */ public String getPesel() { return pesel; } /** * @param pesel the pesel to set */ public void setPesel(String pesel) throws KonstruktorException { if (sprawdzPESEL(pesel)==false) { throw new KonstruktorException("Niepoprawny PESEL"); } else{ this.pesel = pesel; } } /** * @return the płeć */ public Płcie getPłeć() { return płeć; } /** * @param płeć the płeć to set */ public void setPłeć(Płcie płeć) { this.płeć = płeć; } public void setPłeć(String płeć) { if(płeć.equals("M")){ this.płeć = Płcie.M; }else{ this.płeć= Płcie.K; } } public Najemca(){} public Najemca(String imię, String nazwisko, String pesel, String płeć) throws KonstruktorException { this.setImię(imię); this.setNazwisko(nazwisko); this.setPesel(pesel); if(płeć.equals("M")){ this.płeć = Płcie.M; }else{ this.płeć= Płcie.K; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Najemca:"+"\n"); sb.append("Imię: ").append(this.imię+"\n"); sb.append("Nazwisko: ").append(this.nazwisko+"\n"); sb.append("PESEL: ").append(this.pesel+"\n"); sb.append("Płeć: ").append(this.płeć.toString()+"\n"); return sb.toString(); } public static boolean sprawdzPESEL(String PESEL) { int[] wagi = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3}; int sumaKontrolna = 0; ///sprawdzanie czy każdy element z numeru PESEL jest liczbą oraz czy długość wynosi 11 cyfr for (int i = 0; i < PESEL.length() - 1; i++) { if (isNumeric(PESEL.charAt(i)) == false || PESEL.length() != 11) { return false; } } //Console.WriteLine("Pesel jest z cyfr i ma długość OK"); ///obliczanie sumy kontrolnej (waga * kolejne cyfry z PESELu) sumaKontrolna = Character.getNumericValue(PESEL.charAt(0)) * wagi[0] + Character.getNumericValue(PESEL.charAt(1)) * wagi[1] + Character.getNumericValue(PESEL.charAt(2)) * wagi[2] + Character.getNumericValue(PESEL.charAt(3)) * wagi[3] + Character.getNumericValue(PESEL.charAt(4)) * wagi[4] + Character.getNumericValue(PESEL.charAt(5)) * wagi[5] + Character.getNumericValue(PESEL.charAt(6)) * wagi[6] + Character.getNumericValue(PESEL.charAt(7)) * wagi[7] + Character.getNumericValue(PESEL.charAt(8)) * wagi[8] + Character.getNumericValue(PESEL.charAt(9)) * wagi[9]; sumaKontrolna %= 10; sumaKontrolna = 10 - sumaKontrolna; sumaKontrolna %= 10; ///sprawdzenie czy suma kontrolna zgadza się z ostatnią cyfrą PESELu if(sumaKontrolna == Character.getNumericValue(PESEL.charAt(10))) { return true; } else return false; } //ta funkcja sprawdza czy podany char jest liczbą (potrzebna mi była do peselu) public static boolean isNumeric(char strNum) { String nowy = Character.toString(strNum); try { double d = Double.parseDouble(nowy); } catch (NumberFormatException | NullPointerException nfe) { return false; } return true; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.CompoundBorder; import javax.swing.border.EtchedBorder; /** * * @author Magda */ public class Swing3 { private final static String newline = "\n"; Swing3(Zbior z1){ /***********************/ //Ustawienie tła ramki BufferedImage myImage = null; try{ myImage = ImageIO.read(new File("images\\img2.jpg")); } catch(IOException e) { } JFrame ramka = new JFrame("Rezerwacje"); ramka.setContentPane(new ImagePanel(myImage)); /***********************/ // Tworzenie przycisku powrotu JButton powrot = new JButton("Powrót"); powrot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent event){ new Swing(z1); ramka.setVisible(false); ramka.dispose(); } }); powrot.setBounds(50,50,150,50); ramka.add(powrot); /***********************/ //Formularz dodania najemcy JLabel naglowek = new JLabel(); naglowek.setText("<html><p>Dodaj najemce&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p><hr/>" + "<p>Imię:</p><p></p><p>Nazwisko:</p><p></p><p>Pesel:</p>" + "<p></p><p>Płeć:</p>" + "</html>"); naglowek.setBounds(50,150,450,400); naglowek.setFont(new Font("Serif", Font.PLAIN, 21)); naglowek.setForeground(Color.BLACK); naglowek.setOpaque(true); naglowek.setBackground(Color.white); naglowek.setBorder( new CompoundBorder( new CompoundBorder( BorderFactory.createLineBorder(Color.LIGHT_GRAY,10), BorderFactory.createLineBorder(Color.GRAY,6) ), BorderFactory.createLineBorder(Color.WHITE,10) ) ); naglowek.setVerticalAlignment(SwingConstants.TOP); ramka.add(naglowek); /***********************/ JTextField imie = new JTextField("Imię"); imie.setBounds(26,95,190,25); imie.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { imie.setBorder(BorderFactory.createLineBorder(Color.BLUE,1)); } public void focusLost(FocusEvent e) { imie.setBorder(BorderFactory.createLineBorder(Color.GRAY,1)); } }); naglowek.add(imie); /***********************/ JTextField nazwisko = new JTextField("Nazwisko"); nazwisko.setBounds(26,150,190,25); nazwisko.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { nazwisko.setBorder(BorderFactory.createLineBorder(Color.BLUE,1)); } public void focusLost(FocusEvent e) { nazwisko.setBorder(BorderFactory.createLineBorder(Color.GRAY,1)); } }); naglowek.add(nazwisko); /***********************/ JTextField pesel = new JTextField("NR PESEL"); pesel.setBounds(26,205,190,25); pesel.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { pesel.setBorder(BorderFactory.createLineBorder(Color.BLUE,1)); } public void focusLost(FocusEvent e) { pesel.setBorder(BorderFactory.createLineBorder(Color.GRAY,1)); } }); naglowek.add(pesel); /***********************/ String plcie[] = {"K","M"}; JComboBox plec = new JComboBox(plcie); plec.setBounds(26,260,190,25); plec.setBackground(Color.WHITE); naglowek.add(plec); /***********************/ JLabel etykietaTA = new JLabel("Lista Najemców"); etykietaTA.setBounds(226, 20, 190, 30); naglowek.add(etykietaTA); JTextArea textArea = new JTextArea(5, 20); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setBounds(230,55,190, 100); textArea.setEditable(false); for(int i=0 ; i<z1.getListaNajemcow().size();i++){ textArea.append((z1.wypiszNajemcow(i)+ newline)); } naglowek.add(textArea); /***********************/ JButton submit = new JButton("Dodaj"); submit.setBounds(26,300,190,25); submit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent event){ Najemca tmp= new Najemca(); try { tmp =new Najemca(imie.getText(),nazwisko.getText(),pesel.getText(), plec.getSelectedItem().toString()); z1.DodajNajemce(tmp); } catch (KonstruktorException ex) { Logger.getLogger(Swing3.class.getName()).log(Level.SEVERE, null, ex); } } }); naglowek.add(submit); String[] rekord = new String[20]; int i = 0; for (Najemca n : z1.getListaNajemcow()) { rekord[i] = n.getImię() +" "+n.getNazwisko(); i++; } JList list = new JList(rekord); //data has type Object[] list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP); list.setVisibleRowCount(-1); //list.setBounds(230, 160 , 190, 80); //list.setBackground(Color.GRAY); //list.setBorder(BorderFactory.createLineBorder(Color.black)); // ... JScrollPane listScroller = new JScrollPane(list); //listScroller.setPreferredSize(new Dimension(80, 10)); listScroller.setBounds(230, 160, 190, 80); listScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); naglowek.add(listScroller); /***********************/ //Ustawienia ramki ramka.setSize(600,600); ramka.setResizable(false); ramka.setLayout(null); ramka.setVisible(true); ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ramka.setLocationRelativeTo(null); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projektsale2; import java.util.ArrayList; /** * * @author Admin */ public class Zbior { private ArrayList<Budynek> spisBudynkow = new ArrayList<Budynek>(); private ArrayList<Najemca> listaNajemcow = new ArrayList<Najemca>(); private int rezerwacjeRazem; private int numer; public ArrayList<Budynek> getSpisBudynkow() { return spisBudynkow; } public void setSpisBudynkow(ArrayList<Budynek> spisBudynkow) { this.spisBudynkow = spisBudynkow; } public ArrayList<Najemca> getListaNajemcow() { return listaNajemcow; } public void setListaNajemcow(ArrayList<Najemca> listaNajemcow) { this.listaNajemcow = listaNajemcow; } public int getRezerwacjeRazem() { return rezerwacjeRazem; } public void setRezerwacjeRazem(int rezerwacjeRazem) { this.rezerwacjeRazem = rezerwacjeRazem; } public int getNumer() { return numer; } public void setNumer(int numer) { this.numer = numer; } public Zbior() { listaNajemcow = new ArrayList<Najemca>(); spisBudynkow = new ArrayList<Budynek>(); numer = 0; rezerwacjeRazem = 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("LISTA budynków: ").append('\n'); for(Budynek b : spisBudynkow) { sb.append("Nazwa budynku: " + b.getNazwa()).append('\n'); sb.append("Udogodnienia: ").append('\n'); sb.append("Wi-Fi: " + b.isWifi() + '\n' + "Winda: " + b.isWinda() + '\n' + "Gastronomia: " + b.isGastronomia() + '\n'); sb.append("Lista sal: " + '\n'); for(Sala s : b.getListaSal()) { sb.append(s.getNazwa() + '\n'); sb.append(s.getTyp()).append('\n'); sb.append(s.getPojemność()).append('\n'); } } sb.append("Spis Najemców: "+'\n'); for(Najemca n : listaNajemcow) { sb.append(n).append('\n'); } return sb.toString(); } public void DodajBudynek(Budynek b) { spisBudynkow.add(b); b.IDbud = spisBudynkow.size(); } public void UsunBudynek(Budynek b) { spisBudynkow.remove(b); } public void DodajNajemce(Najemca n) { listaNajemcow.add(n); n.idNajemcy = listaNajemcow.size(); } public void UsunNajemce(Najemca n) { listaNajemcow.remove(n); } public String wypiszNajemcow (int i){ return (listaNajemcow.get(i).getImię().toString()+" "+listaNajemcow.get(i).getNazwisko().toString()); } public String WypiszSale(int i) { Budynek b = spisBudynkow.get(i); StringBuilder sb = new StringBuilder(); for(Sala s : b.getListaSal()) { sb.append(s.getNazwa() +" ( Typ: "+s.getTyp()+", Pojemność: "+s.getPojemność()+" )"+ '\n'); } return sb.toString(); } } <file_sep>package projektsale2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import projektsale2.Sala.Właściwość; import java.sql.*; /** * * @author Admin */ public class ProjektSale { static String[] daneZBazy = new String[10]; /** * @param args the command line arguments */ public static void main(String[] args) throws KonstruktorException { String[] tmpRecord = new String[10]; String polaczenieURL = "jdbc:mysql://localhost/rezerwacje?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&user=root&password="; Connection conn = null; String query = "SELECT * FROM najemcy"; String query2 = "SELECT * FROM budynki"; String query3 = "SELECT * FROM sale"; String query4 = "SELECT * FROM rezerwacje"; Najemca n1 = new Najemca("Dawid","Jobs","98052408891",Płcie.M.toString()); Najemca n2 = new Najemca("Steve","Jobs","98052408891",Płcie.M.toString()); Zbior z1 = new Zbior(); //z1.DodajNajemce(n1); //z1.DodajNajemce(n2); Sala s1 = new Sala("114", Właściwość.ćwiczeniowa, 32); Budynek b1 = new Budynek("D14", true, true, true); b1.DodajSale(s1); //z1.DodajBudynek(b1); try { //Ustawiamy dane dotyczące podłączenia conn = DriverManager.getConnection(polaczenieURL); //Ustawiamy sterownik MySQL Class.forName("com.mysql.cj.jdbc.Driver"); //Uruchamiamy zapytanie do bazy danych Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { tmpRecord = wyswietlDaneZBazy(rs); Najemca tmpNajemca = new Najemca(tmpRecord[0],tmpRecord[1],tmpRecord[2],tmpRecord[3]); tmpNajemca.idNajemcy = rs.getInt(1); z1.DodajNajemce(tmpNajemca); } rs = st.executeQuery(query2); int j = 1; while (rs.next()) { Budynek tmpBudynek = new Budynek(rs.getString(2),rs.getBoolean(3),rs.getBoolean(4),rs.getBoolean(5)); tmpBudynek.IDbud = rs.getInt(1); z1.DodajBudynek(tmpBudynek); j++; } rs = st.executeQuery(query3); while (rs.next()) { tmpRecord = wyswietlDaneZBazy(rs); for(Budynek b: z1.getSpisBudynkow()){ if(b.IDbud == rs.getInt(5)){ Sala tmpSala = new Sala(rs.getString(2),rs.getString(3),rs.getInt(4)); tmpSala.idBud = rs.getInt(5); tmpSala.idSali = rs.getInt(1); b.DodajSale(tmpSala); b.getListaSal().get(b.getListaSal().size()-1).idSali = rs.getInt(1); System.out.println("___SALA W BUD_____"+ tmpSala.idBud+"__"+ tmpSala.getNazwa().toString()+"________-_____t"+tmpSala.getTyp().toString()); } } //z1.DodajBudynek(new Budynek(rs.getString(2),rs.getBoolean(3),rs.getBoolean(4),rs.getBoolean(5))); } rs = st.executeQuery(query4); while(rs.next()){ tmpRecord = wyswietlDaneZBazyBudynek(rs); for(Budynek b: z1.getSpisBudynkow()){ for(Sala s: b.getListaSal()){ if(s.idSali == rs.getInt(3)){ Rezerwacja tmpRezerwacja = new Rezerwacja(z1.getListaNajemcow().get(rs.getInt(2)-1),rs.getString(4),rs.getString(5),rs.getString(6)); tmpRezerwacja.idRezerwacji = rs.getInt(1); tmpRezerwacja.idSali = rs.getInt(3); s.DodajRezerwację(tmpRezerwacja); System.out.println(Integer.toString(tmpRezerwacja.idRezerwacji)+ b.getNazwa()+"____nr sali:_____"+Integer.toString(tmpRezerwacja.idSali) +"__________" + tmpRezerwacja); } } } } conn.close(); } //Wyrzuć wyjątki jężeli nastąpią błędy z podłączeniem do bazy danych lub blędy zapytania o dane catch(ClassNotFoundException wyjatek) { System.out.println("Problem ze sterownikiem"); } catch(SQLException wyjatek) { //e.printStackTrace(); //System.out.println("Problem z logowaniem\nProsze sprawdzic:\n nazwę użytkownika, hasło, nazwę bazy danych lub adres IP serwera"); System.out.println("SQLException: " + wyjatek.getMessage()); System.out.println("SQLState: " + wyjatek.getSQLState()); System.out.println("VendorError: " + wyjatek.getErrorCode()); } new Swing(z1); } static String[] wyswietlDaneZBazy(ResultSet rs){ try{ System.out.println("WYSWIETL DANE Z BAZY \n NR: "+rs.getInt(1)+"\n"); daneZBazy[0] = rs.getString(2); daneZBazy[1] = rs.getString(3); daneZBazy[2] = rs.getString(4); daneZBazy[3] = rs.getString(5); System.out.println("\n" + daneZBazy[0] + " "); System.out.println("\n" + daneZBazy[1] + " "); System.out.println("\n" + daneZBazy[2] + " "); System.out.println("\n" + daneZBazy[3] + " "); } catch(SQLException e) { e.printStackTrace(); } return daneZBazy; } static String[] wyswietlDaneZBazyBudynek(ResultSet rs){ try{ daneZBazy[0] = rs.getString(2); daneZBazy[1] = rs.getString(3); daneZBazy[2] = rs.getString(4); daneZBazy[3] = rs.getString(5); daneZBazy[4] = rs.getString(6); System.out.println("\n" + daneZBazy[0] + " "); System.out.println("\n" + daneZBazy[1] + " "); System.out.println("\n" + daneZBazy[2] + " "); System.out.println("\n" + daneZBazy[3] + " "); System.out.println("\n" + daneZBazy[4] + " "); } catch(SQLException e) { e.printStackTrace(); } return daneZBazy; } } <file_sep># RoomBooking Project of room booking app, made with <NAME> and <NAME>
36bd3bd9ea454f26b0dc78a61395257371110b7e
[ "Markdown", "Java" ]
8
Java
JakGor/RoomBooking
ef58a9d095adfcb5a774c4f96d4fe7d5dd150956
4b01353903d17293e91431cf86926d5f6d223854
refs/heads/master
<file_sep># Simple Login System A simple login system web application developed using php [laravel](https://laravel.com) framework. ### Application features * Google login integrated api * Receiving email for verification ## Getting Started ### Prerequisites Following steps assume that you have installed 1. [Oracle VM VirtualBox](https://www.virtualbox.org) 2. [Vagrant](https://www.vagrantup.com) 3. [Homestead](https://laravel.com/docs/5.4/homestead) ~ if not please install them at first ### Download the project - Change the directory to your Homestead folder where 'Vagrantfile' is placed - Open terminal and type `vagrant up` it may take a few minutes - Now ssh to your box using this command `vagrant ssh` - Now change the directory to the folder you used to create new applications' projects in using `cd [DIRECTORY]` - Download project files through `git clone https://github.com/islambayoumy/LoginSystem.git` ### Setting up mysql database - Go type `mysql` in the terminal - `create database LoginApp;` - `exit` ### Congfigure Mail - Open .env - Go change 'MAIL_USERNAME' and 'MAIL_PASSWORD' to your personal/server email and password ~ this for sending confirmation mail ### Adding site - Add site 'loginsystem.app' to 'Homestead.yaml' and '/etc/hosts/' files ### Migrate database - Now back to terminal, `cd [LoginSystem]` - Type the following command `php artisan migrate` `vagrant provision` ## Browsing application Now you can browse the application through http://loginsystem.app:8000 <file_sep><?php namespace App\Http\Controllers; use Socialite; use App\SocialProvider; use App\User; class GoogleController extends Controller { /** * Redirect the user to the google authentication page. * * @return Response */ public function redirectToProvider() { return Socialite::driver('google')->redirect(); } /** * Obtain the user information from google. * * @return Response */ public function handleProviderCallback() { try{ $socialUser = Socialite::driver('google')->user(); } catch(Exception $e){ return redirect('/'); } $socialProvider = SocialProvider::where('provider_id',$socialUser->getId())->first(); if(!$socialProvider){ $name = explode(" ", $socialUser->getName(), 2); $data = [ 'firstname' => $name[0], 'lastname' => $name[1], 'password' => '<PASSWORD>', 'is_activated' => 1 ]; $user = User::firstOrCreate( ['email' => $socialUser->getEmail()], [ 'firstname' => $name[0], 'lastname' => $name[1], 'password' => '<PASSWORD>', 'is_activated' => 1 ] ); $user->socialProviders()->create([ 'provider_id' => $socialUser->getId(), 'provider' => 'google' ]); } else{ $user = $socialProvider->user; } auth()->login($user); return redirect('/home'); } }
2962452ee46a9f9f868cbd403bbbe13b37c63373
[ "Markdown", "PHP" ]
2
Markdown
islambayoumy/LoginSystem
f9967f56f80943e93b5ca211c14b1039193100e2
5407502b2d215776ce8a3d2b37defcbf3bd4a3bf
refs/heads/master
<repo_name>EnoroF/gmyqq<file_sep>/src/gMystar.cc #include "gMystar.h" #include <pthread.h> /* static member */ Mystar *gMystar::mystar; bool gMystar::flag; Glib::RefPtr<Gtk::StatusIcon> gMystar::status_icon; Window *gMystar::MainWindow; CheckButton *gMystar::autologin_checkbutton; Button *gMystar::connect_button; Label *gMystar::status_label; int gMystar::window_x; int gMystar::window_y; sigc::connection gMystar::c; Notify::Notification *gMystar::n; /* gMystar::gMystar(int argc, char *argv[]) { Main kit(argc, argv); mystar = new Mystar(); flag = true; //tray status_icon = StatusIcon::create_from_file("/usr/gMystar/disconnect.png"); if(status_icon) { status_icon->set_tooltip("用gtkmm和glade做的锐捷客户端."); status_icon->signal_activate().connect(sigc::mem_fun(*this, &gMystar::on_tray_clicked)); } else { cout<<"create tray icon error!\n"; } refXml = Gnome::Glade::Xml::create("/etc/gMystar/ui.glade"); //refXml = Gnome::Glade::Xml::create("./gMystar.glade"); MainWindow= NULL; MainWindow= refXml->get_widget("gMystar", MainWindow); nickname_entry= NULL; nickname_entry = refXml->get_widget("nickname", nickname_entry); nickname_entry->set_text(mystar->user.get_nickname()); username_entry= NULL; username_entry= refXml->get_widget("username", username_entry); username_entry->set_text(mystar->user.get_username()); password_entry= NULL; password_entry= refXml->get_widget("password", password_entry); password_entry->set_text(<PASSWORD>ar->user.get_password()); fakeAddress_entry = NULL; fakeAddress_entry = refXml->get_widget("fakeAddress", fakeAddress_entry); fakeAddress_entry->set_text(mystar->user.get_fakeAddress()); autologin_checkbutton = NULL; autologin_checkbutton = refXml->get_widget("autologin_checkbutton",autologin_checkbutton); connect_button = NULL; connect_button = refXml->get_widget("connect_button", connect_button); if(connect_button) { gMystar::c = connect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_connect_button_clicked)); } disconnect_button = NULL; disconnect_button = refXml->get_widget("disconnect_button", disconnect_button); if(disconnect_button) { gMystar::c = disconnect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_disconnect_button_clicked)); } quit_button = NULL; quit_button = refXml->get_widget("quit_button", quit_button); if(quit_button) { quit_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_quit_button_clicked)); } status_label = NULL; status_label = refXml->get_widget("status",status_label); MainWindow->set_focus(*connect_button); MainWindow->show(); if(mystar->autologin) on_connect_button_clicked(); kit.run(); //这样的话在hide时不退出程序 } */ gMystar::gMystar() { mystar = new Mystar(); flag = true; //tray status_icon = StatusIcon::create_from_file("/usr/share/gMystar/data/disconnect.png"); if(status_icon) { status_icon->set_tooltip("用gtkmm和glade做的锐捷客户端."); status_icon->signal_activate().connect(sigc::mem_fun(*this, &gMystar::on_tray_clicked)); } else { cout<<"create tray icon error!\n"; } refXml = Gnome::Glade::Xml::create("/usr/share/gMystar/data/gMystar.glade","main_window"); if(!refXml) exit(271); VBox* main_window = NULL; main_window = refXml->get_widget("main_window", main_window); nickname_entry= NULL; nickname_entry = refXml->get_widget("nickname", nickname_entry); nickname_entry->set_text(mystar->user.get_nickname()); username_entry= NULL; username_entry= refXml->get_widget("username", username_entry); username_entry->set_text(mystar->user.get_username()); password_entry= NULL; password_entry= refXml->get_widget("password", password_entry); password_entry->set_text(mystar->user.get_password()); fakeAddress_entry = NULL; fakeAddress_entry = refXml->get_widget("fakeAddress", fakeAddress_entry); fakeAddress_entry->set_text(mystar->user.get_fakeAddress()); autologin_checkbutton = NULL; autologin_checkbutton = refXml->get_widget("autologin_checkbutton",autologin_checkbutton); connect_button = NULL; connect_button = refXml->get_widget("connect_button", connect_button); if(connect_button) { gMystar::c = connect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_connect_button_clicked)); } disconnect_button = NULL; disconnect_button = refXml->get_widget("disconnect_button", disconnect_button); if(disconnect_button) { gMystar::c = disconnect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_disconnect_button_clicked)); } quit_button = NULL; quit_button = refXml->get_widget("quit_button", quit_button); if(quit_button) { quit_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_quit_button_clicked)); } status_label = NULL; status_label = refXml->get_widget("status",status_label); /* VBox* main_window = dynamic_cast<VBox*>(refXml->get_widget("main_window")); nickname_entry = dynamic_cast<Entry*>(refXml->get_widget("nickname")); nickname_entry->set_text(mystar->user.get_nickname()); username_entry = dynamic_cast<Entry*>(refXml->get_widget("name")); username_entry->set_text(mystar->user.get_username()); password_entry = dynamic_cast<Entry*>(refXml->get_widget("password")); password_entry->set_text(mystar->user.get_password()); fakeAddress_entry = dynamic_cast<Entry*>(refXml->get_widget("fakeAddress")); fakeAddress_entry->set_text(mystar->user.get_fakeAddress()); autologin_checkbutton = dynamic_cast<CheckButton*>(refXml->get_widget("autologin_checkbutton")); connect_button = dynamic_cast<Button*>(refXml->get_widget("connect_button")); if(connect_button) { gMystar::c = connect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_connect_button_clicked)); } disconnect_button = dynamic_cast<Button*>(refXml->get_widget("disconnect_button")); if(disconnect_button) { gMystar::c = disconnect_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_disconnect_button_clicked)); } quit_button = dynamic_cast<Button*>(refXml->get_widget("quit_button")); if(quit_button) { quit_button->signal_clicked().connect(sigc::mem_fun(*this, &gMystar::on_quit_button_clicked)); } //status_label = dynamic_cast<Label*>(refXml->get_widget("status")); */ add(*main_window); show_all(); if(mystar->autologin) on_connect_button_clicked(); } gMystar::~gMystar() { } void gMystar::on_quit_button_clicked() { //MainWindow->hide();//这样只是隐藏了,如何结束呢? hide();//这样只是隐藏了,如何结束呢? } void gMystar::on_disconnect_button_clicked() { mystar->logout(SIGINT); status_label->set_label("logout..."); if(!pthread_cancel(authen_thread)) cout<<"取消认证。。。\n"; } void gMystar::on_connect_button_clicked() { cout<<"用于连接的账号信息是:"<<endl; char str[20]; strcpy(str,nickname_entry->get_text().c_str()); mystar->user.set_nickname(str); strcpy(str,username_entry->get_text().c_str()); mystar->user.set_username(str); strcpy(str,password_entry->get_text().c_str()); mystar->user.set_password(str); strcpy(str,fakeAddress_entry->get_text().c_str()); mystar->user.set_fakeAddress(str); int res = pthread_create(&authen_thread, NULL,gMystar::test, NULL); if(res!=0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } int res2 = pthread_create(&change_ui_thread, NULL,gMystar::change_ui, NULL); if(res2!=0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } } void gMystar::help() { printf("to use no gui mode, please type --nogui\n"); } void gMystar::show_message(const char *message) { cout<<message; status_label->set_text(message); } void gMystar::on_tray_clicked() { if(MainWindow->is_visible()) hide_window(); else show_window(); } void gMystar::show_window() { MainWindow->move(window_x, window_y); cout<<"resume the position("<<window_x<<","<<window_y<<")"<<endl; MainWindow->show(); } void gMystar::hide_window() { //MainWindow->get_position(window_x, window_y); //cout<<"save the current position ("<<window_x<<","<<window_y<<")"<<endl; //hide(); } void *gMystar::test(void *a) { mystar->authen(); } void *gMystar::change_ui(void *a) { while(flag) { int status = mystar->get_status(); switch(status) { case 0: status_label->set_label(">> Searching for server...\n"); break; case 1: status_label->set_label(" Sending user name..."); break; case 2: status_label->set_label(" Sending password..."); break; case 3: status_icon->set_from_file("/usr/share/gMystar/data/connect.png"); status_label->set_label("keep sending echo..."); Notify::init("Icon test"); n = new Notify::Notification("gMystar", "连接成功", "appointment-new"); n->set_timeout(1000); //1 seconds n->show(); hide_window(); if(autologin_checkbutton->get_active()) mystar->autologin=true; else mystar->autologin=false; mystar->save_file(); flag=false; break; case 5://网口断开状态 n = new Notify::Notification("gMystar", "网络断开,请检查网络。。", "appointment-new"); n->set_timeout(1000); //1 seconds n->show(); flag=false; default: flag=true; break; } } } bool gMystar::on_key_press_event(GdkEventKey *ev) { if(ev->type!=GDK_KEY_PRESS) return Window::on_key_press_event(ev); switch(ev->keyval) { case GDK_w: if(ev->state & GDK_CONTROL_MASK) //hide_window(); hide(); default: return Window::on_key_press_event(ev); } return true; } <file_sep>/src/myqq.h /* * myqq.h ------come from myqq.c,coverted by amoblin * * main() A small console for MyQQ. * * Copyright (C) 2008 <NAME> (<EMAIL>) * * 2008-01-31 Created. * 2008-2-5 Add more commands. * 2008-7-15 Mr. Wugui said "There's no accident in the world.", * but I always see accident in my code :) * 2008-10-1 Character color support and nonecho password. * 2009-1-25 Use UTF-8 as a default type. * * Description: This file mainly includes the functions about * Parsing Input Commands. * Warning: this file should be in UTF-8. * */ #include <stdio.h> #include <ctype.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #ifdef __WIN32__ #include <conio.h> #include <winsock.h> #include <wininet.h> #include <windows.h> #else #include <termios.h> //read password #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> //amoblin #include <ncurses.h> //curses中包含stdio.h #include <panel.h> #include <string> #include <time.h> #include <sys/stat.h> #endif extern "C" { #include "qqclient.h" #include "buddy.h" #include "qun.h" #include "group.h" #include "memory.h" #include "utf8.h" #include "config.h" #include "qqsocket.h" } using namespace std; #define MSG need_reset = 1; setcolor( color_index ); printf #define QUN_BUF_SIZE 80*100 #define BUDDY_BUF_SIZE 80*500 #define PRINT_BUF_SIZE 80*500*3 static char* qun_buf, *buddy_buf, *print_buf; static uint to_uid = 0; //send message to that guy. static uint qun_int_uid; //internal qun id if entered. static char input[1024]; static int enter = 0; static qqclient* qq; static int need_reset; enum { CMD_EXIT = 0, CMD_EXIT2,//CMD_EXIT3, CMD_SAY, CMD_SAY2, CMD_TO, CMD_TO2, CMD_HELP, CMD_STATUS, CMD_ENTER, CMD_ENTER2, CMD_LEAVE, CMD_LEAVE2, CMD_WHO, CMD_WHO2, CMD_VIEW, CMD_VIEW2, CMD_QUN, CMD_QUN2, CMD_INFO, CMD_INFO2, CMD_UPDATE, CMD_UPDATE2, CMD_CHANGE, CMD_CHANGE2, CMD_TEST, CMD_VERIFY, CMD_VERIFY2, CMD_ADD, CMD_ADD2, CMD_DEL }; static char commands[][16]= { "exit", "q",//"quit", "say", "s", "to", "t", //talk with buddy. "help", "status", "enter", "e", // "leave", "l", "list", "ls", //who "listall", "la", //view "listgroup", "lg", //qun "info", "i", "update", "u", "change", "c", "test", "verify", "r", "add","a", "del" }; static char help_msg[]= "欢迎使用 MyQQ2009 beta1 中文版\n" "这是一个为程序员和电脑爱好者制作的" "迷你控制台即时通讯软件,享受它吧!\n" "help: 显示以下帮助信息.\n" "add/a: 添加好友. add+QQ号码.\n" "listall/la: 所有好(群)友列表.(指向前操作)\n" "list/ls: 在线好(群)友列表.(指向前操作)\n" "listgroup/lg: 显示群列表.(指向前操作)\n" "to/t: 指向某个QQ号或者前面的编号.\n" "enter/e: 指向某个群号或者前面的编号.\n" "leave/l: 离开群.(指向后操作)\n" "say/s: 发送信息.(指向后操作)\n" "info/i: 查看相应信息.(指向后操作)\n" "update/u: 更新所有列表.\n" "status: 改变状态(online|away|busy|killme|hidden)\n" "verify/r: 输入验证码(验证码在verify目录下).\n" "change/c: 更换用户登陆.\n" "exit/q: 退出.\n" ; #ifdef __WIN32__ #define CCOL_GREEN FOREGROUND_GREEN #define CCOL_LIGHTBLUE FOREGROUND_BLUE | FOREGROUND_GREEN #define CCOL_REDGREEN FOREGROUND_RED | FOREGROUND_GREEN #define CCOL_NONE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE static int color_index = CCOL_NONE; static void charcolor( int col ) { color_index = col; } static void setcolor( int col ) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | col); } #else #define CCOL_NONE "\033[0m" #define CCOL_BLACK "\033[0;30m" #define CCOL_DARKGRAY "\033[1;30m" #define CCOL_BLUE "\033[0;34m" #define CCOL_LIGHTBLUE "\033[1;34m" #define CCOL_GREEN "\033[0;32m" #define CCOL_LIGHTGREEN "\033[1;32m" #define CCOL_CYAN "\033[0;36m" #define CCOL_LIGHTCYAN "\033[1;36m" #define CCOL_RED "\033[0;31m" #define CCOL_LIGHTRED "\033[1;31m" #define CCOL_PURPLE "\033[0;35m" #define CCOL_LIGHTPURPLE "\033[1;35m" #define CCOL_LIGHTBROWN "\033[0;33m" #define CCOL_YELLOW "\033[1;33m" #define CCOL_LIGHTGRAY "\033[0;37m" #define CCOL_WHITE "\033[1;37m" #define CCOL_REDGREEN CCOL_YELLOW //static char* color_index = CCOL_NONE; const static char* color_index = CCOL_NONE; //--amoblin static void charcolor( const char* col ) { color_index = (char*)col; } static void setcolor( const char* col ) { printf("%s", col ); } #endif //含颜色控制 #define RESET_INPUT \ if( need_reset )\ { charcolor( CCOL_NONE );\ if( enter ){ \ MSG("In {%s}> ", _TEXT( myqq_get_qun_name( qq, qun_int_uid ) ) ); \ }else{ \ MSG("To [%s]> ", _TEXT( myqq_get_buddy_name( qq, to_uid ) ) );} \ fflush( stdout ); \ need_reset = 0;\ } #ifdef __WIN32__ #define _TEXT to_gb_force static char* to_gb_force( char* s ) { // memset( print_buf, 0, PRINT_BUF_SIZE ); utf8_to_gb( s, print_buf, PRINT_BUF_SIZE-1 ); return print_buf; } static char* to_utf8( char* s ) { // memset( print_buf, 0, PRINT_BUF_SIZE ); gb_to_utf8( s, print_buf, PRINT_BUF_SIZE-1 ); return print_buf; } #else #define _TEXT #endif static int _getline(char *s, int lim) { char *t; int c; t = s; while (--lim>1 && (c=getchar()) != EOF && c != '\n') *s++ = c; *s = '\0'; return s - t; } //static char* mode_string( int mode ) const static char* mode_string( int mode ) //--amoblin { switch( mode ) { case QQ_ONLINE: return "Online"; case QQ_AWAY: return "Away"; case QQ_BUSY: return "Busy"; case QQ_OFFLINE: return "Offline"; case QQ_HIDDEN: return "Hidden"; case QQ_KILLME: return "Kill Me"; case QQ_QUIET: return "Quiet"; } return "Unknown"; } static char* skip_line( char* p, int ln ) { while( *p && ln-- ) { p ++; while( *p && *p!='\n' ) p++; } return p; } //static char* myqq_get_buddy_name( qqclient* qq, uint uid ) const static char* myqq_get_buddy_name( qqclient* qq, uint uid ) //--amoblin { static char tmp[16]; qqbuddy* b = buddy_get( qq, uid, 0 ); if( b ) return b->nickname; if( uid == 10000 ) return "System"; if( uid != 0 ) { sprintf( tmp, "%u" , uid ); return tmp; } return "Nobody"; } const static char* myqq_get_qun_name( qqclient* qq, uint uid ) //--amoblin { static char tmp[16]; qqqun* q = qun_get( qq, uid, 0 ); if( q ) return q->name; if( uid != 0 ) { sprintf( tmp, "%u" , uid ); return tmp; } return "[q==NULL]"; } const static char* myqq_get_qun_member_name( qqclient* qq, uint int_uid, uint uid ) //-amoblin { static char tmp[16]; qqqun* q = qun_get( qq, int_uid, 0 ); if( q ) { qunmember* m = qun_member_get( qq, q, uid, 0 ); if( m ) return m->nickname; if( uid != 0 ) { sprintf( tmp, "%u" , uid ); return tmp; } return "[m==NULL]"; } return "[q==NULL]"; } static int myqq_send_im_to_qun( qqclient* qq, uint int_uid, char* msg, int wait ) { qun_send_message( qq, int_uid, msg ); if( wait ) { if( qqclient_wait( qq, 15 ) < 0 ) return -1; } return 0; } static int myqq_send_im_to_buddy( qqclient* qq, uint int_uid, char* msg, int wait ) { buddy_send_message( qq, int_uid, msg ); if( wait ) { if( qqclient_wait( qq, 15 ) < 0 ) return -1; } return 0; } static int myqq_get_buddy_info( qqclient* qq, uint uid, char* buf, int size ) { qqbuddy *b = buddy_get( qq, uid, 0 ); if( size < 256 ) return -1; if( b == NULL ) return -2; int len, ip = htonl(b->ip); len = sprintf( buf, "好友昵称\t%-32s\n" "用户账号\t%-32d\n" "IP地址\t\t%-32s\n" "IP端口\t\t%-32d\n" "头像\t\t%-32d\n" "年龄\t\t%-32d\n" "性别\t\t%-32s\n" "状态\t\t%-32s\n", b->nickname, b->number, inet_ntoa( *(struct in_addr*)&ip ), b->port, b->face, b->age, (b->sex==0x00)?"Male": (b->sex==0x01)?"Female":"Asexual", mode_string(b->status) ); return len; } //Note: this function change the source string directly. static char* util_escape( char* str ) { unsigned char* ch; ch = (unsigned char*)str; while( *ch ) { if( *ch < 0x80 ) //ASCII?? { if( !isprint(*ch) ) //if not printable?? *ch = ' '; //use space instead.. ch ++; //skip one } else { ch +=2; //skip two } } return str; } /* The output buf looks like this: L8bit L16bit L16bit L32bit 1 357339036 online Xiao xia 2 273310179 offline <NAME> */ //Note: size must be big enough static int myqq_get_buddy_list( qqclient* qq, char* buf, int size, char online ) { int i, len = 0; //avoid editing the array buf[0] = 0; pthread_mutex_lock( &qq->buddy_list.mutex ); int ln = 1; for( i=0; i<qq->buddy_list.count; i++ ) { qqbuddy * b = (qqbuddy*)qq->buddy_list.items[i]; if( online && b->status == QQ_OFFLINE ) continue; len = sprintf( buf, "%s%-8d%-16d%-16s%-16.64s\n", buf, ln ++, b->number, mode_string( (int) b->status ), util_escape( b->nickname ) ); if( len + 80 > size ) break; } pthread_mutex_unlock( &qq->buddy_list.mutex ); return len; } /* The output buf looks like this: L8bit L16bit L16bit L32bit 1 467788923 12118724 Xinxing Experimental School 2 489234223 13223423 SGOS2007 */ //Note: size must be big enough static int myqq_get_qun_list( qqclient* qq, char* buf, int size ) { int i, len = 0, ln=1; //avoid editing the array buf[0] = 0; pthread_mutex_lock( &qq->qun_list.mutex ); for( i=0; i<qq->qun_list.count; i++ ) { qqqun * q = (qqqun *)qq->qun_list.items[i]; len = sprintf( buf, "%s%-8d%-16d%-16d%-16.64s\n", buf, ln ++, q->number, q->ext_number, util_escape( q->name ) ); if( len + 80 > size ) break; } pthread_mutex_unlock( &qq->qun_list.mutex ); return len; } /* The output buf looks like this: L8bit L16bit L16bit L32bit 1 357339036 Manager Xiaoxia 2 273310179 Fellow <NAME> */ //Note: size must be big enough static int myqq_get_qun_member_list( qqclient* qq, uint int_uid, char* buf, int size, char online ) { qqqun * q = qun_get( qq, int_uid, 0 ); if( !q )return 0; //Hope the Qun won't get removed while we are using it. int i, len = 0, ln = 1; buf[0] = 0; pthread_mutex_lock( &q->member_list.mutex ); for( i=0; i<q->member_list.count; i++ ) { qunmember * m = (qunmember *)q->member_list.items[i]; if( online && m->status == QQ_OFFLINE ) continue; len = sprintf( buf, "%s%-8d%-16d%-16s%-16.64s\n", buf, ln++, m->number, (m->role&1)?"Admin":"Fellow", util_escape( m->nickname ) ); if( len + 80 > size ) break; } pthread_mutex_unlock( &q->member_list.mutex ); return len; } //interface for getting qun information /* Output style: */ static int myqq_get_qun_info( qqclient* qq, uint int_uid, char* buf, int size ) { char cate_str[4][10] = {"Classmate", "Friend", "Workmate", "Other" }; qqqun *q = qun_get( qq, int_uid, 0 ); if( !q )return 0; int len; if( size < 256 ) return -1; if( q == NULL ) return -2; len = sprintf( buf, "名称\t\t%-32s\n" "内部号码\t%-32d\n" "群号码\t\t%-32d\n" "群类型\t\t%-32s\n" "是否允许加入\t%-32s\n" "群分类\t\t%-32s\n" "创建人\t\t%-32d\n" "成员数量\t%-32d\n" "群的简介\n%-32s\n" "群的公告\n%-32s\n", q->name, q->number, q->ext_number, (q->type==0x01)?"Normal":"Special", (q->auth_type==0x01)?"No": (q->auth_type==0x02)?"Yes": (q->auth_type==0x03)?"RejectAll":"Unknown", q->category > 3 ? cate_str[3] : cate_str[(int)q->category], q->owner, q->member_list.count, q->intro, q->ann ); return len; } /* //含颜色控制 void buddy_msg_callback ( qqclient* qq, uint uid, time_t t, char* msg ) { charcolor( CCOL_LIGHTBLUE ); //red color char timestr[12]; char msgstr[64]; struct tm * timeinfo; //char* nick = myqq_get_buddy_name( qq, uid ); const char* nick = myqq_get_buddy_name( qq, uid ); //--amoblin timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", uid ); p = strstr( buddy_buf, tmp ); if( p ) { p -= 8; if( p>=buddy_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s[", ln, timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } else { sprintf( msgstr, "\n%s[", timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } */ /* //含颜色控制 void qun_msg_callback ( qqclient* qq, uint uid, uint int_uid, time_t t, char* msg ) { charcolor( CCOL_REDGREEN ); //red color char timestr[12]; char msgstr[64]; const char* qun_name = myqq_get_qun_name( qq, int_uid ); //--amoblin const char* nick = myqq_get_qun_member_name( qq, int_uid, uid ); struct tm * timeinfo; timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", int_uid ); p = strstr( qun_buf, tmp ); if( p ) { p -= 8; if( p>=qun_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s{", ln, timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } else { sprintf( msgstr, "\n%s{", timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } */ #ifndef __WIN32__ //int read_password(char*); #endif class Irssi { public: Irssi(); ~Irssi(); void set_statusbar(char *); void show(const char *); void show_command(char *); void show_int(uint); void init(uint); void get_command(char *); int len(int); void exit(); private: WINDOW *title; WINDOW *textarea; WINDOW *statusbar; WINDOW *commandline; int row,col; }; class Myqq { public: Myqq(int ,char **); ~Myqq(); void set_account(uint acc); protected: bool login(); //登录 void welcome_message(); void help(); //命令帮助 bool authen(); //登录验证 void get_command(char *); //取得输入命令 void parse_command(char *); //分析命令并执行 bool init(); void parse_command_line(int , char**); void checkAndSetConfig(); void init_file(); int save_file(); char *get_online_buddies(); char *get_all(); char *get_groups(); void list_online_buddies(); void list_all(); void list_groups(); void begin_talk_to_buddy(char *); void send_message_to_buddy(char *); void change_status(); void add_buddy(char *); void logout(); bool send_message(int); void quit(); void error(char *); void qun_msg_callback (qqclient* qq, uint uid, uint int_uid, time_t t, char* msg ); void buddy_msg_callback ( qqclient* qq, uint uid, time_t t, char* msg ); qqclient *qq; private: //char account[32]; //用户名 uint account; //用户名 char password[32]; //密码 int status; //状态:0,未登录;1,在线,2,隐身,3,busy,4... char *config_file; WINDOW *qq_window[4]; uint buddy_number; }; <file_sep>/src/checkAndSetConfig.cc #include "myqq.h" #include "tinyxml/tinyxml.h" #include "tinyxml/tinystr.h" void Myqq::checkAndSetConfig() { TiXmlDocument config_dom(config_file); if(config_dom.LoadFile()) { cout<<"找到配置文件。。。\n"; } else { init_file(); return; } TiXmlElement* root = config_dom.RootElement(); if(root == NULL) return; TiXmlElement* UsersElement = root->FirstChildElement(); if(UsersElement==NULL) return; TiXmlElement* UserElement = UsersElement->FirstChildElement(); if(UserElement==NULL) return; TiXmlElement *account = UserElement->FirstChildElement(); TiXmlElement *password = account->NextSiblingElement(); TiXmlElement *mode = password->NextSiblingElement(); this->account = atoi(account->GetText()); strcpy(this->password,password->GetText()); if(atoi(mode->GetText())==0) qq->mode = QQ_ONLINE; else qq->mode = QQ_HIDDEN; } void Myqq::init_file() { //创建一个XML的文档对象。 TiXmlDocument *myDocument = new TiXmlDocument(); TiXmlDeclaration *title = new TiXmlDeclaration("1.0","utf-8","yes"); myDocument->LinkEndChild(title); TiXmlComment *comment = new TiXmlComment("update the information below"); myDocument->LinkEndChild(comment); //创建一个根元素并连接。 TiXmlElement *RootElement = new TiXmlElement("myqq_config"); myDocument->LinkEndChild(RootElement); //创建一个users元素并连接。 TiXmlElement *UsersElement = new TiXmlElement("users"); RootElement->LinkEndChild(UsersElement); //创建一个user元素并连接。 TiXmlElement *userElement = new TiXmlElement("user"); UsersElement->LinkEndChild(userElement); //设置user元素的属性。 TiXmlElement *tempElement = new TiXmlElement("account"); userElement->LinkEndChild(tempElement); TiXmlText *tempContent = new TiXmlText("0"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("password"); userElement->LinkEndChild(tempElement); tempContent = new TiXmlText("0"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("mode"); userElement->LinkEndChild(tempElement); tempContent = new TiXmlText("0"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQPacketLog"); RootElement->LinkEndChild(tempElement); tempContent = new TiXmlText("false"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQTerminalLog"); RootElement->LinkEndChild(tempElement); tempContent = new TiXmlText("false"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQLogDir"); RootElement->LinkEndChild(tempElement); tempContent = new TiXmlText("./log"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQVerifyDir"); RootElement->LinkEndChild(tempElement); tempContent = new TiXmlText("./verify"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQNetwork"); RootElement->LinkEndChild(tempElement); tempContent = new TiXmlText("UDP"); tempElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQTcpServerList"); RootElement->LinkEndChild(tempElement); TiXmlElement *itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.31.10:443"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.17.32:443"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.58.3:443"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.31.10:443"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.31.10:443"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.31.10:443"); itemElement->LinkEndChild(tempContent); tempElement = new TiXmlElement("QQUdpServerList"); RootElement->LinkEndChild(tempElement); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.58.3:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.31.10:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("172.16.17.32:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("sz6.tencent.com:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("sz7.tencent.com:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("sz8.tencent.com:8000"); itemElement->LinkEndChild(tempContent); itemElement = new TiXmlElement("item"); tempElement->LinkEndChild(itemElement); tempContent = new TiXmlText("sz9.tencent.com:8000"); itemElement->LinkEndChild(tempContent); myDocument->SaveFile(config_file); cout<<"初始化配置文件到"<<config_file<<endl; } int Myqq::save_file() { TiXmlDocument mystarconf(config_file); if(mystarconf.LoadFile()) { TiXmlElement* mystarroot = mystarconf.RootElement(); if(mystarroot == NULL) return 1; TiXmlElement* UsersElement = mystarroot->FirstChildElement(); if(UsersElement==NULL) return 1; TiXmlElement* UserElement = UsersElement->FirstChildElement(); if(UserElement==NULL) return 1; TiXmlElement *nickname = UserElement->FirstChildElement(); TiXmlElement *username = nickname->NextSiblingElement(); TiXmlElement *password = username->NextSiblingElement(); TiXmlElement *fakeAddress = password->NextSiblingElement(); TiXmlText *tempContent = new TiXmlText("QQ账号"); nickname->ReplaceChild(nickname->FirstChild(), *tempContent); tempContent = new TiXmlText("密码"); username->ReplaceChild(username->FirstChild(), *tempContent); TiXmlElement *config = UsersElement->NextSiblingElement(); TiXmlElement *autologinElement = config->FirstChildElement(); cout<<"save to "<<config_file<<endl; mystarconf.SaveFile(); return 0; } } <file_sep>/Makefile # Makefile for MyQQ MyQQ_HOME=. SRC=$(MyQQ_HOME)/src BIN=$(MyQQ_HOME)/bin OBJ=$(MyQQ_HOME)/obj DATA=$(MyQQ_HOME)/data EXEC=$(BIN)/gmyqq CC= g++ # Use for compile. CFLAGS = `pkg-config --cflags dbus-glib-1 libglademm-2.4 gtkmm-2.4 libnotifymm-1.0 libnm_glib` # Use for link. CLIBS = `pkg-config --libs dbus-glib-1 gtkmm-2.4 libglademm-2.4 libnotifymm-1.0 libnm_glib` -lpthread -lncursesw -lpanel -s OBJS=qqsocket.o qqcrypt.o md5.o debug.o qqclient.o memory.o config.o packetmgr.o qqpacket.o \ prot_login.o protocol.o prot_misc.o prot_im.o prot_user.o list.o buddy.o group.o qun.o \ prot_group.o prot_qun.o prot_buddy.o loop.o utf8.o util.o crc32.o \ tinyxml/tinystr.o tinyxml/tinyxml.o tinyxml/tinyxmlerror.o tinyxml/tinyxmlparser.o\ gmyqq.o myqq.o checkAndSetConfig.o SRCS:= $(addsuffix .c, $(basename $(OBJS))) OBJS:=$(addprefix $(OBJ)/, $(OBJS)) SRCS:=$(addprefix $(SRC)/,$(OBJS)) all: $(EXEC) @echo done. $(EXEC): $(OBJS) $(CC) $(CLIBS) $^ -g -o $@ $(OBJ)/%.o : $(SRC)/%.c gcc `pkg-config --cflags dbus-glib-1 libnm_glib` -c $< -o $@ $(OBJ)/%.o:$(SRC)/%.cc $(CC) $(CFLAGS) -c $< -o $@ $(OBJ)/%.o : $(SRC)/%.cpp $(CC) -c $< -o $@ .PHONY: clean cleanobj clean: rm -f $(OBJ)/*.o run: (cd $(BIN);./gmyqq) runc: (cd $(BIN);./gmyqq --nogui) runt: (cd $(BIN);./gmyqq --test) runt1: (cd $(BIN);./gmyqq --test -u 1140048821) runt2: (cd $(BIN);./gmyqq --test -u 1147071944) update: @echo update. install: cp -vr $(BIN) ~/bin/MyQQ cp -v $(DATA)/myqq ~/bin release: $(MyQQ_HOME)/export <file_sep>/src/qqclient.c /* * qqclient.c * * QQ Client. * * Copyright (C) 2008 <NAME> * * 2008-7-12 Created. * 2008-10-26 TCP UDP Server Infos are loaded from configuration file. * * Description: This file mainly includes the functions about * loading configuration, connecting server, guard thread, basic interface * */ #include <string.h> #include <stdlib.h> #include <unistd.h> #ifdef __WIN32__ #include <winsock.h> #include <wininet.h> #else #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #endif #include "md5.h" #include "memory.h" #include "debug.h" #include "config.h" #include "qqsocket.h" #include "packetmgr.h" #include "protocol.h" #include "qqclient.h" #include "qun.h" #include "group.h" #include "buddy.h" #include "util.h" static server_item tcp_servers[MAX_SERVER_ADDR]; static server_item udp_servers[MAX_SERVER_ADDR]; static int tcp_server_count = 0, udp_server_count = 0; static uint last_server_ip = 0, last_server_port = 0; //for quick login //static uchar last_server_info[15]; static void read_server_addr( server_item* srv, char* s, int* count ) { char ip[32], port[10], read_name = 1, *p; int j = 0; for( p=s; ; p++ ){ if( *p == ':' ){ ip[j]=0; j=0; read_name = 0; }else if( *p=='|' || *p=='\0' ){ port[j]=0; j=0; read_name = 1; if( *count < MAX_SERVER_ADDR ){ strncpy( srv[*count].ip, ip, 31 ); srv[*count].port = atoi( port ); // printf("%s:%d\n", srv[*count].ip, srv[*count].port ); (*count) ++; } if( *p=='\0' ) break; }else{ if( read_name ){ if( j<31 ) ip[j++] = *p; }else{ if( j<9 ) port[j++] = *p; } } } } static void read_config( qqclient* qq ) { assert( g_conf ); if( !tcp_server_count && !udp_server_count ){ //const char* tcps, *udps; char* tcps, *udps; //---amoblin:把字符串从函数参数里调出,赋给数组再用。 tcps =(char *) config_readstr( g_conf, "QQTcpServerList"); udps =(char *) config_readstr( g_conf, "QQUdpServerList"); if( tcps ){ read_server_addr( tcp_servers, tcps, &tcp_server_count ); } if( udps ){ read_server_addr( udp_servers, udps, &udp_server_count ); } } qq->log_packet = config_readint( g_conf, "QQPacketLog"); if( config_readstr( g_conf, "QQNetwork") && stricmp( (char *)config_readstr( g_conf, "QQNetwork"), "TCP" ) == 0 ) qq->network = TCP; else qq->network = UDP; if( config_readstr( g_conf, "QQVerifyDir" ) ) strncpy( qq->verify_dir, (char *)config_readstr( g_conf, "QQVerifyDir" ), PATH_LEN ); if( qq->verify_dir == NULL ) strcpy( qq->verify_dir, "./web/verify" ); mkdir_recursive( qq->verify_dir ); } int qqclient_create( qqclient* qq, uint num, char* pass ) { uchar md5_pass[16]; //加密密码 md5_state_t mst; md5_init( &mst ); md5_append( &mst, (md5_byte_t*)pass, strlen(pass) ); md5_finish( &mst, (md5_byte_t*)md5_pass ); return qqclient_md5_create( qq, num, md5_pass ); } static void delete_func(const void *p) { DEL( p ); } int qqclient_md5_create( qqclient* qq, uint num, uchar* md5_pass ) { md5_state_t mst; //make sure all zero memset( qq, 0, sizeof( qqclient ) ); qq->number = num; memcpy( qq->md5_pass1, md5_pass, 16 ); // md5_init( &mst ); md5_append( &mst, (md5_byte_t*)qq->md5_pass1, 16 ); md5_finish( &mst, (md5_byte_t*)qq->md5_pass2 ); qq->mode = QQ_ONLINE; qq->process = P_INIT; read_config( qq ); qq->version = QQ_VERSION; // list_create( &qq->buddy_list, MAX_BUDDY ); list_create( &qq->qun_list, MAX_QUN ); list_create( &qq->group_list, MAX_GROUP ); loop_create( &qq->event_loop, MAX_EVENT, delete_func ); loop_create( &qq->msg_loop, MAX_EVENT, delete_func ); pthread_mutex_init( &qq->mutex_event, NULL ); //create self info qq->self = buddy_get( qq, qq->number, 1 ); if( !qq->self ){ DBG("[%d] Fatal error: qq->self == NULL", qq->number); return -1; } return 0; } #define INTERVAL 5 static void* qqclient_keepalive( void* data ) { qqclient* qq = (qqclient*) data; int counter = 0; DBG("keepalive"); while( qq->process != P_INIT ) { counter ++; if( counter % INTERVAL == 0 ) { if( qq->process == P_LOGGING || qq->process == P_LOGIN ) { packetmgr_check_packet( qq, 5 ); if( qq->process == P_LOGIN ) { //1次心跳/分钟 if( counter % ( 1 *60*INTERVAL) == 0 ) { prot_user_keep_alive( qq ); } //10分钟刷新在线列表 QQ2009是5分钟刷新一次。 if( counter % ( 10 *60*INTERVAL) == 0 ) { prot_buddy_update_online( qq, 0 ); qun_update_online_all( qq ); } //30分钟刷新状态和刷新等级 if( counter % ( 30 *60*INTERVAL) == 0 ) { prot_user_change_status( qq ); prot_user_get_level( qq ); } // if( qq->online_clock == 0 ) // { //刚登录上了 // memcpy( last_server_info, qq->data.server_data, 15 ); // last_server_ip = qq->server_ip; // last_server_port = qq->server_port; // } // //等待登录完毕 if( ! qq->login_finish ) { if(loop_is_empty(&qq->packetmgr.ready_loop)&&loop_is_empty(&qq->packetmgr.sent_loop) ) { qq->login_finish = 1; //we can recv message now. } } qq->online_clock ++; } } } USLEEP( 1000/INTERVAL ); } DBG("end."); return NULL; } int connect_server( qqclient* qq ) { //connect server if( qq->socket ) qqsocket_close( qq->socket ); if( qq->network == TCP ){ qq->socket = qqsocket_create( TCP, NULL, 0 ); }else{ qq->socket = qqsocket_create( UDP, NULL, 0 ); } if( qq->socket < 0 ){ DBG("can't not create socket. ret=%d", qq->socket ); return -1; } struct in_addr addr; addr.s_addr = htonl( qq->server_ip ); DBG("connecting to %s:%d", inet_ntoa( addr ), qq->server_port ); if( qqsocket_connect2( qq->socket, qq->server_ip, qq->server_port ) < 0 ){ DBG("can't not connect server %s", inet_ntoa( addr ) ); return -1; } return 0; } void qqclient_get_server(qqclient* qq) { int i; struct sockaddr_in addr; if( last_server_ip == 0 ){ //random an ip if( qq->network == TCP && tcp_server_count>0 ){ i = rand()%tcp_server_count; netaddr_set( tcp_servers[i].ip, &addr ); qq->server_ip = ntohl( addr.sin_addr.s_addr ); qq->server_port = tcp_servers[i].port; }else{ if( udp_server_count <1 ){ qq->process = P_ERROR; DBG("no server for logging."); } i = rand()%udp_server_count; netaddr_set( udp_servers[i].ip, &addr ); qq->server_ip = ntohl( addr.sin_addr.s_addr ); qq->server_port = udp_servers[i].port; } }else{ qq->server_ip = last_server_ip; qq->server_port = last_server_port; last_server_ip = 0; // memcpy( qq->data.server_data, last_server_info, 15 ); } } int qqclient_login( qqclient* qq ) { DBG("login"); int ret; if( qq->process != P_INIT ) { DBG("please logout first"); return -1; } qqclient_set_process( qq, P_LOGGING ); srand( qq->number + time(NULL) ); //start packetmgr packetmgr_start( qq ); packetmgr_new_seqno( qq ); qqclient_get_server( qq ); ret = connect_server( qq ); if( ret < 0 ) { qq->process = P_ERROR; return ret; } //ok, already connected to the server //send touch packet // if( last_server_ip == 0 ){ prot_login_touch( qq ); // }else{ // prot_login_touch_with_info( qq, last_server_info, 15 ); // } //keep ret = pthread_create( &qq->thread_keepalive, NULL, qqclient_keepalive, (void*)qq ); return 0; } void qqclient_logout( qqclient* qq ) { if( qq->process == P_INIT ) return; if( qq->process == P_LOGIN ){ int i; for( i = 0; i<4; i++ ) prot_login_logout( qq ); }else{ DBG("process = %d", qq->process ); } qq->login_finish = 0; qqclient_set_process( qq, P_INIT ); qqsocket_close( qq->http_sock ); qqsocket_close( qq->socket ); DBG("joining keepalive"); #ifdef __WIN32__ pthread_join( qq->thread_keepalive, NULL ); #else if( qq->thread_keepalive ) pthread_join( qq->thread_keepalive, NULL ); #endif packetmgr_end( qq ); } void qqclient_cleanup( qqclient* qq ) { if( qq->process != P_INIT ) qqclient_logout( qq ); pthread_mutex_lock( &qq->mutex_event ); qun_member_cleanup( qq ); list_cleanup( &qq->buddy_list ); list_cleanup( &qq->qun_list ); list_cleanup( &qq->group_list ); loop_cleanup( &qq->event_loop ); loop_cleanup( &qq->msg_loop ); pthread_mutex_destroy( &qq->mutex_event ); } int qqclient_verify( qqclient* qq, uint code ) { if( qq->login_finish ){ prot_user_request_token( qq, qq->data.operating_number, qq->data.operation, 1, code ); }else{ qqclient_set_process( qq, P_LOGGING ); prot_login_request( qq, &qq->data.verify_token, code, 0 ); } DBG("verify code: %x", code ); return 0; } int qqclient_add( qqclient* qq, uint number, char* request_str ) { qqbuddy* b = buddy_get( qq, number, 0 ); if( b && b->verify_flag == VF_OK ) { prot_buddy_verify_addbuddy( qq, 03, number ); //允许一个请求x }else{ strncpy( qq->data.addbuddy_str, request_str, 50 ); prot_buddy_request_addbuddy( qq, number ); } return 0; } int qqclient_del( qqclient* qq, uint number ) { qq->data.operating_number = number; prot_user_request_token( qq, number, OP_DELBUDDY, 6, 0 ); return 0; } int qqclient_wait( qqclient* qq, int sec ) { int i; //we don't want to cleanup the data while another thread is waiting here. if( pthread_mutex_trylock( &qq->mutex_event ) != 0 ) return -1; //busy? for( i=0; (sec==0 || i<sec) && qq->process!=P_INIT; i++ ){ if( loop_is_empty(&qq->packetmgr.ready_loop) && loop_is_empty(&qq->packetmgr.sent_loop) ) { pthread_mutex_unlock( &qq->mutex_event ); return 0; } SLEEP(1); } pthread_mutex_unlock( &qq->mutex_event ); return -1; } void qqclient_change_status( qqclient* qq, uchar mode ) { qq->mode = mode; prot_user_change_status( qq ); } // wait: <0 wait until event arrives // wait: 0 don't need to wait, return directly if no event // wait: n(n>0) wait n secondes. // return: 1:ok 0:no event int qqclient_get_event( qqclient* qq, char* event, int size, int wait ) { char* buf; //we don't want to cleanup the data while another thread is waiting here. if( pthread_mutex_trylock( &qq->mutex_event ) != 0 ) return -1; //busy? for( ; ; ){ if( qq->process == P_INIT ){ pthread_mutex_unlock( &qq->mutex_event ); return -1; } buf =(char *) loop_pop_from_head( &qq->event_loop ); if( buf ){ int len = strlen( buf ); if( len < size ){ strcpy( event, buf ); }else{ DBG("buffer too small."); } delete_func( buf ); pthread_mutex_unlock( &qq->mutex_event ); return 1; } if( qq->online_clock > 10 ){ buf =(char *) loop_pop_from_head( &qq->msg_loop ); if( buf ){ int len = strlen( buf ); if( len < size ){ strcpy( event, buf ); }else{ DBG("buffer too small."); } delete_func( buf ); pthread_mutex_unlock( &qq->mutex_event ); return 1; } } if( wait<0 || wait> 0 ){ if( wait>0) wait--; USLEEP( 200 ); }else{ break; } } pthread_mutex_unlock( &qq->mutex_event ); return 0; } int qqclient_put_event( qqclient* qq, char* event ) { char* buf; int len = strlen( event ); //NEW( buf, len+1 ); //amoblin:redefine NEW char buf_tmp[len+1]; memset( buf_tmp, 0, len+1); buf = buf_tmp; if( !buf ) return -1; strcpy( buf, event ); loop_push_to_tail( &qq->event_loop, (void*)buf ); return 0; } int qqclient_put_message( qqclient* qq, char* msg ) { char* buf; int len = strlen( msg ); //NEW( buf, len+1 ); char buf_tmp[len+1]; memset( buf_tmp, 0, len+1); buf = buf_tmp; if( !buf ) return -1; strcpy( buf, msg ); loop_push_to_tail( &qq->msg_loop, (void*)buf ); return 0; } void qqclient_set_process( qqclient *qq, int process ) { qq->process = process; char event[16]; sprintf( event, "process^$%d", process ); qqclient_put_event( qq, event ); } <file_sep>/data/test.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import gtk import gtk.glade class MainWindow(): def __init__(self): self.gladefile="gmyqq.glade" self.xml=gtk.glade.XML(self.gladefile) self.window = self.xml.get_widget("main_window") self.window.set_title("gmyqq") self.window.set_default_size(800, 600) self.window.connect('destroy', gtk.main_quit) self.window.show_all(); def main(): win = MainWindow(); gtk.main() if __name__ == '__main__': main() <file_sep>/src/gmyqq.h #include <gtkmm.h> #include <libglademm.h> #include <libnotifymm.h> #include <boost/lexical_cast.hpp> #include "myqq.h" using namespace Gtk; class gMyqq { public: gMyqq(); ~gMyqq(); protected: void on_tray_clicked(); void show_window(); void hide_window(); void on_textview_enter_key_pressed(); TextView *message_textview; Glib::RefPtr<Gnome::Glade::Xml> refXml; Glib::RefPtr<Gdk::Pixbuf> ui_logo; Window *main_window; Entry *username_entry; Entry *password_entry; Entry *fakeAddress_entry; Entry *nickname_entry; static CheckButton *autologin_checkbutton; static Button *connect_button; Button *disconnect_button; Button *quit_button; Label *status_label; //Glib::RefPtr<Gtk::StatusIcon> status_icon; //Glib::RefPtr<Gtk::StatusBar> status_bar; pthread_t authen_thread; pthread_t change_ui_thread; int window_x; int window_y; static sigc::connection c; static Notify::Notification *n; }; <file_sep>/src/config.h //config.h #ifndef _CONFIG_H #define _CONFIG_H #define CONFIG_NAME_LEN 64 #define CONFIG_VALUE_LEN 256 typedef struct config_item{ char name[CONFIG_NAME_LEN]; char value[CONFIG_VALUE_LEN]; }config_item; typedef struct cconfig{ int item_count; config_item *items[1024]; }config; //amobline:add const to argument 2 //int config_open( config* c, const char* filename ); //int config_readint( config*c, const char* name ); //char* config_readstr( config*c, const char* name ); //void config_close( config* c ); // void config_init(); void config_end(); extern config *g_conf; #endif <file_sep>/src/prot_buddy.c /* * prot_buddy.c * * QQ Protocol. Part Buddy * * Copyright (C) 2008 <NAME> * * 2008-7-12 Created. * * Description: This file mainly includes the functions about * */ #include <time.h> #include <stdlib.h> #include <string.h> #include "qqclient.h" #include "memory.h" #include "debug.h" #include "qqpacket.h" #include "packetmgr.h" #include "protocol.h" #include "buddy.h" void prot_buddy_update_list( struct qqclient* qq, ushort pos ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_GET_BUDDY_LIST ); if( !p ) return; bytebuffer *buf = p->buf; put_byte( buf, 01 ); put_int( buf, 00000000 ); put_int( buf, 00000000 ); put_byte( buf, 02 ); put_word( buf, pos ); put_word( buf, 0 ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_update_list_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; buf->pos += 10; ushort next_pos = get_word( buf ); buf->pos += 5; uint number; qqbuddy* b; while( buf->pos < buf->len-5 ){ //5 rest bytes I dont know number = get_int( buf ); b = buddy_get( qq, number, 1 ); if( b == NULL ){ DBG("Error: failed to allocate buddy."); break; } b->face = get_word( buf ); b->age = get_byte( buf ); b->sex = get_byte( buf ); uchar name_len = get_byte( buf ); //name_len get_data( buf, (uchar*)b->nickname, name_len ); b->nickname[name_len] = 0; buf->pos += 27; } if( next_pos != 0xffff ){ prot_buddy_update_list( qq, next_pos ); }else{ DBG("buddy_count: %d", qq->buddy_list.count ); buddy_set_all_off( qq ); #ifndef NO_BUDDY_DETAIL_INFO prot_buddy_update_signiture( qq, 0 ); prot_buddy_update_account( qq, 0 ); prot_buddy_update_alias( qq ); #endif buddy_put_event( qq ); } } void prot_buddy_update_online( struct qqclient* qq, uint next_number ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_GET_BUDDY_ONLINE ); if( !p ) return; bytebuffer *buf = p->buf; put_byte( buf, 0x02 ); //get buddies put_int( buf, next_number ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_update_online_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar next_order = get_byte( buf ); uint number; qqbuddy* b; uint max_number = 0; while( buf->pos < buf->len ){ number = get_int( buf ); if( number > max_number ) max_number = number; b = buddy_get( qq, number, 0 ); if( !b ){ DBG("buddy_get(%d) failed.", number ); break; } get_byte( buf ); b->ip = get_int( buf ); b->port = get_word( buf ); get_byte( buf ); b->status = get_byte( buf ); b->version = get_word( buf ); get_data( buf, b->session_key, 16 ); buf->pos += 11; } if( next_order != 0xff ){ prot_buddy_update_online( qq, max_number ); }else{ buddy_put_event( qq ); return; } } void prot_buddy_status( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uint number = get_int( buf ); qqbuddy* b = buddy_get( qq, number, 0 ); if( b ){ get_byte( buf ); b->ip = get_int( buf ); b->port = get_word( buf ); get_byte( buf ); b->status = get_byte( buf ); DBG("status to %x", b->status ); b->version = get_word( buf ); get_data( buf, b->session_key, 16 ); char event[64]; sprintf( event, "buddystatus^$%u^$%s", number, buddy_status_string(b->status) ); qqclient_put_event( qq, event ); } } void prot_buddy_update_signiture( struct qqclient* qq, uint pos ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_GET_BUDDY_SIGN ); if( !p ) return; bytebuffer *buf = p->buf; //sort buddy_sort_list( qq ); put_byte( buf, 0x83 ); //command put_byte( buf, 0x00 ); //start at pos int i, j, count=1; pthread_mutex_lock( &qq->buddy_list.mutex ); for( i=0; i<qq->buddy_list.count; i++ ) if( ((qqbuddy*)qq->buddy_list.items[i])->number >= pos ) break; count = MIN_( 50, qq->buddy_list.count-i ); if( count == 0 ){ pthread_mutex_unlock( &qq->buddy_list.mutex ); DBG("signiture finished."); packetmgr_del_packet( &qq->packetmgr, p ); return; } put_byte( buf, count ); for( j=i; j<i+count; j++ ){ put_int( buf, ((qqbuddy*)qq->buddy_list.items[j])->number ); // put_int( buf, 0 ); } pthread_mutex_unlock( &qq->buddy_list.mutex ); post_packet( qq, p, SESSION_KEY ); } #ifndef NO_BUDDY_DETAIL_INFO void prot_buddy_update_signiture_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar cmd = get_byte( buf ); switch( cmd ){ case 0x83: { uchar result = get_byte( buf ); if( result!=0 ){ DBG("reuslt = %d", result ); return; } uint next_pos; next_pos = get_int( buf ); while( buf->pos < buf->len ){ uint number = get_int( buf ); qqbuddy* b = buddy_get( qq, number, 0 ); if( !b ){ DBG("buddy_get(%d) failed", number); return; } b->sign_time = get_int( buf ); uchar len = get_byte( buf ); // len = MIN( len, SIGNITURE_LEN-1 ); get_data( buf, (uchar*)b->signiture, len ); b->signiture[len] = 0; // DBG("sign: %s %s", b->nickname, b->signiture ); } if( next_pos != 0 && next_pos != 0xffffffff ){ //send else prot_buddy_update_signiture( qq, next_pos ); } } break; default: DBG("unknown cmd = %x", cmd ); } } void prot_buddy_update_account( struct qqclient* qq, uint pos ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_ACCOUNT ); if( !p ) return; bytebuffer *buf = p->buf; //sort buddy_sort_list( qq ); put_byte( buf, 0x01 ); //command put_int( buf, qq->number ); //start at pos int i, j, count; pthread_mutex_lock( &qq->buddy_list.mutex ); for( i=0; i<qq->buddy_list.count; i++ ) if( ((qqbuddy*)qq->buddy_list.items[i])->number >= pos ) break; count = MIN_( 50, qq->buddy_list.count-i ); if( count == 0 ){ pthread_mutex_unlock( &qq->buddy_list.mutex ); DBG("account finished."); packetmgr_del_packet( &qq->packetmgr, p ); return; } put_byte( buf, count ); for( j=i; j<i+count; j++ ){ put_int( buf, ((qqbuddy*)qq->buddy_list.items[j])->number ); // } pthread_mutex_unlock( &qq->buddy_list.mutex ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_update_account_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar cmd = get_byte( buf ); switch( cmd ){ case 0x01: { get_int(buf ); //self number ushort result = get_word( buf ); if( result!=0x0001 ){ DBG("reuslt = %d", result ); return; } uint next_pos; next_pos = get_int( buf ); int count; count = get_word( buf ); while( buf->pos < buf->len ){ uint number = get_int( buf ); qqbuddy* b = buddy_get( qq, number, 0 ); if( !b ){ DBG("b==NULL"); return; } b->account_flag = get_int( buf ); if( b->account_flag > 0 ){ uchar len = get_byte( buf ); len = MIN_( len, ACCOUNT_LEN-1 ); get_data( buf, (uchar*)b->account, len ); b->account[len] = 0; // DBG("account: %s %s", b->nickname, b->account ); } } if( next_pos != 0 && next_pos != 0xffffffff ){ //send else prot_buddy_update_account( qq, next_pos ); } } break; case 0x03: { uchar type, result; uint number; type = get_byte( buf ); number = get_int( buf ); result = get_byte( buf ); if( result != 00 ){ DBG("failed to verify adding buddy msg."); } DBG("verified adding buddy msg %u result: %d", number, result ); } break; default: DBG("unknown cmd = %x", cmd ); } } void prot_buddy_update_alias( struct qqclient* qq ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_BUDDY_ALIAS ); if( !p ) return; bytebuffer *buf = p->buf; put_byte( buf, 0x68 ); //command put_byte( buf, 0x00 ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_update_alias_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar cmd = get_byte( buf ); switch( cmd ){ case 0x68: { uchar result = get_byte( buf ); if( result!=0x01 ){ DBG("reuslt = %d", result ); return; } while( buf->pos < buf->len ){ uint number = get_int( buf ); qqbuddy* b = buddy_get( qq, number, 0 ); if( !b ){ DBG("b==NULL"); return; } uchar len = get_byte( buf ); len = MIN_( len, ALIAS_LEN-1 ); get_data( buf, (uchar*)b->alias, len ); b->alias[len] = 0; // DBG("alias: %s %s", b->nickname, b->alias ); } buddy_put_event( qq ); } break; default: DBG("unknown cmd = %x", cmd ); } } #endif void prot_buddy_request_addbuddy( struct qqclient* qq, uint number ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_ADDBUDDY_REQUEST ); if( !p ) return; bytebuffer *buf = p->buf; put_int( buf, number ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_request_addbuddy_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uint number = get_int( buf ); uchar result = get_byte( buf ); uchar flag = get_byte( buf ); //verify flag if( result == 0 ){ qq->data.operating_number = number; qqbuddy* b = buddy_get( qq, number , 1 ); if( b ){ b->verify_flag = flag; } switch( flag ){ case 00: //允许任何人 prot_user_request_token( qq, number, OP_ADDBUDDY, 1, 0 ); break; case 01: //需要验证 prot_user_request_token( qq, number, OP_ADDBUDDY, 1, 0 ); break; case 02: { char msg[128]; sprintf( msg, "[%u]拒绝被任何人加为好友。", number ); buddy_msg_callback( qq, 100, time(NULL), msg ); break; } case 03: //answer question { char msg[128]; sprintf( msg, "[%u]需要回答问题才能加为好友。", number ); buddy_msg_callback( qq, 100, time(NULL), msg ); break; } default: DBG("Unknown flag = %x", flag ); } } } void prot_buddy_verify_addbuddy( struct qqclient* qq, uchar cmd, uint number ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_ADDBUDDY_VERIFY ); if( !p ) return; bytebuffer *buf = p->buf; put_byte( buf, cmd ); //command put_int( buf, number ); put_word( buf, 0x0000 ); switch( cmd ){ case 03: // put_byte( buf, 0x00 ); break; case 02: // put_word( buf, qq->data.user_token.len ); put_data( buf, qq->data.user_token.data, qq->data.user_token.len ); put_byte( buf, 1 ); put_byte( buf, 0 ); put_byte( buf, strlen(qq->data.addbuddy_str) ); put_data( buf, (uchar*)qq->data.addbuddy_str, strlen(qq->data.addbuddy_str) ); break; case 01: put_word( buf, qq->data.user_token.len ); put_data( buf, qq->data.user_token.data, qq->data.user_token.len ); put_byte( buf, 0x00 ); break; case 00: // put_word( buf, qq->data.user_token.len ); put_data( buf, qq->data.user_token.data, qq->data.user_token.len ); put_byte( buf, 1 ); put_byte( buf, 0 ); break; } post_packet( qq, p, SESSION_KEY ); } void prot_buddy_verify_addbuddy_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar cmd = get_byte( buf ); uint number; number = get_int( buf ); switch( cmd ) { case 0x02: break; //wait for reply.. case 0x00: break; case 0x03: case 0x01: { uchar result = get_byte( buf ); if( result == 0x00 ) { char msg[128]; DBG("add buddy %u ok!! [cmd=%x]", number, cmd ); sprintf( msg, "你已经把[%u]添加为好友。", number ); buddy_msg_callback( qq, 100, time(NULL), msg ); //refresh buddylist buddy_update_list( qq ); } else { DBG("failed to add buddy %u result=%d", number, result ); } } break; default: DBG("unknown cmd = %x", cmd ); } } void prot_buddy_del_buddy( struct qqclient* qq, uint number ) { qqpacket* p = packetmgr_new_send( qq, QQ_CMD_DEL_BUDDY ); if( !p ) return; bytebuffer *buf = p->buf; put_byte( buf, qq->data.user_token.len ); put_data( buf, qq->data.user_token.data, qq->data.user_token.len ); char s[16]; sprintf( s, "%u", number ); put_data( buf, (uchar*)s, strlen(s) ); post_packet( qq, p, SESSION_KEY ); } void prot_buddy_del_buddy_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; if( get_byte( buf ) != 0 ){ DBG("Failed to del buddy %u.", qq->data.operating_number ); }else{ char msg[128]; buddy_remove( qq, qq->data.operating_number ); sprintf( msg, "删除好友[%u]成功。", qq->data.operating_number ); buddy_msg_callback( qq, 100, time(NULL), msg ); } } <file_sep>/src/gmyqq.cc #include <pthread.h> #include "gmyqq.h" /* static member */ gMyqq::gMyqq() { //tray //status_icon = StatusIcon::create_from_file("../data/gmyqq.png"); //if(status_icon) //{ // status_icon->set_tooltip("gmyqq, a qq client for linux."); // status_icon->signal_activate().connect(sigc::mem_fun(*this, &gMyqq::on_tray_clicked)); //} //else // { // cout<<"create tray icon error!\n"; // } refXml = Gnome::Glade::Xml::create("../data/gmyqq.glade","main_window"); if(!refXml) exit(271); //status_bar=NULL; //status_bar = refXml->get_widget("statusbar",status_bar); //status_bar->set_text("welcome to gmyqq!"); //status_label=NULL; //status_label= refXml->get_widget("message_label",status_bar); //status_label->set_text("welcome to gmyqq!"); message_textview=NULL; message_textview = refXml->get_widget("message_textview",message_textview); //message_textview->signal_clicked().connect(); main_window = NULL; main_window = refXml->get_widget("main_window", main_window); main_window->set_default_size(800,600); main_window->set_title("gmyqq"); //ui_logo = Gdk::Pixbuf::create_from_file("/home/laputa/Projects/gmyqq/data/gmchess.png"); //main_window->set_icon(ui_logo); main_window->set_focus(*message_textview); main_window->show_all(); /* board= Gtk::manage(new Board(*this)); box_board->pack_start(*board); // 设置Treeview区 Gtk::ScrolledWindow* scrolwin=dynamic_cast<Gtk::ScrolledWindow*> (ui_xml->get_widget("scrolledwindow")); m_refTreeModel = Gtk::ListStore::create(m_columns); m_treeview.set_model( m_refTreeModel); scrolwin->add(m_treeview); m_treeview.append_column(_("bout"),m_columns.step_bout); m_treeview.append_column(" ",m_columns.player); m_treeview.append_column(_("step"),m_columns.step_line); m_treeview.set_events(Gdk::BUTTON_PRESS_MASK); m_treeview.signal_button_press_event().connect(sigc::mem_fun(*this, &MainWindow::on_treeview_click),false); change_status(); Gtk::ScrolledWindow* scroll_book=dynamic_cast<Gtk::ScrolledWindow*> (ui_xml->get_widget("scrolledwin_book")); m_bookview= new BookView(this); scroll_book->add(*m_bookview); */ } gMyqq::~gMyqq() { } void gMyqq::on_tray_clicked() { if(main_window->is_visible()) hide_window(); else show_window(); } void gMyqq::show_window() { //main_window->move(window_x, window_y); //cout<<"resume the position("<<window_x<<","<<window_y<<")"<<endl; main_window->show(); } void gMyqq::hide_window() { //MainWindow->get_position(window_x, window_y); //cout<<"save the current position ("<<window_x<<","<<window_y<<")"<<endl; main_window->hide(); } void gMyqq::on_textview_enter_key_pressed() { } int myqq(int argc, char** argv); int main(int argc, char *argv[]) { if(argc > 1) { if(!strcmp(argv[1],"--nogui")) { myqq(argc,argv); } else if(!strcmp(argv[1],"--help")) { } else if(!strcmp(argv[1],"--test")) { Myqq myqq(argc,argv); } else { cout<<"usage: gMystar --help for more details"<<endl; } } else { Gtk::Main kit(argc, argv); gMyqq gmyqq; kit.run(); } return 0; } <file_sep>/src/memory.h #ifndef _MEMORY_H #define _MEMORY_H #include <time.h> #include <pthread.h> #define MEMO_LEN 64 #define MAX_ALLOCATION 4096 typedef struct allocation{ void* pointer; time_t time_alloc; int size; char memo[MEMO_LEN]; }allocation; typedef struct mem_detail{ int item_count; allocation* items[MAX_ALLOCATION]; pthread_mutex_t mutex_mem; }mem_detail; //#define NEW( p, size ) { p = malloc(size); memset( p, 0, size ); } #define NEW( p, size ,type) { p =(type*) malloc(size); memset( p, 0, size ); } #define DEL( p ) { free((void*)p); p = NULL; } // //#define NEW( p, size ) memory_new_detail( (void**)&p, size, __FILE__, (char*)__func__, __LINE__, #p ); //#define MNEW( p, size, memo ) memory_new( (void**)&p, size, memo ); //#define DEL( p ) {memory_delete( (void*)p ); p = NULL;} void memory_init(); void memory_new( void** p, int size, char* memo ); void memory_new_detail( void** p, int size, char* file, char* function, int line, char* name ); void memory_delete( void* p ); void memory_end(); void memory_print(); #endif <file_sep>/src/group.h #ifndef _GROUP_H #define _GROUP_H #include "qqdef.h" typedef struct qqgroup{ uint number; //internal number char name[GROUPNAME_LEN]; }qqgroup; struct qqclient; qqgroup* group_get( struct qqclient* qq, uint number, int create ); void group_remove( struct qqclient* qq, uint number ); void group_update_list( struct qqclient* qq ); void group_update_info( struct qqclient* qq, qqgroup* g ); void group_put_event( struct qqclient* qq ); #endif <file_sep>/src/main.cc #include "gmyqq.h" #define USERNAME 1147071944 int main(int argc, char *argv[]) { if(argc == 2) { if(!strcmp(argv[1],"--nogui")) { //myqq(argc,argv); } else if(!strcmp(argv[1],"--help")) { //gMystar::help(); } else if(!strcmp(argv[1],"--test")) { } else if(!strcmp(argv[1],"-s")) { } else { //cout<<"usage: gmyqq--help for more details"<<endl; } } else { Gtk::Main kit(argc, argv); gMyQQ gmyqq; kit.run(); } return 0; } <file_sep>/src/vit.c /********************************************************************************************* *改编自http://en.allexperts.com/q/C-1587/text-editor-using-ncurses.htm 2008-11-04 * ******************************************************************************************/ #include <curses.h> //curses中包含stdio.h #include <string.h> #define CTRL(c) ((c) & 037) #define FONTCOLOR COLOR_WHITE #define NUMBERCOLOR COLOR_RED #define SYSCOL 4 #define SYSROW 2 #define FONTCOLOR1 COLOR_BLACK #define FONTCOLOR2 COLOR_RED int row, col; //全局光标坐标,初始值0,0 int file_row, file_col; //文件行列值0,0 bool saved; bool isWelcome; char file_name[10]; //WINDOW *number_line; //显示行号窗口 //WINDOW *status_bar; //设置 void init_curses() //初始化光标环境 { initscr(); /* if(has_colors()) { start_color(); init_pair(1, FONTCOLOR, COLOR_BLACK); attron(COLOR_PAIR(1)); attron(A_BOLD); } */ cbreak(); nonl(); noecho(); intrflush(stdscr, FALSE); keypad(stdscr, TRUE); //curs_set(0); //0表示不显示光标 //refresh(); } void statusbar(char *str) //状态栏 { char message[COLS]; //mvwaddstr(status_bar,LINES-SYSROW,0,str); //char position[6]; //sprintf(position,"%2d,%-2d",row+1,col-SYSCOL+1); //中间对齐 //mvwaddstr(status_bar,LINES-SYSROW, COLS-6, position); //mvaddstr(LINES-SYSROW, COLS-6, position); if(!strcmp(file_name, "")) mvprintw(LINES-SYSROW,0,"%s","[No Name]"); else mvprintw(LINES-SYSROW,0,"%s",file_name); mvprintw(LINES-SYSROW,COLS-6,"%2d,%-3d",file_row,file_col); //usleep(10); } void set_command_line(char *str)//设置命令行 { //mvwaddstr(status_bar,1, 0, str); mvaddstr(LINES-1, 0, str); wrefresh(stdscr); } len(int lineno) { int linelen = COLS - 1; while (linelen >= 0 && mvinch(lineno, linelen) == ' ') linelen--; return linelen + 1; } /*初始化*/ void init(int argc,char **argv) { saved=1; FILE *fd; init_curses(); //初始光标 setline(1,0); if (argc == 1) //无参数 { strcpy(file_name, ""); statusbar(NULL); Show_Welcome(); } else //有参数,只读第一个,忽略其他 { isWelcome=0; //file_name=argv[1]; strcpy(file_name,argv[1]); read_file(file_name); } col=SYSCOL; } read_file(char *fn) //读文件 { FILE *fd; fd = fopen(fn, "rb"); if (fd == NULL) //如果文件不存在 return; file_row= 1;//文件行号 int row= 0;//编辑器行号 int length = SYSCOL;//计算每行长度 int c; bool newline=0; while ((c = getc(fd)) != EOF) { if (row == LINES - SYSROW) //末尾两行空出来 break; if(newline) { setline(file_row,row); //设置行号 newline=0; } if (c == '\n') //如果遇到换行 { row++; file_row++; length=SYSCOL; newline=1; continue; } if(!(length%COLS)) //如果超长 { row++; length = SYSCOL; move(row,SYSCOL); } addch(c); length++; } fclose(fd); if(has_colors()) { start_color(); init_pair(1, FONTCOLOR, COLOR_BLACK); init_pair(2, FONTCOLOR1, COLOR_BLACK); init_pair(3,FONTCOLOR2,COLOR_BLACK); //attron(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); attron(A_BOLD); } for(;row<LINES - SYSROW;row++) mvprintw(row,2,"~"); if(has_colors()) { attroff(COLOR_PAIR(1)); attroff(A_BOLD); //standout(); } } setline(int line,int editor_line) //设置行号:在editor_line前三列显示line值 { /* * 前三列用来显示行号用 * 循环从低位到高位分解line为一个一个字符,并从右到左显示出来 * 显示用addch(char figure); * 左移一位用move(row,col--); * *2008年5月5日上午,田磊写了本函数的大致过程,主要是数字转化字符串的思路,但行号显示有问题。 * * 2008年5月5日下午,我,肖山,肥坚一起探讨,终于把这个行号弄出来了!在这里感谢两位了。 */ //standend(); if(has_colors()) { start_color(); init_pair(1, FONTCOLOR, COLOR_BLACK); init_pair(2, FONTCOLOR1, COLOR_BLACK); init_pair(3,FONTCOLOR2,COLOR_BLACK); //attron(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); attron(A_BOLD); } //col=SYSCOL-2; //从这里输出个位 //move(editor_line,col); mvprintw(editor_line,0,"%3d",line); /* int div;//商 int rest;//余数 do { div=line/10; rest=line%10; //move(0,0); //waddch(number_line,rest+48); addch(rest+48); move(editor_line,--col); line=div; } while(div); */ move(editor_line,SYSCOL); //从这里输出文本数据 if(has_colors()) { attroff(COLOR_PAIR(1)); attroff(A_BOLD); //standout(); } //wrefresh(editor_line); } Show_Welcome(void) //初始页 { int iLine = LINES/2 -6; //LINES代表当前运行终端行数 int iCol = COLS/2; //COLS代表当前运行终端列数 mvaddstr(iLine, iCol-7,"VIT - Vi Tiny"); mvaddstr(iLine+2, iCol-6,"Version 1.0"); mvaddstr(iLine+3, iCol-6,"by D.C.T.X."); mvaddstr(iLine+4, iCol-22,"VIT is open source and freely distributable"); mvaddstr(iLine+6, iCol-21,"Help the survivers of earthquake in Sichuan"); mvaddstr(iLine+7, iCol-21,"type :q<Enter> to exit"); //idlok(stdscr, TRUE); //keypad(stdscr, TRUE); //refresh(); //usleep(10); isWelcome=true; } /*编辑模式*/ edit() //编辑模式 { int c; file_row=file_col=1; while(1) //一直循环 { statusbar(NULL); move(row, col); refresh(); c = getch(); /* Editor commands */ switch(c) //可用命令 { /* hjkl and arrow keys: move cursor * in direction indicated */ case 'h': case KEY_LEFT: case KEY_BACKSPACE: move_back(); break; case 'j': case KEY_DOWN: move_down(); break; case 'k': case KEY_UP: move_up(); break; case 'l': case KEY_RIGHT: move_forward(); break; /* i: enter insert mode */ case KEY_IC: case 'i': insert(); break; /* a: append insert mode */ case 'a': if (col < COLS - 1) col++; insert(); break; /* x: delete current character */ case KEY_DC: case 'x': delete_character(); break; /* o: open up a new line and enter insert mode */ case KEY_IL: case 'o': //move_down(); //move(--row, col = SYSCOL); //前四列显示行号用 insertln(); file_row++; row++; setline(file_row,row); insert(); break; /* d: delete current line */ case KEY_DL: case 'd': delete_line(); break; /* ^L: redraw screen */ case KEY_CLEAR: case CTRL('L'): wrefresh(curscr); break; case ':': //进入命令模式 command(':'); break; case '/': command('/'); //进入检索模式 break; case '?': command('?'); //进入逆向检索模式 break; case 'n': find_next(); break; default: statusbar("unextended operator"); break; } } } delete_character() { delch(); int i; for(i=1;mvinch(row+i,SYSCOL-2) == ' ';i++) { chtype c = mvinch(row+i,SYSCOL); mvaddch(row+i-1,COLS-1,c); mvdelch(row+i,SYSCOL); } } delete_line() { if(has_colors()) { start_color(); init_pair(1, FONTCOLOR, COLOR_BLACK); init_pair(2, FONTCOLOR1, COLOR_BLACK); init_pair(3,FONTCOLOR2,COLOR_BLACK); //attron(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); attron(A_BOLD); } deleteln();//删除当前行 int i; /*防止状态栏上移*/ move(LINES-SYSROW-1,0); clrtoeol(); mvprintw(LINES-SYSROW-1,2,"~"); int a; //chtype finger; int finger; bool first=1; for (a=row;a<LINES-SYSROW;a++) { for(i=SYSCOL-2;i>=0;i--) { finger=mvinch(a,i) & A_CHARTEXT; if(finger == '~')//到行尾了 break; if(finger == ' ') { if(first) { deleteln(); a--; } break; } else { first=0; if(finger==48) //如果是零 { addch(57);//输出9 } else { addch(finger-1); break; } } } if((mvinch(row,SYSCOL-2) & A_CHARTEXT)== '~')//到行尾了 { move_up(); break; } } if(has_colors()) { attroff(COLOR_PAIR(1)); attroff(A_BOLD); //standout(); } } move_back() { if (col > SYSCOL) { col--; file_col--; } else if(mvinch(row, SYSCOL-2) == ' ') { row--; col=COLS-1; file_col--; } } move_forward() { if (col < COLS - 1) { col++; file_col++; } else if(mvinch(row+1, SYSCOL-2) == ' ') { row++; col=SYSCOL; file_col++; } } move_down() { int i=1; while((mvinch(row+i, SYSCOL-2) & A_CHARTEXT) == ' ') i++; if((mvinch(row+i, SYSCOL-2) & A_CHARTEXT) == '~'){} else if(row+i < LINES - 2) { row=row+i; file_row++; file_col=col-3; //让每行都在控制范围内 } } move_up() { if (row > 0) { int i; for(i=1;mvinch(row-i, SYSCOL-2) == ' ';i++){} row=row-i; file_row--; file_col = col-3; } else { //setstatusbar(); } } /*命令模式*/ command(int type) // { move(LINES-1,0); clrtoeol(); addch(type); int posi=1; int c; int i=0; for(;;) { c=getch(); if (c == 27) //ESC键返回编辑模式edit { //move(LINES - 1, 0); clrtoeol(); break; } if (c == 13) //回车键执行命令 { char command_str[COLS]; int n = len(LINES-1); int i; for(i=0;i<n;i++) command_str[i] = mvinch(LINES-1,i+1) & A_CHARTEXT; command_str[n]='\0'; //很重要!否则会有乱码 switch(type) { case ':': execute(command_str); break; case '/': search(command_str); break; case '?': reverse_search(command_str); break; default: break; } break; } else if(c == KEY_BACKSPACE) { if(posi>1)//防越界 { posi--; move(LINES-1,posi); delch(); } else break; } else { if(posi<COLS-1) { addch(c); posi++; } } } } execute(char *command_str) { char *pch = strtok(command_str," "); if(pch != NULL) { if(!strcmp(pch,"q")) //退出 quit(); else if(!strcmp(pch,"w")) { pch = strtok(NULL, " "); if(pch!=NULL) strcpy(file_name, pch); write_file(file_name); } else if(!strcmp(pch,"wq")) //保存并退出 { pch = strtok (NULL, " "); if(pch==NULL) write_file(file_name); else write_file(pch); quit(); } else if(!strcmp(pch,"q!")) //强制退出 { extern void perror(), exit(); endwin(); exit(2); } else if(!strcmp(pch,"r")) { pch = strtok(NULL," "); if(pch!=NULL) { move(row,col); read_file(pch); } else statusbar("please input a file name"); } } } write_file(char *file_nm) { if(file_nm==NULL) { mvprintw(LINES-1,0,"%s","E32: No File Name"); } else { int i, n, l; FILE *food; food = fopen(file_nm, "w"); for (l = 0; l < LINES - SYSCOL; l++) { n = len(l); for (i = SYSCOL; i < n; i++) putc(mvinch(l, i) & A_CHARTEXT, food); if((mvinch(l+1,2) & A_CHARTEXT) != ' ') putc('\n', food); } fclose(food); saved=1; mvprintw(LINES-SYSROW,20,"%s"," "); } } quit() { extern void perror(), exit(); if(saved) { endwin(); exit(2); } else { mvprintw(LINES-1,0,"%s","No Saved!Please save and quit(wq) or Not save and quit!(q!)"); //提示:未保存,请先保存再退出(wq)或不保存退出(q!) } } /*插入模式*/ insert() //插入模式 { int c; //standout(); statusbar(NULL); set_command_line("-- INSERT --"); //standend(); move(row, col); refresh(); for (;;) { c = getch(); if (c == 27) //ESC键返回编辑模式edit { if(col>SYSCOL)//防越界 col--; set_command_line(" "); break; } else { saved=0; if(c == KEY_BACKSPACE) { if(col>SYSCOL)//防越界 { col--; move(row,col); delch(); } } else { if(isWelcome) //清除欢迎画面 { clear(); statusbar(NULL); set_command_line("-- INSERT --"); setline(1,0); col=4; move(row,col); isWelcome=0; } insch(c); //statusbar(NULL); mvprintw(LINES-SYSROW,20,"[+]"); move(row, ++col); } } } move(LINES - 1, COLS - 20); clrtoeol(); move(row, col); refresh(); } /*检索模式*/ search(char *exgre) { } reverse_search(char *exgre) { } find_next(char *sub_str) // { } /*主函数*/ int main(int argc,char **argv) //主函数 { char file_name[10]; //strcpy(file_name,argv[1]); init(argc, argv); //初始化 edit(); //进入编辑模式 return 0; } <file_sep>/src/buddy.h #ifndef _BUDDY_H #define _BUDDY_H #include "qqdef.h" typedef struct qqbuddy{ uint number; char nickname[NICKNAME_LEN]; uint ip; ushort port; ushort face; uchar age; uchar sex; uchar gid; uchar qqshow; uchar flag; uchar session_key[16]; uchar status; ushort version; uchar verify_flag; //00 允许 01 验证 02 拒绝 03 问题 uint sign_time; uchar account_flag; #ifndef NO_BUDDY_DETAIL_INFO char signiture[SIGNITURE_LEN]; char account[ACCOUNT_LEN]; //email account char alias[ALIAS_LEN]; char info_string[MAX_USER_INFO][USER_INFO_LEN]; #else char signiture[1]; char account[1]; char alias[1]; char info_string[1][1]; #endif }qqbuddy; struct qqclient; qqbuddy* buddy_get( struct qqclient* qq, uint number, int create ); void buddy_remove( struct qqclient* qq, uint number ); void buddy_update_list( struct qqclient* qq ); void buddy_update_info( struct qqclient* qq, qqbuddy* b ); void buddy_sort_list( struct qqclient* qq ); int buddy_send_message( struct qqclient* qq, uint number, char* msg ); void buddy_set_all_off( struct qqclient* qq ); void buddy_put_event( struct qqclient* qq ); char* buddy_status_string( int st ); #endif <file_sep>/src/qqcrypt.h /** * The QQ2003C protocol plugin * * for gaim * * Copyright (C) 2004 Puzzlebird * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************** * Reorganized by Minmin <<EMAIL>>, 2005-3-27 ************************************************** */ #ifndef _CRYPT_H #define _CRYPT_H int qqdecrypt( unsigned char* instr, int instrlen, unsigned char* key, unsigned char* outstr, int* outstrlen_ptr); void qqencrypt( unsigned char* instr, int instrlen, unsigned char* key, unsigned char* outstr, int* outstrlen_ptr); #endif //_CRYPT_H <file_sep>/src/myqq.cc #include "myqq.h" #ifndef __WIN32__ int read_password(char *lineptr) { struct termios old, new_; int nread; /* Turn echoing off and fail if we can't. */ if (tcgetattr (fileno (stdout), &old) != 0) return -1; new_ = old; new_.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new_) != 0) return -1; /* Read the password. */ nread = scanf ("%31s", lineptr); /* Restore terminal. */ (void) tcsetattr (fileno (stdout), TCSAFLUSH, &old); return nread; } #endif Irssi *irssi; /* void buddy_msg_callback ( qqclient* qq, uint uid, time_t t, char* msg ) { charcolor( CCOL_LIGHTBLUE ); //red color char timestr[12]; char msgstr[64]; struct tm * timeinfo; //char* nick = myqq_get_buddy_name( qq, uid ); const char* nick = myqq_get_buddy_name( qq, uid ); //--amoblin timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", uid ); p = strstr( buddy_buf, tmp ); if( p ) { p -= 8; if( p>=buddy_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s[", ln, timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); (msg); RESET_INPUT } } else { sprintf( msgstr, "\n%s[", timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } void qun_msg_callback ( qqclient* qq, uint uid, uint int_uid, time_t t, char* msg ) { charcolor( CCOL_REDGREEN ); //red color char timestr[12]; char msgstr[64]; const char* qun_name = myqq_get_qun_name( qq, int_uid ); //--amoblin const char* nick = myqq_get_qun_member_name( qq, int_uid, uid ); struct tm * timeinfo; timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", int_uid ); p = strstr( qun_buf, tmp ); if( p ) { p -= 8; if( p>=qun_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s{", ln, timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } else { sprintf( msgstr, "\n%s{", timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); RESET_INPUT } } */ void buddy_msg_callback ( qqclient* qq, uint uid, time_t t, char* msg ) { charcolor( CCOL_LIGHTBLUE ); //red color char timestr[12]; char msgstr[64]; struct tm * timeinfo; //char* nick = myqq_get_buddy_name( qq, uid ); const char* nick = myqq_get_buddy_name( qq, uid ); //--amoblin timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", uid ); p = strstr( buddy_buf, tmp ); if( p ) { p -= 8; if( p>=buddy_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s[", ln, timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 //irssi->show(msgstr); irssi->show( _TEXT( msg ) ); } } else { sprintf( msgstr, "\n%s[", timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 //MSG("%s", _TEXT( msgstr ) ); //puts( _TEXT( msg ) ); irssi->show(msg); } } void qun_msg_callback ( qqclient* qq, uint uid, uint int_uid, time_t t, char* msg ) { charcolor( CCOL_REDGREEN ); //red color char timestr[12]; char msgstr[64]; const char* qun_name = myqq_get_qun_name( qq, int_uid ); //--amoblin const char* nick = myqq_get_qun_member_name( qq, int_uid, uid ); struct tm * timeinfo; timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", int_uid ); p = strstr( qun_buf, tmp ); if( p ) { p -= 8; if( p>=qun_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s{", ln, timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 //MSG("%s", _TEXT( msgstr ) ); irssi->show(msg); } } else { sprintf( msgstr, "\n%s{", timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 //MSG("%s", _TEXT( msgstr ) ); irssi->show(msg); } } Myqq::Myqq(int argc,char **argv) { if(!init()) return; status=0; //初始化状态,未登录 /* irssi = new Irssi; irssi->init(account); while(true) { char command[256]; char *temp=command; get_command(temp); //得到命令 } endwin(); */ parse_command_line(argc, argv); } void Myqq::parse_command_line(int argc,char **argv) { if(argc==4) { account=atoi(argv[3]); } else if(argc==2) checkAndSetConfig();//gmyqqrc.xml while(!status) login(); if(status>0) { irssi = new Irssi; irssi->init(account); while(status) { char command[256]; char *temp=command; get_command(temp); //得到命令 } } } void Myqq::set_account(uint acc) { account=acc; } bool Myqq::login() { if(account==0) { cout<<"QQ账号:"; cin>>account; } if(*password == NULL||!strcmp(password,"0")) { cout<<"QQ密码:"; #ifdef __WIN32__ uint pwi; char pswd; for(pwi=0;pwi<=32;pwi++) { pswd = getch(); //逐次赋值,但不回显 if(pswd == '\x0d')//回车则终止循环 { password[pwi] ='\0';//getch需要补'\0'以适合原程序 break; } if(pswd == '\x08')//删除键则重输QQ密码 { if( pwi>0 ) pwi=-1; MSG("%s",_TEXT("\n请重输QQ密码:")); continue; } printf("*"); //以星号代替字符 password[pwi] =pswd; } #else //LINUX read_password( password ); #endif cout<<endl<<"是否隐身登陆?(y/n)"; cin>>input; qq->mode = *input=='y' ? QQ_HIDDEN : QQ_ONLINE; qq->mode = QQ_HIDDEN; } qqclient_create( qq, account, password ); //包装的 qqclient_login(qq); cout<<"登陆中..."<<endl; while( qq->process == P_LOGGING ) qqclient_wait( qq, 1 ); while( qq->process == P_VERIFYING ) { char temp[32]; sprintf(temp,"%d",account); string account_str(temp); string command("eog ./verify/"); command +="*.png&"; cout<<command.c_str(); system(command.c_str()); //自动调出验证码图片 cout<<"请输入验证码(验证码目录下): "; cin>>input; qqclient_verify( qq, *(uint*)input ); while( qq->process == P_LOGGING ) qqclient_wait( qq, 1 ); } if( qq->process != P_LOGIN ) //登录是否成功的判定依据! { switch( qq->process ) { case P_ERROR: cout<<"网络错误.\n"; status=-1; return false; case P_DENIED: cout<<"您的QQ需要激活(http://jihuo.qq.com).\n"; #ifdef __WIN32__ ShellExecute(NULL,"open","http://jihuo.qq.com/",NULL,NULL,SW_SHOWNORMAL); #endif status=-1; return false; case P_WRONGPASS: cout<<"您的密码错误."<<endl; status=-1; return false; } cout<<"now will logout..."<<endl; qqclient_logout( qq ); qqclient_cleanup( qq ); return false; } cout<<"success!"<<endl; status=1; return true; } bool Myqq::authen() { if(true) //登录失败 { cout<<"登录失败!请重新登录"<<endl; return false; } else return true; } void Myqq::help() { irssi->show("这是模仿irssi做的QQ图形界面。相信熟悉irssi的都知道:前有'/'的为命令,没有'/'的话直接当做消息发出。下面列出现在实现的命令:\n\ /a QQ: 添加好友QQ.\n\ /la: list all:所有好(群)友列表.\n\ /ls: list buddies:非隐身好(群)友列表.\n\ /lg: list group:显示群列表.\n\ /t N: 准备和编号为N的好友对话.\n\ enter/e: 指向某个群号或者前面的编号.\n\ leave/l: 离开群.(指向后操作)\n\ info/i: 查看相应信息.(指向后操作)\n\ update/u: 更新所有列表.\n\ status: 改变状态(online|away|busy|killme|hidden)\n\ verify/r: 输入验证码(验证码在verify目录下).\n\ change/c: 更换用户登陆.\n\ /exit 退出.\n\ /quit: 退出.\n\ /h: help:显示帮助信息.\n\ /help: help:显示帮助信息.\n\ 第一次使用会生成~/.gmyqq/gmyqqrx.xml配置文件,修改此文件可实现自动登录。\n"); } void Myqq::get_command(char *command) { irssi->get_command(command); switch(command[0]) { case '/': irssi->show_command(command); parse_command(command); break; case '\n': break; default: send_message_to_buddy(command); } } void Myqq::parse_command(char *command) { //move(LINES-1,11); //clrtoeol(); time_t t = time(NULL); struct tm *local = localtime(&t); char *pch = strtok(command," "); if(pch != NULL) { if(!strcmp(pch,"/ls")) list_online_buddies(); else if(!strcmp(pch,"/la")) list_all(); else if(!strcmp(pch,"/lg")) list_groups(); else if(!strcmp(pch,"/t")) { pch = strtok(NULL, " "); if(pch!=NULL) { begin_talk_to_buddy(pch); } } else if(!strcmp(pch,"/status")) change_status(); else if(!strcmp(pch,"/s")) { pch = strtok(NULL, " "); if(pch!=NULL) { send_message_to_buddy(pch); } } else if(!strcmp(pch,"/a")) { pch = strtok(NULL, " "); if(pch!=NULL) { add_buddy(pch); } } else if(!strcmp(pch,"/logout")) logout(); else if(!strcmp(pch,"/h") || !strcmp(pch,"/help")) help(); else if(!strcmp(pch,"/exit") || !strcmp(pch,"/quit")) quit(); else error(pch); } } char *Myqq::get_online_buddies() { } char *Myqq::get_all() { } char *Myqq::get_groups() { } void Myqq::list_online_buddies() //'ls' { myqq_get_buddy_list( qq, buddy_buf, QUN_BUF_SIZE, 1 ); irssi->show(buddy_buf); myqq_get_qun_member_list( qq, qun_int_uid, buddy_buf, QUN_BUF_SIZE, 1 ); //irssi->show(buddy_buf); } void Myqq::list_all() //'la' { myqq_get_qun_member_list( qq, qun_int_uid, buddy_buf, BUDDY_BUF_SIZE, 0 ); irssi->show(buddy_buf); myqq_get_buddy_list( qq, buddy_buf, BUDDY_BUF_SIZE, 0 ); irssi->show(buddy_buf); } void Myqq::list_groups() //'lg' { myqq_get_qun_list( qq, qun_buf, QUN_BUF_SIZE ); irssi->show(qun_buf); } void Myqq::begin_talk_to_buddy(char *arg) //'/t' { enter=0; if( enter )//判断是否在群里 { irssi->show("您在一个群中, 你可以和任何人谈话.\n"); } int n = atoi( arg ); if( n < 0xFFFF ) { char *p; p = skip_line( buddy_buf, n-1 ); if( p ) { sscanf( p, "%u%u", &n, &buddy_number); irssi->show(myqq_get_buddy_name(qq, buddy_number)); } } else { buddy_number = n; irssi->show(myqq_get_buddy_name(qq, buddy_number)); } //sprintf( print_buf, "to: %s 没有找到.\n", arg ); //cout<<print_buf; } void Myqq::send_message_to_buddy(char *arg) { enter=0; if( enter ) { /* #ifdef __WIN32__ if( myqq_send_im_to_qun( qq, qun_int_uid, to_utf8(arg), 1 ) < 0 ) #else if( myqq_send_im_to_qun( qq, qun_int_uid, arg, 1 ) < 0 ) #endif { MSG("%s",_TEXT("超时: 您的消息发送失败.\n")); } */ } else { if( buddy_number == 0 ) { //MSG("%s",_TEXT("say: 和谁谈话?\n")); } #ifdef __WIN32__ if( myqq_send_im_to_buddy( qq, buddy_number, to_utf8(arg), 1 ) < 0 ) #else if( myqq_send_im_to_buddy( qq, buddy_number, arg, 1 ) < 0 ) #endif { irssi->show("超时: 您的消息发送失败."); } else { irssi->show(arg); } } } void Myqq::change_status() { /* //改变状态 qqclient_change_status( qq, QQ_AWAY ); qqclient_change_status( qq, QQ_HIDDEN ); qqclient_change_status( qq, QQ_KILLME ); qqclient_change_status( qq, QQ_BUSY ); */ qqclient_change_status( qq, QQ_ONLINE ); } void Myqq::add_buddy(char *arg) { irssi->show("添加:"); qqclient_add( qq, atoi(arg), "nothing"); } void Myqq::logout() { irssi->exit(); status = 0; qqclient_logout( qq ); qqclient_cleanup( qq ); config_end(); DEL( qq ); MSG("%s",_TEXT("离开.\n")); DEL( qun_buf ); DEL( buddy_buf ); DEL( print_buf ); setcolor( CCOL_NONE ); memory_end(); } void Myqq::quit() { irssi->exit(); cout<<"waiting for exit..."<<endl; status = 0; qqclient_logout( qq ); cout<<"qqclient logout"<<endl; qqclient_cleanup( qq ); cout<<"qqclient cleanup"<<endl; config_end(); cout<<"config end..."<<endl; DEL( qq ); cout<<"del qq "<<endl; cout<<"离开.\n"; DEL( qun_buf ); cout<<"del groups buffer"; DEL( buddy_buf ); cout<<"del buddies buffer"; DEL( print_buf ); cout<<"del print buffer"; setcolor( CCOL_NONE ); cout<<"setcolor ..."; memory_end(); cout<<"memory end..."<<endl; } void Myqq::error(char *pch) { irssi->show("unknown command , type '/help' for more information"); } Myqq::~Myqq() { } bool Myqq::init() { setlocale(LC_ALL,""); account = 0; *password = <PASSWORD>; static char file[20]; strcpy(file,getenv("HOME")); strcat(file,"/.gmyqq"); mkdir(file,0777); strcat(file,"/gmyqqrc.xml"); config_file = file; int cmdid, lastcmd=-1, len; char cmd[16], arg[1008]; srand(time(NULL)); //init data config_init(); qqsocket_init(); NEW( qun_buf, QUN_BUF_SIZE, char); NEW( buddy_buf, BUDDY_BUF_SIZE ,char); NEW( print_buf, PRINT_BUF_SIZE, char); NEW( qq, sizeof(qqclient), qqclient); if( !qun_buf || !buddy_buf || !print_buf || !qq ) { cout<<"no enough memory."; return false; } return true; } void Myqq::buddy_msg_callback ( qqclient* qq, uint uid, time_t t, char* msg ) { charcolor( CCOL_LIGHTBLUE ); //red color char timestr[12]; char msgstr[64]; struct tm * timeinfo; const char* nick = myqq_get_buddy_name( qq, uid ); //--amoblin timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", uid ); p = strstr( buddy_buf, tmp ); if( p ) { p -= 8; if( p>=buddy_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s[", ln, timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 irssi->show(msgstr); } } else { sprintf( msgstr, "\n%s[", timestr ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 irssi->show(msgstr); } } void Myqq::qun_msg_callback ( qqclient* qq, uint uid, uint int_uid, time_t t, char* msg ) { charcolor( CCOL_REDGREEN ); //red color char timestr[12]; char msgstr[64]; const char* qun_name = myqq_get_qun_name( qq, int_uid ); //--amoblin const char* nick = myqq_get_qun_member_name( qq, int_uid, uid ); struct tm * timeinfo; timeinfo = localtime ( &t ); strftime( timestr, 12, "%H:%M:%S", timeinfo ); char tmp[20], *p; sprintf( tmp, "%-16d", int_uid ); p = strstr( qun_buf, tmp ); if( p ) { p -= 8; if( p>=qun_buf ) { int ln; sscanf( p, "%d", &ln ); sprintf( msgstr, "\n%d)%s{", ln, timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); } } else { sprintf( msgstr, "\n%s{", timestr ); strcat( msgstr, qun_name ); strcat( msgstr, "}[" ); strcat( msgstr, nick ); strcat( msgstr, "]\n\t" );//二次修改 MSG("%s", _TEXT( msgstr ) ); puts( _TEXT( msg ) ); } } Irssi::Irssi() { //PANEL *my_panel; initscr(); start_color(); init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_BLACK, COLOR_WHITE); cbreak(); nonl(); noecho(); title = newwin(1,COLS,0,0); textarea = newwin(LINES-3,COLS,1,0); statusbar = newwin(1,COLS,LINES-2,0); commandline = newwin(1,COLS,LINES-1,0); wbkgd(title,COLOR_PAIR(1)); wbkgd(textarea,COLOR_PAIR(2)); wbkgd(statusbar,COLOR_PAIR(1)); wbkgd(commandline,COLOR_PAIR(2)); //wrefresh(title); //wrefresh(statusbar); //wrefresh(textarea); //wrefresh(commandline); refresh(); intrflush(stdscr, FALSE); keypad(commandline, TRUE); cbreak(); } void Irssi::show(const char *str) { wmove(textarea,1,0); wclrtobot(textarea); time_t t = time(NULL); struct tm *local = localtime(&t); getyx(textarea,row,col); mvwprintw(textarea,1,0,"%s",str); wrefresh(textarea); move(LINES-1,11); } void Irssi::show_int(uint str) { time_t t = time(NULL); struct tm *local = localtime(&t); getyx(textarea,row,col); mvwprintw(textarea,1,0,"%d",str); wrefresh(textarea); } void Irssi::show_command(char *str) { time_t t = time(NULL); struct tm *local = localtime(&t); getyx(textarea,row,col); mvwprintw(textarea,0,0,"%2d:%2d %s",local->tm_hour,local->tm_min,str); wrefresh(textarea); } void Irssi::init(uint account) { char message[COLS]; time_t t = time(NULL); struct tm *local = localtime(&t); mvwprintw(title,0,COLS/2-10,"Welcome to gmyqq"); wprintw(statusbar,"[%2d:%2d] [%d] [1]",local->tm_hour,local->tm_min,account); wprintw(commandline,"[(status)]"); wrefresh(title); wrefresh(statusbar); wrefresh(textarea); wrefresh(commandline); refresh(); row=col=0; } void Irssi::get_command(char *command_str) { mvwprintw(commandline,0,0,"[(status)] "); wclrtoeol(commandline); move(LINES-1,11); int posi=11; int c; int i=0; while(true) { c=getch(); if (c == 27) { wmove(commandline,0,11); wclrtoeol(commandline); wrefresh(commandline); break; } else if (c == 13) //回车键执行命令 { int n = len(0); int i; for(i=0;i<n;i++) { command_str[i] = mvwinch(commandline,0,i+11) & A_CHARTEXT; } command_str[n]='\0'; //很重要!否则会有乱码 wmove(commandline,0,11); wclrtoeol(commandline); wrefresh(commandline); break; } else if(c == 127) { if(posi>11)//防越界 { posi--; mvwdelch(commandline,0,posi); wrefresh(commandline); } } else { if(posi<COLS-1) { waddch(commandline,c); wrefresh(commandline); posi++; } } } } int Irssi::len(int lineno) { int linelen = COLS - 1; while (linelen >= 0 && mvwinch(commandline,lineno, linelen) == ' ') linelen--; return linelen + 1; } void Irssi::exit() { delwin(title); delwin(textarea); delwin(statusbar); delwin(commandline); endwin(); } int myqq(int argc, char** argv) { //-----init---- int cmdid, lastcmd=-1, len; char cmd[16], arg[1008]; srand(time(NULL)); //init data config_init(); qqsocket_init(); NEW( qun_buf, QUN_BUF_SIZE, char); NEW( buddy_buf, BUDDY_BUF_SIZE ,char); NEW( print_buf, PRINT_BUF_SIZE, char); NEW( qq, sizeof(qqclient), qqclient); if( !qun_buf || !buddy_buf || !print_buf || !qq ) { MSG("%s","no enough memory."); return -1; } //login lab:if(argc<3) { uint uid; //uid=USERNAME; char password[32]; MSG("%s",_TEXT("QQ账号:")); scanf("%u", &uid ); MSG("%s",_TEXT("QQ密码:")); #ifdef __WIN32__ uint pwi; char pswd; for(pwi=0;pwi<=32;pwi++) { pswd = getch(); //逐次赋值,但不回显 if(pswd == '\x0d')//回车则终止循环 { password[pwi] ='\0';//getch需要补'\0'以适合原程序 break; } if(pswd == '\x08')//删除键则重输QQ密码 { if( pwi>0 ) pwi=-1; MSG("%s",_TEXT("\n请重输QQ密码:")); continue; } printf("*"); //以星号代替字符 password[pwi] =<PASSWORD>; } #else //LINUX read_password( password ); #endif MSG("%s",_TEXT("\n是否隐身登陆?(y/n)")); scanf("%s", input ); qqclient_create( qq, uid, password ); qq->mode = *input=='y' ? QQ_HIDDEN : QQ_ONLINE; qqclient_login( qq ); scanf("%c", input ); //If I don't add this, it will display '>' twice. } else { qqclient_create( qq, atoi(argv[1]), argv[2] ); if( argc > 3 ) qq->mode = atoi(argv[3])!=0 ? QQ_HIDDEN : QQ_ONLINE; qqclient_login( qq ); } MSG("%s",_TEXT("登陆中...\n")); while( qq->process == P_LOGGING ) qqclient_wait( qq, 1 ); while( qq->process == P_VERIFYING ) { string command("eog ./verify/"); command +="*.png&"; cout<<command.c_str(); system(command.c_str()); //自动调出验证码图片 MSG("%s",_TEXT("请输入验证码(验证码目录下): ")); scanf( "%s", input ); qqclient_verify( qq, *(uint*)input ); while( qq->process == P_LOGGING ) qqclient_wait( qq, 1 ); } if( qq->process != P_LOGIN ) //登录是否成功的判定依据! { switch( qq->process ) { case P_ERROR: MSG("%s",_TEXT("网络错误.\n")); goto lab; case P_DENIED: MSG("%s",_TEXT("您的QQ需要激活(http://jihuo.qq.com).\n")); #ifdef __WIN32__ ShellExecute(NULL,"open","http://jihuo.qq.com/",NULL,NULL,SW_SHOWNORMAL); #endif goto lab; case P_WRONGPASS: MSG("%s",_TEXT("您的密码错误.\n")); goto lab; } qqclient_logout( qq ); qqclient_cleanup( qq ); return 0; } //登录成功! MSG("%s", _TEXT(help_msg) ); while( qq->process != P_INIT ) { RESET_INPUT len = _getline( input, 1023 ); if( len < 1 ) continue; char* sp = strchr( input, ' ' ); if( sp ) { *sp = '\0'; strncpy( cmd, input, 16-1 ); strncpy( arg, sp+1, 1008-1 ); *sp = ' '; } else { strncpy( cmd, input, 16-1 ); arg[0] = '\0'; } need_reset = 1; for( cmdid=0; cmdid<sizeof(commands)/16; cmdid++ ) if( strcmp( commands[cmdid], cmd )==0 ) break; SELECT_CMD: switch( cmdid ) { case CMD_TO: case CMD_TO2: { if( enter ) { MSG("%s",_TEXT("您在一个群中, 你可以和任何人谈话.\n")); break; } int n = atoi( arg ); if( n < 0xFFFF ) { char *p; p = skip_line( buddy_buf, n-1 ); if( p ) { sscanf( p, "%u%u", &n, &to_uid ); sprintf( print_buf, "您将和 %s 进行谈话\n", myqq_get_buddy_name(qq, to_uid) ); MSG("%s", _TEXT(print_buf) ); break; } } else { to_uid = n; sprintf( print_buf, "您将和 %s 进行谈话\n", myqq_get_buddy_name(qq, to_uid) ); MSG("%s", _TEXT(print_buf) ); break; } sprintf( print_buf, "to: %s 没有找到.\n", arg ); MSG("%s", _TEXT(print_buf) ); break; } case CMD_SAY: case CMD_SAY2: { if( enter ) { #ifdef __WIN32__ if( myqq_send_im_to_qun( qq, qun_int_uid, to_utf8(arg), 1 ) < 0 ) #else if( myqq_send_im_to_qun( qq, qun_int_uid, arg, 1 ) < 0 ) #endif { MSG("%s",_TEXT("超时: 您的消息发送失败.\n")); } } else { if( to_uid == 0 ) { MSG("%s",_TEXT("say: 和谁谈话?\n")); break; } #ifdef __WIN32__ if( myqq_send_im_to_buddy( qq, to_uid, to_utf8(arg), 1 ) < 0 ) #else if( myqq_send_im_to_buddy( qq, to_uid, arg, 1 ) < 0 ) #endif { MSG("%s",_TEXT("超时: 您的消息发送失败.\n")); } } break; } case CMD_EXIT: case CMD_EXIT2: //case CMD_EXIT3: goto end; case CMD_HELP: MSG("%s", _TEXT(help_msg) ); break; case CMD_STATUS: if( strcmp( arg, "away") == 0 ) qqclient_change_status( qq, QQ_AWAY ); else if( strcmp( arg, "online") == 0 ) qqclient_change_status( qq, QQ_ONLINE ); else if( strcmp( arg, "hidden") == 0 ) qqclient_change_status( qq, QQ_HIDDEN ); else if( strcmp( arg, "killme") == 0 ) qqclient_change_status( qq, QQ_KILLME ); else if( strcmp( arg, "busy") == 0 ) qqclient_change_status( qq, QQ_BUSY ); else { MSG("%s",_TEXT("未知状态\n") ); } break; case CMD_ENTER: case CMD_ENTER2: { int n = atoi( arg ); if( n < 0xFFFF ) { char *p; p = skip_line( qun_buf, n-1 ); if( p ) { sscanf( p, "%u%u", &n, &qun_int_uid ); sprintf( print_buf, "您在 %s 群中\n", myqq_get_qun_name( qq, qun_int_uid) ); MSG("%s", _TEXT(print_buf) ); enter = 1; break; } } else { qun_int_uid = n; sprintf( print_buf, "您在 %s 群中\n", myqq_get_qun_name( qq, qun_int_uid) ); MSG("%s", _TEXT(print_buf) ); enter = 1; break; } sprintf( print_buf, "enter: %s 没有找到.\n", arg ); MSG("%s", _TEXT(print_buf) ); break; } case CMD_LEAVE: case CMD_LEAVE2: if( !enter ) { MSG("%s",_TEXT("您没有进入群.\n")); break; } enter = 0; sprintf( print_buf, "离开 %s. 您将和 %s 进行谈话\n", myqq_get_qun_name( qq, qun_int_uid ), myqq_get_buddy_name( qq, to_uid ) ); MSG("%s", _TEXT(print_buf) ); break; case CMD_QUN: case CMD_QUN2: { myqq_get_qun_list( qq, qun_buf, QUN_BUF_SIZE ); MSG("%s", _TEXT( qun_buf ) ); break; } case CMD_UPDATE: case CMD_UPDATE2: qun_update_all( qq ); buddy_update_list( qq ); group_update_list( qq ); MSG("%s",_TEXT("更新中...\n")); if( qqclient_wait( qq, 20 )<0 ) { MSG("%s",_TEXT("更新超时.\n")); } break; case CMD_INFO: case CMD_INFO2: { if( !enter ) { if( to_uid==0 ) { MSG("%s",_TEXT("请先选择一个好友.\n")); } else { char* buf = (char*)malloc(1024*4); //4kb enough! if( myqq_get_buddy_info( qq, to_uid, buf, 1024*4 ) < 0 ) { sprintf( print_buf, "获取 %s 的信息失败\n", myqq_get_buddy_name( qq, to_uid ) ); MSG("%s", _TEXT(print_buf) ); } else { MSG("%s", _TEXT( buf ) ); } free(buf); } } else { char* buf = (char*)malloc(1024*4); //4kb enough! if( myqq_get_qun_info( qq, qun_int_uid, buf, 1024*4 ) < 0 ) { sprintf( print_buf, "获取 %s 的信息失败\n", myqq_get_qun_name( qq, qun_int_uid ) ); MSG("%s", _TEXT(print_buf) ); } else { MSG( "%s",_TEXT( buf ) ); } free(buf); } break; } case CMD_VIEW: case CMD_VIEW2: if( enter ) //'lg' { myqq_get_qun_member_list( qq, qun_int_uid, buddy_buf, BUDDY_BUF_SIZE, 0 ); MSG("%s", _TEXT( buddy_buf ) ); } else //'la' { myqq_get_buddy_list( qq, buddy_buf, BUDDY_BUF_SIZE, 0 ); MSG("%s", _TEXT( buddy_buf ) ); } break; case CMD_WHO: case CMD_WHO2: if( enter ) { myqq_get_qun_member_list( qq, qun_int_uid, buddy_buf, QUN_BUF_SIZE, 1 ); MSG("%s", _TEXT( buddy_buf ) ); } else { myqq_get_buddy_list( qq, buddy_buf, QUN_BUF_SIZE, 1 ); MSG("%s", _TEXT( buddy_buf ) ); } break; case CMD_CHANGE: case CMD_CHANGE2: qqclient_logout( qq ); qqclient_cleanup( qq ); myqq( 0, NULL ); goto end; case CMD_VERIFY: case CMD_VERIFY2: qqclient_verify( qq, *((uint*)arg) ); break; case CMD_ADD: case CMD_ADD2: { sprintf( print_buf, "添加[%d]的附言(默认空):", atoi(arg) ); MSG("%s", _TEXT(print_buf) ); _getline( input, 50 ); qqclient_add( qq, atoi(arg), input ); break; } case CMD_DEL: qqclient_del( qq, atoi(arg) ); break; default: //use it as the last cmd's argument if( lastcmd && *input ) { cmdid = lastcmd; strncpy( arg, input, 1008-1 ); *input = 0; goto SELECT_CMD; } break; } lastcmd = cmdid; } end: qqclient_logout( qq ); qqclient_cleanup( qq ); config_end(); DEL( qq ); MSG("%s",_TEXT("离开.\n")); DEL( qun_buf ); DEL( buddy_buf ); DEL( print_buf ); setcolor( CCOL_NONE ); memory_end(); return 0; } <file_sep>/src/gMystar.h #include "Mystar.h" #include <gtkmm.h> #include <libglademm.h> #include <libnotifymm.h> #include <boost/lexical_cast.hpp> using namespace Gtk; class gMystar:public Window { public: //gMystar(int argc, char* argv[]); gMystar(); ~gMystar(); static void help(); static Mystar *mystar; protected: bool on_key_press_event(GdkEventKey *); void on_quit_button_clicked(); void on_connect_button_clicked(); void on_disconnect_button_clicked(); void on_tray_clicked(); static void show_message(const char *message); void show_window(); static void hide_window(); //static void *authen(void *); static void *test(void *); static void *change_ui(void *); Glib::RefPtr<Gnome::Glade::Xml> refXml; static Window *MainWindow; Entry *username_entry; Entry *password_entry; Entry *fakeAddress_entry; Entry *nickname_entry; static CheckButton *autologin_checkbutton; static Button *connect_button; Button *disconnect_button; Button *quit_button; static Label *status_label; static Glib::RefPtr<Gtk::StatusIcon> status_icon; pthread_t authen_thread; pthread_t change_ui_thread; static bool flag; static int window_x; static int window_y; static sigc::connection c; static Notify::Notification *n; };
d6c4ae9246401ee68fe9b14d53e5abe1401b3af8
[ "C", "Python", "Makefile", "C++" ]
18
C++
EnoroF/gmyqq
efc292037a0b94f495ec898fd8e053fc1042a3e8
eef4dd0dab084093510017f06eadc18f72b37a76
refs/heads/main
<file_sep>export const ADD_PRODUCT = 'ADD_PRODUCT'; export const REMOVE_PRODUCT = 'REMOVE_PRODUCT'; export const INCREASE_PRODUCT_QUANTITY = 'INCREASE_PRODUCT_QUANTITY'; export const DECREASE_PRODUCT_QUANTITY = 'DECREASE_PRODUCT_QUANTITY'; export const CLEAR_CART = "CLEAR_CART"; export const addProduct = (product) => ({ type: ADD_PRODUCT, payload: product }); export const removeProduct = (product) => ({ type: REMOVE_PRODUCT, payload: product }); export const increaseProductQuantity = (product) => ({ type: INCREASE_PRODUCT_QUANTITY, payload: product }); export const decreaseProductQuantity = (product) => ({ type: DECREASE_PRODUCT_QUANTITY, payload: product }); export const clearCart = () => ({ type: CLEAR_CART });<file_sep>import React from 'react'; import Inventory from '../../data'; import Item from '../items/item_index'; import { connect } from "react-redux"; import { fetchAllItems, fetchItem } from '../../actions/item_actions'; class LandingPage extends React.Component { constructor(props) { super(props); } componentDidMount() { if (!this.props.isLoaded) { this.props.fetchAllItems(); } else { return null; } } render() { const animals = Object.keys(Inventory).map((animal, i) => { return ( <li key={i}><Item data={Inventory[animal]}/></li> ) }) return ( <div className='landing-page'> <h1>Shop your favorite zodiac posters!</h1> <ul> {animals} </ul> </div> ) } } const msp = (state) => { return { items: state.items, isLoaded: (state.items.ox !== undefined) }; } const mdp = (dispatch) => ({ fetchAllItems: () => dispatch(fetchAllItems()), fetchItem: (item) => dispatch(fetchItem(item)) }) export default connect(msp, mdp)(LandingPage);<file_sep>import * as ItemUtil from '../utils/item_util'; export const RECEIVE_ALL_ITEMS = "RECEIVE_ALL_ITEMS"; export const RECEIVE_ITEM = "RECEIVE_ITEM"; const receiveAllItems = (items) => ({ type: RECEIVE_ALL_ITEMS, items }); const receiveItem = (item) => ({ type: RECEIVE_ITEM, item }); export const fetchAllItems = () => dispatch => ( dispatch(receiveAllItems(ItemUtil.fetchAllItems())) ); export const fetchItem = (item) => dispatch => ( ItemUtil.fetchItem(item) .then((item) => dispatch(receiveItem(item))) );<file_sep>import React from 'react'; import { Route, Switch } from 'react-router-dom'; import NavBar from './nav/navbar'; import Cart from './cart/cart'; import LandingPage from './landing_page/landing_page'; import ItemShow from './items/item_show'; const App = () => ( <div className="main"> <NavBar /> <Route exact path="/" component={LandingPage} /> <Route exact path="/cart" component={Cart} /> <Route exact path="/:sku/:item" component={ItemShow} /> </div> ); export default App;<file_sep>import Inventory from '../data'; export const fetchAllItems = () => { return Inventory; } export const fetchItem = (item) => { return Inventory[item]; }<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { removeProduct, increaseProductQuantity, decreaseProductQuantity, clearCart } from '../../actions/cart_actions'; import Confirmation from '../confirmation/confirmation'; class Cart extends React.Component { constructor(props) { super(props); this.state = { purchaseModal: false } this.handlePurchase = this.handlePurchase.bind(this); } handlePurchase() { this.setState({ purchaseModal: true }); } render() { const intToFloat = (num, decPlaces) => num.toFixed(decPlaces); const items = this.props.cartItems.map((item, i) => { const discountAvail = item.onSale; let price = discountAvail ? intToFloat(item.price * 0.85, 2) : intToFloat(item.price, 2); let subtotal = intToFloat(price * item.quantity, 2); return ( <li key={i} className={item.quantity === 0 ? "cart-item-hidden" : "cart-item"}> <div> <Link to={`/${item.sku}/${item.name}`}><img src={item.image} /></Link> <Link to={`/${item.sku}/${item.name}`}><p className="cart-item-name">{item.name}</p></Link> <p className="cart-item-price"> <p><strong>Item Price</strong>: ${price}</p> <p><strong>Item Subtotal</strong>: ${subtotal}</p> </p> </div> <div> <button id="quantity-button" onClick={() => { this.props.decreaseProductQuantity(item) }}>-</button> {item.quantity} <button id="quantity-button" onClick={() => { this.props.increaseProductQuantity(item) }}>+</button> <button id="quantity-button" onClick={() => { this.props.removeProduct(item) }}>Remove Product</button> </div> </li> ) }); let subtotal = 0; let totalQuantity = 0; for (let i = 0; i < this.props.cartItems.length; i++) { const item = this.props.cartItems[i]; totalQuantity += item.quantity; subtotal += item.onSale ? (item.price * item.quantity) * 0.85 : (item.price * item.quantity); } const total = intToFloat(subtotal + 0.0625 * subtotal + 3, 2); subtotal = intToFloat(subtotal, 2); const tax = intToFloat(0.0625 * subtotal, 2); const shipping = intToFloat(3, 2); return ( <> <div className="cart-page"> <div className="cart-left"> <h2>Your Items</h2> {items.length ? <ul className="cart-items"> {items} {items.length ? <button id="quantity-button" onClick={() => this.props.clearCart()}>Clear All</button> : null } </ul> : (<div className="no-items-cart">No Items!<br /><Link to="/" className="browse-items"><button>Browse Items Here</button></Link></div>)} </div> <div className="cart-right"> <section className={items.length ? "order-summary" : "order-summary-hidden"}> <h3>Order Summary</h3> <p><strong>Total Items</strong>: {totalQuantity}</p> <p><strong>Subtotal</strong>: ${subtotal}</p> <p><strong>Tax</strong>: ${tax}</p> <p><strong>Shipping</strong>: ${shipping}</p> <p><strong>Total</strong>: ${total}</p> <button onClick={this.handlePurchase}>Purchase</button> </section> </div> </div> {this.state.purchaseModal ? <div className="modal-background"> <div className="modal-inner"> <Confirmation total={total} totalQuantity={totalQuantity}/> <Link to="/"><button onClick={() => this.props.clearCart()}>Done</button></Link> </div> </div> : null} </> ) } } const msp = (state) => ({ cartItems: state.cart.products, }) const mdp = (dispatch) => ({ removeProduct: data => dispatch(removeProduct(data)), increaseProductQuantity: data => dispatch(increaseProductQuantity(data)), decreaseProductQuantity: data => dispatch(decreaseProductQuantity(data)), clearCart: () => dispatch(clearCart()) }) export default connect(msp, mdp)(Cart);<file_sep>const Inventory = { rat: { inventory: 100, image: 'assets/images/rat.jpg', name: 'Rat', description: 'Quick-witted, smart, charming, and persuasive', sku: 'Z0000', price: 10.00, onSale: true }, ox: { inventory: 100, image: 'assets/images/ox.jpg', name: 'Ox', description: 'Patient, kind, stubborn, and conservative', sku: 'Z0001', price: 10.00, onSale: true }, tiger: { inventory: 100, image: 'assets/images/tiger.jpg', name: 'Tiger', description: 'Authoritative, emotional, courageous, and intense', sku: 'Z0002', price: 10.00, onSale: true }, rabbit: { inventory: 100, image: '../assets/images/rabbit.jpg', name: 'Rabbit', description: 'Popular, compassionate, and sincere', sku: 'Z0003', price: 10.00, onSale: false }, dragon: { inventory: 100, image: 'assets/images/dragon.jpg', name: 'Dragon', description: 'Energetic, fearless, warm-hearted, and charismatic', sku: 'Z0004', price: 10.00, onSale: false }, snake: { inventory: 100, image: 'assets/images/snake.jpg', name: 'Snake', description: 'Charming, gregarious, introverted, generous, and smart', sku: 'Z0005', price: 10.00, onSale: false }, horse: { inventory: 100, image: 'assets/images/horse.jpg', name: 'Horse', description: 'Energetic, independent, impatient, and enjoy traveling', sku: 'Z0006', price: 10.00, onSale: false }, sheep: { inventory: 100, image: 'assets/images/sheep.jpg', name: 'Sheep', description: 'Mild-mannered, shy, kind, and peace-loving', sku: 'Z0007', price: 10.00, onSale: false }, monkey: { inventory: 100, image: 'assets/images/monkey.jpg', name: 'Monkey', description: 'Fun, energetic, and active', sku: 'Z0008', price: 10.00, onSale: false }, rooster: { inventory: 100, image: 'assets/images/rooster.jpg', name: 'Rooster', description: 'Independent, practical, hard-working, and observant', sku: 'Z0009', price: 10.00, onSale: false }, dog: { inventory: 100, image: 'assets/images/dog.jpg', name: 'Dog', description: 'Patient, diligent, generous, faithful, and kind', sku: 'Z0010', price: 10.00, onSale: false }, pig: { inventory: 100, image: 'assets/images/pig.jpg', name: 'Pig', description: 'Loving, tolerant, honest, and appreciative of luxury', sku: 'Z0011', price: 10.00, onSale: false } }; export default Inventory;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { addProduct } from "../../actions/cart_actions"; class ItemShow extends React.Component { constructor(props) { super(props); this.state = { modal: false } this.handleAddToCart = this.handleAddToCart.bind(this); this.closeModal = this.closeModal.bind(this); } handleAddToCart() { this.props.addProduct(this.props.item); this.setState({ modal: true }); } closeModal() { this.setState({ modal: false }); } render() { const intToFloat = (num, decPlaces) => num.toFixed(decPlaces); const price = intToFloat(this.props.item.price, 2); const discountAvail = this.props.item.onSale; const discountedPrice = intToFloat(price * 0.85, 2); return ( <> <div className="item-show-container"> <div className="item-show-page"> <div className="image-container"> <img src={this.props.item.image} /> </div> <div className="item-info-container"> <h3>{this.props.item.name}</h3> <p><strong>Traits:</strong> {this.props.item.description}</p> <p><strong>SKU:</strong> {this.props.item.sku}</p> <p><strong>Inventory:</strong> {this.props.item.inventory}</p> {discountAvail ? <p className="on-sale-now">On Sale Now!</p> : null} <p className="item-price"> <span className={discountAvail ? "strikeout" : ""}>{`$${price}`}</span> <span className="discount-price">{discountAvail ? ` $${discountedPrice}` : ""}</span> </p> </div> <button className="add-to-cart-btn" onClick={this.handleAddToCart}>Add To Cart</button> </div> </div> {this.state.modal ? <div className="modal-background"> <div className="add-modal-inner"> <p>Added!</p> <button onClick={this.closeModal}>Close</button> </div> </div> : null} </> ) } } const msp = (state, ownProps) => { return { item: state.items[ownProps.match.params.item.toLowerCase()] }; } const mdp = dispatch => ({ addProduct: data => dispatch(addProduct(data)) }) export default connect(msp, mdp)(ItemShow);<file_sep>import { RECEIVE_ALL_ITEMS, RECEIVE_ITEM } from '../actions/item_actions'; import { ADD_PRODUCT, REMOVE_PRODUCT, INCREASE_PRODUCT_QUANTITY, DECREASE_PRODUCT_QUANTITY } from '../actions/cart_actions'; const ItemsReducer = (state = [], action) => { Object.freeze(state); let nextState = Object.assign([], state); let updatedItem; switch (action.type) { case RECEIVE_ALL_ITEMS: return action.items; case RECEIVE_ITEM: nextState[action.item] = action.item; return nextState; case REMOVE_PRODUCT: updatedItem = action.payload.name.toLowerCase(); const incrementedItem = { ...nextState[updatedItem] }; incrementedItem.inventory += action.payload.quantity; nextState[updatedItem] = incrementedItem; return nextState; case DECREASE_PRODUCT_QUANTITY: updatedItem = action.payload.name.toLowerCase(); const incrementedItm = { ...nextState[updatedItem] }; incrementedItm.inventory++; nextState[updatedItem] = incrementedItm; return nextState; case ADD_PRODUCT: updatedItem = action.payload.name.toLowerCase(); const decrementedItem = { ...nextState[updatedItem] }; decrementedItem.inventory--; nextState[updatedItem] = decrementedItem; return nextState; case INCREASE_PRODUCT_QUANTITY: updatedItem = action.payload.name.toLowerCase(); const decrementedItm = { ...nextState[updatedItem] }; decrementedItm.inventory--; nextState[updatedItem] = decrementedItm; return nextState; default: return state; } } export default ItemsReducer;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; class NavBar extends React.Component { constructor(props) { super(props); } render() { let quantity = 0; this.props.cartItems.forEach(item => quantity += item.quantity); return ( <div className='nav-container'> <div className='home'> <Link to='/'><h1>Zodiac Attack</h1></Link> </div> <div className='links'> <Link to='/cart'> <div>My Cart <span className="cart-quantity">{quantity}</span></div> </Link> </div> </div> ); } } const msp = (state) => ({ cartItems: state.cart.products, }) export default connect(msp, null)(NavBar);
8d189cabe8651df04283e6dff380427cc02904c4
[ "JavaScript" ]
10
JavaScript
nancyma713/Zodiac-Attack
f642fc05ac56db8a65613cfc9348d4e6b9d7eaf0
c5c45b18e748ea345e7f4eca62f1417f80107f15
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Class; /** * * @author <NAME> */ public class Comissionado extends Funcionario{ double comissao; public Comissionado(double comissao, double salario, String senha, int id, String nome, String CPF, String cargo, String login) { super(salario, senha, id, nome, CPF, cargo,login); this.comissao = comissao; } public double getComissao() { return comissao; } public void setComissao(double comissao) { this.comissao = comissao; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Class; /** * * @author <NAME> */ public class Cliente extends Pessoa{ int idade; String logradouro; int n_casa; String cep; String bairro; String cidade; String estado; String telefone; //nome, cpf, idadeConvertida, logradouro, n_casaConvertido, cepConvertido, bairro, cidade, estado, telefone public Cliente(){ super(0, "", ""); this.idade = 0; this.logradouro = ""; this.n_casa = 0; this.cep = ""; this.bairro = ""; this.cidade = ""; this.estado = ""; this.telefone = ""; } public Cliente(int id, String nome, String CPF, int idade, String logradouro, int n_casa, String cep, String bairro,String cidade,String estado,String telefone) { super(id, nome, CPF); this.idade = idade; this.logradouro = logradouro; this.n_casa = n_casa; this.cep = cep; this.bairro = bairro; this.cidade = cidade; this.estado = estado; this.telefone = telefone; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public String getLogradouro() { return logradouro; } public void setLogradouro(String logradouro) { this.logradouro = logradouro; } public int getN_casa() { return n_casa; } public void setN_casa(int n_casa) { this.n_casa = n_casa; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.interfaces; import java.util.ArrayList; import projetox.Class.Funcionario; /** * * @author <NAME> */ public interface Interface_Funcionario { public String Cadastrar_Funcionario(Funcionario novo); public ArrayList<Funcionario> buscar_Funcionario(String nome) throws Exception; public void atualizar_Funcionario(Funcionario novo,int id)throws Exception; public String remover_Funcionario(int id)throws Exception; public boolean veirificarRemocao(String cargo)throws Exception; public boolean veirificarAtualizacao()throws Exception; public Funcionario VerificarLogin(String login,String senha) throws Exception; public boolean verificarLoginDisponivel(String login) throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.interfaces; import java.util.ArrayList; import projetox.Class.Pessoa; /** * * @author <NAME> */ public interface Interface_Pessoa { public String Cadastrar_Pessoa(); public ArrayList<Pessoa> buscar_Pessoa() throws Exception; public String remover_Pessoa()throws Exception; public void atualizar_Pessoa()throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Class; import java.util.Date; /** * * @author <NAME> */ public class Aluguel extends Operacao{ double diaria; Date datainicial; Date datafinal; double juros; public Aluguel(double diaria, Date datainicial, Date datafinal, double juros, int id, Funcionario funcionario, Cliente cliente, Carro carro) { super(id, funcionario, cliente, carro); this.diaria = diaria; this.datainicial = datainicial; this.datafinal = datafinal; this.juros = juros; } public double getDiaria() { return diaria; } public void setDiaria(double diaria) { this.diaria = diaria; } public Date getDatainicial() { return datainicial; } public void setDatainicial(Date datainicial) { this.datainicial = datainicial; } public Date getDatafinal() { return datafinal; } public void setDatafinal(Date datafinal) { this.datafinal = datafinal; } public double getJuros() { return juros; } public void setJuros(double juros) { this.juros = juros; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Documentos; /** * * @author <NAME> */ public class Documento { /* Situação Atual Gerenciar Carro Buscar - ok Atualizar - OK (ATUALIZA TODOS OS CARROS) Remover - OK Cadastrar - ok Cliente Buscar - ok Atualizar - ok Remover - ok Cadastrar - ok Funcionario Buscar - ok Atualizar - ok Remover - ok Cadastrar - ok Operacao Aluguel... Buscar - Sem Nada Atualizar - Sem Nada Remover - Sem Nada Cadastrar - Sem Nada Vendas... Buscar - Sem Nada Atualizar - Sem Nada Remover - Sem Nada Cadastrar - Sem Nada Folha de Pagamento Buscar - Sem Nada Atualizar - Sem Nada Remover - Sem Nada Cadastrar - Sem Nada Variaveis de Sistema Abrir Banco - ok Fechar Banco - ok Esta Classe se destina a Comentar sobre o Projeto, Informações pertinentes a implementação do Modelo, ou de como Algum erro está se comportando. Modelo do projeto _______________________________________________ View -Envia os dados da tela pra Fachada; -Recebe os dados de Fachada Fachada -Receber os dados de View Enviar os dados para Controller Receber os dados de Controller -Retorna os dados para View Controller -Recebe os dados de Controller -Envia os dados para Model -Recebe os dados de Model -Retorna os dados para Fachada Model -Recebe os dados de Controller Envia os dados pro Banco Recebe os dados do Banco -Retorna os dados para Controller Create = Cadastrar Read = Listar Update = Atualizar Delete = Remover */ // TelaCadastrarFuncionario-> // facade_Funcionario-> // Controller_Funcionario-> // Model_Funcionario } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Class; import java.util.ArrayList; import java.util.Date; /** * * @author <NAME> */ public class Venda extends Operacao{ double preco; int parcelas; String data; Funcionario fun = new Funcionario(); Cliente cli = new Cliente(); Carro ca = new Carro(); public Venda(){ super(); this.preco = preco; this.parcelas = parcelas; this.data = data; } public Venda(double preco, int parcelas, String data, int id, Funcionario funcionario, Cliente cliente, Carro carro) { super(id, funcionario, cliente, carro); this.preco = preco; this.parcelas = parcelas; this.data = data; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public int getParcelas() { return parcelas; } public void setParcelas(int parcelas) { this.parcelas = parcelas; } public String getData() { return data; } public void setData(String data) { this.data = data; } public void setCarro(ArrayList<Carro> fi) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.controller; import java.util.ArrayList; import projetox.Class.Cliente; import projetox.Class.Cliente; import projetox.Model.Model_Cliente; import projetox.Model.Model_Cliente; /** * * @author <NAME> */ public class Controller_Cliente { Model_Cliente model = new Model_Cliente(); public String Validar_Cadastro(String nome, String cpf, String idade,String logradouro,String n_casa,String cep,String bairro,String cidade,String estado,String telefone){ //fazer validacoes aqui //Transformar Variaveis //int idade; int idadeConvertido = Integer.parseInt(idade); //String logradouro; //int n_casa; int n_casaConvertido = Integer.parseInt(n_casa); //String cep; //String bairro; //String cidade; //String estado; //String telefone; Cliente novo = new Cliente(idadeConvertido, nome, cpf, idadeConvertido, logradouro, n_casaConvertido, cep, bairro, cidade, estado, telefone); return model.Cadastrar_Cliente(novo); } public String Validar_Atualizar(){ return ""; } public ArrayList<Cliente> ValidarBusca(String nome)throws Exception { ArrayList<Cliente> clientes = new ArrayList(); clientes = model.buscar_Cliente(nome); return clientes; } public String verificarRemocao(int id)throws Exception { if(id==0) { throw new Exception("Informe um usuário para ser excluido"); } boolean retorno; //retorno = model.veirificarRemocao(id); retorno = false; if(retorno == true) { throw new Exception("Você é o último usuário Administrador, por isso não pode ser removido"); } model.remover_Cliente(id); return ""; } public String verificaAtualizacao()throws Exception { boolean retorno = true; retorno = model.veirificarAtualizacao(); if(retorno == true) { return "Você não pode atualizar o último Administrador para funcionáio"; } return "ok"; } public String validarAtualizacao(Cliente novo,int id)throws Exception { if(novo.getNome().trim().equals("")) { throw new Exception("Informe o nome do funcionario"); } if(novo.getNome().trim().length()<10) { throw new Exception("Informe o nome completo do funcionario "); } /* if(novo.getLogin().trim().equals("")) { throw new Exception("Informe o Login do funcionario"); } if(novo.getLogin().trim().length()<4) { throw new Exception("Informe um Login válido"); } if(novo.getSenha().trim().equals("")) { throw new Exception("Informe a senha do funcionario"); } if(novo.getSenha().trim().length()<4) { throw new Exception("A senha deve ter no minimo 4 caracteres "); } if(!login.equals(novo.getLogin())) { boolean retorno; retorno = model.verificarLoginDisponivel(novo.getLogin()); if(retorno == true) { throw new Exception("Já existe um usuário com esse Login"); } }*/ return model.atualizar_Cliente(novo,id); } public ArrayList<Cliente> validarConsultaDeNome(String nome) throws Exception { ArrayList<Cliente> arryclientes = new ArrayList<>(); arryclientes = model.buscar_Cliente(nome); return arryclientes; } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.facade; import java.util.ArrayList; import projetox.Class.Funcionario; import projetox.controller.Controller_Funcionario; /** * * @author <NAME> */ public class Facade_Funcionario { Controller_Funcionario control = new Controller_Funcionario(); public String Cadastrar_Funcionario(String nome, String cpf, String senha, String cargo, String salario, String login) throws Exception{ return control.Validar_Cadastro(nome, cpf, senha, cargo, salario,login); } public ArrayList Listar_Funcionarios(String nome) throws Exception{ ArrayList<Funcionario> Funcionarios = new ArrayList<>(); return control.ValidarBusca(nome); } public String Excluir_Funcionario(int id,String cargo) throws Exception{ return control.verificarRemocao(id,cargo); } public String Atualizar_Funcionario(){ return ""; } public String verificaAtualizacao()throws Exception { return control.verificaAtualizacao(); } public String validar_Atualizacao(Funcionario novo,int id,String login)throws Exception{ control.validarAtualizacao(novo, id, login); return "validado"; } public Funcionario validar_Login(String login,String senha) throws Exception{ try { return control.validar_Login(login,senha); } catch (Exception e) { throw new Exception("12345:Login ou Senha invalida"); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.view; /** * * @author <NAME> */ public class TelaDevolucao2 extends javax.swing.JFrame { /** * Creates new form TelaDevolucao */ public TelaDevolucao2() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { JTextDataDevolucao = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); JBtnMulta = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); JTextCpf = new javax.swing.JLabel(); JTextNome = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); JTextDataLocacao = new javax.swing.JLabel(); JBtnDevolucao = new javax.swing.JButton(); JTextValorTotal = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Devolução"); JTextDataDevolucao.setText("jLabel9"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); jLabel5.setText("Valor Total R$"); jLabel6.setText("Data da Devolução:"); JBtnMulta.setText("Aplicar Multa"); JBtnMulta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnMultaActionPerformed(evt); } }); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Cliente")); jLabel1.setText("CPF:"); jLabel8.setText("Nome:"); JTextCpf.setText("jLabel3"); JTextNome.setText("jLabel4"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(JTextCpf) .addGap(69, 69, 69) .addComponent(jLabel8) .addGap(18, 18, 18) .addComponent(JTextNome) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JTextCpf)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(JTextNome)))) ); jLabel11.setText("Data da Locação:"); JTextDataLocacao.setText("jLabel9"); JBtnDevolucao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/Próximo.png"))); // NOI18N JBtnDevolucao.setText("Devolução"); JBtnDevolucao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnDevolucaoActionPerformed(evt); } }); JTextValorTotal.setText("jLabel9"); jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/Logo Menor.png"))); // NOI18N 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) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(JBtnMulta) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JBtnDevolucao)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel11) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JTextDataLocacao) .addComponent(JTextValorTotal) .addComponent(JTextDataDevolucao)))) .addGap(0, 1, Short.MAX_VALUE))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(jLabel12) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jLabel12) .addGap(18, 18, 18) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(JTextValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(JTextDataLocacao)) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(JTextDataDevolucao)) .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(JBtnMulta) .addComponent(JBtnDevolucao)) .addGap(21, 21, 21)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void JBtnMultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnMultaActionPerformed }//GEN-LAST:event_JBtnMultaActionPerformed private void JBtnDevolucaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnDevolucaoActionPerformed }//GEN-LAST:event_JBtnDevolucaoActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(TelaDevolucao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaDevolucao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaDevolucao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaDevolucao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaDevolucao().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton JBtnDevolucao; private javax.swing.JButton JBtnMulta; private javax.swing.JLabel JTextCpf; private javax.swing.JLabel JTextDataDevolucao; private javax.swing.JLabel JTextDataLocacao; private javax.swing.JLabel JTextNome; private javax.swing.JLabel JTextValorTotal; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.view; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import projetox.Class.Funcionario; import projetox.facade.Facade_Funcionario; /** * * @author <NAME> */ public class TelaGerenciarFuncionario extends javax.swing.JFrame { /** * Creates new form Tela_Gerenciar_Usuario */ //inicializações ArrayList<Funcionario> funcionarios = new ArrayList<>(); Facade_Funcionario fachada = new Facade_Funcionario(); //Criando modelo da Tabela DefaultTableModel model = new DefaultTableModel(); int codigo_defaut = 0; public TelaGerenciarFuncionario() { initComponents(); } public TelaGerenciarFuncionario(int codigo) { initComponents(); this.setLocationRelativeTo(null); model.setColumnIdentifiers(new String[]{"Nome", "Login", "Cargo", "Id"}); jTable.setModel(model); codigo_defaut = codigo; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabelNome = new javax.swing.JLabel(); JBtnBuscar = new javax.swing.JButton(); jTextBuscar = new javax.swing.JTextField(); JBtnAtualizar = new javax.swing.JButton(); JBtnRemover = new javax.swing.JButton(); JBtnCadastrar = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Gerenciar Funcionario - ProjetoX"); jLabelNome.setText("Nome"); JBtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/search.png"))); // NOI18N JBtnBuscar.setText("Buscar"); JBtnBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnBuscarActionPerformed(evt); } }); JBtnAtualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/loading.png"))); // NOI18N JBtnAtualizar.setText("Atualizar"); JBtnAtualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnAtualizarActionPerformed(evt); } }); JBtnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/delete.png"))); // NOI18N JBtnRemover.setText("Remover"); JBtnRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnRemoverActionPerformed(evt); } }); JBtnCadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/Próximo.png"))); // NOI18N JBtnCadastrar.setText("Novo Funcionário"); JBtnCadastrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnCadastrarActionPerformed(evt); } }); jTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jTable); 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, false) .addComponent(jScrollPane2) .addGroup(layout.createSequentialGroup() .addComponent(jTextBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(JBtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabelNome, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JBtnRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JBtnCadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JBtnAtualizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelNome, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(JBtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(185, 185, 185) .addComponent(JBtnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(JBtnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(JBtnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))) .addContainerGap(22, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void JBtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnBuscarActionPerformed DefaultTableModel model = new DefaultTableModel(); model.setColumnIdentifiers(new String[]{"Nome", "Login", "Cargo", "Id"}); String nome = jTextBuscar.getText(); try { funcionarios = fachada.Listar_Funcionarios(nome); for (int i = 0; i < funcionarios.size(); i++) { model.addRow(new String[]{funcionarios.get(i).getNome(), funcionarios.get(i).getLogin(), funcionarios.get(i).getCargo(), String.valueOf(funcionarios.get(i).getId())}); } } catch (Exception ex) { JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Erro: ", JOptionPane.ERROR_MESSAGE); } jTable.setModel(model); }//GEN-LAST:event_JBtnBuscarActionPerformed private void JBtnAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnAtualizarActionPerformed Funcionario funcionario = new Funcionario(); if (jTable.getRowCount() > 0) { int index = jTable.getSelectedRow(); for (int i = 0; i < funcionarios.size(); i++) { if (index == i) { TelaAtualizarFuncionario atualizar = new TelaAtualizarFuncionario(funcionarios.get(i)); atualizar.show(); } } DefaultTableModel model = new DefaultTableModel(); model.setColumnIdentifiers(new String[]{"Nome", "Login", "Cargo", "Codigo"}); jTable.setModel(model); } }//GEN-LAST:event_JBtnAtualizarActionPerformed private void JBtnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnCadastrarActionPerformed TelaCadastrarFuncionario TelaCad = new TelaCadastrarFuncionario(); TelaCad.show(); }//GEN-LAST:event_JBtnCadastrarActionPerformed private void JBtnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnRemoverActionPerformed int id = 0; String cargo = ""; int index = 0; try { index = jTable.getSelectedRow(); for (int i = 0; i < funcionarios.size(); i++) { if (i == index) { cargo = funcionarios.get(i).getCargo(); id = funcionarios.get(i).getId(); } } String result = fachada.Excluir_Funcionario(id,cargo); JOptionPane.showMessageDialog(rootPane, "Usuário Removido"); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE); } DefaultTableModel model = new DefaultTableModel(); model.setColumnIdentifiers(new String[]{"Nome", "login", "Tipo", "Codigo"}); jTable.setModel(model); }//GEN-LAST:event_JBtnRemoverActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(TelaGerenciarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaGerenciarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaGerenciarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaGerenciarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaGerenciarFuncionario().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton JBtnAtualizar; private javax.swing.JButton JBtnBuscar; private javax.swing.JButton JBtnCadastrar; private javax.swing.JButton JBtnRemover; private javax.swing.JLabel jLabelNome; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable; private javax.swing.JTextField jTextBuscar; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.Class; /** * * @author <NAME> */ public class Estoque { int id; Carro carro; int quantidade; boolean aluguel; public Estoque(int id, Carro carro, int quantidade, boolean aluguel) { this.id = id; this.carro = carro; this.quantidade = quantidade; this.aluguel = aluguel; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Carro getCarro() { return carro; } public void setCarro(Carro carro) { this.carro = carro; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public boolean isAluguel() { return aluguel; } public void setAluguel(boolean aluguel) { this.aluguel = aluguel; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.view; import java.awt.Color; /** * * @author <NAME> */ public class TelaAluguel extends javax.swing.JFrame { /** * Creates new form TelaCadastrarAluguel */ public TelaAluguel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jBFinalizar = new javax.swing.JButton(); jTextDatainicial = new javax.swing.JLabel(); JTextDatafinaj = new javax.swing.JLabel(); JTextDatainicial = new javax.swing.JLabel(); jPanelFilme1 = new javax.swing.JPanel(); jTextModelo = new javax.swing.JLabel(); JTextModelo = new javax.swing.JTextField(); jBPesquisarFilmes1 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); Valor = new javax.swing.JLabel(); JTextDatafinal = new com.toedter.calendar.JDateChooser(); jButton1 = new javax.swing.JButton(); jPanelCliente = new javax.swing.JPanel(); jMatricula = new javax.swing.JLabel(); jtextnome = new javax.swing.JLabel(); JTextNome = new javax.swing.JTextField(); JBtnPesquisarCliente = new javax.swing.JButton(); CPF = new javax.swing.JLabel(); JlabelCodigo = new javax.swing.JLabel(); jValorTotal = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("<NAME>"); setBackground(new java.awt.Color(51, 51, 255)); jBFinalizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/Próximo.png"))); // NOI18N jBFinalizar.setText("Finalizar"); jBFinalizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBFinalizarActionPerformed(evt); } }); jTextDatainicial.setText("Data de Locação :"); JTextDatafinaj.setText("Data de Devolução :"); JTextDatainicial.setText("Data"); jPanelFilme1.setBorder(javax.swing.BorderFactory.createTitledBorder("Carro")); jTextModelo.setText("Modelo:"); jBPesquisarFilmes1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/search.png"))); // NOI18N jBPesquisarFilmes1.setText("Pesquisar"); jBPesquisarFilmes1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBPesquisarFilmes1ActionPerformed(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable1.setName("tabela"); // NOI18N jTable1.setOpaque(false); jScrollPane2.setViewportView(jTable1); javax.swing.GroupLayout jPanelFilme1Layout = new javax.swing.GroupLayout(jPanelFilme1); jPanelFilme1.setLayout(jPanelFilme1Layout); jPanelFilme1Layout.setHorizontalGroup( jPanelFilme1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilme1Layout.createSequentialGroup() .addGroup(jPanelFilme1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelFilme1Layout.createSequentialGroup() .addComponent(jTextModelo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(JTextModelo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBPesquisarFilmes1)) .addComponent(jScrollPane2)) .addContainerGap()) ); jPanelFilme1Layout.setVerticalGroup( jPanelFilme1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilme1Layout.createSequentialGroup() .addGroup(jPanelFilme1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextModelo) .addComponent(JTextModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBPesquisarFilmes1)) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)) ); Valor.setText(" "); Valor.setMaximumSize(new java.awt.Dimension(0, 4)); Valor.setMinimumSize(new java.awt.Dimension(0, 4)); Valor.setPreferredSize(new java.awt.Dimension(0, 4)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(Valor, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Valor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/delete.png"))); // NOI18N jButton1.setText("Remover"); // NOI18N jButton1.setToolTipText(""); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanelCliente.setBorder(javax.swing.BorderFactory.createTitledBorder("Cliente")); jMatricula.setText("CPF:"); jtextnome.setText("Nome:"); JTextNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JTextNomeActionPerformed(evt); } }); JBtnPesquisarCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/search.png"))); // NOI18N JBtnPesquisarCliente.setText("Pesquisar"); JBtnPesquisarCliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBtnPesquisarClienteActionPerformed(evt); } }); javax.swing.GroupLayout jPanelClienteLayout = new javax.swing.GroupLayout(jPanelCliente); jPanelCliente.setLayout(jPanelClienteLayout); jPanelClienteLayout.setHorizontalGroup( jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelClienteLayout.createSequentialGroup() .addComponent(jMatricula) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(JlabelCodigo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CPF) .addGap(76, 76, 76) .addComponent(jtextnome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JTextNome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JBtnPesquisarCliente) .addContainerGap()) ); jPanelClienteLayout.setVerticalGroup( jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jMatricula) .addComponent(JBtnPesquisarCliente) .addComponent(jtextnome) .addComponent(JTextNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CPF) .addComponent(JlabelCodigo)) ); jValorTotal.setText("Valor Total R$"); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetox/view/Imagens/Logo Menor.png"))); // NOI18N 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.TRAILING) .addComponent(jPanelFilme1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelCliente, javax.swing.GroupLayout.Alignment.LEADING, 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.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jBFinalizar, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JTextDatafinaj) .addComponent(jTextDatainicial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JTextDatainicial) .addComponent(JTextDatafinal, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(309, 309, 309) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1) .addGroup(layout.createSequentialGroup() .addComponent(jValorTotal) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(17, 17, 17))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(202, 202, 202) .addComponent(jLabel4) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelFilme1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextDatainicial) .addComponent(JTextDatainicial)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jValorTotal, javax.swing.GroupLayout.Alignment.LEADING))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(JTextDatafinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(JTextDatafinaj, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE) .addComponent(jBFinalizar) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jBFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBFinalizarActionPerformed }//GEN-LAST:event_jBFinalizarActionPerformed private void jBPesquisarFilmes1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBPesquisarFilmes1ActionPerformed TelaConsultaCarro tcarro = new TelaConsultaCarro(); tcarro.show(); }//GEN-LAST:event_jBPesquisarFilmes1ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed }//GEN-LAST:event_jButton1ActionPerformed private void JBtnPesquisarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBtnPesquisarClienteActionPerformed TelaConsultaCliente tcc = new TelaConsultaCliente(); tcc.show(); }//GEN-LAST:event_JBtnPesquisarClienteActionPerformed private void JTextNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JTextNomeActionPerformed }//GEN-LAST:event_JTextNomeActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(TelaAluguel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaAluguel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaAluguel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaAluguel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaAluguel().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel CPF; private javax.swing.JButton JBtnPesquisarCliente; private javax.swing.JLabel JTextDatafinaj; private com.toedter.calendar.JDateChooser JTextDatafinal; private javax.swing.JLabel JTextDatainicial; private javax.swing.JTextField JTextModelo; private javax.swing.JTextField JTextNome; private javax.swing.JLabel JlabelCodigo; private javax.swing.JLabel Valor; private javax.swing.JButton jBFinalizar; private javax.swing.JButton jBPesquisarFilmes1; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jMatricula; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanelCliente; private javax.swing.JPanel jPanelFilme1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JLabel jTextDatainicial; private javax.swing.JLabel jTextModelo; private javax.swing.JLabel jValorTotal; private javax.swing.JLabel jtextnome; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetox.interfaces; import java.util.ArrayList; import projetox.Class.Carro; /** * * @author <NAME> */ public interface Interface_Carro { public String Cadastrar_Carro(); public ArrayList<Carro> buscar_Carro() throws Exception; public String remover_Carro()throws Exception; public void atualizar_Carro()throws Exception; public boolean veirificarRemocao()throws Exception; public boolean veirificarAtualizacao()throws Exception; }
d2d8e97cacc1338ad96d1541ace32885950636a0
[ "Java" ]
14
Java
luandp/ProjetoX
aa6213bdb46d46165d75fbb3db99bab29ecdb88a
34cce48079795ad6f1c806968c03fbc9af297859
refs/heads/master
<file_sep>package camt.se331.shoppingcart.entity; import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; import javax.persistence.*; import javax.persistence.Entity; import java.util.Date; import java.util.List; /** * Created by Dto on 2/7/2015. */ @Entity public class ShoppingCart { @Id @GeneratedValue Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ShoppingCart)) return false; ShoppingCart that = (ShoppingCart) o; if (!id.equals(that.id)) return false; if (!getSelectedProducts().equals(that.getSelectedProducts())) return false; return getPurchaseDate().equals(that.getPurchaseDate()); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + getSelectedProducts().hashCode(); result = 31 * result + getPurchaseDate().hashCode(); return result; } @OneToMany(fetch = FetchType.EAGER) @Cascade(CascadeType.ALL) List<SelectedProduct> selectedProducts; @Temporal(TemporalType.TIMESTAMP) Date purchaseDate; public double getTotalProductPrice(){ return 0.0; }; public List<SelectedProduct> getSelectedProducts() { return selectedProducts; } public void setSelectedProducts(List<SelectedProduct> selectedProducts) { this.selectedProducts = selectedProducts; } public Date getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public ShoppingCart(List<SelectedProduct> selectedProducts) { this.selectedProducts = selectedProducts; } public ShoppingCart() { } } <file_sep>listProduct.name=name listProduct.description=description listProduct.price=price listProduct.edit=edit listProduct.delete=delete listProduct.total=Total listProduct.netPrice=total Price listProduct.amount=amount <file_sep>package camt.se331.shoppingcart.service; import camt.se331.shoppingcart.dao.ShoppingCartDao; import camt.se331.shoppingcart.entity.ShoppingCart; import camt.se331.shoppingcart.repository.ShoppingCartRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; /** * Created by liuyahong on 2016/3/28. */ @Service public class ShoppingCartServiceImpl implements ShoppingCartService { @Autowired ShoppingCartDao shoppingCartDao; @Override public ShoppingCart findById(Long id) { return shoppingCartDao.findById(id); } @Override public List<ShoppingCart> getShoppingCarts() { return null; } @Override public List<ShoppingCart> getShoppingCartBetween(Date stateDate,Date stopDate) { return null; } @Override public ShoppingCart addShoppingCart(ShoppingCart shoppingCart) { return shoppingCartDao.addShoppingCart(shoppingCart); } @Override public ShoppingCart deleteShoppingCart(ShoppingCart shoppingCart) { return null; } }
efd709328cffa142e19860d1a40369ba45c6bb6e
[ "Java", "INI" ]
3
Java
skyonsky/SE331-lab07
b3ebe76c235d40a560136b860064bc0784b5cbf2
531a4529b242533a3651aecc66cb018f49e4c805
refs/heads/main
<repo_name>angelxmoreno/twitter-export<file_sep>/backend/src/services/Cache/index.ts import cacheManager, { Cache } from 'cache-manager'; import { memoryCache } from './memory'; import { redisCache } from './redis'; import { diskCache } from './file'; const cacheEngines: Cache[] = []; [memoryCache, redisCache, diskCache].forEach(engine => { if (engine) { cacheEngines.push(engine); } }); export const buildCacheKey = (namespace: string, ...args: unknown[]): string => `${namespace} - ${JSON.stringify(args)}`; export default cacheManager.multiCaching(cacheEngines); <file_sep>/backend/src/index.ts import 'reflect-metadata'; import server from './server'; import Env from './helpers/Env'; import dbConnection from './database'; const PORT = Env.string('PORT'); const start = async () => { const connection = await dbConnection.connect(); console.log(`⚡️[database]: Connection established: ${connection.name}`); server.listen(PORT, () => { console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`); }); }; start().catch(console.error); <file_sep>/README.md # twitter-export A tool for exporting Twitter connections <file_sep>/backend/src/entities/EntityTimeBase.ts import { CreateDateColumn, DeleteDateColumn, UpdateDateColumn } from 'typeorm'; export abstract class EntityTimeBase { @UpdateDateColumn() updated: Date; @CreateDateColumn() created: Date; @DeleteDateColumn() deleted: Date; } <file_sep>/backend/src/services/TwitterUserService.ts /* eslint-disable camelcase */ import Twit from 'twit'; import { In } from 'typeorm'; import Env from '../helpers/Env'; import { UserEntity } from '../entities/UserEntity'; import RepositoryManager from './RepositoryManager'; import { TwitterUser } from '../TwitterEntities'; import chunk from '../helpers/chunk'; import { FollowersRepository } from '../repositories/FollowersRepository'; import { TwitterUsersRepository } from '../repositories/TwitterUsersRepository'; import { TwitterUserEntity } from '../entities/TwitterUserEntity'; export interface RequestTokenResponse { oauth_token: string; oauth_token_secret: string; oauth_callback_confirmed: 'true'; } export class TwitterUserService { protected user: UserEntity; protected userClient: Twit; protected repos: { followers: FollowersRepository; twitterUsers: TwitterUsersRepository; }; constructor(user: UserEntity, consumer_key: string, consumer_secret: string) { this.user = user; this.userClient = new Twit({ consumer_key, consumer_secret, access_token: user.oauthToken, access_token_secret: user.oauthTokenSecret, }); this.repos = { followers: RepositoryManager.getFollowers(), twitterUsers: RepositoryManager.getTwitterUsers(), }; } async get<T>(uri: string, params?: Twit.Params): Promise<T> { const { data } = await this.userClient.get(uri, params); return (data as unknown) as T; } async buildFollowerEntities(cursor?: string): Promise<void> { const { data } = (await this.userClient.get('followers/ids', { count: 5000, stringify_ids: true, cursor, })) as { data: { ids: string[]; next_cursor_str: string } }; const { ids, next_cursor_str } = data; await this.repos.followers.linkIds(this.user, ids); await this.userLookUp(ids); if (next_cursor_str !== '0' && next_cursor_str !== '-1') { await this.buildFollowerEntities(next_cursor_str); } } protected async getExistingTwitterUsersByIds(twitterUserIds: string[]): Promise<TwitterUser[]> { const batchSize = 500; const chunked = chunk(twitterUserIds, batchSize); const chunkedPromises = chunked.map(ids => { return this.repos.twitterUsers.findMany({ where: { id: In(ids) }, }); }); return (await Promise.all(chunkedPromises)) .flat() // flatten (TwitterUserEntity[]|undefined)[] to (TwitterUserEntity|undefined)[] .filter((entity): entity is TwitterUserEntity => entity !== undefined) // filter (TwitterUserEntity|undefined)[] to TwitterUserEntity[] .map(entity => entity && entity.data); // map TwitterUserEntity[] to TwitterUser[] } async userLookUp(ids: string[]): Promise<TwitterUser[]> { const existingTwitterUsers = await this.getExistingTwitterUsersByIds(ids); const existingIds = existingTwitterUsers.map(twitterUser => twitterUser.id_str); const filteredIds = ids.filter(id => existingIds.indexOf(id) === -1); const chunked = chunk(filteredIds, 20); // twitter API does 20 lookups at a time const promises = chunked.map(async user_ids => { const { data } = await this.userClient.get('users/lookup', { user_id: user_ids.join(','), }); return data as TwitterUser; }); const newTwitterUsers = (await Promise.all(promises)).flat(); await this.repos.twitterUsers.saveManyRaw(newTwitterUsers); return existingTwitterUsers.concat(newTwitterUsers); } } const twitterUserServiceFactory = (user: UserEntity): TwitterUserService => new TwitterUserService(user, Env.string('TWITTER_CONSUMER_KEY'), Env.string('TWITTER_CONSUMER_SECRET')); export default twitterUserServiceFactory; <file_sep>/backend/.eslintrc.js module.exports = { extends: ['airbnb-base', 'plugin:@typescript-eslint/recommended', 'prettier', 'plugin:prettier/recommended'], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2018, sourceType: 'module', project: './tsconfig.json', extraFileExtensions: ['.json'], }, plugins: ['json-format', '@typescript-eslint', 'prettier'], rules: { 'import/prefer-default-export': 0, 'class-methods-use-this': 0, 'no-nested-ternary': 0, 'no-plusplus': 0, 'global-require': 0, 'no-console': 0, 'import/no-unresolved': 0, 'prettier/prettier': [ 'error', { singleQuote: true, trailingComma: 'all', arrowParens: 'avoid', endOfLine: 'auto', printWidth: 120, }, ], 'no-use-before-define': 'off', '@typescript-eslint/no-use-before-define': ['error'], 'import/extensions': ['error', 'never'], 'no-shadow': 'off', '@typescript-eslint/no-shadow': ['error'], }, }; <file_sep>/frontend/src/router/appHistory.ts import { createBrowserHistory } from 'history'; const appHistory = createBrowserHistory(); export default appHistory; <file_sep>/backend/src/services/RepositoryManager.ts import { getCustomRepository } from 'typeorm'; import { UsersRepository } from '../repositories/UsersRepository'; import { TwitterUsersRepository } from '../repositories/TwitterUsersRepository'; import { FollowersRepository } from '../repositories/FollowersRepository'; export default class RepositoryManager { static getUsers(): UsersRepository { return getCustomRepository(UsersRepository); } static getTwitterUsers(): TwitterUsersRepository { return getCustomRepository(TwitterUsersRepository); } static getFollowers(): FollowersRepository { return getCustomRepository(FollowersRepository); } } <file_sep>/backend/src/repositories/UsersRepository.ts import { EntityRepository } from 'typeorm'; import { AccessTokenResponse } from 'twitter-lite'; import { DeepPartial } from 'typeorm/browser'; import RepositoryBase from './RepositoryBase'; import { UserEntity } from '../entities/UserEntity'; @EntityRepository(UserEntity) export class UsersRepository extends RepositoryBase<UserEntity> { findByTwitterId(id: string): Promise<UserEntity | undefined> { return this.findOne({ twitterUserId: id }); } async createFromAccessTokenResponse(accessTokenResponse: AccessTokenResponse): Promise<UserEntity> { const partial: DeepPartial<UserEntity> = { oauthToken: accessTokenResponse.oauth_token, oauthTokenSecret: accessTokenResponse.oauth_token_secret, screenName: accessTokenResponse.screen_name, twitterUserId: accessTokenResponse.user_id, }; let user = await this.findByTwitterId(accessTokenResponse.user_id); if (!user) { user = await this.create(partial); } else { user = this.repository.merge(user, partial); } await this.save(user); return user; } } <file_sep>/deploy/Dockerfile FROM mhart/alpine-node:14 RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY ../backend . RUN yarn install && \ yarn build EXPOSE 3000 CMD [ "yarn", "start" ] <file_sep>/frontend/src/mobx/stores/AuthStore.ts import { makeAutoObservable, runInAction, transaction } from 'mobx'; import { persist } from 'mobx-persist'; import { UserEntity } from '../entities/UserEntity'; import Auth, { UserWithJWTResponse } from '../../api/Auth'; import appHistory from '../../router/appHistory'; export default class AuthStore { @persist('object') user?: UserEntity; @persist jwt?: string; @persist isAuthenticated = false; isLoading = false; constructor() { makeAutoObservable(this); } setUser(user: UserEntity, jwt: string): void { transaction(() => { this.isAuthenticated = true; this.user = user; this.jwt = jwt; }); } unsetUser(): void { transaction(() => { this.isAuthenticated = false; this.user = undefined; this.jwt = undefined; }); appHistory.push({ pathname: '/', }); } async checkOAuthParams(): Promise<void> { const url = new URL(window.location.toString()); const params = url.searchParams; if (params.has('oauth_token') && params.has('oauth_verifier')) { this.isLoading = true; const oauth_token = params.get('oauth_token') as string; const oauth_verifier = params.get('oauth_verifier') as string; const returnTo = params.get('returnTo') as string; url.searchParams.delete('oauth_token'); url.searchParams.delete('oauth_verifier'); url.searchParams.delete('returnTo'); try { const { user, jwt }: UserWithJWTResponse = await Auth.getAccessTokens(oauth_token, oauth_verifier); runInAction(() => { this.setUser(user, jwt); this.isLoading = false; }); } catch (e) { // eslint-disable-next-line no-console console.error('Error getting access tokens', e.message); } finally { this.isLoading = false; appHistory.push({ pathname: returnTo, search: url.search, }); } } return undefined; } getLogInUrl(fromPath?: string): Promise<string> { return Auth.getAuthorizeUrl(fromPath); } } <file_sep>/frontend/src/pages/index.ts import Home from './Home'; import LogIn from './LogIn'; import Search from './Search'; import User from './User'; import Followers from './Followers'; export default { Home, User, Search, LogIn, Followers }; <file_sep>/backend/src/TwitterEntities.ts import Twit from 'twit'; export type TwitterUser = Twit.Twitter.User; <file_sep>/backend/src/controllers/IndexController.ts import { Get, JsonController } from 'routing-controllers'; @JsonController() export default class IndexController { @Get('/') home(): string { console.log('I am the home route'); return 'Express + TypeScript Server'; } } <file_sep>/backend/src/entities/UserEntity.ts import { Column, Entity, Index } from 'typeorm'; import { EntityBase } from './EntityBase'; import twitterUserServiceFactory, { TwitterUserService } from '../services/TwitterUserService'; @Entity() export class UserEntity extends EntityBase { @Column() oauthToken: string; @Column() oauthTokenSecret: string; @Index({ unique: true }) @Column() twitterUserId: string; @Index({ unique: true }) @Column() screenName: string; protected twitterUserService: TwitterUserService; get twitterClient(): TwitterUserService { if (!this.twitterUserService) { this.twitterUserService = twitterUserServiceFactory(this); } return this.twitterUserService; } } <file_sep>/backend/src/services/Cache/memory.ts import cacheManager from 'cache-manager'; export const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 5 }); <file_sep>/backend/src/helpers/chunk.ts const chunk = <T>(arr: T[], size: number): T[][] => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); export default chunk; <file_sep>/backend/src/repositories/RepositoryBase.ts import { AbstractRepository, FindManyOptions } from 'typeorm'; import { FindConditions } from 'typeorm/find-options/FindConditions'; import { FindOneOptions } from 'typeorm/find-options/FindOneOptions'; import { DeepPartial } from 'typeorm/common/DeepPartial'; import { SaveOptions } from 'typeorm/repository/SaveOptions'; import buildPaginator from 'pagination-apis'; import paginatorDecorator, { PaginatorResponse } from '../helpers/paginatorDecorator'; export type PaginateOptions = { page: number; limit: number; maximumLimit: number; }; export interface Paginate { data: Array<unknown>; total: number; totalPages: number; previous?: string; next?: string; } export default class RepositoryBase<Entity> extends AbstractRepository<Entity> { paginationOptions: PaginateOptions = { page: 1, limit: 20, maximumLimit: 100, }; findOne(conditions?: FindConditions<Entity>, options?: FindOneOptions<Entity>): Promise<Entity | undefined> { return this.repository.findOne(conditions, options); } findMany(conditions?: FindManyOptions<Entity>): Promise<Entity[] | undefined> { return this.repository.find(conditions); } create(entityLike: DeepPartial<Entity>): Entity { return this.repository.create(entityLike); } save(entity: Entity, options?: SaveOptions): Promise<Entity> { return this.repository.save(entity, options); } get(id: string): Promise<Entity> { return this.repository.findOneOrFail(id); } async upsert(conditions: FindConditions<Entity>, partial: DeepPartial<Entity>): Promise<[Entity, boolean]> { let found = true; let entity = await this.findOne(conditions); if (!entity) { found = false; entity = this.create(partial); } else { found = true; entity = this.repository.merge(entity, partial); } return [await this.save(entity), found]; } async paginate<T>( findOptions?: FindManyOptions<Entity>, paginationOptions?: Partial<PaginateOptions>, transformPredicate?: (entity: Entity) => T, ): Promise<PaginatorResponse<T>> { const { skip, limit, page } = buildPaginator({ ...this.paginationOptions, ...paginationOptions, }); const findPaginatedOptions: FindManyOptions<Entity> = { ...findOptions, take: limit, skip, }; const [entities, total] = await this.repository.findAndCount(findPaginatedOptions); const data: T[] = transformPredicate ? entities.map(transformPredicate) : ((entities as unknown[]) as T[]); return paginatorDecorator<T>(data, total, page, limit); } } <file_sep>/backend/src/database.ts import 'reflect-metadata'; import { getConnectionManager } from 'typeorm'; import Env from './helpers/Env'; import CakePhpNamingStrategy from './helpers/CakePhpNamingStrategy'; const connectionManager = getConnectionManager(); const dbConnection = connectionManager.create({ type: 'mysql', namingStrategy: new CakePhpNamingStrategy(), url: Env.string('DATABASE_URL', 'mysql://127.0.0.1/db'), entities: [`${__dirname}/entities/*.{js,ts}`], synchronize: Env.bool('DATABASE_SYNCING', true), logging: Env.bool('DATABASE_LOGGING', true), }); export default dbConnection; <file_sep>/frontend/src/mobx/entities/UserEntity.ts export type UserEntity = { id: string; twitterUserId: string; screenName: string; }; <file_sep>/backend/src/services/Cache/redis.ts import { Cache } from 'cache-manager'; import Env from '../../helpers/Env'; import redisCacheFromUrl from '../../helpers/redisCacheFromUrl'; const redisUrl = Env.string('REDIS_URL', ''); export const redisCache: Cache | undefined = redisUrl ? redisCacheFromUrl(redisUrl, 60) : undefined; <file_sep>/backend/src/middlewares/NotFoundMiddleware.ts import { ExpressMiddlewareInterface, Middleware, NotFoundError } from 'routing-controllers'; import { Request, Response } from 'express'; import normalizeError from '../helpers/normalizeError'; @Middleware({ type: 'after' }) export class NotFoundMiddleware implements ExpressMiddlewareInterface { public use(req: Request, res: Response): void { if (!res.headersSent) { const payload = normalizeError(new NotFoundError(`${req.method} ${req.path} not found`)); console.log('payload', payload); res.status(404).json(payload); } res.end(); } } <file_sep>/backend/src/entities/EntityBase.ts import { PrimaryGeneratedColumn } from 'typeorm'; import { EntityTimeBase } from './EntityTimeBase'; export abstract class EntityBase extends EntityTimeBase { @PrimaryGeneratedColumn('uuid') id: string; } <file_sep>/backend/src/helpers/Env.ts import getenv from 'getenv.ts'; import dotenv from 'dotenv'; import dotenvExpand from 'dotenv-expand'; dotenvExpand(dotenv.config()); export default getenv; <file_sep>/backend/src/entities/FollowerEntity.ts import { Entity, Index, ManyToOne, PrimaryColumn } from 'typeorm'; import { EntityTimeBase } from './EntityTimeBase'; import { TwitterUserEntity } from './TwitterUserEntity'; @Entity() @Index(['twitterUserId', 'followerId'], { unique: true }) export class FollowerEntity extends EntityTimeBase { @PrimaryColumn() twitterUserId: string; @PrimaryColumn() followerId: string; @ManyToOne(() => TwitterUserEntity, { createForeignKeyConstraints: false, nullable: true, }) follower: TwitterUserEntity; } <file_sep>/deploy/buildFe.sh #!/usr/bin/env bash cd ./frontend/ yarn install yarn build <file_sep>/backend/src/helpers/userWithJwtResponse.ts import { UserEntity } from '../entities/UserEntity'; import JwtService from '../services/JwtService'; export type UserWithJWTResponse = { jwt: string; user: { id: string; twitterUserId: string; screenName: string; }; }; const JwtResponseFromUser = (user: UserEntity): UserWithJWTResponse => { const jwt = JwtService.fromUser(user); return { jwt, user: { id: user.id, twitterUserId: user.twitterUserId, screenName: user.screenName, }, }; }; export default JwtResponseFromUser; <file_sep>/backend/src/controllers/AuthController.ts import { CurrentUser, Get, JsonController, QueryParam } from 'routing-controllers'; import { AccessTokenOptions, AccessTokenResponse } from 'twitter-lite'; import twitterAuthService, { RequestTokenResponse } from '../services/TwitterAuthService'; import RepositoryManager from '../services/RepositoryManager'; import { UserEntity } from '../entities/UserEntity'; import userWithJwtResponse, { UserWithJWTResponse } from '../helpers/userWithJwtResponse'; @JsonController('/auth') export default class AuthController { @Get('/request-token') getRequestToken(@QueryParam('callback_url') callbackUrl: string): Promise<RequestTokenResponse> { return twitterAuthService.getRequestToken(callbackUrl); } @Get('/access-token') async getJwtFromAccessToken( @QueryParam('oauth_token') oauthToken: string, @QueryParam('oauth_verifier') oauthVerifier: string, ): Promise<UserWithJWTResponse> { const options: AccessTokenOptions = { oauth_token: oauthToken, oauth_verifier: oauthVerifier, }; const accessTokens: AccessTokenResponse = await twitterAuthService.getAccessToken(options); const user = await RepositoryManager.getUsers().createFromAccessTokenResponse(accessTokens); return userWithJwtResponse(user); } @Get('/check') async getCurrentUser(@CurrentUser({ required: true }) user: UserEntity): Promise<UserWithJWTResponse> { return userWithJwtResponse(user); } } <file_sep>/backend/src/helpers/redisCacheFromUrl.ts import redisStore from 'cache-manager-ioredis'; import { URL } from 'url'; import cacheManager, { Cache, CacheOptions, StoreConfig } from 'cache-manager'; const redisCacheFromUrl = (urlString: string, ttl: number): Cache => { const url = new URL(urlString); const config: StoreConfig & CacheOptions = { store: redisStore, host: url.hostname, port: url.port, password: <PASSWORD>, db: url.pathname.replace('/', ''), ttl, }; return cacheManager.caching(config); }; export default redisCacheFromUrl; <file_sep>/backend/src/helpers/currentUserChecker.ts import { Action } from 'routing-controllers'; import { isDevelopment } from './node-env'; import JwtService from '../services/JwtService'; import RepositoryManager from '../services/RepositoryManager'; import Env from '../helpers/Env'; import { UserEntity } from '../entities/UserEntity'; const currentUserChecker = (action: Action): Promise<UserEntity | undefined> => { const authorization = action.request.header('Authorization'); const jwt = authorization?.split(' ')[1]; return jwt === '<PASSWORD>' && isDevelopment() ? RepositoryManager.getUsers().get(Env.string('TEST_USER_ID')) : JwtService.toUser(jwt); }; export default currentUserChecker; <file_sep>/backend/src/helpers/paginatorDecorator.ts export type PaginatorResponse<T> = { data: T[]; pagination: { total: number; page: number; limit: number; totalPages: number; prev: boolean; next: boolean; }; }; const paginatorDecorator = <T>(data: T[], total: number, page: number, limit: number): PaginatorResponse<T> => { const totalPages = Math.ceil(total / limit); return { pagination: { total, page, limit, totalPages, prev: page > 1, next: page < totalPages, }, data, }; }; export default paginatorDecorator; <file_sep>/frontend/src/utils/isDevelopment.ts const isDevelopment = (): boolean => process.env.NODE_ENV === 'development'; export default isDevelopment; <file_sep>/backend/src/repositories/FollowersRepository.ts import { DeepPartial, EntityRepository } from 'typeorm'; import RepositoryBase from './RepositoryBase'; import { FollowerEntity } from '../entities/FollowerEntity'; import { UserEntity } from '../entities/UserEntity'; @EntityRepository(FollowerEntity) export class FollowersRepository extends RepositoryBase<FollowerEntity> { linkIds(user: UserEntity, ids: string[]): Promise<FollowerEntity[]> { const partials: DeepPartial<FollowerEntity>[] = ids.map(id => ({ twitterUserId: user.twitterUserId, followerId: id, })); return this.repository.save(partials); } } <file_sep>/frontend/src/mobx/index.ts /* eslint-disable no-console */ import { Context, createContext, useContext } from 'react'; import { create } from 'mobx-persist'; import { configure } from 'mobx'; import AuthStore from './stores/AuthStore'; configure({ enforceActions: 'observed' }); // don't allow state modifications outside actions type RootStore = { authStore: AuthStore; }; export const rootStore: RootStore = { authStore: new AuthStore(), }; export const StoreContext: Context<RootStore> = createContext(rootStore); export const useStore = (): RootStore => useContext(StoreContext); export async function hydrateStores(): Promise<void> { const hydrate = create({ storage: localStorage, jsonify: true, }); const promises = Object.keys(rootStore).map(storeName => { const store = rootStore[storeName as keyof RootStore]; return hydrate(storeName, store) .then(() => console.log(`${storeName} has been hydrated`)) .catch(e => console.error(`Issue hydrating ${storeName}: `, e)); }); await Promise.all(promises); await rootStore.authStore.checkOAuthParams(); } <file_sep>/backend/src/controllers/TwitterController.ts import { CurrentUser, Get, JsonController, QueryParams } from 'routing-controllers'; import Twit from 'twit'; import { FindManyOptions } from 'typeorm'; import { UserEntity } from '../entities/UserEntity'; import { TwitterUser } from '../TwitterEntities'; import RepositoryManager from '../services/RepositoryManager'; import { PaginateOptions } from '../repositories/RepositoryBase'; import { PaginatorResponse } from '../helpers/paginatorDecorator'; import { FollowerEntity } from '../entities/FollowerEntity'; import Cache, { buildCacheKey } from '../services/Cache'; @JsonController('/api') export default class TwitterController { @Get('/self') async self( @QueryParams() params: Twit.Params, @CurrentUser({ required: true }) user: UserEntity, ): Promise<TwitterUser> { return Cache.wrap(buildCacheKey('twitterUser', user.twitterUserId), async () => { const twitterUser = await user.twitterClient.get<TwitterUser>('/account/verify_credentials', params); await RepositoryManager.getTwitterUsers().saveRaw(twitterUser); return twitterUser; }); } @Get('/followers') async followers( @QueryParams() params: { page: number }, @CurrentUser({ required: true }) user: UserEntity, ): Promise<PaginatorResponse<TwitterUser>> { const paginationOptions: Partial<PaginateOptions> = { page: params.page, }; const findOptions: FindManyOptions<FollowerEntity> = { where: { twitterUserId: user.twitterUserId }, relations: ['follower'], }; await Cache.wrap(buildCacheKey('buildFollowers', user.twitterUserId), async () => { await user.twitterClient.buildFollowerEntities(); return 'done'; }); return Cache.wrap(buildCacheKey('followers', user.twitterUserId, paginationOptions, findOptions), async () => { return RepositoryManager.getFollowers().paginate<TwitterUser>( findOptions, paginationOptions, entity => entity.follower.data, ); }); } } <file_sep>/frontend/src/api/Auth.ts import axios from 'axios'; import getenv from 'getenv'; import { UserEntity } from '../mobx/entities/UserEntity'; import isDevelopment from '../utils/isDevelopment'; const BASE_DOMAIN = isDevelopment() ? 'http://localhost:4000' : getenv('REACT_APP_BE_DOMAIN'); const REQUEST_TOKEN_URL = '/auth/request-token'; const ACCESS_TOKEN_URL = '/auth/access-token'; const CALLBACK_URL = isDevelopment() ? 'http://localhost:3000/' : getenv('REACT_APP_CALLBACK_URL'); export interface RequestTokenResponse { oauth_token: string; oauth_token_secret: string; oauth_callback_confirmed: 'true'; } export interface UserWithJWTResponse { jwt: string; user: UserEntity; } const buildAuthorizeUrlFromRequestTokens = (requestTokens: RequestTokenResponse): string => `https://api.twitter.com/oauth/authorize?oauth_token=${requestTokens.oauth_token}`; const getRequestTokens = async (fromPath?: string): Promise<RequestTokenResponse> => { try { const { data } = await axios.get<RequestTokenResponse>(BASE_DOMAIN + REQUEST_TOKEN_URL, { params: { callback_url: `${CALLBACK_URL}?returnTo=${fromPath}` }, }); // eslint-disable-next-line no-console console.log('RequestTokenResponse', data); return data; } catch (e) { // eslint-disable-next-line no-console console.error(BASE_DOMAIN + REQUEST_TOKEN_URL, e); throw new Error(e.message); } }; const getAuthorizeUrl = async (fromPath?: string): Promise<string> => { const requestTokens = await getRequestTokens(fromPath); return buildAuthorizeUrlFromRequestTokens(requestTokens); }; const getAccessTokens = async (oauth_token: string, oauth_verifier: string): Promise<UserWithJWTResponse> => { try { const { data } = await axios.get<UserWithJWTResponse>(BASE_DOMAIN + ACCESS_TOKEN_URL, { params: { oauth_token, oauth_verifier }, }); // eslint-disable-next-line no-console console.log('UserWithJWTResponse', data); return data; } catch (e) { // eslint-disable-next-line no-console console.error(BASE_DOMAIN + REQUEST_TOKEN_URL, e); throw new Error(e.message); } }; const Auth = { getAuthorizeUrl, getAccessTokens }; export default Auth; <file_sep>/backend/src/helpers/normalizeError.ts import { HttpError } from 'routing-controllers'; interface ErrorWithStatus extends Error { status?: number; code?: number; httpCode?: number; } interface ErrorContainer { errors?: ((ErrorWithStatus & ErrorContainer) | string)[]; } export type GenericError = ErrorContainer & ErrorWithStatus & HttpError; export interface ErrorPayload { status: number; message: string; type?: string; errors?: ErrorPayload[]; } const normalizeError = (error: GenericError | string): ErrorPayload => { let status = 500; let message = 'Unknown Error'; let errors; let type: string | undefined; if (typeof error === 'string') { status = 500; message = error; } else if (error.httpCode) { status = error.httpCode; message = error.message || error.name; type = error.message ? error.name : undefined; } else if (error.message) { status = error.status && error.status > 0 ? error.status : status; message = error.message; type = error.name; } else if (error.errors) { status = 500; message = 'Multiple Errors'; errors = error.errors.map(row => normalizeError(row as GenericError)); if (errors.length === 1) { return errors[0]; } } else { console.log('Unable to parse error: ', error); console.log('type', error.name); } return { status, message, errors, type }; }; export default normalizeError; <file_sep>/frontend/src/mobx/stores/CounterStore.ts import { makeAutoObservable } from 'mobx'; import { persist } from 'mobx-persist'; export default class CounterStore { @persist count = 0; constructor() { makeAutoObservable(this); } increment(): void { this.count++; } decrement(): void { this.count--; } } <file_sep>/backend/src/helpers/node-env.ts import Env from './Env'; export const isDevelopment = (): boolean => { return Env.string('NODE_ENV') === 'development'; }; <file_sep>/backend/src/repositories/TwitterUsersRepository.ts import { DeepPartial, EntityRepository, FindConditions } from 'typeorm'; import RepositoryBase from './RepositoryBase'; import { TwitterUserEntity } from '../entities/TwitterUserEntity'; import { TwitterUser } from '../TwitterEntities'; @EntityRepository(TwitterUserEntity) export class TwitterUsersRepository extends RepositoryBase<TwitterUserEntity> { async saveRaw(user: TwitterUser): Promise<TwitterUserEntity> { const conditions: FindConditions<TwitterUserEntity> = { id: user.id_str }; const partial: DeepPartial<TwitterUserEntity> = { id: user.id_str, data: user, }; const [twitterUser] = await this.upsert(conditions, partial); return twitterUser; } saveManyRaw(users: TwitterUser[]): Promise<TwitterUserEntity[]> { const partials: DeepPartial<TwitterUserEntity>[] = users.map(user => ({ id: user.id_str, data: user })); return this.repository.save(partials); } } <file_sep>/backend/src/server.ts import { Application } from 'express'; import { createExpressServer } from 'routing-controllers'; import compression from 'compression'; import morgan from 'morgan'; import { isDevelopment } from './helpers/node-env'; import { JsonErrorHandler } from './middlewares/JsonErrorHandler'; import { NotFoundMiddleware } from './middlewares/NotFoundMiddleware'; import currentUserChecker from './helpers/currentUserChecker'; import Env from './helpers/Env'; const server: Application = createExpressServer({ routePrefix: Env.string('API_PREFIX', ''), cors: true, defaultErrorHandler: false, currentUserChecker, controllers: [`${__dirname}/controllers/*`], middlewares: [NotFoundMiddleware, JsonErrorHandler], development: isDevelopment(), }); server.use(compression()); server.use(morgan(isDevelopment() ? 'tiny' : 'combined')); export default server; <file_sep>/backend/src/services/Cache/file.ts import cacheManager from 'cache-manager'; import fsStore from 'cache-manager-fs-hash'; export const diskCache = cacheManager.caching({ store: fsStore, options: { path: 'cache', // path for cached files ttl: 60 * 12, // time to life in seconds subdirs: true, // create subdirectories to reduce the // files in a single dir (default: false) zip: true, // zip files to save diskspace (default: false) }, }); <file_sep>/backend/src/helpers/CakePhpNamingStrategy.ts import { SnakeNamingStrategy } from 'typeorm-naming-strategies'; import { snakeCase } from 'typeorm/util/StringUtils'; import pluralize from 'pluralize'; import { Table } from 'typeorm'; export default class CakePhpNamingStrategy extends SnakeNamingStrategy { tableName(className: string, customName: string): string { return customName || pluralize(snakeCase(className.replace('Entity', ''))); } indexName(tableOrName: Table | string, columnNames: string[], where?: string): string { const clonedColumnNames = [...columnNames]; clonedColumnNames.sort(); const tableName = tableOrName instanceof Table ? tableOrName.name : tableOrName; const replacedTableName = tableName.replace('.', '_'); let key = `${replacedTableName}_${clonedColumnNames.join('_')}`; if (where) key += `_${where}`; return key.substr(0, 20); } } <file_sep>/Makefile include .env help: ## Help menu @echo "App Tasks" @cat $(MAKEFILE_LIST) | pcregrep -o -e "^([\w]*):\s?##(.*)" @echo start: ## starts docker compose docker-compose -f docker-compose.yml up restart: ## starts docker compose docker-compose restart stop: ## stops all containers docker-compose stop ssh: ## connect to fpm container docker exec -it $(APP_PREFIX)-fpm ash mysql: ## connect to mysql container docker exec -it $(APP_PREFIX)-mysql bash prod: ## ssh into prod server ssh $(PROD_SSH_URL) -p 7822 -t "cd $(PROD_PATH) ; bash" <file_sep>/backend/src/services/TwitterAuthService.ts /* eslint-disable camelcase */ import Twitter, { AccessTokenOptions, AccessTokenResponse } from 'twitter-lite'; import Env from '../helpers/Env'; export interface RequestTokenResponse { oauth_token: string; oauth_token_secret: string; oauth_callback_confirmed: 'true'; } export class TwitterAuthService { protected consumer_key: string; protected consumer_secret: string; protected authClient: Twitter; constructor(consumer_key: string, consumer_secret: string) { this.consumer_key = consumer_key; this.consumer_secret = consumer_secret; this.authClient = new Twitter({ consumer_key, consumer_secret }); } getAccessToken(options: AccessTokenOptions): Promise<AccessTokenResponse> { return this.authClient.getAccessToken(options); } getRequestToken(twitterCallbackUrl: string | 'oob'): Promise<RequestTokenResponse> { return (this.authClient.getRequestToken(twitterCallbackUrl) as unknown) as Promise<RequestTokenResponse>; } } const twitterAuthService = new TwitterAuthService( Env.string('TWITTER_CONSUMER_KEY'), Env.string('TWITTER_CONSUMER_SECRET'), ); export default twitterAuthService; <file_sep>/backend/src/entities/TwitterUserEntity.ts import { Column, Entity, PrimaryColumn } from 'typeorm'; import { TwitterUser } from '../TwitterEntities'; import { EntityTimeBase } from './EntityTimeBase'; @Entity() export class TwitterUserEntity extends EntityTimeBase { @PrimaryColumn('varchar') id: string; @Column({ type: 'simple-json' }) data: TwitterUser; }
3874a81990ef3d80e0277fd5768f24fc20da8cf9
[ "Markdown", "JavaScript", "Makefile", "TypeScript", "Dockerfile", "Shell" ]
46
TypeScript
angelxmoreno/twitter-export
28b81e16efe23a46b19d4b6f062a5291745150e6
261cd28c8a2cdd3849b58f8e82058fdb4deefdb5
refs/heads/master
<repo_name>deathbob/Engine-Yard-Contest-July-2009<file_sep>/contest.rb require 'digest/sha1' class Bob def initialize @phrase_to_match = "I would much rather hear more about your whittling project" @hash_to_match = Digest::SHA1.hexdigest(@phrase_to_match).to_i(16) @dictionary = open("dict.txt").readlines @current_best = 160 @picks = '' end def compute_hamming_distance(to_test) temp = @hash_to_match ^ to_test acc = 0 (temp.size * 8 - 1).downto(0) do |n| acc = acc + temp[n] end acc end def show_binary(num) (num.size * 8 - 1).downto(0) do |n| print num[n] end end def fill_picks @picks = '' 12.times do @picks << @dictionary[rand(999)].chomp + ' ' end @picks.chop! end def hash_picks @picks_hash = Digest::SHA1.hexdigest(@picks).to_i(16) end def cycle fill_picks hash_picks distance = compute_hamming_distance(@picks_hash) if distance < @current_best puts distance.to_s + " " + @picks # f = open("keepers.txt", 'a') # f << distance << " "<< @picks << "\n" # f.close @current_best = distance end end end bob = Bob.new 1000000.times do bob.cycle end
433cdcaf69b6da1c109961244e3be88d7c5c37dd
[ "Ruby" ]
1
Ruby
deathbob/Engine-Yard-Contest-July-2009
01d88d1655d7ed8de702b46c05a21107d57557df
5476218b43f32cccae5bd248d0403d0f895e2ab6