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>const admin = require("firebase-admin"); //dotenv module is required to parse the environment variables into json format require("dotenv").config(); //parsing the environment variable into JSON format const serviceAccount = JSON.parse(process.env.GOOGLE_CREDS); //snippet required for initialization admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); //function that returns the db (for export purposes) const getDb = () => { //the firestore database const _db = admin.firestore(); if (_db) { return _db; } else { console.log(err); } }; const getFieldValue = () => { const FieldValue = admin.firestore.FieldValue; if (FieldValue) { return FieldValue; } else { console.log(err); } }; exports.getDb = getDb; exports.getFieldValue = getFieldValue; <file_sep>const express = require("express"); //importing the Alumni-api POST services const alumniPost = require("../api-services/alumni-api/post/alumniPost"); //create router const router = express.Router(); // create application/json parser const jsonParser = express.json(); /* ==========================================================|| ROUTES ||======================================================================= */ //login POST request for alumni router.post("/api/alumni/login", jsonParser, alumniPost.postLogin); router.post("/api/alumni/editEntry", jsonParser, alumniPost.postEditEntry); router.post( "/api/alumni/getAlumniInfo", jsonParser, alumniPost.postGetAlumniInfo ); module.exports = router; <file_sep>const getDb = require("../../../Firebase/firebaseConfig").getDb; exports.postLogin = async (req, res, next) => { const id = req.body.username; const password = req.body.password; console.log(id, password); //getting the database const db = getDb(); //reference to the collection const studentUserCredentialsRef = await db .collection("users") .doc("student-user") .collection("student-user-credentials"); //getting the document where id == username and password == <PASSWORD> const studentUser = await studentUserCredentialsRef .where("id", "==", id) .where("password", "==", password) .limit(1) .get(); //send response to client if (!studentUser.empty) { const studentUserData = await studentUser.docs[0].data(); return res.json({ studentUser: studentUserData, }); } else { console.log("[*] Error in postLogin"); return res.status(404).send("Not Found"); } }; <file_sep>const express = require("express"); //importing the General-api GET services const generalGet = require("../api-services/general-api/get/generalGet"); //importing the General-api POST services const generalPost = require("../api-services/general-api/post/generalPost"); //create router const router = express.Router(); // create application/json parser const jsonParser = express.json(); /* ==========================================================|| ROUTES ||======================================================================= */ //get batches GET request router.get("/api/general/getBatches", jsonParser, generalGet.getBatches); //get Batch data POST request router.post("/api/general/getbatchinfo", jsonParser, generalPost.postBatchInfo); //get Alumni Data POST request router.post( "/api/general/getAlumniInfo", jsonParser, generalPost.postAlumniData ); module.exports = router; <file_sep>const express = require("express"); const getDb = require("./Firebase/firebaseConfig").getDb; const app = express(); const cors = require("cors"); const adminApiRoutes = require("./api-routes/adminApiRoutes"); const generalApiRoutes = require("./api-routes/generalApiRoutes"); const alumniApiRoutes = require("./api-routes/alumniApiRoutes"); const studentApiRoutes = require("./api-routes/studentApiRoutes"); app.use(cors()); app.use(adminApiRoutes); app.use(generalApiRoutes); app.use(alumniApiRoutes); app.use(studentApiRoutes); // console.log(getDb()); //start the app at port 5000 app.listen(5000); <file_sep>const crypto = require("crypto"); const getDb = require("../../../Firebase/firebaseConfig").getDb; const getFieldValue = require("../../../Firebase/firebaseConfig").getFieldValue; exports.postLogin = async (req, res, next) => { const username = req.body.username; const password = req.body.password; //getting the database const db = getDb(); //reference to the admin-user-credentials collection const adminUserCredentialsRef = await db .collection("users") .doc("admin-user") .collection("admin-user-credentials"); //getting the document where id == username and password == <PASSWORD> const adminUser = await adminUserCredentialsRef .where("id", "==", username) .where("password", "==", password) .limit(1) .get(); //send response to client if (!adminUser.empty) { const id = await adminUser.docs[0].data().id; return res.json({ id: id, }); } else { console.log("[*] Error in postLogin"); return res.status(404).send("Not Found"); } }; exports.postEdit = async (req, res, next) => { const db = getDb(); const alumniData = req.body.alumniData; delete alumniData.key; try { const alumniDocRef = await db .collection("alumni-db") .doc(`${alumniData.batch}`) .collection("alumni-data") .doc(`${alumniData.id}`); const response = await alumniDocRef.set(alumniData); return res.status(200).send("Success"); } catch { console.log("[*] Error in postEdit"); return res.status(404).send("Not Found"); } }; exports.postAddEntry = async (req, res, next) => { const db = getDb(); const values = req.body.values; try { //create alumni Entry const alumniDocRef = await db .collection("alumni-db") .doc(values.batch) .collection("alumni-data") .doc(values.id); await alumniDocRef.set(values); //set password const password = crypto.randomBytes(3).toString("hex"); const batchDocRef = await db.collection("alumni-db").doc(values.batch); await batchDocRef.set( { passwords: { [values.id]: password, }, }, { merge: true } ); //create user const userDocRef = await db .collection("users") .doc("alumni-user") .collection("alumni-user-credentials") .doc(values.id); await userDocRef.set({ alumniDataRef: alumniDocRef, id: values.id, password: <PASSWORD>, }); return res.status(200).send("Success"); } catch { console.log("[*] Error in postAddEntry"); return res.status(404).send("Error"); } }; exports.postDeleteEntry = async (req, res, next) => { const db = getDb(); const values = req.body.values; try { //delete alumni entry const alumniDocRef = await db .collection("alumni-db") .doc(values.batch) .collection("alumni-data") .doc(values.id); await alumniDocRef.delete(); //delete password const batchDocRef = await db.collection("alumni-db").doc(values.batch); const FieldValue = getFieldValue(); await batchDocRef.set( { passwords: { [values.id]: FieldValue.delete(), }, }, { merge: true } ); //delete user const userDocRef = await db .collection("users") .doc("alumni-user") .collection("alumni-user-credentials") .doc(values.id); await userDocRef.delete(); return res.status(200).send("Success"); } catch { console.log("[*] Error in postDeleteEntry"); return res.status(404).send("Error"); } }; exports.postAddBatch = async (req, res, next) => { const batch = req.body.batch; const alumniDataArr = req.body.alumniData; console.log(typeof alumniDataArr); const db = getDb(); try { const batchDocRef1 = db.collection("alumni-db").doc(batch); const batchDoc = await batchDocRef1.get(); if (batchDoc.exists) { return res.send("The Batch Already Exists!"); } else { await batchDocRef1.set({ batchName: batch }); alumniDataArr.forEach(async (alumniData) => { const alumniDocRef = await db .collection("alumni-db") .doc(batch) .collection("alumni-data") .doc(alumniData.id); await alumniDocRef.set(alumniData); //set password const password = crypto.randomBytes(3).toString("hex"); const batchDocRef = await db.collection("alumni-db").doc(batch); await batchDocRef.set( { passwords: { [alumniData.id]: <PASSWORD>, }, }, { merge: true } ); //create user const userDocRef = await db .collection("users") .doc("alumni-user") .collection("alumni-user-credentials") .doc(alumniData.id); await userDocRef.set({ alumniDataRef: alumniDocRef, id: alumniData.id, password: <PASSWORD>, }); }); return res.status(200).send("Success"); } } catch { console.log("[*] Error in postAddBatch"); return res.status(404).send("Error"); } }; <file_sep># Alumni-Management-Server The server/backend code for an Alumni Management System built with [NodeJs](https://nodejs.dev/), [Express](https://expressjs.com/) and [Firebase](https://firebase.google.com/). [Firebase Admin SDK](https://firebase.google.com/docs/admin/setup) has been used for facilitating the use of Firebase on a server. [FireStore](https://firebase.google.com/docs/firestore) is used as the Alumni Database. - The client/frontend can be found [here](https://github.com/Neyen108/Alumni-Management-Client). ## 🛠 Installing 1. Install dependencies ```bash npm install ``` 2. Fire up the server and watch files ```bash npm start ``` ## 🛠 Local Development Environment To run this project on your own Development Environment. Create a .env file in the working directory. The .env file should look like this: GOOGLE_CREDS={ [your firebase service account details json](https://firebase.google.com/docs/admin/setup#initialize-sdk) } Once set up, run: ```bash npm install npm start ``` And the project should load up. ## 🛠 Built with - [NodeJs](https://nodejs.dev/) - [ExpressJs](https://expressjs.com/) - [Firebase](https://firebase.google.com/) <file_sep>const getDb = require("../../../Firebase/firebaseConfig").getDb; exports.postLogin = async (req, res, next) => { const id = req.body.username; const password = req.body.password; console.log(id, password); //getting the database const db = getDb(); //reference to the collection const alumniUserCredentialsRef = await db .collection("users") .doc("alumni-user") .collection("alumni-user-credentials"); //getting the document where id == username and password == <PASSWORD> const alumniUser = await alumniUserCredentialsRef .where("id", "==", id) .where("password", "==", password) .limit(1) .get(); //send response to client if (!alumniUser.empty) { const alumniUserData = await alumniUser.docs[0].data(); return res.json({ alumniUser: alumniUserData, }); } else { console.log("[*] Error in postLogin"); return res.status(404).send("Not Found"); } }; exports.postGetAlumniInfo = async (req, res, next) => { const alumniDataRef = req.body.alumniDataRef; const db = getDb(); const segment = alumniDataRef._path.segments; try { const alumniDataDoc = await db .doc(`${segment[0]}/${segment[1]}/${segment[2]}/${segment[3]}`) .get(); const alumniData = await alumniDataDoc.data(); return res.json({ alumniData: alumniData, }); } catch { console.log("[*] Error in postgetAlumniInfo"); return res.status(404).send("Not Found"); } }; exports.postEditEntry = async (req, res, next) => {};
9ee51322d0d6be9fac54ac284cf818ef2cc0cfc7
[ "JavaScript", "Markdown" ]
8
JavaScript
Neyen108/Alumni-Management-Server
1b4709c21bc7c5dbd58ad4ddfb1a9d8de80c8d3b
a583d10ebb07307acb1fb200eceee22881d6bd04
refs/heads/master
<file_sep># Optional In this tutorial I will discuss about the [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html), which was introduced in java 8. To understand java.util.Optional fully we need to understand - [What is Optional](./README.md#What-is-Optional ) - [Why to use Optional](./README.md#Why-to-use-Optional) - [How to use Optional](./README.md#How-to-use-Optional) **Note**: In all examples given below I am refering below files: - [Student.java](./src/main/java/com/techgurukul/stream/optional/Student.java) - [StudentDTO.java](./src/main/java/com/techgurukul/stream/optional/StudentDTO.java) - [Teacher.java](./src/main/java/com/techgurukul/stream/optional/Teacher.java) While writing this tutorial I used below technologies: - Java 11.0.2 - junit-jupiter 5.6.2 ### What is Optional As name implies, Optional gives an option to choose. In java terms its a class that contain a value which either be null or non-null. ### Why to use Optional In java its very common to get NullPointerException and this exception triggered when some operation done on null reference. To overcome this problem java introduced **java.util.Optional** which basically contain the value whether it is null or non-null and provide methods which enforces the idea of ***null checking***. > null checking: It forces user to check null before doing any other operation. Optional provide many methods which can be used for this like ifPresent, isEmpty. In simple terms Optional gives an alternative to remove NullPointerException as much as possible. For more details about why to use Optional, please check [here](https://www.oracle.com/java/technologies/java8-optional.html). ### How to use Optional 1. **Creating an Optional Object**: - ***Empty Optional***: Optional.empty() method creates an empty Optional with no/null value inside. In below code you can see how to create an empty Integer Optional: ```java Optional<Integer> empty = Optional.empty(); ``` Generally, this is used as a return type from a method instead of null reference. For example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } return studentDTO; } ``` Since java 8: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } return Optional.of(studentDTO); } ``` - **Optional with non-null value**: Optional.of(T value) method creates an Optional for non-null value, if you pass null then you will get NullPointerException. In below code you can see how to create a non-null Integer Optional: ```java Optional<Integer> nonEmpty = Optional.of(Integer.valueOf(2)); ``` - **Optional with null or non-null value**: Optional.ofNullable(T value) method creates an Optional for null and non-null values. - When null passed to ofNullable method it creates an empty Optional ```java Optional<String> emptyOptional = Optional.ofNullable(null); ``` - When non-null passed to ofNullable method it creates non-null optional using Optional.of(T value) method. ```java Optional<String> nonEmpty = Optional.ofNullable(Integer.valueOf(2)); ``` To check whether the optional contains value or not you can use **Optional.isPresent** or **Optional.isEmpty** methods. In below code you can see how to create a Optional for null or non-null Integer Optional. ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalCreateTest.java).*** 2. **Get value from an Optional**: The simplest way to get non-null value from Optional is to use get() method. If you try to fetch value from an empty Optional or null value optional, then this method will throw NoSuchElementException. ```java @Test void test_get_OptionalValue() { Optional<String> emptyOptional = Optional.ofNullable(null); assertThrows(NoSuchElementException.class, () -> emptyOptional.get()); Optional<String> nonEmptyOptionalByOfNullable = Optional.ofNullable("testOptional"); assertTrue(nonEmptyOptionalByOfNullable.get().equals("testOptional")); Optional<String> nonEmptyOptionalByOf = Optional.of("testOptional"); assertTrue(nonEmptyOptionalByOf.get().equals("testOptional")); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalGetTest.java).*** 3. **Checking of value in Optional**: Optional class provided two methods to check whether the optional is empty or having some value. - **isPresent**: Optional.isPresent() return true for non-null optioanl otherwise false. ```java @Test void test_isPresent() { Optional<String> emptyOptional = Optional.ofNullable(null); assertFalse(emptyOptional.isPresent());//created without value so value is not present Optional<String> nonEmptyOptional = Optional.ofNullable("testOptional"); assertTrue(nonEmptyOptional.isPresent());//created with value so value is present } ``` - **isEmpty**: Optional.isEmpty() return true for null/empty optional otherwise true. ```java @Test void test_isEmpty() { Optional<String> emptyOptional = Optional.ofNullable(null); assertTrue(emptyOptional.isEmpty());//created without value so it's empty Optional<String> nonEmptyOptional = Optional.ofNullable("testOptional"); assertFalse(nonEmptyOptional.isEmpty());//created with value so it's not empty } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalValidationTest.java).*** 4. **Other helper methods**: Optional class provides many other helper methods which can be used with optional. So, let’s check one by one all the methods with examples: - **ifPresent with action**: Optional class have ifPresent overloaded methods which perform the given action if the value is present else does nothing. Syntax: ```java public void ifPresent(Consumer<? super T> action) ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } return studentDTO; } ``` Since java 8: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); Optional.ofNullable(student.getName()).ifPresent(studentDTO::setName); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/IfPresentUtilTest.java).*** - **ifPresentOrElse with action**: This method was added in java 9, it is similar to **ifPresent with action**, the only different thing is that you can also mention action which should be performs when optional is empty or having null value. Syntax: ```java public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } else { studentDTO.setName("test"); } return studentDTO; } ``` Since java 9: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); Optional.ofNullable(student.getName()).ifPresentOrElse(studentDTO::setName, () -> studentDTO.setName("test")); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/IfPresentOrElseUtilTest.java).*** - **orElse**: This method return the value if it is non-null otherwise return the value specified in orElse(T other). Syntax: ```java public T orElse(T other) ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } else { studentDTO.setName("test"); } return studentDTO; } ``` Since java 8: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setName(Optional.ofNullable(student.getName()).orElse("test")); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrElseUtilTest.java).*** - **orElseGet**: It is same as [orElse](./README.md#orElse), the only difference is that if optional is null/empty then return value will be produced by the [supplying](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html) function. In simple terms if optional is empty then the get method from implementation of the [Supplier](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html) interface will be executed and will return the value. Syntax: ```java public T orElseGet(Supplier<? extends T> supplier) ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } else { studentDTO.setName("test"); } return studentDTO; } ``` Since java 8: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setName(Optional.ofNullable(student.getName()).orElseGet(() -> "test")); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrElseGetUtilTest.java).*** ***Check the [difference between orElse and OrElseGet](./README.md#difference-between-orElse-and-OrElseGet)***. - **orElseThrow**: This method was added in java 10. This method return the value if it is non-null otherwise throw NoSuchElementException. Syntax: ```java public T orElseThrow() ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getGender()) { studentDTO.setGender(student.getGender()); } else { throw new NoSuchElementException("Gender can not be empty."); } return studentDTO; } ``` Since java 10 ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setGender(Optional.ofNullable(student.getGender()).orElseThrow()); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrElseThrowUtilTest.java).*** - **orElseThrow with custom exception**: This method return the value if it is non-null otherwise throw custom exception. Syntax: ```java public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X ``` Example: Before java 8: ```java public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getGender()) { studentDTO.setGender(student.getGender()); } else { throw new RuntimeException("Gender can not be empty.") } return studentDTO; } ``` Since java 8: ```java public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setGender(Optional.ofNullable(student.getGender()).orElseThrow(() -> new RuntimeException("Gender can not be empty."))); return Optional.of(studentDTO); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrElseThrowCustomeExceptionUtilTest.java).*** - **or**: This method was added in java 9. This method return the current Optional if it is non-null otherwise returns an Optional produced by the supplying function. Syntax: ```java public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) ``` Example: ```java public static Optional<Student> getStudent(Student student) { Student dfaultStudentObj = new Student("defaultName", 001, "<EMAIL>") return Optional.ofNullable(student).or(() -> Optional.of(dfaultStudentObj)); } ``` In above example you can see, if student object is null then this methods returns dfaultStudentObj optional. ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrUtilTest.java).*** - **filter**: If a value is present, and the value matches the given predicate/condition then returns current Optional otherwise empty Optional. Syntax: ```java public Optional<T> filter(Predicate<? super T> predicate) ``` Example: ```java @Test void test_filter() { Student stu = new Student("test", 123, "<EMAIL>"); Optional<Student> studentOptional = Optional.of(stu); Optional<Student> filteredStudentOptional = studentOptional.filter(st -> "test".equals(st.getName())); assertTrue(filteredStudentOptional.equals(studentOptional)); assertTrue(filteredStudentOptional.isPresent()); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalFilterTest.java)*** for more filter examples. - **map**: If a value is not present returns an empty Optional otherwise apply the mapping function to convert optional value to different type and wrap the result in Optional using ofNullable and returns the same. Syntax: ```java public <U> Optional<U> map(Function<? super T, ? extends U> mapper) ``` Example: ```java @Test void test_filter() { Student stu = new Student("test", 123, "<EMAIL>"); Optional<Student> studentOptional = Optional.of(stu); Optional<String> nameOptional = studentOptional.map(Student::getName); assertFalse(nameOptional.isEmpty()); assertTrue(nameOptional.isPresent()); assertTrue(nameOptional.get().equals(stu.getName())); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalMapTest.java)*** for more map examples. - **flatMap**: It is same as **map**, except that it won't wrap the result in Optional. **Note**: The mapped value should also be an optional Syntax: ```java public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) ``` Example: ```java @Test void test_filter() { Teacher nullTeacher = Optional.of(new Teacher("tTest", "Computer")); Optional<Teacher> nullTeacherOptional = Optional.ofNullable(nullTeacher); Optional<String> depFlatMap = teacher.flatMap(Teacher::getDepartment); assertTrue(depFlatMap.get().equals("Computer")); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptionalFlatMapTest.java)*** for more flatMap examples. - **stream**: This method was added in java 9. If a value is present, returns a [Stream](https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html) containing only that value, otherwise returns an empty [Stream](https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html). Syntax: ```java public Stream<T> stream() ``` Example: ```java @Test void test_stream() { Optional<Integer> integerOptional = Optional.of(Integer.valueOf(2)); Stream<Integer> integerStream = integerOptional.stream(); assertTrue(integerStream.findFirst().isPresent()); } ``` ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OptioanStreamTest.java)***. ### Difference between orElse and OrElseGet: When Optional.orElse method used, this execute statement defined in orElse part as well, it doesn’t matter whether the optional is empty or not. It means if the orElse method have some complex or transaction logic which should be executed only when optional is empty, will always be executed. So ***use orElse method with care else you will get unwanted results in your code***. When Optional.orElseGet method used, this execute statement defined in orElseGet only if optional is empty. By default, every time use orElseGet method unless there is specific requirement (like in case where return object which is already defined.) to use orElse. ***Check source code [here](./src/test/java/com/techgurukul/stream/optional/OrElseVsOrElseGetUtilTest.java)*** to see the impact of using orElse method. <file_sep>package com.techgurukul.stream.optional; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; import org.junit.jupiter.api.Test; class IfPresentUtilTest { @Test void test_convertStudentToStudentDto_beforeJava8() { // with null student reference StudentDTO nullStudentDTO = IfPresentUtil.toStudentDtoBeforeJava8(null); assertNull(nullStudentDTO); // with non null student reference Student student = new Student("test", 123, "<EMAIL>"); StudentDTO studentDTO = IfPresentUtil.toStudentDtoBeforeJava8(student); assertTrue(studentDTO.getName().equals(student.getName())); assertTrue(studentDTO.getEmail().equals(student.getEmail())); assertTrue(studentDTO.getRollNumber().equals(student.getRollNumber())); } @Test void test_convertStudentToStudentDto_sinceJava8() { // with null student reference Optional<StudentDTO> nullStudentDTO = IfPresentUtil.toStudentDtoSinceJava8(null); assertTrue(nullStudentDTO.isEmpty()); // with non null student reference Student student = new Student("test", 123, "<EMAIL>"); Optional<StudentDTO> studentDtoOptinal = IfPresentUtil.toStudentDtoSinceJava8(student); if (studentDtoOptinal.isPresent()) { // force null check StudentDTO studentDTO = studentDtoOptinal.get(); assertTrue(studentDTO.getName().equals(student.getName())); assertTrue(studentDTO.getEmail().equals(student.getEmail())); assertTrue(studentDTO.getRollNumber().equals(student.getRollNumber())); } } } <file_sep>package com.techgurukul.stream.optional; import java.util.Optional; public class OrUtil { public static Optional<Student> getStudent(Student student) { return Optional.ofNullable(student) .or(() -> Optional.of(new Student("defaultName", 001, "<EMAIL>"))); } private OrUtil() { } } <file_sep>package com.techgurukul.stream.optional; import java.util.Optional; import java.util.Random; import java.util.logging.Logger; public class OrElseUtil { private static final Logger LOGGER = Logger.getLogger(OrElseUtil.class.getName()); static int maxRollNumber = 10; static int minRollNumber = 1; static Random r = new Random(); public static StudentDTO toStudentDtoBeforeJava8(Student student) { if (student == null) { return null; } StudentDTO studentDTO = new StudentDTO(); if (null != student.getName()) { studentDTO.setName(student.getName()); } else { studentDTO.setName("test"); } if (null != student.getRollNumber()) { studentDTO.setRollNumber(student.getRollNumber()); } else { studentDTO.setRollNumber(getRollNumber()); } if (null != student.getEmail() && !student.getEmail().isEmpty()) { studentDTO.setEmail(student.getEmail()); } else { studentDTO.setEmail("<EMAIL>"); } return studentDTO; } private static Integer getRollNumber() { LOGGER.info("Generate random number"); int rollNumber = r.nextInt((maxRollNumber - minRollNumber) + 1) + minRollNumber; LOGGER.info("Generated random number is: " + rollNumber); return rollNumber; } public static Optional<StudentDTO> toStudentDtoSinceJava8(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setName(Optional.ofNullable(student.getName()).orElse("test")); studentDTO.setRollNumber(Optional.ofNullable(student.getRollNumber()).orElse(getRollNumber())); studentDTO.setEmail(Optional.ofNullable(student.getEmail()).orElse("<EMAIL>")); return Optional.of(studentDTO); } private OrElseUtil() { } } <file_sep>package com.techgurukul.stream.optional; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.Test; class OptioanStreamTest { @Test void test_stream() { Optional<Integer> integerOptioanl = Optional.of(Integer.valueOf(2)); Stream<Integer> integerStream = integerOptioanl.stream(); assertTrue(integerStream.findFirst().isPresent()); } } <file_sep>package com.techgurukul.stream.optional; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; import org.junit.jupiter.api.Test; public class OptionalValidationTest { /** * This test shows how we can use isEmpty method to check if there is a value in * it or not */ @Test void test_isEmpty() { Optional<String> emptyOptional = Optional.ofNullable(null); assertTrue(emptyOptional.isEmpty());//created without value so it's empty Optional<String> nonEmptyOptional = Optional.ofNullable("testOptional"); assertFalse(nonEmptyOptional.isEmpty());//created with value so it's not empty } /** * This test shows how we can use isPresent method to check if there is a value * in it or not */ @Test void test_isPresent() { Optional<String> emptyOptional = Optional.ofNullable(null); assertFalse(emptyOptional.isPresent());//created without value so value is not present Optional<String> nonEmptyOptional = Optional.ofNullable("testOptional"); assertTrue(nonEmptyOptional.isPresent());//created with value so value is present } } <file_sep>package com.techgurukul.stream.optional; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; import org.junit.jupiter.api.Test; public class OptionalFlatMapTest { /** * This test shows how we can use flatMap method which is same as Map, the only * thing it doesn't wrap the return value in Optional. * * if given optional is empty/null then returns empty Optional. * if given optional is non-empty then simply return the value without wrapping in Optional. * * Simple map returns Optional of Optional whereas flatMap returns only Optional, if mapped value is Optional * * Note: The mapped value should also be an optional */ @Test void test_flatMap() { // Null or empty optional Teacher nullTeacher = null; Optional<Teacher> nullTeacherOptioanl = Optional.ofNullable(nullTeacher); Optional<Optional<String>> nullTeacherMapOptional = nullTeacherOptioanl.map(Teacher::getDepartment); assertTrue(nullTeacherMapOptional.isEmpty()); Optional<String> nullTeacherFlatMapOptional = nullTeacherOptioanl.flatMap(Teacher::getDepartment); assertTrue(nullTeacherFlatMapOptional.isEmpty()); // Non null optional Optional<Teacher> teacher = Optional.of(new Teacher("tTest", "Computer")); Optional<Optional<String>> depMap = teacher.map(Teacher::getDepartment); assertTrue(depMap.get().get().equals("Computer")); Optional<String> depFlatMap = teacher.flatMap(Teacher::getDepartment); assertTrue(depFlatMap.get().equals("Computer")); } } <file_sep>package com.techgurukul.stream.optional; import java.util.Optional; import java.util.Random; import java.util.logging.Logger; public class OrElseVsOrElseGetUtil { private static final Logger LOGGER = Logger.getLogger(OrElseVsOrElseGetUtil.class.getName()); static int maxRollNumber = 10; static int minRollNumber = 1; static Random r = new Random(); private static Integer getRollNumber() { long startTime = System.currentTimeMillis(); LOGGER.info("Generate random number."); try { Thread.sleep(2000l); } catch (InterruptedException e) { LOGGER.info("Error in thread sleep."); Thread.currentThread().interrupt(); } int rollNumber = r.nextInt((maxRollNumber - minRollNumber) + 1) + minRollNumber; LOGGER.info(() -> "Generated random number is: " + rollNumber + " Total time taken: " + (System.currentTimeMillis() - startTime)/1000 + "Sec"); return rollNumber; } public static Optional<StudentDTO> toStudentDtoByOrElse(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setName(Optional.ofNullable(student.getName()).orElse("test")); studentDTO.setRollNumber(Optional.ofNullable(student.getRollNumber()).orElse(getRollNumber())); studentDTO.setEmail(Optional.ofNullable(student.getEmail()).orElse("<EMAIL>")); return Optional.of(studentDTO); } public static Optional<StudentDTO> toStudentDtoByOrElseGet(Student student) { if (student == null) { return Optional.empty(); } StudentDTO studentDTO = new StudentDTO(); studentDTO.setName(Optional.ofNullable(student.getName()).orElseGet(() -> "test")); studentDTO.setRollNumber( Optional.ofNullable(student.getRollNumber()).orElseGet(OrElseVsOrElseGetUtil::getRollNumber)); studentDTO.setEmail(Optional.ofNullable(student.getEmail()).orElseGet(() -> "<EMAIL>")); return Optional.of(studentDTO); } private OrElseVsOrElseGetUtil() { } } <file_sep># stream Java Stream tutorial <file_sep>package com.techgurukul.stream.optional; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.NoSuchElementException; import java.util.Optional; import org.junit.jupiter.api.Test; public class OptionalGetTest { /** * This test cases shows how we can retrieve value from a non-null optional * using get method of Optional class optional */ @Test void test_get_OptionalValue() { Optional<String> emptyOptional = Optional.ofNullable(null); assertThrows(NoSuchElementException.class, () -> emptyOptional.get()); Optional<String> nonEmptyOptionalByOfNullable = Optional.ofNullable("testOptional"); assertTrue(nonEmptyOptionalByOfNullable.get().equals("testOptional")); Optional<String> nonEmptyOptionalByOf = Optional.of("testOptional"); assertTrue(nonEmptyOptionalByOf.get().equals("testOptional")); } }
ca1664b57968ce7525459fb79882cd231a97a1fb
[ "Markdown", "Java" ]
10
Markdown
techgurukulbharat/stream
f16ac7ac75b1fb96c8531ad2e088ff28cb394340
322561c1f38ead87a4ff795482ff224a92f974e7
refs/heads/master
<file_sep>import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys #1 driver = webdriver.Firefox(executable_path="C:\\geckodriver\geckodriver.exe") driver.get("http://www.ynet.co.il") driver = webdriver.Chrome(executable_path="C:\\Chromedriver\chromedriver.exe") for i in range(10): time.sleep(1) driver.get("http://www.walla.co.il") #2 urlTitle = driver.title print("title: "+driver.title) ##
d1d0a6b062d1c08aafe65d6e4c6deb65a457331e
[ "Python" ]
1
Python
liorberi/automation
f2e2be02ea23e03b174199834286b4f622532ab1
b73bd181d40a87ae3b670164a21ab07e7f5cb847
refs/heads/master
<file_sep>f1-utils ======== retrieve_stats.py - Retrieves F1 GP results for any event Usage: #### Get specific session ```sh $python retrieve_stats.py 2013 Spain qualifying ``` Will return JSON-encoded results for the 2013 Spain Quailfying session: ```javascript {"2013": {"Spain": {"qualifying": [{"Q1": "1:21.913", "Q3": " 1:20.718", "Q2": " 1:21.776", "No": "9", "Laps": "12", "Driver": "<NAME>", "Pos" : "1", "Team": "Mercedes"}, {"Q1": "1:21.728", "Q3": " 1:20.972", "Q2": " 1:21.001", "No": "10", "Laps": "12", "Driver": "<NAME>", "Pos": "2 ", "Team": "Mercedes"}, {"Q1": "1:22.158", "Q3": " 1:21.054", "Q2": " 1:21.602", "No": "1", "Laps": "12", "Driver": "<NAME>", "Pos": "3", "Team": "Red Bull Racing-Renault"}, {"Q1": "1:22.210", "Q3": " 1:21.177", "Q2": " 1:21.676", "No": "7", "Laps": "17", "Driver": "Kimi R\u00e4ikk\u00 f6nen", "Pos": "4", "Team": "Lotus-Renault"}, ... ``` #### Get all sessions ```sh $python retrieve_stats.py 2013 Monaco all ``` will return ```javascript {"2013": {"Monaco": {"practice 1": [{"No": "9", "Laps": "31", "Driver": "<NAME>", "Pos": "1", "Gap": "[]", "Team": "Mercedes", "Time/Retired": "1:16.195"}, ... "practice 2": [..], "practice 3": [..], "qualifying": [..], "race": [..] ``` --- import_practies.py - Imports all practices sessions from a JSON, given through stdin: ```sh $python retrieve_stats.py 2013 Spain all > 2013_Spain_all.json $python import_practices.py < 2013_Spain_all.json ``` or just using pipe without intermediate files: ```sh $python retrieve_stats.py 2013 Spain all | python import_practices.py ``` Will add all entries to the `practices` table. If there are entries with unknown drivers, new entry will be added. Driver birthday and nationality would be fetched from wiki page, if found Base tables and API for F1 results could be found here: http://ergast.com/mrd/ <file_sep>__author__ = "<NAME>" __license__ = "GPL" __email__ = "<EMAIL>" """ Retrieve times from F1.com website Times of interest: * practice 1, 2, 3 ** qualifying ** race Invoke: python retrieve_stats YEAR GPNAME EVENT GPNAME i.e. Spain, Monaco, etc EVENT "practice 1", "practice 2", "practice 3", "qualifying", "race", "all" Returns json-string { year: { gpname: { event: [results-array], ... } } } Dependencies: BeautifulSoup: #easy_install beautifulsoup4 or #apt-get install python-beautifulsoup """ import re import sys import urllib import pickle import json from BeautifulSoup import BeautifulSoup from BeautifulSoup import Tag from BeautifulSoup import NavigableString from pprint import pprint if len(sys.argv) < 3: print "Not enough arguments." print sys.argv[0], " year gp-name [type]" print "" print "\t year: i.e. 2013" print "\tgp-name: i.e. Monaco" print "\t type: practice 1|practice 2|practice 3|qualifying|race|all default 'all'" print "" exit(1) def _absUrl(url): """ Makes absolute url if needed """ return url if url.startswith('http:') else ("http://www.formula1.com" + url) def _fmtNode(node): """ Parsing table rows, node could be simple text or another list of nodes (<a>text</a>) we need only text part here """ if type(node) == list and len(node) > 0: if isinstance(node[0], Tag): return unicode(node[0].string) else: return unicode(node[0]) return unicode(node) def findGpUrl(year, gpname): """ finds all links with 'gpname' within them and returns first one found """ soup = BeautifulSoup(urllib.urlopen("http://www.formula1.com/results/season/%s/" % year )) eventLink = [a.parent['href'] for a in soup.findAll("a", text=re.compile(gpname))] if len(eventLink) == 0: print "No GP found for year=%s and gpname=%s" % (year, gpname) sys.exit(1) return eventLink[0] def parseGpEvent(gpUrl, eventType): """ parse times for specific gp eventType: practice X|qualifying|race gp url is a race results url, for past events """ soup = BeautifulSoup(urllib.urlopen(_absUrl(gpUrl))) # adjust url for different types if eventType != 'race': links = [a.parent['href'] for a in soup.findAll('a', text=re.compile(eventType.upper()))] if len(links) == 0: print "Event type: %s not found for GP %s" % (eventType, gpUrl) return soup = BeautifulSoup(urllib.urlopen(_absUrl(links[0]))) # find table with results # there seems to be only one table with rows at the moment table = soup.findAll("tr") hdr = [_fmtNode(x.contents) for x in table[0].contents if isinstance(x, Tag)] lns = [] for row in table[1::]: tds = [_fmtNode(x.contents) for x in row.contents if isinstance(x, Tag)] # datarow = dict(zip(hdr, tds)) lns.append(dict(zip(hdr, tds))) return lns year = sys.argv[1] gpname = sys.argv[2] rtype = sys.argv[3] if len(sys.argv) == 4 else 'all' if rtype == 'all': rtype = ['practice 1', 'practice 2', 'practice 3', 'qualifying', 'race'] else: rtype = [rtype] gpUrl = findGpUrl(year, gpname) events = {} for eventType in rtype: events[eventType] = parseGpEvent(gpUrl, eventType) data = {} data[year] = {} data[year][gpname] = events print json.dumps(data) <file_sep>__author__ = "<NAME>" __license__ = "GPL" __email__ = "<EMAIL>" DB_HOST = "localhost" DB_USER = "root" DB_PASSWORD = "<PASSWORD>" DB_NAME = "f1db" """ Import practices results into statistics table from http://ergast.com/mrd/ using returned by retrieve_stats.py JSON Attention!! Will delete all results for given event&session before inserting Mysql table: DROP TABLE IF EXISTS `practices`; CREATE TABLE IF NOT EXISTS `practices` ( `practiceId` int(11) NOT NULL AUTO_INCREMENT, `practiceNumber` tinyint(4) NOT NULL DEFAULT '1', `raceId` int(11) NOT NULL DEFAULT '0', `driverId` int(11) NOT NULL DEFAULT '0', `constructorId` int(11) NOT NULL DEFAULT '0', `number` int(11) NOT NULL DEFAULT '0', `position` int(11) DEFAULT NULL, `time` varchar(255) DEFAULT NULL, `gap` varchar(255) DEFAULT NULL, `milliseconds` int(11) DEFAULT NULL, `laps` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`practiceId`), UNIQUE KEY `practiceNumber` (`practiceNumber`,`raceId`,`driverId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; Dependencies: * MySQL-python #apt-get install python-mysqldb """ import sys import json import MySQLdb import urllib2 import time import re from pprint import pprint ########################### def _getRaceId(year, raceName, db): """ Find raceId in races table Will successfully try to shorten race name to overcome GP titles like "Spanish GP - Spain", "Great Britain" -> British etc.. """ if raceName == 'Great Britain': raceName = 'British' cur = db.cursor() for i in range(3): numrows = cur.execute("SELECT raceId FROM races WHERE year=%s AND name LIKE %s", (year, raceName+'%')) if numrows == 1: return cur.fetchone()[0] # try shorter names raceName = raceName[:-1] return None def _getTeamId(name, db): """ Tryint to find contstructor team for a given name Some tricks apply, though: STR -> Toro Rosso Red Bull Racing -> Red Bull """ cur = db.cursor() if cur.execute("SELECT constructorId FROM constructors WHERE name LIKE %s ", name): return cur.fetchone()[0] # try just first part, without Engine supplier name = name.split('-')[0] if name == 'STR': name = '<NAME>' if name == 'Red Bull Racing': name = 'Red Bull' if cur.execute("SELECT constructorId FROM constructors WHERE name LIKE %s OR %s LIKE name", (name, name)): return cur.fetchone()[0] return None def _getDriverId(name, db): """ Trying to find driver by name or by wiki-url If none found, will add new entry (with fetched DOB, Nationality from wiki) """ cur = db.cursor() name = re.sub("(\s+)", " ", name) # strip double spaces urlName = name.replace(' ', '_') if cur.execute("SELECT driverId FROM drivers WHERE CONCAT(forename, ' ', surname) LIKE %s OR url LIKE %s", (name, '%' + urlName)) == 1: return cur.fetchone()[0] print "No entry found for %s... will create one, okay?" % name # try url opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.1')] url = 'http://en.wikipedia.org/wiki/'+urlName page = opener.open(url).read() if page: try: birthday = re.search('<span\s+class="bday">(\d{4}-\d{2}-\d{2})</span>', page).group(1) except Exception, e: birthday = '0000-00-00' try: nationality = re.search("Nationality(</a>)?</th>.+?</span>\s*<a[^>]+>([^<]+)</a></td>", page, flags=re.DOTALL|re.IGNORECASE).groups(1)[1] except Exception, e: nationality = '' forename, surname = name.split(" ", 1) driverRef = surname.lower().replace(' ', '') print "Inserting new driver (%s,%s,%s,%s,%s, %s)" % (driverRef, forename, surname, birthday, nationality, url) try: cur.execute("INSERT INTO drivers (driverRef, forename, surname, dob, nationality, url) " "VALUES(%s, %s, %s, %s, %s, %s)", (driverRef, forename, surname, birthday, nationality, url)) except MySQLdb.Error, e: print "Error inserting: ", e return cur.lastrowid return None def _timeToMs(times): if times == 'No time': return 0 r = map(int, re.split(r"[:.,]", times)) if len(r) == 3: return (r[0]*60 + r[1]) * 1000 + r[2] return 0 ########################## try: json = json.loads("".join(sys.stdin)) except Exception, e: print "Invalid json." raise # connect to db db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=<PASSWORD>, db=DB_NAME) for year in json.keys(): for race in json[year].keys(): raceId = _getRaceId(year, race, db) if raceId is None: print "Couldn't find raceId for %s-%s" % (year, race) break for eventType in json[year][race].keys(): if not eventType.startswith('pract'): print "Skipping %s session" % eventType continue practiceNumber = eventType[-1] eventData = json[year][race][eventType] print "Proceeding %s-%s Session: %s (raceId=%s)" % (year, race, eventType, raceId) cur = db.cursor() cur.execute("DELETE FROM practices WHERE raceId=%s AND practiceNumber=%s", (raceId, practiceNumber)) for row in eventData: driverId = _getDriverId(row['Driver'], db) teamId = _getTeamId(row['Team'], db) if driverId is None or teamId is None: print "Will not import entry, unknown driverId, teamId: Driver: %s, Team: %s" % (row['Driver'], row['Team']) continue cur.execute("INSERT INTO practices (practiceNumber, raceId, driverId, " "constructorId, number, position, time, milliseconds, laps, gap) " "VALUES (%s, %s, %s ,%s, %s, %s, %s, %s, %s, %s)", (practiceNumber, raceId, driverId, teamId, row['No'], row['Pos'], row['Time/Retired'], _timeToMs(row['Time/Retired']), row['Laps'], row['Gap'])) print "Done!" db.close()
4857c4047b9fa0e2f0637580976daff2034f26f6
[ "Markdown", "Python" ]
3
Markdown
lotas/f1-utils
b853f1bff6c98782ac0f40876116b6815eada2cc
a946fcddbf38c1b1a4a28ab8a679ba01aa97b987
refs/heads/master
<file_sep># QueryEvaluateTechniques Term-At-A-Time and Document-At-A-Time (AND, OR with both) <file_sep>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; public class IRP02 { static File file; static FileWriter fw; static Writer bw; static List<List<Integer>> positionsArrayTaatAnd = new ArrayList<List<Integer>>(); static List<List<Integer>> positionsArrayTaatOr = new ArrayList<List<Integer>>(); static List<List<Integer>> positionsArrayDaatAnd = new ArrayList<List<Integer>>(); static List<List<Integer>> positionsArrayDaatOr = new ArrayList<List<Integer>>(); public static void main(String[] args) throws IOException { String path_of_index = args[0]; String inputFileName = args[2]; String outputFileName = args[1]; // String path_of_index = "C:\\Users\\Jay\\Downloads\\Phone_Stuff\\New folder\\535 Information Retrieval\\Project-02\\index"; // String inputFileName = "input1.txt"; // String outputFileName = "output.txt"; file = new File(outputFileName); if (!file.exists()) { file.createNewFile(); } bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8")); positionsArrayTaatAnd = new ArrayList<List<Integer>>(); positionsArrayTaatOr = new ArrayList<List<Integer>>(); positionsArrayDaatAnd = new ArrayList<List<Integer>>(); positionsArrayDaatOr = new ArrayList<List<Integer>>(); HashMap<String,LinkedList<Integer>> hm = createPostings(path_of_index); String query = ""; try { File fileInputDir = new File(inputFileName); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileInputDir), "UTF8")); while((query = bufferedReader.readLine()) != null) { GetPostings(hm, query); TaatAnd(query, positionsArrayTaatAnd); TaatOr(query, positionsArrayTaatOr); DaatAnd(query, positionsArrayDaatAnd); DaatOr(query, positionsArrayDaatOr); positionsArrayTaatAnd.clear(); positionsArrayTaatOr.clear(); positionsArrayDaatAnd.clear(); positionsArrayDaatOr.clear(); } bufferedReader.close(); } catch(FileNotFoundException ex) { bw.write("Unable to open file '" + inputFileName + "'"); } catch(IOException ex) { bw.write("Error reading file"); } bw.close(); } static HashMap<String,LinkedList<Integer>> createPostings(String path_of_index) throws IOException{ Directory dirIndex = FSDirectory.open(Paths.get(path_of_index)); IndexReader indexReader = DirectoryReader.open(dirIndex); Fields fields = MultiFields.getFields(indexReader); // Extracting Field Names ArrayList<String> fieldNames = new ArrayList<String>(); for(String field : fields){ if(field.indexOf("text_")>-1) fieldNames.add(field); // Filtering Required Field Names } HashMap<String,LinkedList<Integer>> hm = new HashMap<String,LinkedList<Integer>>(); for(String field : fieldNames){ Terms terms = fields.terms(field); // Extracting terms for particular field TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; while((byteRef = iterator.next()) != null) { String st = byteRef.utf8ToString(); LinkedList<Integer> postings = new LinkedList<Integer>(); PostingsEnum poEnum = null; poEnum = iterator.postings(poEnum); // Retreiving Postings for particular term int position; while((position = poEnum.nextDoc()) != PostingsEnum.NO_MORE_DOCS){ postings.add(position); // Adding the values of postings to LinkedList } hm.put(st, postings); // Adding to hashmap, key: term, value: List of postings } } return hm; } static void GetPostings(HashMap<String, LinkedList<Integer>> hm, String query) throws IOException { String terms[] = query.split(" "); for(String term : terms){ bw.write("GetPostings"+" \n"); bw.write(term+" \n"); bw.write("Postings list: "); if(hm.containsKey(term)){ LinkedList<Integer> postingsList = hm.get(term); // Retreiving postings for terms in query positionsArrayTaatAnd.add(postingsList); positionsArrayTaatOr.add(postingsList); positionsArrayDaatAnd.add(postingsList); positionsArrayDaatOr.add(postingsList); for(Integer position: postingsList){ bw.write(position+" "); // Printing postings to file } } bw.write("\n"); } } static void TaatAnd(String query, List<List<Integer>> posArray) throws IOException { bw.write("TaatAnd \n"); String terms[] = query.split(" "); for(String term : terms){ bw.write(term+" "); } bw.write("\n"); bw.write("Results: "); int minIndex = 0, compareCount=0; boolean isFirst = true; // flag variable to note addition of first term ArrayList<Integer> results = new ArrayList<Integer>(); int size = posArray.size(); while(size>0){ minIndex = 0; // Pointing to next available term's postings list /* minSize = posArray.get(minIndex).size(); // Finding index of array having least size for(int i=0; i<size; i++){ if(minSize > posArray.get(i).size()){ minSize = posArray.get(i).size(); minIndex = i; } } */ if(isFirst){ // Initial addition of postings of first term to intermediate result for(int i=0; i < posArray.get(minIndex).size(); i++){ results.add(posArray.get(minIndex).get(i)); } posArray.remove(minIndex); // Removing postings list of particular term after parsing a postings list of particular term isFirst = false; // Changing of flag variable, after first term's postings list is parsed } else{ int ai, aj=0, check = -1; // ai to keep pointer to results list, aj to keep pointer current term's postings list int resultsSize = results.size(); int temp = posArray.get(minIndex).size(); // temp to keep size of current term's postings list for(ai=0; ai<resultsSize; ai++){ int result = results.get(ai); // assigning (ai)th element of results list to result if(aj<temp){ check = (int)((posArray.get(minIndex)).get(aj)); // assigning (aj)th element of current terms's postings list to check aj++; for(; aj < temp && result > check; ){ // Comparisions //System.out.println("Comparing here "+result+" "+check); check = (int)((posArray.get(minIndex)).get(aj++)); compareCount++; } compareCount++; if(aj != 0) aj--; if(result != (int)((posArray.get(minIndex)).get(aj))){ results.remove(ai); // removing (ai)th element of results if not found in current term's postings list resultsSize = results.size(); ai--; } } else{ results.remove(ai); // removing (ai)th element of results if not found in current term's postings list resultsSize = results.size(); ai--; } } posArray.remove(minIndex); } size = posArray.size(); } if(results.size() == 0){ bw.write("empty "); } for(int result : results){ bw.write(result+" "); } bw.write("\n"); //System.out.println("Number of documents in results: "+results.size()+" \n"); bw.write("Number of documents in results: "+results.size()+" \n"); bw.write("Number of comparisons: "+ compareCount + " \n"); } static void TaatOr(String query, List<List<Integer>> posArray) throws IOException { bw.write("TaatOr \n"); int compareCount = 0; String terms[] = query.split(" "); for(String term : terms){ bw.write(term+" "); } bw.write("\n"); bw.write("Results: "); ArrayList<Integer> results = new ArrayList<Integer>(); results.clear(); ArrayList<Integer> tempResults = new ArrayList<Integer>(); int size = posArray.size(); for(int i=0; i<size; i++){ if(i==0){ for(int j=0; j < posArray.get(i).size(); j++){ results.add(posArray.get(i).get(j)); } } else{ tempResults.clear(); tempResults.addAll(results); results.clear(); int newElement=-1, oldElement=-1; int j=0, k=0; // Merging postings list of current and temporary results which is initially empty for(j=0, k=0; j<posArray.get(i).size() && k<tempResults.size(); ){ newElement = posArray.get(i).get(j); oldElement = tempResults.get(k); if(newElement < oldElement){ results.add(newElement); compareCount++; j++; } else if(newElement > oldElement){ results.add(oldElement); compareCount++; k++; } else if(newElement == oldElement){ results.add(oldElement); compareCount++; k++; j++; } } // Adding of remaining terms for(;j<posArray.get(i).size();){ newElement = posArray.get(i).get(j); results.add(newElement); j++; } for(;k<tempResults.size();){ oldElement = tempResults.get(k); results.add(oldElement); k++; } } } if(results.size() == 0){ bw.write("empty "); } for(int result : results){ bw.write(result+" "); } bw.write("\n"); bw.write("Number of documents in results: "+results.size()+" \n"); bw.write("Number of comparisons: "+ compareCount + " \n"); } static void DaatAnd(String query, List<List<Integer>> posArray) throws IOException { bw.write("DaatAnd \n"); String terms[] = query.split(" "); for(String term : terms){ bw.write(term+" "); } bw.write("\n"); bw.write("Results: "); int compareCount=0; ArrayList<Integer> results = new ArrayList<Integer>(); int size = posArray.size(); int termPtr[] = new int[size]; for(int i=0; i<size; i++){ termPtr[i] = 0; } boolean flag = true, found = false; //int k = 0; if(posArray.size()>0){ for(int i=0; i<posArray.get(0).size(); i++){ int docId = posArray.get(0).get(i); flag = true; // considering docId is found in other terms' postings list for(int j=1; j<size && flag; j++){ found = false; for(int k=termPtr[j]; k<posArray.get(j).size(); k++){ int tDocId = posArray.get(j).get(k); if(tDocId == docId){ termPtr[j] = k; compareCount++; found = true; break; } else if(tDocId > docId){ termPtr[j] = k; flag = false; // indicating that posting not found compareCount++; break; } else{ compareCount++; } } if(found == false) flag = false; } if(flag == true){ results.add(docId); } } } if(results.size() == 0){ bw.write("empty "); } for(int result : results){ bw.write(result+" "); } bw.write("\n"); bw.write("Number of documents in results: "+results.size()+" \n"); bw.write("Number of comparisons: "+ compareCount + " \n"); } static void DaatOr(String query, List<List<Integer>> posArray) throws IOException { bw.write("DaatOr \n"); String terms[] = query.split(" "); for(String term : terms){ bw.write(term+" "); } bw.write("\n"); bw.write("Results: "); int compareCount=0; ArrayList<Integer> results = new ArrayList<Integer>(); ArrayList<Integer> remaining = new ArrayList<Integer>(); int size = posArray.size(); int termPtr[] = new int[size]; for(int i=0; i<size; i++){ termPtr[i] = 0; } if(posArray.size()>0){ for(int i=0; i<posArray.get(0).size(); i++){ int docId = posArray.get(0).get(i); for(int j=1; j<size; j++){ for(int k=termPtr[j]; k<posArray.get(j).size(); k++){ //for(int k=0; k<posArray.get(j).size(); k++){ int tDocId = posArray.get(j).get(k); if(tDocId == docId){ termPtr[j] = k; compareCount++; remaining.add(tDocId); break; } else if(tDocId > docId){ termPtr[j] = k; compareCount++; remaining.add(tDocId); break; } else{ remaining.add(tDocId); compareCount++; } } } results.add(docId); } } // Adding remaining tail-end postings to remaining for(int j=1; j<size; j++){ for(int k=termPtr[j]; k<posArray.get(j).size(); k++){ //for(int k=0; k<posArray.get(j).size(); k++){ int tDocId = posArray.get(j).get(k); remaining.add(tDocId); } } results.addAll(remaining); Collections.sort(results); int ressize = results.size(); // Removing Duplicates for(int i=0; i<ressize-1; i++){ int a = results.get(i); int b = results.get(i+1); if(a == b){ results.remove(i); ressize = results.size(); i--; } } if(results.size() == 0){ bw.write("empty "); } for(int result : results){ bw.write(result + " "); } bw.write("\n"); bw.write("Number of documents in results: "+ results.size()+" \n"); bw.write("Number of comparisons: "+ compareCount + " \n"); } }
edbe032bb370dcd6b739d97a83258d3bb3afbedc
[ "Markdown", "Java" ]
2
Markdown
programmerspoint8/QueryEvaluateTechniques
79e98b1771de7b60e56475c813f30827e16ba739
59b569c9e4f65ab9b53dca68eacb891d1cf2590d
refs/heads/main
<repo_name>AtomicBlom/MLEM<file_sep>/MLEM/Input/KeysExtensions.cs using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Input; using MLEM.Misc; namespace MLEM.Input { /// <summary> /// A set of extension methods for dealing with <see cref="Keys"/> and <see cref="Keyboard"/> /// </summary> public static class KeysExtensions { /// <summary> /// All enum values of <see cref="ModifierKey"/> /// </summary> public static readonly ModifierKey[] ModifierKeys = EnumHelper.GetValues<ModifierKey>().ToArray(); /// <summary> /// Returns all of the keys that the given modifier key represents /// </summary> /// <param name="modifier">The modifier key</param> /// <returns>All of the keys the modifier key represents</returns> public static IEnumerable<Keys> GetKeys(this ModifierKey modifier) { switch (modifier) { case ModifierKey.Shift: yield return Keys.LeftShift; yield return Keys.RightShift; break; case ModifierKey.Control: yield return Keys.LeftControl; yield return Keys.RightControl; break; case ModifierKey.Alt: yield return Keys.LeftAlt; yield return Keys.RightAlt; break; } } /// <summary> /// Returns the modifier key that the given key represents. /// If there is no matching modifier key, <see cref="ModifierKey.None"/> is returned. /// </summary> /// <param name="key">The key to convert to a modifier key</param> /// <returns>The modifier key, or <see cref="ModifierKey.None"/></returns> public static ModifierKey GetModifier(this Keys key) { foreach (var mod in ModifierKeys) { if (GetKeys(mod).Contains(key)) return mod; } return ModifierKey.None; } /// <inheritdoc cref="GetModifier(Microsoft.Xna.Framework.Input.Keys)"/> public static ModifierKey GetModifier(this GenericInput input) { return input.Type == GenericInput.InputType.Keyboard ? GetModifier((Keys) input) : ModifierKey.None; } /// <summary> /// Returns whether the given key is a modifier key or not. /// </summary> /// <param name="key">The key</param> /// <returns>If the key is a modifier key</returns> public static bool IsModifier(this Keys key) { return GetModifier(key) != ModifierKey.None; } /// <inheritdoc cref="IsModifier(Microsoft.Xna.Framework.Input.Keys)"/> public static bool IsModifier(this GenericInput input) { return GetModifier(input) != ModifierKey.None; } } /// <summary> /// An enum representing modifier keys. /// A modifier key is a key that is usually pressed as part of key combination to change the function of a regular key. /// </summary> public enum ModifierKey { /// <summary> /// No modifier key. Only used for <see cref="KeysExtensions.GetModifier(Keys)"/> /// </summary> None, /// <summary> /// The shift modifier key. This represents Left Shift and Right Shift keys. /// </summary> Shift, /// <summary> /// The control modifier key. This represents Left Control and Right Control. /// </summary> Control, /// <summary> /// The alt modifier key. This represents Alt and Alt Graph. /// </summary> Alt } }<file_sep>/Docs/index.md <img src="../Media/Logo.svg" width="25%" > **MLEM Library for Extending MonoGame** is an addition to the game framework [MonoGame](https://www.monogame.net/) that provides extension methods, quality of life improvements and additional features like a ui system and easy input handling. # What next? - Get it on [NuGet](https://www.nuget.org/packages?q=mlem) - Get prerelease builds on [BaGet](https://nuget.ellpeck.de) - See the source code on [GitHub](https://github.com/Ellpeck/MLEM) - See tutorials and API documentation on this website - Check out [the demos](https://github.com/Ellpeck/MLEM/tree/main/Demos) on [Desktop](https://github.com/Ellpeck/MLEM/tree/main/Demos.DesktopGL) or [Android](https://github.com/Ellpeck/MLEM/tree/main/Demos.Android) - See [the changelog](../CHANGELOG.md) for information on updates # Made with MLEM - [A Breath of Spring Air](https://ellpeck.itch.io/a-breath-of-spring-air), a short platformer ([Source](https://git.ellpeck.de/Ellpeck/GreatSpringGameJam)) - [Don't Wake Up](https://ellpeck.itch.io/dont-wake-up), a short puzzle game ([Source](https://github.com/Ellpeck/DontLetGo)) - [Tiny Life](https://tinylifegame.com), an isometric life simulation game ([Modding API](https://github.com/Ellpeck/TinyLifeExampleMod)) If you created a game with the help of MLEM, you can get it added to this list by submitting it on the [issue tracker](https://github.com/Ellpeck/MLEM/issues). If its source is public, other people will be able to use your project as an example, too! # Gallery Here are some images that show a couple of MLEM's features. MLEM.Ui in action: <img src="../Media/Ui.gif"> MLEM's text formatting system: <img src="../Media/Formatting.png"> # Friends of MLEM There are several other NuGet packages and tools that work well in combination with MonoGame and MLEM. Here are some of them: - [Contentless](https://github.com/Ellpeck/Contentless), a tool that removes the need to add assets to the MonoGame Content Pipeline manually - [GameBundle](https://github.com/Ellpeck/GameBundle), a tool that packages MonoGame and other .NET Core applications into several distributable formats - [ButlerDotNet](https://github.com/Ellpeck/ButlerDotNet), a tool that automatically downloads and invokes itch.io's butler - [MonoGame.Extended](https://github.com/craftworkgames/MonoGame.Extended), a package that also provides several additional features for MonoGame - [Coroutine](https://github.com/Ellpeck/Coroutine), a package that implements Unity-style coroutines for any project<file_sep>/Tests/DataTests.cs using System; using System.Diagnostics; using System.IO; using Microsoft.Xna.Framework; using MLEM.Data; using MLEM.Data.Json; using MLEM.Misc; using Newtonsoft.Json; using NUnit.Framework; namespace Tests { public class DataTests { private readonly TestObject testObject = new(Vector2.One, "test") { Vec = new Vector2(10, 20), Point = new Point(20, 30), Dir = Direction2.Left, OtherTest = new TestObject(Vector2.One, "other") { Vec = new Vector2(70, 30), Dir = Direction2.Right } }; [Test] public void TestJsonSerializers() { var serializer = JsonConverters.AddAll(new JsonSerializer()); var writer = new StringWriter(); serializer.Serialize(writer, this.testObject); var ret = writer.ToString(); Assert.AreEqual(ret, "{\"Vec\":\"10 20\",\"Point\":\"20 30\",\"OtherTest\":{\"Vec\":\"70 30\",\"Point\":\"0 0\",\"OtherTest\":null,\"Dir\":\"Right\"},\"Dir\":\"Left\"}"); var read = serializer.Deserialize<TestObject>(new JsonTextReader(new StringReader(ret))); Assert.AreEqual(this.testObject, read); } [Test] public void TestCopy() { var copy = this.testObject.Copy(); Assert.AreEqual(this.testObject, copy); Assert.AreSame(this.testObject.OtherTest, copy.OtherTest); var deepCopy = this.testObject.DeepCopy(); Assert.AreEqual(this.testObject, deepCopy); Assert.AreNotSame(this.testObject.OtherTest, deepCopy.OtherTest); } [Test] public void TestCopySpeed() { const int count = 1000000; var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < count; i++) this.testObject.Copy(); stopwatch.Stop(); TestContext.WriteLine($"Copy took {stopwatch.Elapsed.TotalMilliseconds / count * 1000000}ns on average"); stopwatch.Restart(); for (var i = 0; i < count; i++) this.testObject.DeepCopy(); stopwatch.Stop(); TestContext.WriteLine($"DeepCopy took {stopwatch.Elapsed.TotalMilliseconds / count * 1000000}ns on average"); } private class TestObject { public Vector2 Vec; public Point Point; public Direction2 Dir { get; set; } public TestObject OtherTest; public TestObject(Vector2 test, string test2) { } protected bool Equals(TestObject other) { return this.Vec.Equals(other.Vec) && this.Point.Equals(other.Point) && Equals(this.OtherTest, other.OtherTest) && this.Dir == other.Dir; } public override bool Equals(object obj) { return ReferenceEquals(this, obj) || obj is TestObject other && this.Equals(other); } public override int GetHashCode() { return HashCode.Combine(this.Vec, this.Point, this.OtherTest, (int) this.Dir); } } } }<file_sep>/MLEM.Data/DataTextureAtlas.cs using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using MLEM.Textures; namespace MLEM.Data { /// <summary> /// This class represents an atlas of <see cref="TextureRegion"/> objects which are loaded from a special texture atlas file. /// To load a data texture atlas, you can use <see cref="DataTextureAtlasExtensions.LoadTextureAtlas"/>. /// To see the structure of a Data Texture Atlas, you can check out the sandbox project: <see href="https://github.com/Ellpeck/MLEM/blob/main/Sandbox/Content/Textures/Furniture.atlas"/>. /// Additionally, if you are using Aseprite, there is a script to automatically populate it: <see href="https://github.com/Ellpeck/MLEM/blob/main/Utilities/Populate%20Data%20Texture%20Atlas.lua"/> /// </summary> public class DataTextureAtlas { /// <summary> /// The texture to use for this atlas /// </summary> public readonly TextureRegion Texture; /// <summary> /// Returns the texture region with the given name, or null if it does not exist. /// </summary> /// <param name="name">The region's name</param> public TextureRegion this[string name] { get { this.regions.TryGetValue(name, out var ret); return ret; } } /// <summary> /// Returns an enumerable of all of the <see cref="TextureRegion"/>s in this atlas. /// </summary> public IEnumerable<TextureRegion> Regions => this.regions.Values; private readonly Dictionary<string, TextureRegion> regions = new Dictionary<string, TextureRegion>(); private DataTextureAtlas(TextureRegion texture) { this.Texture = texture; } /// <summary> /// Loads a <see cref="DataTextureAtlas"/> from the given loaded texture and texture data file. /// </summary> /// <param name="texture">The texture to use for this data texture atlas</param> /// <param name="content">The content manager to use for loading</param> /// <param name="infoPath">The path, including extension, to the atlas info file</param> /// <param name="pivotRelative">If this value is true, then the pivot points passed in the info file will be relative to the coordinates of the texture region, not relative to the entire texture's origin.</param> /// <returns>A new data texture atlas with the given settings</returns> public static DataTextureAtlas LoadAtlasData(TextureRegion texture, ContentManager content, string infoPath, bool pivotRelative = false) { var info = new FileInfo(Path.Combine(content.RootDirectory, infoPath)); string text; using (var reader = info.OpenText()) text = reader.ReadToEnd(); var atlas = new DataTextureAtlas(texture); // parse each texture region: "<name> loc <u> <v> <w> <h> piv <px> <py>" followed by extra data in the form "key <x> <y>" foreach (Match match in Regex.Matches(text, @"(.+)\W+loc\W+([0-9]+)\W+([0-9]+)\W+([0-9]+)\W+([0-9]+)(?:\W+piv\W+([0-9.]+)\W+([0-9.]+))?(?:\W+(\w+)\W+([0-9.]+)\W+([0-9.]+))*")) { var name = match.Groups[1].Value.Trim(); // location var loc = new Rectangle( int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[4].Value), int.Parse(match.Groups[5].Value)); // pivot var piv = Vector2.Zero; if (match.Groups[6].Success) { piv = new Vector2( float.Parse(match.Groups[6].Value, CultureInfo.InvariantCulture) - (pivotRelative ? 0 : loc.X), float.Parse(match.Groups[7].Value, CultureInfo.InvariantCulture) - (pivotRelative ? 0 : loc.Y)); } var region = new TextureRegion(texture, loc) { PivotPixels = piv, Name = name }; // additional data if (match.Groups[8].Success) { for (var i = 0; i < match.Groups[8].Captures.Count; i++) { region.SetData(match.Groups[8].Captures[i].Value, new Vector2( float.Parse(match.Groups[9].Captures[i].Value, CultureInfo.InvariantCulture) - (pivotRelative ? 0 : loc.X), float.Parse(match.Groups[10].Captures[i].Value, CultureInfo.InvariantCulture) - (pivotRelative ? 0 : loc.Y))); } } atlas.regions.Add(name, region); } return atlas; } } /// <summary> /// A set of extension methods for dealing with <see cref="DataTextureAtlas"/>. /// </summary> public static class DataTextureAtlasExtensions { /// <summary> /// Loads a <see cref="DataTextureAtlas"/> from the given texture and texture data file. /// </summary> /// <param name="content">The content manager to use for loading</param> /// <param name="texturePath">The path to the texture file</param> /// <param name="infoPath">The path, including extension, to the atlas info file, or null if "<paramref name="texturePath"/>.atlas" should be used</param> /// <param name="pivotRelative">If this value is true, then the pivot points passed in the info file will be relative to the coordinates of the texture region, not relative to the entire texture's origin.</param> /// <returns>A new data texture atlas with the given settings</returns> public static DataTextureAtlas LoadTextureAtlas(this ContentManager content, string texturePath, string infoPath = null, bool pivotRelative = false) { var texture = new TextureRegion(content.Load<Texture2D>(texturePath)); return DataTextureAtlas.LoadAtlasData(texture, content, infoPath ?? $"{texturePath}.atlas", pivotRelative); } } }<file_sep>/MLEM/Extensions/CollectionExtensions.cs using System.Collections.Generic; using System.Linq; namespace MLEM.Extensions { /// <summary> /// A set of extensions for dealing with collections of various kinds /// </summary> public static class CollectionExtensions { /// <summary> /// This method returns a set of possible combinations of n items from n different sets, where the order of the items in each combination is based on the order of the input sets. /// For a version of this method that returns indices rather than entries, see <see cref="IndexCombinations{T}"/>. /// <example> /// Given the input set <c>{{1, 2, 3}, {A, B}, {+, -}}</c>, the returned set would contain the following sets: /// <code> /// {1, A, +}, {1, A, -}, {1, B, +}, {1, B, -}, /// {2, A, +}, {2, A, -}, {2, B, +}, {2, B, -}, /// {3, A, +}, {3, A, -}, {3, B, +}, {3, B, -} /// </code> /// </example> /// </summary> /// <param name="things">The different sets to be combined</param> /// <typeparam name="T">The type of the items in the sets</typeparam> /// <returns>All combinations of set items as described</returns> public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<IEnumerable<T>> things) { var combos = Enumerable.Repeat(Enumerable.Empty<T>(), 1); foreach (var t in things) combos = combos.SelectMany(c => t.Select(c.Append)); return combos; } /// <summary> /// This method returns a set of possible combinations of n indices of items from n different sets, where the order of the items' indices in each combination is based on the order of the input sets. /// For a version of this method that returns entries rather than indices, see <see cref="Combinations{T}"/>. /// <example> /// Given the input set <c>{{1, 2, 3}, {A, B}, {+, -}}</c>, the returned set would contain the following sets: /// <code> /// {0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, /// {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, /// {2, 0, 0}, {2, 0, 1}, {2, 1, 0}, {2, 1, 1} /// </code> /// </example> /// </summary> /// <param name="things">The different sets to be combined</param> /// <typeparam name="T">The type of the items in the sets</typeparam> /// <returns>All combinations of set items as described</returns> public static IEnumerable<IEnumerable<int>> IndexCombinations<T>(this IEnumerable<IEnumerable<T>> things) { var combos = Enumerable.Repeat(Enumerable.Empty<int>(), 1); foreach (var t in things) combos = combos.SelectMany(c => t.Select((o, i) => c.Append(i))); return combos; } } }<file_sep>/MLEM.Ui/Elements/RadioButton.cs using Microsoft.Xna.Framework; using MLEM.Ui.Style; namespace MLEM.Ui.Elements { /// <summary> /// A radio button element to use inside of a <see cref="UiSystem"/>. /// A radio button is a variation of a <see cref="Checkbox"/> that causes all other radio buttons in the same <see cref="Group"/> to be deselected upon selection. /// </summary> public class RadioButton : Checkbox { /// <summary> /// The group that this radio button has. /// All other radio buttons in the same <see cref="RootElement"/> that have the same group will be deselected when this radio button is selected. /// </summary> public string Group; /// <summary> /// Creates a new radio button with the given settings /// </summary> /// <param name="anchor">The radio button's anchor</param> /// <param name="size">The radio button's size</param> /// <param name="label">The label to display next to the radio button</param> /// <param name="defaultChecked">If the radio button should be checked by default</param> /// <param name="group">The group that the radio button has</param> public RadioButton(Anchor anchor, Vector2 size, string label, bool defaultChecked = false, string group = "") : base(anchor, size, label, defaultChecked) { this.Group = group; // don't += because we want to override the checking + unchecking behavior of Checkbox this.OnPressed = element => { this.Checked = true; foreach (var sib in this.GetSiblings()) { if (sib is RadioButton radio && radio.Group == this.Group) radio.Checked = false; } }; } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.Texture.SetFromStyle(style.RadioTexture); this.HoveredTexture.SetFromStyle(style.RadioHoveredTexture); this.HoveredColor.SetFromStyle(style.RadioHoveredColor); this.Checkmark.SetFromStyle(style.RadioCheckmark); } } }<file_sep>/MLEM/Misc/Easings.cs using System; namespace MLEM.Misc { /// <summary> /// This class contains a set of easing functions, adapted from <see href="https://easings.net"/>. /// These can be used for ui elements or any other kind of animations. /// By default, each function takes an input that ranges between 0 and 1, and produces an output that roughly ranges between 0 and 1. To change this behavior, you can use <see cref="ScaleInput"/> and <see cref="ScaleOutput"/>. /// </summary> public static class Easings { /// <summary><see href="https://easings.net/#easeInSine"/></summary> public static readonly Easing InSine = p => 1 - (float) Math.Cos(p * Math.PI / 2); /// <summary><see href="https://easings.net/#easeOutSine"/></summary> public static readonly Easing OutSine = p => (float) Math.Sin(p * Math.PI / 2); /// <summary><see href="https://easings.net/#easeInOutSine"/></summary> public static readonly Easing InOutSine = p => -((float) Math.Cos(p * Math.PI) - 1) / 2; /// <summary><see href="https://easings.net/#easeInQuad"/></summary> public static readonly Easing InQuad = p => p * p; /// <summary><see href="https://easings.net/#easeOutQuad"/></summary> public static readonly Easing OutQuad = p => 1 - (1 - p) * (1 - p); /// <summary><see href="https://easings.net/#easeInOutQuad"/></summary> public static readonly Easing InOutQuad = p => p < 0.5F ? 2 * p * p : 1 - (-2 * p + 2) * (-2 * p + 2) / 2; /// <summary><see href="https://easings.net/#easeInCubic"/></summary> public static readonly Easing InCubic = p => p * p * p; /// <summary><see href="https://easings.net/#easeOutCubic"/></summary> public static readonly Easing OutCubic = p => 1 - (1 - p) * (1 - p) * (1 - p); /// <summary><see href="https://easings.net/#easeInOutCubic"/></summary> public static readonly Easing InOutCubic = p => p < 0.5F ? 4 * p * p * p : 1 - (-2 * p + 2) * (-2 * p + 2) * (-2 * p + 2) / 2; /// <summary><see href="https://easings.net/#easeInExpo"/></summary> public static readonly Easing InExpo = p => p == 0 ? 0 : (float) Math.Pow(2, 10 * p - 10); /// <summary><see href="https://easings.net/#easeOutExpo"/></summary> public static readonly Easing OutExpo = p => p == 1 ? 1 : 1 - (float) Math.Pow(2, -10 * p); /// <summary><see href="https://easings.net/#easeInOutExpo"/></summary> public static readonly Easing InOutExpo = p => p == 0 ? 0 : p == 1 ? 1 : p < 0.5F ? (float) Math.Pow(2, 20 * p - 10) / 2 : (2 - (float) Math.Pow(2, -20 * p + 10)) / 2; /// <summary><see href="https://easings.net/#easeInCirc"/></summary> public static readonly Easing InCirc = p => 1 - (float) Math.Sqrt(1 - p * p); /// <summary><see href="https://easings.net/#easeOutCirc"/></summary> public static readonly Easing OutCirc = p => (float) Math.Sqrt(1 - (p - 1) * (p - 1)); /// <summary><see href="https://easings.net/#easeInOutCirc"/></summary> public static readonly Easing InOutCirc = p => p < 0.5F ? (1 - (float) Math.Sqrt(1 - 2 * p * (2 * p))) / 2 : ((float) Math.Sqrt(1 - (-2 * p + 2) * (-2 * p + 2)) + 1) / 2; /// <summary><see href="https://easings.net/#easeInBack"/></summary> public static readonly Easing InBack = p => 2.70158F * p * p * p - 1.70158F * p * p; /// <summary><see href="https://easings.net/#easeOutBack"/></summary> public static readonly Easing OutBack = p => 1 + 2.70158F * (p - 1) * (p - 1) * (p - 1) + 1.70158F * (p - 1) * (p - 1); /// <summary><see href="https://easings.net/#easeInOutBack"/></summary> public static readonly Easing InOutBack = p => p < 0.5 ? 2 * p * (2 * p) * ((2.594909F + 1) * 2 * p - 2.594909F) / 2 : ((2 * p - 2) * (2 * p - 2) * ((2.594909F + 1) * (p * 2 - 2) + 2.594909F) + 2) / 2; /// <summary><see href="https://easings.net/#easeInElastic"/></summary> public static readonly Easing InElastic = p => p == 0 ? 0 : p == 1 ? 1 : -(float) Math.Pow(2, 10 * p - 10) * (float) Math.Sin((p * 10 - 10.75) * 2.094395F); /// <summary><see href="https://easings.net/#easeOutElastic"/></summary> public static readonly Easing OutElastic = p => p == 0 ? 0 : p == 1 ? 1 : (float) Math.Pow(2, -10 * p) * (float) Math.Sin((p * 10 - 0.75) * 2.0943951023932F) + 1; /// <summary><see href="https://easings.net/#easeInOutElastic"/></summary> public static readonly Easing InOutElastic = p => p == 0 ? 0 : p == 1 ? 1 : p < 0.5 ? -((float) Math.Pow(2, 20 * p - 10) * (float) Math.Sin((20 * p - 11.125) * 1.39626340159546F)) / 2 : (float) Math.Pow(2, -20 * p + 10) * (float) Math.Sin((20 * p - 11.125) * 1.39626340159546F) / 2 + 1; /// <summary><see href="https://easings.net/#easeInBounce"/></summary> public static readonly Easing InBounce = p => 1 - OutBounce(1 - p); /// <summary><see href="https://easings.net/#easeOutBounce"/></summary> public static readonly Easing OutBounce = p => { const float n1 = 7.5625F; const float d1 = 2.75F; if (p < 1 / d1) { return n1 * p * p; } else if (p < 2 / d1) { return n1 * (p -= 1.5F / d1) * p + 0.75F; } else if (p < 2.5 / d1) { return n1 * (p -= 2.25F / d1) * p + 0.9375F; } else { return n1 * (p -= 2.625F / d1) * p + 0.984375F; } }; /// <summary><see href="https://easings.net/#easeInOutBounce"/></summary> public static readonly Easing InOutBounce = p => p < 0.5 ? (1 - OutBounce(1 - 2 * p)) / 2 : (1 + OutBounce(2 * p - 1)) / 2; /// <summary> /// Scales the input of an easing function, which is usually between 0 and 1, to a given minimum and maximum. /// Note that the minimum needs to be smaller than the maximum. /// </summary> /// <param name="easing">The easing function to scale</param> /// <param name="min">The minimum input value</param> /// <param name="max">The maximum input value</param> /// <returns>The scaled easing function</returns> public static Easing ScaleInput(this Easing easing, float min, float max) { return p => easing((p - min) / (max - min)); } /// <summary> /// Scales the output of an easing function, which is usually between 0 and 1, to a given minimum and maximum. /// Note that the minimum needs to be smaller than the maximum. /// </summary> /// <param name="easing">The easing function to scale</param> /// <param name="min">The minimum output value</param> /// <param name="max">The maximum output value</param> /// <returns>The scaled easing function</returns> public static Easing ScaleOutput(this Easing easing, float min, float max) { return p => easing(p) * (max - min) + min; } /// <summary> /// Causes the easing functino to play fully, and then play fully in reverse, in the span between an input of 0 and 1. /// In some places, this behavior is also called "auto-reversing". /// </summary> /// <param name="easing">The easing function to play in reverse as well</param> /// <returns>An auto-reversing version of the easing function</returns> public static Easing AndReverse(this Easing easing) { return p => p <= 0.5F ? easing(p * 2) : easing(1 - (p - 0.5F) * 2); } /// <summary> /// A delegate method used by <see cref="Easings"/>. /// </summary> /// <param name="percentage">The percentage into the easing function. Either between 0 and 1, or, if <see cref="Easings.ScaleInput"/> was used, between an arbitary set of values.</param> public delegate float Easing(float percentage); } }<file_sep>/MLEM/Formatting/Codes/UnderlineCode.cs using System.Text.RegularExpressions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Font; using MLEM.Misc; namespace MLEM.Formatting.Codes { /// <inheritdoc /> public class UnderlineCode : Code { private readonly float thickness; private readonly float yOffset; /// <inheritdoc /> public UnderlineCode(Match match, Regex regex, float thickness, float yOffset) : base(match, regex) { this.thickness = thickness; this.yOffset = yOffset; } /// <inheritdoc /> public override bool DrawCharacter(GameTime time, SpriteBatch batch, char c, string cString, int indexInToken, ref Vector2 pos, GenericFont font, ref Color color, ref float scale, float depth) { // don't underline spaces at the end of lines if (c == ' ' && this.Token.DisplayString.Length > indexInToken + 1 && this.Token.DisplayString[indexInToken + 1] == '\n') return false; var (w, h) = font.MeasureString(cString) * scale; var t = h * this.thickness; batch.Draw(batch.GetBlankTexture(), new RectangleF(pos.X, pos.Y + this.yOffset * h - t, w, t), color); return false; } /// <inheritdoc /> public override bool EndsHere(Code other) { return other is UnderlineCode || other is ResetFormattingCode; } } }<file_sep>/MLEM.Data/Json/StaticJsonConverter.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <summary> /// A <see cref="JsonConverter{T}"/> that doesn't actually serialize the object, but instead serializes the name given to it by the underlying <see cref="Dictionary{T,T}"/>. /// Optionally, the name of a <see cref="Dictionary{TKey,TValue}"/> can be passed to this converter when used in the <see cref="JsonConverterAttribute"/> by passing the arguments for the <see cref="StaticJsonConverter{T}(Type,string)"/> constructor as <see cref="JsonConverterAttribute.ConverterParameters"/>. /// </summary> /// <typeparam name="T">The type of the object to convert</typeparam> public class StaticJsonConverter<T> : JsonConverter<T> { private readonly Dictionary<string, T> entries; private readonly Dictionary<T, string> inverse; /// <summary> /// Creates a new static json converter using the given underlying <see cref="Dictionary{T,T}"/>. /// </summary> /// <param name="entries">The dictionary to use</param> public StaticJsonConverter(Dictionary<string, T> entries) { this.entries = entries; this.inverse = entries.ToDictionary(kv => kv.Value, kv => kv.Key); } /// <summary> /// Creates a new static json converter by finding the underlying <see cref="Dictionary{TKey,TValue}"/> from the given type and member name /// </summary> /// <param name="type">The type that the dictionary is declared in</param> /// <param name="memberName">The name of the dictionary itself</param> public StaticJsonConverter(Type type, string memberName) : this(GetEntries(type, memberName)) { } /// <inheritdoc /> public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer) { if (!this.inverse.TryGetValue(value, out var key)) throw new InvalidOperationException($"Cannot write {value} that is not a registered entry"); writer.WriteValue(key); } /// <inheritdoc /> public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) { var val = reader.Value?.ToString(); if (val == null) return default; this.entries.TryGetValue(val, out var ret); return ret; } private static Dictionary<string, T> GetEntries(Type type, string memberName) { const BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; var value = type.GetProperty(memberName, flags)?.GetValue(null) ?? type.GetField(memberName, flags)?.GetValue(null); if (value == null) throw new ArgumentException($"There is no property or field value for name {memberName}", nameof(memberName)); return value as Dictionary<string, T> ?? throw new InvalidCastException($"{value} is not of expected type {typeof(T)}"); } } }<file_sep>/MLEM/Formatting/TextFormatter.cs using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Xna.Framework; using MLEM.Extensions; using MLEM.Font; using MLEM.Formatting.Codes; using MLEM.Misc; namespace MLEM.Formatting { /// <summary> /// A text formatter is used for drawing text using <see cref="GenericFont"/> that contains different colors, bold/italic sections and animations. /// To format a string of text, use the codes as specified in the constructor. To tokenize and render a formatted string, use <see cref="Tokenize"/>. /// </summary> public class TextFormatter : GenericDataHolder { /// <summary> /// The formatting codes that this text formatter uses. /// The <see cref="Regex"/> defines how the formatting code should be matched. /// </summary> public readonly Dictionary<Regex, Code.Constructor> Codes = new Dictionary<Regex, Code.Constructor>(); /// <summary> /// The macros that this text formatter uses. /// A macro is a <see cref="Regex"/> that turns a snippet of text into another snippet of text. /// Macros can resolve recursively and can resolve into formatting codes. /// </summary> public readonly Dictionary<Regex, Macro> Macros = new Dictionary<Regex, Macro>(); /// <summary> /// Creates a new text formatter with a set of default formatting codes. /// </summary> public TextFormatter() { // font codes this.Codes.Add(new Regex("<b>"), (f, m, r) => new FontCode(m, r, fnt => fnt.Bold)); this.Codes.Add(new Regex("<i>"), (f, m, r) => new FontCode(m, r, fnt => fnt.Italic)); this.Codes.Add(new Regex(@"<s(?: #([0-9\w]{6,8}) (([+-.0-9]*)))?>"), (f, m, r) => new ShadowCode(m, r, m.Groups[1].Success ? ColorHelper.FromHexString(m.Groups[1].Value) : Color.Black, new Vector2(float.TryParse(m.Groups[2].Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var offset) ? offset : 2))); this.Codes.Add(new Regex("<u>"), (f, m, r) => new UnderlineCode(m, r, 1 / 16F, 0.85F)); this.Codes.Add(new Regex("</(s|u|l)>"), (f, m, r) => new ResetFormattingCode(m, r)); this.Codes.Add(new Regex("</(b|i)>"), (f, m, r) => new FontCode(m, r, null)); // color codes foreach (var c in typeof(Color).GetProperties()) { if (c.GetGetMethod().IsStatic) { var value = (Color) c.GetValue(null); this.Codes.Add(new Regex($"<c {c.Name}>"), (f, m, r) => new ColorCode(m, r, value)); } } this.Codes.Add(new Regex(@"<c #([0-9\w]{6,8})>"), (f, m, r) => new ColorCode(m, r, ColorHelper.FromHexString(m.Groups[1].Value))); this.Codes.Add(new Regex("</c>"), (f, m, r) => new ColorCode(m, r, null)); // animation codes this.Codes.Add(new Regex(@"<a wobbly(?: ([+-.0-9]*) ([+-.0-9]*))?>"), (f, m, r) => new WobblyCode(m, r, float.TryParse(m.Groups[1].Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var mod) ? mod : 5, float.TryParse(m.Groups[2].Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var heightMod) ? heightMod : 1 / 8F)); this.Codes.Add(new Regex("</a>"), (f, m, r) => new AnimatedCode(m, r)); // macros this.Macros.Add(new Regex("~"), (f, m, r) => GenericFont.Nbsp.ToCachedString()); this.Macros.Add(new Regex("<n>"), (f, m, r) => '\n'.ToCachedString()); } /// <summary> /// Tokenizes a string, returning a tokenized string that is ready for splitting, measuring and drawing. /// </summary> /// <param name="font">The font to use for tokenization. Note that this font needs to be the same that will later be used for splitting, measuring and/or drawing.</param> /// <param name="s">The string to tokenize</param> /// <param name="alignment">The text alignment that should be used. Note that this alignment needs to be the same that will later be used for splitting, measuring and/or drawing.</param> /// <returns></returns> public TokenizedString Tokenize(GenericFont font, string s, TextAlignment alignment = TextAlignment.Left) { // resolve macros s = this.ResolveMacros(s); var tokens = new List<Token>(); var codes = new List<Code>(); // add the formatting code right at the start of the string var firstCode = this.GetNextCode(s, 0, 0); if (firstCode != null) codes.Add(firstCode); var index = 0; var rawIndex = 0; while (rawIndex < s.Length) { var next = this.GetNextCode(s, rawIndex + 1); // if we've reached the end of the string if (next == null) { var sub = s.Substring(rawIndex, s.Length - rawIndex); tokens.Add(new Token(codes.ToArray(), index, rawIndex, StripFormatting(font, sub, codes), sub)); break; } // create a new token for the content up to the next code var ret = s.Substring(rawIndex, next.Match.Index - rawIndex); var strippedRet = StripFormatting(font, ret, codes); tokens.Add(new Token(codes.ToArray(), index, rawIndex, strippedRet, ret)); // move to the start of the next code rawIndex = next.Match.Index; index += strippedRet.Length; // remove all codes that are incompatible with the next one and apply it codes.RemoveAll(c => c.EndsHere(next)); codes.Add(next); } return new TokenizedString(font, alignment, s, StripFormatting(font, s, tokens.SelectMany(t => t.AppliedCodes)), tokens.ToArray()); } /// <summary> /// Resolves the macros in the given string recursively, until no more macros can be resolved. /// This method is used by <see cref="Tokenize"/>, meaning that it does not explicitly have to be called when using text formatting. /// </summary> /// <param name="s">The string to resolve macros for</param> /// <returns>The final, recursively resolved string</returns> public string ResolveMacros(string s) { // resolve macros that resolve into macros bool matched; do { matched = false; foreach (var macro in this.Macros) { s = macro.Key.Replace(s, m => { // if the match evaluator was queried, then we know we matched something matched = true; return macro.Value(this, m, macro.Key); }); } } while (matched); return s; } private Code GetNextCode(string s, int index, int maxIndex = int.MaxValue) { var (c, m, r) = this.Codes .Select(kv => (c: kv.Value, m: kv.Key.Match(s, index), r: kv.Key)) .Where(kv => kv.m.Success && kv.m.Index <= maxIndex) .OrderBy(kv => kv.m.Index) .FirstOrDefault(); return c?.Invoke(this, m, r); } private static string StripFormatting(GenericFont font, string s, IEnumerable<Code> codes) { foreach (var code in codes) s = code.Regex.Replace(s, code.GetReplacementString(font)); return s; } /// <summary> /// Represents a text formatting macro. Used by <see cref="TextFormatter.Macros"/>. /// </summary> /// <param name="formatter">The text formatter that created this macro</param> /// <param name="match">The match for the macro's regex</param> /// <param name="regex">The regex used to create this macro</param> public delegate string Macro(TextFormatter formatter, Match match, Regex regex); } }<file_sep>/Docs/articles/input.md # Input Handler The **MLEM** base package features an extended `InputHandler` class that allows for finer control over inputs, like the ability to query a new *pressed* state as well as a repeat events implementation for both keyboard and gamepad input. Rather than using an event-based structure, the MLEM input handler relies on the game's `Update` frames: To query input through the input handler, you have to query it every Update frame, and input information will only be available for a single update frame in most situations. ## Setting it up To set it up, all you have to do is create a new instance. The constructor optionally accepts parameters to enable or disable certain kinds of input. ```cs this.InputHandler = new InputHandler(); ``` Additionally, you will have to call the input handler's `Update` method each update call of your game: ```cs this.InputHandler.Update(); ``` ## Querying pressed keys A *pressed* key is a key that wasn't down the last update but is held down the current update. This behavior can be useful for things like ui buttons, where holding down the mouse button shouldn't constantly keep triggering the button. You can query if any key, mouse button or gamepad button is pressed as follows: ```cs var mouse = this.InputHandler.IsPressed(MouseButton.Left); var key = this.InputHandler.IsPressed(Keys.A); // Is any gamepad's A button pressed var gamepad = this.InputHandler.IsPressed(Buttons.A); // Is the 2nd gamepad's A button pressed var gamepad2 = this.InputHandler.IsPressed(Buttons.A, 2); ``` ### Repeat events Keyboard and gamepad repeat events can be enabled or disabled through the `HandleKeyboardRepeats` and `HandleGamepadRepeats` properties in the input handler. Additionally, you can configure the time that it takes until the first repeat is triggered through the `KeyRepeatDelay` property, and you can configure the delay between repeat events through the `KeyRepeatRate` property. When enabled, repeat events for *pressing* are automatically triggered. This means that calling `IsPressed` every update call would return `true` for a control that is being held down every `KeyRepeatRate` seconds after `KeyRepeatDelay` seconds have passed once. ## Gesture handling MonoGame's default touch handling can be a bit wonky to deal with, so the input handler also provides a much better user experience for touch gesture input. To enable touch input, the gestures you want to use first have to be enabled: ```cs InputHandler.EnableGestures(GestureType.Tap); ``` When enabled, a `GestureSample` will be available for the requested gesture type *the frame it is finished*. It can be accessed like so: ```cs if (this.InputHandler.GetGesture(GestureType.Tap, out var sample)) { // The gesture happened this frame Console.WriteLine(sample.Position); } else { // The gesture did not happen this frame } ```<file_sep>/MLEM.Data/Content/Texture2DReader.cs using System.IO; using Microsoft.Xna.Framework.Graphics; namespace MLEM.Data.Content { /// <inheritdoc /> public class Texture2DReader : RawContentReader<Texture2D> { /// <inheritdoc /> protected override Texture2D Read(RawContentManager manager, string assetPath, Stream stream, Texture2D existing) { if (existing != null) { existing.Reload(stream); return existing; } else { return Texture2D.FromStream(manager.GraphicsDevice, stream); } } /// <inheritdoc /> public override string[] GetFileExtensions() { return new[] {"png", "bmp", "gif", "jpg", "tif", "dds"}; } } }<file_sep>/MLEM/Misc/SoundEffectInfo.cs using System; using Microsoft.Xna.Framework.Audio; namespace MLEM.Misc { /// <inheritdoc /> [Obsolete("This class has been moved to MLEM.Sound.SoundEffectInfo in 5.1.0")] public class SoundEffectInfo : Sound.SoundEffectInfo { /// <inheritdoc /> public SoundEffectInfo(SoundEffect sound, float volume = 1, float pitch = 0, float pan = 0) : base(sound, volume, pitch, pan) { } } }<file_sep>/MLEM/Misc/Direction2.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Microsoft.Xna.Framework; using static MLEM.Misc.Direction2; namespace MLEM.Misc { /// <summary> /// An enum that represents two-dimensional directions. /// Both straight and diagonal directions are supported. /// There are several extension methods and arrays available in <see cref="Direction2Helper"/>. /// </summary> [Flags, DataContract] public enum Direction2 { /// <summary> /// No direction. /// </summary> [EnumMember] None = 0, /// <summary> /// The up direction, or -y. /// </summary> [EnumMember] Up = 1, /// <summary> /// The right direction, or +x. /// </summary> [EnumMember] Right = 2, /// <summary> /// The down direction, or +y. /// </summary> [EnumMember] Down = 4, /// <summary> /// The left direction, or -x. /// </summary> [EnumMember] Left = 8, /// <summary> /// The up and right direction, or +x, -y. /// </summary> [EnumMember] UpRight = Up | Right, /// <summary> /// The down and right direction, or +x, +y. /// </summary> [EnumMember] DownRight = Down | Right, /// <summary> /// The up and left direction, or -x, -y. /// </summary> [EnumMember] UpLeft = Up | Left, /// <summary> /// The down and left direction, or -x, +y. /// </summary> [EnumMember] DownLeft = Down | Left } /// <summary> /// A set of helper and extension methods for dealing with <see cref="Direction2"/> /// </summary> public static class Direction2Helper { /// <summary> /// All <see cref="Direction2"/> enum values /// </summary> public static readonly Direction2[] All = EnumHelper.GetValues<Direction2>().ToArray(); /// <summary> /// The <see cref="Direction2.Up"/> through <see cref="Direction2.Left"/> directions /// </summary> public static readonly Direction2[] Adjacent = All.Where(IsAdjacent).ToArray(); /// <summary> /// The <see cref="Direction2.UpRight"/> through <see cref="Direction2.UpLeft"/> directions /// </summary> public static readonly Direction2[] Diagonals = All.Where(IsDiagonal).ToArray(); /// <summary> /// All directions except <see cref="Direction2.None"/> /// </summary> public static readonly Direction2[] AllExceptNone = All.Where(dir => dir != None).ToArray(); private static readonly Direction2[] Clockwise = {Up, UpRight, Right, DownRight, Down, DownLeft, Left, UpLeft}; private static readonly Dictionary<Direction2, int> ClockwiseLookup = Clockwise.Select((d, i) => (d, i)).ToDictionary(kv => kv.d, kv => kv.i); /// <summary> /// Returns if the given direction is considered an "adjacent" direction. /// An adjacent direction is one that is not a diagonal. /// </summary> /// <param name="dir">The direction to query</param> /// <returns>Whether the direction is adjacent</returns> public static bool IsAdjacent(this Direction2 dir) { return dir == Up || dir == Right || dir == Down || dir == Left; } /// <summary> /// Returns if the given direction is considered a diagonal direction. /// </summary> /// <param name="dir">The direction to query</param> /// <returns>Whether the direction is diagonal</returns> public static bool IsDiagonal(this Direction2 dir) { return dir == UpRight || dir == DownRight || dir == UpLeft || dir == DownLeft; } /// <summary> /// Returns the directional offset of a given direction. /// The offset direction will be exactly one unit in each axis that the direction represents. /// </summary> /// <param name="dir">The direction whose offset to query</param> /// <returns>The direction's offset</returns> public static Point Offset(this Direction2 dir) { switch (dir) { case Up: return new Point(0, -1); case Right: return new Point(1, 0); case Down: return new Point(0, 1); case Left: return new Point(-1, 0); case UpRight: return new Point(1, -1); case DownRight: return new Point(1, 1); case DownLeft: return new Point(-1, 1); case UpLeft: return new Point(-1, -1); default: return Point.Zero; } } /// <summary> /// Maps each direction in the given enumerable of directions to its <see cref="Offset"/>. /// </summary> /// <param name="directions">The direction enumerable</param> /// <returns>The directions' offsets, in the same order as the input directions.</returns> public static IEnumerable<Point> Offsets(this IEnumerable<Direction2> directions) { foreach (var dir in directions) yield return dir.Offset(); } /// <summary> /// Returns the opposite of the given direction. /// For "adjacent" directions, this is the direction that points into the same axis, but the opposite sign. /// For diagonal directions, this is the direction that points into the opposite of both the x and y axis. /// </summary> /// <param name="dir">The direction whose opposite to get</param> /// <returns>The opposite of the direction</returns> public static Direction2 Opposite(this Direction2 dir) { switch (dir) { case Up: return Down; case Right: return Left; case Down: return Up; case Left: return Right; case UpRight: return DownLeft; case DownRight: return UpLeft; case DownLeft: return UpRight; case UpLeft: return DownRight; default: return None; } } /// <summary> /// Returns the angle of the direction in radians, where <see cref="Direction2.Right"/> has an angle of 0. /// </summary> /// <param name="dir">The direction whose angle to get</param> /// <returns>The direction's angle</returns> public static float Angle(this Direction2 dir) { var (x, y) = dir.Offset(); return (float) Math.Atan2(y, x); } /// <summary> /// Rotates the given direction clockwise and returns the resulting direction. /// </summary> /// <param name="dir">The direction to rotate</param> /// <param name="fortyFiveDegrees">Whether to rotate by 45 degrees. If this is false, the rotation is 90 degrees instead.</param> /// <returns>The rotated direction</returns> public static Direction2 RotateCw(this Direction2 dir, bool fortyFiveDegrees = false) { return Clockwise[(ClockwiseLookup[dir] + (fortyFiveDegrees ? 1 : 2)) % Clockwise.Length]; } /// <summary> /// Rotates the given direction counter-clockwise and returns the resulting direction. /// </summary> /// <param name="dir">The direction to rotate counter-clockwise</param> /// <param name="fortyFiveDegrees">Whether to rotate by 45 degrees. If this is false, the rotation is 90 degrees instead.</param> /// <returns>The rotated direction</returns> public static Direction2 RotateCcw(this Direction2 dir, bool fortyFiveDegrees = false) { var index = ClockwiseLookup[dir] - (fortyFiveDegrees ? 1 : 2); return Clockwise[index < 0 ? index + Clockwise.Length : index]; } /// <summary> /// Returns the <see cref="Direction2"/> that is closest to the given position's facing direction. /// </summary> /// <param name="offset">The vector whose corresponding direction to get</param> /// <returns>The vector's direction</returns> public static Direction2 ToDirection(this Vector2 offset) { var offsetAngle = (float) Math.Atan2(offset.Y, offset.X); foreach (var dir in AllExceptNone) { if (Math.Abs(dir.Angle() - offsetAngle) <= MathHelper.PiOver4 / 2) return dir; } return None; } /// <summary> /// Returns the <see cref="Direction2"/> that is closest to the given position's facing direction, only taking <see cref="Adjacent"/> directions into account. /// Diagonal directions will be rounded to the nearest vertical direction. /// </summary> /// <param name="offset">The vector whose corresponding direction to get</param> /// <returns>The vector's direction</returns> public static Direction2 To90Direction(this Vector2 offset) { if (offset.X == 0 && offset.Y == 0) return None; if (Math.Abs(offset.X) > Math.Abs(offset.Y)) return offset.X > 0 ? Right : Left; return offset.Y > 0 ? Down : Up; } /// <summary> /// Rotates the given direction by a given reference direction /// </summary> /// <param name="dir">The direction to rotate</param> /// <param name="reference">The direction to rotate by</param> /// <param name="start">The direction to use as the default direction</param> /// <returns>The direction, rotated by the reference direction</returns> public static Direction2 RotateBy(this Direction2 dir, Direction2 reference, Direction2 start = Up) { var diff = ClockwiseLookup[reference] - ClockwiseLookup[start]; if (diff < 0) diff += Clockwise.Length; return Clockwise[(ClockwiseLookup[dir] + diff) % Clockwise.Length]; } } }<file_sep>/MLEM/Pathfinding/AStar3.cs using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace MLEM.Pathfinding { /// <summary> /// A 3-dimensional implementation of <see cref="AStar{T}"/> that uses <see cref="Vector3"/> for positions. /// </summary> public class AStar3 : AStar<Vector3> { private static readonly Vector3[] AdjacentDirs = { new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1) }; private static readonly Vector3[] AllDirs; static AStar3() { var dirs = new List<Vector3>(); for (var x = -1; x <= 1; x++) { for (var y = -1; y <= 1; y++) { for (var z = -1; z <= 1; z++) { if (x == 0 && y == 0 && z == 0) continue; dirs.Add(new Vector3(x, y, z)); } } } AllDirs = dirs.ToArray(); } /// <inheritdoc /> public AStar3(GetCost defaultCostFunction, bool defaultAllowDiagonals, float defaultCost = 1, int defaultMaxTries = 10000) : base(AllDirs, AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) { } /// <inheritdoc /> protected override Vector3 AddPositions(Vector3 first, Vector3 second) { return first + second; } /// <inheritdoc /> protected override float GetManhattanDistance(Vector3 first, Vector3 second) { return Math.Abs(second.X - first.X) + Math.Abs(second.Y - first.Y) + Math.Abs(second.Z - first.Z); } } }<file_sep>/MLEM/Misc/AutoTiling.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MLEM.Misc { /// <summary> /// This class contains a <see cref="DrawAutoTile"/> method that allows users to easily draw a tile with automatic connections. /// For auto-tiling in this manner to work, auto-tiled textures have to be laid out in a format described in <see cref="DrawAutoTile"/>. /// </summary> public static class AutoTiling { /// <summary> /// This method allows for a tiled texture to be drawn in an auto-tiling mode. /// This allows, for example, a grass patch on a tilemap to have nice looking edges that transfer over into a path without any hard edges between tiles. /// /// For auto-tiling in this way to work, the tiles have to be laid out in a specific order. This order is shown in the auto-tiling demo's textures. /// For more information and an example, see <see href="https://github.com/Ellpeck/MLEM/blob/main/Demos/AutoTilingDemo.cs#L20-L28"/> /// </summary> /// <param name="batch"></param> /// <param name="pos"></param> /// <param name="texture"></param> /// <param name="textureRegion"></param> /// <param name="connectsTo"></param> /// <param name="color"></param> /// <param name="rotation"></param> /// <param name="origin"></param> /// <param name="scale"></param> /// <param name="layerDepth"></param> public static void DrawAutoTile(SpriteBatch batch, Vector2 pos, Texture2D texture, Rectangle textureRegion, ConnectsTo connectsTo, Color color, float rotation = 0, Vector2? origin = null, Vector2? scale = null, float layerDepth = 0) { var org = origin ?? Vector2.Zero; var sc = scale ?? Vector2.One; var up = connectsTo(0, -1); var down = connectsTo(0, 1); var left = connectsTo(-1, 0); var right = connectsTo(1, 0); var xUl = up && left ? connectsTo(-1, -1) ? 0 : 4 : left ? 1 : up ? 3 : 2; var xUr = up && right ? connectsTo(1, -1) ? 0 : 4 : right ? 1 : up ? 3 : 2; var xDl = down && left ? connectsTo(-1, 1) ? 0 : 4 : left ? 1 : down ? 3 : 2; var xDr = down && right ? connectsTo(1, 1) ? 0 : 4 : right ? 1 : down ? 3 : 2; var (w, h) = textureRegion.Size; var (w2, h2) = new Point(w / 2, h / 2); batch.Draw(texture, new Vector2(pos.X, pos.Y), new Rectangle(textureRegion.X + 0 + xUl * w, textureRegion.Y + 0, w2, h2), color, rotation, org, sc, SpriteEffects.None, layerDepth); batch.Draw(texture, new Vector2(pos.X + 0.5F * w * sc.X, pos.Y), new Rectangle(textureRegion.X + w2 + xUr * w, textureRegion.Y + 0, w2, h2), color, rotation, org, sc, SpriteEffects.None, layerDepth); batch.Draw(texture, new Vector2(pos.X, pos.Y + 0.5F * h * sc.Y), new Rectangle(textureRegion.X + xDl * w, textureRegion.Y + h2, w2, h2), color, rotation, org, sc, SpriteEffects.None, layerDepth); batch.Draw(texture, new Vector2(pos.X + 0.5F * w * sc.X, pos.Y + 0.5F * h * sc.Y), new Rectangle(textureRegion.X + w2 + xDr * w, textureRegion.Y + h2, w2, h2), color, rotation, org, sc, SpriteEffects.None, layerDepth); } /// <summary> /// A delegate function that determines if a given offset position connects to an auto-tile location. /// </summary> /// <param name="xOff">The x offset</param> /// <param name="yOff">The y offset</param> public delegate bool ConnectsTo(int xOff, int yOff); } }<file_sep>/build.cake #addin Cake.DocFx&version=1.0.0 #tool docfx.console&version=2.51.0 // this is the upcoming version, for prereleases var version = Argument("version", "5.1.0"); var target = Argument("target", "Default"); var branch = Argument("branch", "main"); var config = Argument("configuration", "Release"); Task("Prepare").Does(() => { DotNetCoreRestore("MLEM.sln"); if (branch != "release") { var buildNum = EnvironmentVariable("BUILD_NUMBER"); if (buildNum != null) version += "-" + buildNum; } DeleteFiles("**/*.nupkg"); }); Task("Build").IsDependentOn("Prepare").Does(() =>{ var settings = new DotNetCoreBuildSettings { Configuration = config, ArgumentCustomization = args => args.Append($"/p:Version={version}") }; foreach (var project in GetFiles("**/MLEM*.csproj")) DotNetCoreBuild(project.FullPath, settings); DotNetCoreBuild("Demos/Demos.csproj", settings); }); Task("Test").IsDependentOn("Build").Does(() => { DotNetCoreTest("Tests/Tests.csproj", new DotNetCoreTestSettings { Configuration = config, Collectors = {"XPlat Code Coverage"} }); }); Task("Pack").IsDependentOn("Test").Does(() => { var settings = new DotNetCorePackSettings { Configuration = config, ArgumentCustomization = args => args.Append($"/p:Version={version}") }; foreach (var project in GetFiles("**/MLEM*.csproj")) DotNetCorePack(project.FullPath, settings); }); Task("Push").WithCriteria(branch == "main" || branch == "release").IsDependentOn("Pack").Does(() => { NuGetPushSettings settings; if (branch == "release") { settings = new NuGetPushSettings { Source = "https://api.nuget.org/v3/index.json", ApiKey = EnvironmentVariable("NUGET") }; } else { settings = new NuGetPushSettings { Source = "http://localhost:5000/v3/index.json", ApiKey = EnvironmentVariable("BAGET") }; } settings.SkipDuplicate = true; NuGetPush(GetFiles("**/*.nupkg"), settings); }); Task("Document").Does(() => { var path = "Docs/docfx.json"; DocFxMetadata(path); DocFxBuild(path); }); Task("Default").IsDependentOn("Pack"); Task("Publish").IsDependentOn("Push"); RunTarget(target);<file_sep>/CHANGELOG.md # Changelog MLEM uses [semantic versioning](https://semver.org/). Jump to version: - [5.1.0 (Unreleased)](#510-unreleased) - [5.0.0](#500) ## 5.1.0 (Unreleased) ### MLEM Additions - Added RotateBy to Direction2Helper Fixes - Set default values for InputHandler held and pressed keys to avoid an exception if buttons are held in the very first frame Improvements - Improved NinePatch memory performance - Moved sound-related classes into Sound namespace ### MLEM.Ui Additions - Added a masking character to TextField to allow for password-style text fields Fixes - Fixed a crash if a paragraph has a link formatting code, but no font ## 5.0.0 ### MLEM Additions - Added some Collection extensions, namely for dealing with combinations - Added repeat-ignoring versions of IsKeyPressed and IsGamepadButtonPressed - Added SoundExtensions - Added string truncation to TokenizedString - Added a sprite batch extension to generate a gradient - Added InputsDown and InputsPressed properties to InputHandler - Added text alignment options to tokenized strings Improvements - Allow NinePatches to be drawn tiled rather than stretched - Added the ability for Direction2 to be used as flags - Made Padding and Direction2 DataContracts - Expose the viewport of cameras - Greatly improved the efficiency of line splitting for GenericFont and TokenizedString - Improved performance of TextFormatter tokenization - Replaced TextInputWrapper with a more refined MlemPlatform that includes the ability to open links on various platforms - Allow for underline and shadow formatting codes to be mixed with font changing codes - Exposed Keybind Combinations Fixes - Fixed the input handler querying input when the window is inactive - Fixed UnderlineCode ending in the wrong places because it was marked as a font-changing code Removals - Removed the array-based GetRandomEntry method - Removed obsolete ColorExtension methods ### MLEM.Ui Additions - Added a text scale multiplier value to Paragraph - Added an option to limit auto-height and auto-width in elements to a maximum and minimum size - Added the ability to set a custom viewport for ui systems - Added string truncation to Paragraph - Added a simple way to change the action that is executed when a link is pressed in a paragraph - Added events for when a root element is added or removed - Added an ElementHelper method to create a keybind button - Added text alignment options to paragraphs Improvements - Stop a panel's scroll bar from being removed from its children list automatically - Removed unnecessary GraphicsDevice references from UiSystem - Dispose of panels' render targets to avoid memory leaks - Allow changing the color that a panel renders its texture with Fixes - Fixed auto-sized elements doing too many area update calculations - Fixed a rare stack overflow where scroll bars could get stuck in an auto-hide loop - Fixed auto-sized elements without children not updating their size correctly - Fixed panels drawing children early within the render target (instead of regularly) ### MLEM.Extended Additions - Added GenericFont compatibility for FontStashSharp - Added a method to make sidescrolling collision detection easier with TiledMapCollisions - Added some more TiledMapExtension utility methods Improvements - Reversed the y loop in GetCollidingTiles to account for gravity which is usually more important Fixes - Fixed some number parsing not using the invariant culture ### MLEM.Data Additions - Added StaticJsonConverter - Added DynamicEnum, a cursed custom enumeration class that supports arbitrarily many values Fixes - Fixed some number parsing not using the invariant culture - Fixed RawContentManager crashing with dynamic assemblies present<file_sep>/MLEM/Input/GenericInput.cs using System; using System.Runtime.Serialization; using Microsoft.Xna.Framework.Input; namespace MLEM.Input { /// <summary> /// A generic input represents any kind of input key. /// This includes <see cref="Keys"/> for keyboard keys, <see cref="MouseButton"/> for mouse buttons and <see cref="Buttons"/> for gamepad buttons. /// For creating and extracting inputs from a generic input, the implicit operators and <see cref="Type"/> can be used. /// Note that this type is serializable using <see cref="DataContractAttribute"/>. /// </summary> [DataContract] public readonly struct GenericInput { /// <summary> /// The <see cref="InputType"/> of this generic input's current <see cref="value"/>. /// </summary> [DataMember] public readonly InputType Type; [DataMember] private readonly int value; private GenericInput(InputType type, int value) { this.Type = type; this.value = value; } /// <inheritdoc /> public override string ToString() { var ret = this.Type.ToString(); switch (this.Type) { case InputType.Mouse: ret += ((MouseButton) this).ToString(); break; case InputType.Keyboard: ret += ((Keys) this).ToString(); break; case InputType.Gamepad: ret += ((Buttons) this).ToString(); break; } return ret; } /// <inheritdoc /> public override bool Equals(object obj) { return obj is GenericInput o && this.Type == o.Type && this.value == o.value; } /// <inheritdoc /> public override int GetHashCode() { return ((int) this.Type * 397) ^ this.value; } /// <summary> /// Compares the two generic input instances for equality using <see cref="Equals"/> /// </summary> /// <param name="left">The left input</param> /// <param name="right">The right input</param> /// <returns>Whether the two generic inputs are equal</returns> public static bool operator ==(GenericInput left, GenericInput right) { return left.Equals(right); } /// <summary> /// Compares the two generic input instances for inequality using <see cref="Equals"/> /// </summary> /// <param name="left">The left input</param> /// <param name="right">The right input</param> /// <returns>Whether the two generic inputs are not equal</returns> public static bool operator !=(GenericInput left, GenericInput right) { return !left.Equals(right); } /// <summary> /// Converts a <see cref="Keys"/> to a generic input. /// </summary> /// <param name="keys">The keys to convert</param> /// <returns>The resulting generic input</returns> public static implicit operator GenericInput(Keys keys) { return new GenericInput(InputType.Keyboard, (int) keys); } /// <summary> /// Converts a <see cref="MouseButton"/> to a generic input. /// </summary> /// <param name="button">The button to convert</param> /// <returns>The resulting generic input</returns> public static implicit operator GenericInput(MouseButton button) { return new GenericInput(InputType.Mouse, (int) button); } /// <summary> /// Converts a <see cref="Buttons"/> to a generic input. /// </summary> /// <param name="buttons">The buttons to convert</param> /// <returns>The resulting generic input</returns> public static implicit operator GenericInput(Buttons buttons) { return new GenericInput(InputType.Gamepad, (int) buttons); } /// <summary> /// Converts a generic input to a <see cref="Keys"/>. /// </summary> /// <param name="input">The input to convert</param> /// <returns>The resulting keys</returns> /// <exception cref="ArgumentException">If the given generic input's <see cref="Type"/> is not <see cref="InputType.Keyboard"/> or <see cref="InputType.None"/></exception> public static implicit operator Keys(GenericInput input) { if (input.Type == InputType.None) return Keys.None; return input.Type == InputType.Keyboard ? (Keys) input.value : throw new ArgumentException(); } /// <summary> /// Converts a generic input to a <see cref="MouseButton"/>. /// </summary> /// <param name="input">The input to convert</param> /// <returns>The resulting button</returns> /// <exception cref="ArgumentException">If the given generic input's <see cref="Type"/> is not <see cref="InputType.Mouse"/></exception> public static implicit operator MouseButton(GenericInput input) { return input.Type == InputType.Mouse ? (MouseButton) input.value : throw new ArgumentException(); } /// <summary> /// Converts a generic input to a <see cref="Buttons"/>. /// </summary> /// <param name="input">The input to convert</param> /// <returns>The resulting buttons</returns> /// <exception cref="ArgumentException">If the given generic input's <see cref="Type"/> is not <see cref="InputType.Gamepad"/></exception> public static implicit operator Buttons(GenericInput input) { return input.Type == InputType.Gamepad ? (Buttons) input.value : throw new ArgumentException(); } /// <summary> /// A type of input button. /// </summary> [DataContract] public enum InputType { /// <summary> /// A type representing no value /// </summary> [EnumMember] None, /// <summary> /// A type representing <see cref="MouseButton"/> /// </summary> [EnumMember] Mouse, /// <summary> /// A type representing <see cref="Keys"/> /// </summary> [EnumMember] Keyboard, /// <summary> /// A type representing <see cref="Buttons"/> /// </summary> [EnumMember] Gamepad } } }<file_sep>/MLEM.Extended/Font/GenericBitmapFont.cs using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Font; using MonoGame.Extended.BitmapFonts; namespace MLEM.Extended.Font { /// <inheritdoc/> public class GenericBitmapFont : GenericFont { /// <summary> /// The <see cref="BitmapFont"/> that is being wrapped by this generic font /// </summary> public readonly BitmapFont Font; /// <inheritdoc/> public override GenericFont Bold { get; } /// <inheritdoc/> public override GenericFont Italic { get; } /// <inheritdoc/> public override float LineHeight => this.Font.LineHeight; /// <summary> /// Creates a new generic font using <see cref="BitmapFont"/>. /// Optionally, a bold and italic version of the font can be supplied. /// </summary> /// <param name="font">The font to wrap</param> /// <param name="bold">A bold version of the font</param> /// <param name="italic">An italic version of the font</param> public GenericBitmapFont(BitmapFont font, BitmapFont bold = null, BitmapFont italic = null) { this.Font = font; this.Bold = bold != null ? new GenericBitmapFont(bold) : this; this.Italic = italic != null ? new GenericBitmapFont(italic) : this; } /// <inheritdoc /> protected override Vector2 MeasureChar(char c) { var region = this.Font.GetCharacterRegion(c); return region != null ? new Vector2(region.XAdvance, region.Height) : Vector2.Zero; } /// <inheritdoc/> public override void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { batch.DrawString(this.Font, text, position, color, rotation, origin, scale, effects, layerDepth); } /// <inheritdoc/> public override void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { batch.DrawString(this.Font, text, position, color, rotation, origin, scale, effects, layerDepth); } } }<file_sep>/MLEM/Animations/SpriteAnimation.cs using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Misc; using MLEM.Textures; namespace MLEM.Animations { /// <summary> /// A sprite animation that allows for any number of frames that each last any number of seconds /// </summary> public class SpriteAnimation : GenericDataHolder { private readonly AnimationFrame[] frames; /// <summary> /// Returns the <see cref="AnimationFrame"/> at the given index. /// Index ordering is based on the order that animation frames were added in. /// </summary> /// <param name="index">The index in the list of animation frames</param> public AnimationFrame this[int index] => this.frames[index]; /// <summary> /// The frame that the animation is currently on. /// </summary> public AnimationFrame CurrentFrame { get { // we might have overshot the end time by a little bit, so just return the last frame if (this.TimeIntoAnimation >= this.TotalTime) return this.frames[this.frames.Length - 1]; var accum = 0D; foreach (var frame in this.frames) { accum += frame.Seconds; if (accum >= this.TimeIntoAnimation) return frame; } // if we're here then the time is negative for some reason, so just return the first frame return this.frames[0]; } } /// <summary> /// The texture region that the animation's <see cref="CurrentFrame"/> has /// </summary> public TextureRegion CurrentRegion => this.CurrentFrame.Region; /// <summary> /// The total amount of time that this animation has. /// This is auatomatically calculated based on the frame time of each frame. /// </summary> public readonly double TotalTime; /// <summary> /// The amount of seconds that the animation has been going on for. /// If <see cref="TotalTime"/> is reached, this value resets to 0. /// </summary> public double TimeIntoAnimation { get; private set; } /// <summary> /// The finished state of this animation. /// This is only true for longer than a frame if <see cref="IsLooping"/> is false. /// </summary> public bool IsFinished { get; private set; } /// <summary> /// The name of this animation. This is useful if used in combination with <see cref="SpriteAnimationGroup"/>. /// </summary> public string Name; /// <summary> /// The speed multiplier that this animation should run with. /// Numbers higher than 1 will increase the speed. /// </summary> public float SpeedMultiplier = 1; /// <summary> /// Set to false to stop this animation from looping. /// To check if the animation has finished playing, see <see cref="IsFinished"/>. /// </summary> public bool IsLooping = true; /// <summary> /// A callback that gets fired when the animation completes. /// </summary> public event Completed OnCompleted; /// <summary> /// Set this to true to pause the playback of the animation. /// <see cref="TimeIntoAnimation"/> will not continue and the <see cref="CurrentFrame"/> will not change. /// </summary> public bool IsPaused; /// <summary> /// Creates a new sprite animation that contains the given frames. /// </summary> /// <param name="frames">The frames this animation should have</param> public SpriteAnimation(params AnimationFrame[] frames) { this.frames = frames; foreach (var frame in frames) this.TotalTime += frame.Seconds; } /// <summary> /// Creates a new sprite animation that contains the given texture regions as frames. /// </summary> /// <param name="timePerFrame">The amount of time that each frame should last for</param> /// <param name="regions">The texture regions that should make up this animation</param> public SpriteAnimation(double timePerFrame, params TextureRegion[] regions) : this(Array.ConvertAll(regions, region => new AnimationFrame(region, timePerFrame))) { } /// <summary> /// Creates a new sprite animation based on the given texture regions in rectangle-based format. /// </summary> /// <param name="timePerFrame">The amount of time that each frame should last for</param> /// <param name="texture">The texture that the regions should come from</param> /// <param name="regions">The texture regions that should make up this animation</param> public SpriteAnimation(double timePerFrame, Texture2D texture, params Rectangle[] regions) : this(timePerFrame, Array.ConvertAll(regions, region => new TextureRegion(texture, region))) { } /// <summary> /// Updates this animation, causing <see cref="TimeIntoAnimation"/> to be increased and the <see cref="CurrentFrame"/> to be updated. /// </summary> /// <param name="time">The game's time</param> public void Update(GameTime time) { this.Update(time.ElapsedGameTime); } /// <summary> /// Updates this animation, causing <see cref="TimeIntoAnimation"/> to be increased and the <see cref="CurrentFrame"/> to be updated. /// </summary> /// <param name="elapsed">The amount of time that has passed</param> public void Update(TimeSpan elapsed) { if (this.IsFinished || this.IsPaused) return; this.TimeIntoAnimation += elapsed.TotalSeconds * this.SpeedMultiplier; if (this.TimeIntoAnimation >= this.TotalTime) { if (!this.IsLooping) { this.IsFinished = true; } else { this.Restart(); } this.OnCompleted?.Invoke(this); } } /// <summary> /// Restarts this animation from the first frame. /// </summary> public void Restart() { this.TimeIntoAnimation = 0; this.IsFinished = false; this.IsPaused = false; } /// <summary> /// A callback for when a sprite animation is completed. /// </summary> /// <param name="animation">The animation that has completed</param> public delegate void Completed(SpriteAnimation animation); } /// <summary> /// Represents a single frame of a <see cref="SpriteAnimation"/> /// </summary> public class AnimationFrame { /// <summary> /// The texture region that this frame should render /// </summary> public readonly TextureRegion Region; /// <summary> /// The total amount of seconds that this frame should last for /// </summary> public readonly double Seconds; /// <summary> /// Creates a new animation frame based on a texture region and a time /// </summary> /// <param name="region">The texture region that this frame should render</param> /// <param name="seconds">The total amount of seconds that this frame should last for</param> public AnimationFrame(TextureRegion region, double seconds) { this.Region = region; this.Seconds = seconds; } } }<file_sep>/MLEM.Extended/Tiled/LayerPosition.cs using System.Runtime.Serialization; using MonoGame.Extended.Tiled; namespace MLEM.Extended.Tiled { /// <summary> /// A struct that represents a position on a <see cref="TiledMap"/> with multiple layers. /// </summary> [DataContract] public struct LayerPosition { /// <summary> /// The name of the layer that this position is on /// </summary> [DataMember] public string Layer; /// <summary> /// The x coordinate of this position /// </summary> [DataMember] public int X; /// <summary> /// The y coordinate of this position /// </summary> [DataMember] public int Y; /// <summary> /// Creates a new layer position with the given settings /// </summary> /// <param name="layerName">The layer name</param> /// <param name="x">The x coordinate</param> /// <param name="y">The y coordinate</param> public LayerPosition(string layerName, int x, int y) { this.Layer = layerName; this.X = x; this.Y = y; } /// <inheritdoc cref="Equals(LayerPosition)"/> public static bool operator ==(LayerPosition left, LayerPosition right) { return left.Equals(right); } /// <inheritdoc cref="Equals(LayerPosition)"/> public static bool operator !=(LayerPosition left, LayerPosition right) { return !left.Equals(right); } /// <inheritdoc cref="Equals(object)"/> public bool Equals(LayerPosition other) { return this.Layer == other.Layer && this.X == other.X && this.Y == other.Y; } /// <inheritdoc /> public override bool Equals(object obj) { return obj is LayerPosition other && this.Equals(other); } /// <inheritdoc /> public override int GetHashCode() { var hashCode = this.Layer.GetHashCode(); hashCode = (hashCode * 397) ^ this.X; hashCode = (hashCode * 397) ^ this.Y; return hashCode; } /// <inheritdoc /> public override string ToString() { return $"{nameof(this.Layer)}: {this.Layer}, {nameof(this.X)}: {this.X}, {nameof(this.Y)}: {this.Y}"; } } }<file_sep>/MLEM/Formatting/Codes/ResetFormattingCode.cs using System.Text.RegularExpressions; namespace MLEM.Formatting.Codes { /// <inheritdoc /> public class ResetFormattingCode : Code { /// <inheritdoc /> public ResetFormattingCode(Match match, Regex regex) : base(match, regex) { } /// <inheritdoc /> public override bool EndsHere(Code other) { return true; } } }<file_sep>/MLEM/Formatting/Token.cs using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Font; using MLEM.Formatting.Codes; using MLEM.Misc; namespace MLEM.Formatting { /// <summary> /// A part of a <see cref="TokenizedString"/> that has a certain list of formatting codes applied. /// </summary> public class Token : GenericDataHolder { /// <summary> /// The formatting codes that are applied on this token. /// </summary> public readonly Code[] AppliedCodes; /// <summary> /// The index in the <see cref="Substring"/> that this token starts at. /// </summary> public readonly int Index; /// <summary> /// The index in the <see cref="RawSubstring"/> that this token starts at. /// </summary> public readonly int RawIndex; /// <summary> /// The substring that this token contains. /// </summary> public readonly string Substring; /// <summary> /// The string that is displayed by this token. If the tokenized string has been <see cref="TokenizedString.Split"/> or <see cref="TokenizedString.Truncate"/> has been used, this string will contain the newline characters. /// </summary> public string DisplayString => this.ModifiedSubstring ?? this.Substring; /// <summary> /// The <see cref="DisplayString"/>, but split at newline characters /// </summary> public string[] SplitDisplayString { get; internal set; } /// <summary> /// The substring that this token contains, without the formatting codes removed. /// </summary> public readonly string RawSubstring; internal RectangleF[] Area; internal string ModifiedSubstring; internal Token(Code[] appliedCodes, int index, int rawIndex, string substring, string rawSubstring) { this.AppliedCodes = appliedCodes; this.Index = index; this.RawIndex = rawIndex; this.Substring = substring; this.RawSubstring = rawSubstring; foreach (var code in appliedCodes) code.Token = this; } /// <summary> /// Get the color that this token will be rendered with /// </summary> /// <param name="defaultPick">The default color, if none is specified</param> /// <returns>The color to render with</returns> public Color? GetColor(Color defaultPick) { return this.AppliedCodes.Select(c => c.GetColor(defaultPick)).FirstOrDefault(c => c.HasValue); } /// <summary> /// Get the font that this token will be rendered with /// </summary> /// <param name="defaultPick">The default font, if none is specified</param> /// <returns>The font to render with</returns> public GenericFont GetFont(GenericFont defaultPick) { return this.AppliedCodes.Select(c => c.GetFont(defaultPick)).FirstOrDefault(f => f != null); } /// <summary> /// Draws the token itself, including all of the <see cref="Code"/> instances that this token contains. /// Note that, to draw the token's actual string, <see cref="DrawCharacter"/> is used. /// </summary> /// <param name="time">The time</param> /// <param name="batch">The sprite batch to use</param> /// <param name="pos">The position to draw the token at</param> /// <param name="font">The font to use to draw</param> /// <param name="color">The color to draw with</param> /// <param name="scale">The scale to draw at</param> /// <param name="depth">The depth to draw at</param> public void DrawSelf(GameTime time, SpriteBatch batch, Vector2 pos, GenericFont font, Color color, float scale, float depth) { foreach (var code in this.AppliedCodes) code.DrawSelf(time, batch, pos, font, color, scale, depth); } /// <summary> /// Draws a given character using this token's formatting options. /// </summary> /// <param name="time">The time</param> /// <param name="batch">The sprite batch to use</param> /// <param name="c">The character to draw</param> /// <param name="cString">A single-character string that contains the character to draw</param> /// <param name="indexInToken">The index within this token that the character is at</param> /// <param name="pos">The position to draw the token at</param> /// <param name="font">The font to use to draw</param> /// <param name="color">The color to draw with</param> /// <param name="scale">The scale to draw at</param> /// <param name="depth">The depth to draw at</param> public void DrawCharacter(GameTime time, SpriteBatch batch, char c, string cString, int indexInToken, Vector2 pos, GenericFont font, Color color, float scale, float depth) { foreach (var code in this.AppliedCodes) { if (code.DrawCharacter(time, batch, c, cString, indexInToken, ref pos, font, ref color, ref scale, depth)) return; } // if no code drew, we have to do it ourselves font.DrawString(batch, cString, pos, color, 0, Vector2.Zero, scale, SpriteEffects.None, depth); } /// <summary> /// Gets a list of rectangles that encompass this token's area. /// Note that more than one rectangle is only returned if the string has been split. /// This can be used to invoke events when the mouse is hovered over the token, for example. /// </summary> /// <param name="stringPos">The position that the string is drawn at</param> /// <param name="scale">The scale that the string is drawn at</param> /// <returns>A set of rectangles that this token contains</returns> public IEnumerable<RectangleF> GetArea(Vector2 stringPos, float scale) { return this.Area.Select(a => new RectangleF(stringPos + a.Location * scale, a.Size * scale)); } } }<file_sep>/Utilities/Populate Data Texture Atlas.lua -- This is a lua script for Aseprite that allows automatically populating a MLEM.Data Data Texture Atlas. -- To use this script, you need to select a rectangular area that should be your texture region. -- If you want a custom pivot point, you also need to un-select exactly one pixel, the pivot point. -- When you then execute the script and input the name of the texture region, it gets appended to the "SpriteName.atlas" file. -- get the currently selected sprite local selection = app.activeSprite.selection if selection == nil then return end local bounds = selection.bounds local loc = "loc "..bounds.x.." "..bounds.y.." "..bounds.width.." "..bounds.height.."\n" local piv = "" -- find the pivot point, which should be the only de-selected pixel in the selection for x = bounds.x, bounds.x + bounds.width - 1 do for y = bounds.y, bounds.y + bounds.height - 1 do if not selection:contains(x, y) then piv = "piv "..x.." "..y.."\n" goto foundPivot end end end ::foundPivot:: -- open the name dialog local dialog = Dialog("Populate Data Texture Atlas") :entry{ id = "name", label = "Region Name", focus = true } :button{ id = "ok", text="&OK" } :button{ text = "&Cancel" } dialog:show() local data = dialog.data if not data.ok then return end local name = data.name -- get the atlas file and write the data to it local spriteFile = app.activeSprite.filename local atlas = spriteFile:match("(.+)%..+")..".atlas" local file = io.open(atlas, "a") file:write("\n"..name.."\n"..loc..piv) file:close()<file_sep>/MLEM.Data/Content/RawContentManager.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace MLEM.Data.Content { /// <summary> /// Represents a version of <see cref="ContentManager"/> that doesn't load content binary <c>xnb</c> files, but rather as their regular formats. /// </summary> public class RawContentManager : ContentManager, IGameComponent { private static readonly RawContentReader[] Readers = AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .SelectMany(a => a.GetExportedTypes()) .Where(t => t.IsSubclassOf(typeof(RawContentReader)) && !t.IsAbstract) .Select(t => t.GetConstructor(Type.EmptyTypes).Invoke(null)) .Cast<RawContentReader>().ToArray(); private readonly List<IDisposable> disposableAssets = new List<IDisposable>(); /// <summary> /// The graphics device that this content manager uses /// </summary> public readonly GraphicsDevice GraphicsDevice; /// <summary> /// Creates a new content manager with an optionally specified root directory. /// </summary> /// <param name="serviceProvider">The service provider of your game</param> /// <param name="rootDirectory">The root directory. Defaults to "Content"</param> public RawContentManager(IServiceProvider serviceProvider, string rootDirectory = "Content") : base(serviceProvider, rootDirectory) { if (serviceProvider.GetService(typeof(IGraphicsDeviceService)) is IGraphicsDeviceService s) this.GraphicsDevice = s.GraphicsDevice; } /// <summary> /// Loads a raw asset with the given name, based on the <see cref="ContentManager.RootDirectory"/>. /// If the asset was previously loaded using this method, the cached asset is merely returned. /// </summary> /// <param name="assetName">The path and name of the asset to load, without extension.</param> /// <typeparam name="T">The type of asset to load</typeparam> /// <returns>The asset, either loaded from the cache, or from disk.</returns> public override T Load<T>(string assetName) { if (this.LoadedAssets.TryGetValue(assetName, out var ret) && ret is T t) return t; return this.Read<T>(assetName, default); } /// <inheritdoc/> protected override void ReloadAsset<T>(string originalAssetName, T currentAsset) { this.Read(originalAssetName, currentAsset); } private T Read<T>(string assetName, T existing) { var triedFiles = new List<string>(); foreach (var reader in Readers.Where(r => r.CanRead(typeof(T)))) { foreach (var ext in reader.GetFileExtensions()) { var file = Path.Combine(this.RootDirectory, $"{assetName}.{ext}"); triedFiles.Add(file); if (!File.Exists(file)) continue; using (var stream = File.OpenRead(file)) { var read = reader.Read(this, assetName, stream, typeof(T), existing); if (!(read is T t)) throw new ContentLoadException($"{reader} returned non-{typeof(T)} for asset {assetName}"); this.LoadedAssets[assetName] = t; if (t is IDisposable d && !this.disposableAssets.Contains(d)) this.disposableAssets.Add(d); return t; } } } throw new ContentLoadException($"Asset {assetName} not found. Tried files {string.Join(", ", triedFiles)}"); } /// <inheritdoc/> public override void Unload() { foreach (var d in this.disposableAssets) d.Dispose(); this.disposableAssets.Clear(); base.Unload(); } /// <inheritdoc/> public void Initialize() { } } }<file_sep>/MLEM.Data/Content/XmlReader.cs using System; using System.IO; using System.Xml.Serialization; namespace MLEM.Data.Content { /// <inheritdoc /> public class XmlReader : RawContentReader { /// <inheritdoc /> public override bool CanRead(Type t) { return true; } /// <inheritdoc /> public override object Read(RawContentManager manager, string assetPath, Stream stream, Type t, object existing) { return new XmlSerializer(t).Deserialize(stream); } /// <inheritdoc /> public override string[] GetFileExtensions() { return new[] {"xml"}; } } }<file_sep>/MLEM.Ui/Style/StyleProp.cs using System.Collections.Generic; using MLEM.Ui.Elements; namespace MLEM.Ui.Style { /// <summary> /// A struct used by <see cref="Element"/> to store style properties. /// This is a helper struct that allows default style settings from <see cref="UiStyle"/> to be overridden by custom user settings easily. /// Note that <c>T</c> implicitly converts to <c>StyleProp{T}</c> and vice versa. /// </summary> /// <typeparam name="T">The type of style setting that this property stores</typeparam> public struct StyleProp<T> { /// <summary> /// The currently applied style /// </summary> public T Value { get; private set; } private bool isCustom; /// <summary> /// Creates a new style property with the given custom style. /// </summary> /// <param name="value">The custom style to apply</param> public StyleProp(T value) { this.isCustom = true; this.Value = value; } /// <summary> /// Sets this style property's value and marks it as being set by a <see cref="UiStyle"/>. /// This allows this property to be overridden by custom style settings using <see cref="Set"/>. /// </summary> /// <param name="value">The style to apply</param> public void SetFromStyle(T value) { if (!this.isCustom) { this.Value = value; } } /// <summary> /// Sets this style property's value and marks it as being custom. /// This causes <see cref="SetFromStyle"/> not to override the style value through a <see cref="UiStyle"/>. /// </summary> /// <param name="value"></param> public void Set(T value) { this.isCustom = true; this.Value = value; } /// <summary> /// Returns the current style value or, if <see cref="HasValue"/> is false, the given default value. /// </summary> /// <param name="def">The default to return if this style property has no value</param> /// <returns>The current value, or the default</returns> public T OrDefault(T def) { return this.HasValue() ? this.Value : def; } /// <summary> /// Returns whether this style property has a value assigned to it using <see cref="SetFromStyle"/> or <see cref="Set"/>. /// </summary> /// <returns>Whether this style property has a value</returns> public bool HasValue() { return !EqualityComparer<T>.Default.Equals(this.Value, default); } /// <summary> /// Implicitly converts a style property to its value. /// </summary> /// <param name="prop">The property to convert</param> /// <returns>The style that the style property holds</returns> public static implicit operator T(StyleProp<T> prop) { return prop.Value; } /// <summary> /// Implicitly converts a style to a style property. /// </summary> /// <param name="prop">The property to convert</param> /// <returns>A style property with the given style value</returns> public static implicit operator StyleProp<T>(T prop) { return new StyleProp<T>(prop); } } }<file_sep>/MLEM.Extended/Extensions/NumberExtensions.cs using Microsoft.Xna.Framework; using MLEM.Extensions; using MonoGame.Extended; namespace MLEM.Extended.Extensions { /// <summary> /// A set of extension methods that convert MLEM types to MonoGame.Extended types and vice versa. /// </summary> public static class NumberExtensions { /// <summary> /// Converts a MLEM <see cref="Misc.RectangleF"/> to a MonoGame.Extended <see cref="RectangleF"/>. /// </summary> /// <param name="rect">The rectangle to convert</param> /// <returns>The converted rectangle</returns> public static RectangleF ToExtended(this Misc.RectangleF rect) { return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Converts a MonoGame.Extended <see cref="RectangleF"/> to a MLEM <see cref="Misc.RectangleF"/>. /// </summary> /// <param name="rect">The rectangle to convert</param> /// <returns>The converted rectangle</returns> public static Misc.RectangleF ToMlem(this RectangleF rect) { return new Misc.RectangleF(rect.X, rect.Y, rect.Width, rect.Height); } /// <inheritdoc cref="MLEM.Extensions.NumberExtensions.Penetrate"/> public static bool Penetrate(this RectangleF rect, RectangleF other, out Vector2 normal, out float penetration) { return rect.ToMlem().Penetrate(other.ToMlem(), out normal, out penetration); } } }<file_sep>/MLEM/Textures/NinePatch.cs using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Misc; namespace MLEM.Textures { /// <summary> /// This class represents a texture with nine areas. /// A nine patch texture is useful if a big area should be covered by a small texture that has a specific outline, like a gui panel texture. The center of the texture will be stretched or tiled, while the outline of the texture will remain at its original size, keeping aspect ratios alive. /// The nine patch can then be drawn using <see cref="NinePatchExtensions"/>. /// </summary> public class NinePatch : GenericDataHolder { /// <summary> /// The texture region of this nine patch /// </summary> public readonly TextureRegion Region; /// <summary> /// The padding in each direction that marks where the outline area stops /// </summary> public readonly Padding Padding; /// <summary> /// The <see cref="NinePatchMode"/> that this nine patch should use for drawing /// </summary> public readonly NinePatchMode Mode; /// <summary> /// The nine patches that result from the <see cref="Padding"/> /// </summary> public readonly Rectangle[] SourceRectangles; /// <summary> /// Creates a new nine patch from a texture and a padding /// </summary> /// <param name="texture">The texture to use</param> /// <param name="padding">The padding that marks where the outline area stops</param> /// <param name="mode">The mode to use for drawing this nine patch, defaults to <see cref="NinePatchMode.Stretch"/></param> public NinePatch(TextureRegion texture, Padding padding, NinePatchMode mode = NinePatchMode.Stretch) { this.Region = texture; this.Padding = padding; this.Mode = mode; this.SourceRectangles = new Rectangle[9]; for (var i = 0; i < this.SourceRectangles.Length; i++) this.SourceRectangles[i] = (Rectangle) this.GetRectangleForIndex((RectangleF) this.Region.Area, i); } /// <summary> /// Creates a new nine patch from a texture and a padding /// </summary> /// <param name="texture">The texture to use</param> /// <param name="paddingLeft">The padding on the left edge</param> /// <param name="paddingRight">The padding on the right edge</param> /// <param name="paddingTop">The padding on the top edge</param> /// <param name="paddingBottom">The padding on the bottom edge</param> /// <param name="mode">The mode to use for drawing this nine patch, defaults to <see cref="NinePatchMode.Stretch"/></param> public NinePatch(TextureRegion texture, int paddingLeft, int paddingRight, int paddingTop, int paddingBottom, NinePatchMode mode = NinePatchMode.Stretch) : this(texture, new Padding(paddingLeft, paddingRight, paddingTop, paddingBottom), mode) { } /// <inheritdoc cref="NinePatch(TextureRegion, int, int, int, int, NinePatchMode)"/> public NinePatch(Texture2D texture, int paddingLeft, int paddingRight, int paddingTop, int paddingBottom, NinePatchMode mode = NinePatchMode.Stretch) : this(new TextureRegion(texture), paddingLeft, paddingRight, paddingTop, paddingBottom, mode) { } /// <summary> /// Creates a new nine patch from a texture and a uniform padding /// </summary> /// <param name="texture">The texture to use</param> /// <param name="padding">The padding that each edge should have</param> /// <param name="mode">The mode to use for drawing this nine patch, defaults to <see cref="NinePatchMode.Stretch"/></param> public NinePatch(Texture2D texture, int padding, NinePatchMode mode = NinePatchMode.Stretch) : this(new TextureRegion(texture), padding, mode) { } /// <inheritdoc cref="NinePatch(TextureRegion, int, NinePatchMode)"/> public NinePatch(TextureRegion texture, int padding, NinePatchMode mode = NinePatchMode.Stretch) : this(texture, padding, padding, padding, padding, mode) { } internal RectangleF GetRectangleForIndex(RectangleF area, int index, float patchScale = 1) { var pl = this.Padding.Left * patchScale; var pr = this.Padding.Right * patchScale; var pt = this.Padding.Top * patchScale; var pb = this.Padding.Bottom * patchScale; var centerW = area.Width - pl - pr; var centerH = area.Height - pt - pb; var leftX = area.X + pl; var rightX = area.X + area.Width - pr; var topY = area.Y + pt; var bottomY = area.Y + area.Height - pb; switch (index) { case 0: return new RectangleF(area.X, area.Y, pl, pt); case 1: return new RectangleF(leftX, area.Y, centerW, pt); case 2: return new RectangleF(rightX, area.Y, pr, pt); case 3: return new RectangleF(area.X, topY, pl, centerH); case 4: return new RectangleF(leftX, topY, centerW, centerH); case 5: return new RectangleF(rightX, topY, pr, centerH); case 6: return new RectangleF(area.X, bottomY, pl, pb); case 7: return new RectangleF(leftX, bottomY, centerW, pb); case 8: return new RectangleF(rightX, bottomY, pr, pb); default: throw new ArgumentOutOfRangeException(nameof(index)); } } } /// <summary> /// An enumeration that represents the modes that a <see cref="NinePatch"/> uses to be drawn /// </summary> public enum NinePatchMode { /// <summary> /// The nine resulting patches will each be stretched. /// This mode is fitting for textures that don't have an intricate design on their edges. /// </summary> Stretch, /// <summary> /// The nine resulting paches will be tiled, repeating the texture multiple times. /// This mode is fitting for textures that have a more complex design on their edges. /// </summary> Tile } /// <summary> /// A set of extensions that allow for <see cref="NinePatch"/> rendering /// </summary> public static class NinePatchExtensions { /// <summary> /// Draws a nine patch area using the given sprite batch /// </summary> /// <param name="batch">The batch to draw with</param> /// <param name="texture">The nine patch to draw</param> /// <param name="destinationRectangle">The area that should be covered by this nine patch</param> /// <param name="color">The color to use</param> /// <param name="rotation">The rotation</param> /// <param name="origin">The origin position</param> /// <param name="effects">The effects that the sprite should have</param> /// <param name="layerDepth">The depth</param> /// <param name="patchScale">The scale of each area of the nine patch</param> public static void Draw(this SpriteBatch batch, NinePatch texture, RectangleF destinationRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth, float patchScale = 1) { for (var i = 0; i < texture.SourceRectangles.Length; i++) { var rect = texture.GetRectangleForIndex(destinationRectangle, i, patchScale); if (!rect.IsEmpty) { var src = texture.SourceRectangles[i]; switch (texture.Mode) { case NinePatchMode.Stretch: batch.Draw(texture.Region.Texture, rect, src, color, rotation, origin, effects, layerDepth); break; case NinePatchMode.Tile: var width = src.Width * patchScale; var height = src.Height * patchScale; for (var x = 0F; x < rect.Width; x += width) { for (var y = 0F; y < rect.Height; y += height) { var size = new Vector2(Math.Min(rect.Width - x, width), Math.Min(rect.Height - y, height)); batch.Draw(texture.Region.Texture, new RectangleF(rect.Location + new Vector2(x, y), size), new Rectangle(src.Location, (size / patchScale).ToPoint()), color, rotation, origin, effects, layerDepth); } } break; } } } } /// <inheritdoc cref="Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch,MLEM.Textures.NinePatch,MLEM.Misc.RectangleF,Microsoft.Xna.Framework.Color,float,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Graphics.SpriteEffects,float,float)"/> public static void Draw(this SpriteBatch batch, NinePatch texture, Rectangle destinationRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth, float patchScale = 1) { batch.Draw(texture, (RectangleF) destinationRectangle, color, rotation, origin, effects, layerDepth, patchScale); } /// <inheritdoc cref="Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch,MLEM.Textures.NinePatch,MLEM.Misc.RectangleF,Microsoft.Xna.Framework.Color,float,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Graphics.SpriteEffects,float,float)"/> public static void Draw(this SpriteBatch batch, NinePatch texture, RectangleF destinationRectangle, Color color, float patchScale = 1) { batch.Draw(texture, destinationRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0, patchScale); } /// <inheritdoc cref="Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch,MLEM.Textures.NinePatch,MLEM.Misc.RectangleF,Microsoft.Xna.Framework.Color,float,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Graphics.SpriteEffects,float,float)"/> public static void Draw(this SpriteBatch batch, NinePatch texture, Rectangle destinationRectangle, Color color, float patchScale = 1) { batch.Draw(texture, destinationRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0, patchScale); } } }<file_sep>/MLEM.Data/Json/DynamicEnumConverter.cs using System; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class DynamicEnumConverter : JsonConverter<DynamicEnum> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, DynamicEnum value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } /// <inheritdoc /> public override DynamicEnum ReadJson(JsonReader reader, Type objectType, DynamicEnum existingValue, bool hasExistingValue, JsonSerializer serializer) { return DynamicEnum.Parse(objectType, reader.Value.ToString()); } } }<file_sep>/MLEM.Data/Json/RectangleConverter.cs using System; using System.Globalization; using Microsoft.Xna.Framework; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class RectangleConverter : JsonConverter<Rectangle> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, Rectangle value, JsonSerializer serializer) { writer.WriteValue( value.X.ToString(CultureInfo.InvariantCulture) + " " + value.Y.ToString(CultureInfo.InvariantCulture) + " " + value.Width.ToString(CultureInfo.InvariantCulture) + " " + value.Height.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc /> public override Rectangle ReadJson(JsonReader reader, Type objectType, Rectangle existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = reader.Value.ToString().Split(' '); return new Rectangle( int.Parse(value[0], CultureInfo.InvariantCulture), int.Parse(value[1], CultureInfo.InvariantCulture), int.Parse(value[2], CultureInfo.InvariantCulture), int.Parse(value[3], CultureInfo.InvariantCulture)); } } }<file_sep>/MLEM.Startup/CoroutineEvents.cs using Coroutine; namespace MLEM.Startup { /// <summary> /// This class contains a set of events for the coroutine system that are automatically fired in <see cref="MlemGame"/>. /// </summary> public static class CoroutineEvents { /// <summary> /// This event is fired in <see cref="MlemGame.Update"/> /// </summary> public static readonly Event Update = new Event(); /// <summary> /// This event is fired in <see cref="MlemGame.Draw"/> /// </summary> public static readonly Event Draw = new Event(); } }<file_sep>/Demos/AutoTilingDemo.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Misc; using MLEM.Startup; namespace Demos { /// <summary> /// This is a demo for <see cref="AutoTiling"/>. /// </summary> public class AutoTilingDemo : Demo { private Texture2D texture; private string[] layout; public AutoTilingDemo(MlemGame game) : base(game) { } public override void LoadContent() { base.LoadContent(); // The layout of the texture is important for auto tiling to work correctly. // It needs to be laid out as follows: Five tiles aligned horizontally within the texture file, with the following information // 1. The texture used for filling big areas // 2. The texture used for straight, horizontal borders, with the borders facing away from the center // 3. The texture used for outer corners, with the corners facing away from the center // 4. The texture used for straight, vertical borders, with the borders facing away from the center // 5. The texture used for inner corners, with the corners facing away from the center // Note that the AutoTiling.png texture contains an example of this layout this.texture = LoadContent<Texture2D>("Textures/AutoTiling"); // in this example, a simple string array is used for layout purposes. As the AutoTiling method allows any kind of // comparison, the actual implementation can vary (for instance, based on a more in-depth tile map) this.layout = new[] { "XXX X", "XXXXX", "XX ", "XXXX ", " X " }; } public override void DoDraw(GameTime gameTime) { this.GraphicsDevice.Clear(Color.Black); // the texture region supplied to the AutoTiling method should only encompass the first filler tile's location and size const int tileSize = 8; var region = new Rectangle(0, 0, tileSize, tileSize); // drawing the auto tiles this.SpriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, transformMatrix: Matrix.CreateScale(10)); for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // don't draw non-grass tiles ( ) if (this.layout[y][x] != 'X') continue; var x1 = x; var y1 = y; // the connectsTo function determines for any given tile if it should connect to, that is, auto-tile with the // neighbor in the supplied offset direction. In this example, the layout determines where grass tiles are (X) // and where there are none ( ). bool ConnectsTo(int xOff, int yOff) { // don't auto-tile out of bounds if (x1 + xOff < 0 || y1 + yOff < 0 || x1 + xOff >= 5 || y1 + yOff >= 5) return false; // check if the neighboring tile is also grass (X) return this.layout[y1 + yOff][x1 + xOff] == 'X'; } AutoTiling.DrawAutoTile(this.SpriteBatch, new Vector2(x, y) * tileSize, this.texture, region, ConnectsTo, Color.White); } } this.SpriteBatch.End(); base.DoDraw(gameTime); } } }<file_sep>/MLEM/Textures/TextureRegion.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Misc; namespace MLEM.Textures { /// <summary> /// This class represents a part of a texture. /// </summary> public class TextureRegion : GenericDataHolder { /// <summary> /// The texture that this region is a part of /// </summary> public readonly Texture2D Texture; /// <summary> /// The area that is covered by this texture region /// </summary> public readonly Rectangle Area; /// <summary> /// The top left corner of this texture region /// </summary> public Point Position => this.Area.Location; /// <summary> /// The x coordinate of the top left corner of this texture region /// </summary> public int U => this.Area.X; /// <summary> /// The y coordinate of the top left corner of this texture region /// </summary> public int V => this.Area.Y; /// <summary> /// The size of this texture region /// </summary> public Point Size => this.Area.Size; /// <summary> /// The width of this texture region /// </summary> public int Width => this.Area.Width; /// <summary> /// The height of this texture region /// </summary> public int Height => this.Area.Height; /// <summary> /// The pivot point of this texture region, where 0, 0 is the top left and 1, 1 is the bottom right of the texture. /// When drawing, this will be seen as the origin from where to start drawing. /// </summary> public Vector2 Pivot = Vector2.Zero; /// <summary> /// The <see cref="Pivot"/> of this texture region, but in absolute pixels rather than percentage. /// </summary> public Vector2 PivotPixels { get => this.Pivot * this.Size.ToVector2(); set => this.Pivot = value / this.Size.ToVector2(); } /// <summary> /// The name of this texture region. By default, this name is <see cref="string.Empty"/>. /// </summary> public string Name = string.Empty; /// <summary> /// Creates a new texture region from a texture and a rectangle which defines the region's area /// </summary> /// <param name="texture">The texture to use</param> /// <param name="area">The area that this texture region should cover</param> public TextureRegion(Texture2D texture, Rectangle area) { this.Texture = texture; this.Area = area; } /// <summary> /// Creates a new texture region that spans the entire texture /// </summary> /// <param name="texture">The texture to use</param> public TextureRegion(Texture2D texture) : this(texture, new Rectangle(0, 0, texture.Width, texture.Height)) { } /// <summary> /// Creates a new texture region based on a texture and area coordinates /// </summary> /// <param name="texture">The texture to use</param> /// <param name="u">The x coordinate of the top left corner of this area</param> /// <param name="v">The y coordinate of the top left corner of this area</param> /// <param name="width">The width of this area</param> /// <param name="height">The height of this area</param> public TextureRegion(Texture2D texture, int u, int v, int width, int height) : this(texture, new Rectangle(u, v, width, height)) { } /// <summary> /// Creates a new texture region based on a texture, a position and a size /// </summary> /// <param name="texture">The texture to use</param> /// <param name="uv">The top left corner of this area</param> /// <param name="size">The size of this area</param> public TextureRegion(Texture2D texture, Point uv, Point size) : this(texture, new Rectangle(uv, size)) { } /// <summary> /// Creates a new texture region which is a sub-region of the given texture region /// </summary> /// <param name="region">The texture region to create a sub-region of</param> /// <param name="area">The new texture region area</param> public TextureRegion(TextureRegion region, Rectangle area) : this(region, area.Location, area.Size) { } /// <summary> /// Creates a new texture region which is a sub-region of the given texture region /// </summary> /// <param name="region">The texture region to create a sub-region of</param> /// <param name="u">The x coordinate of the top left corner of this area</param> /// <param name="v">The y coordinate of the top left corner of this area</param> /// <param name="width">The width of this area</param> /// <param name="height">The height of this area</param> public TextureRegion(TextureRegion region, int u, int v, int width, int height) : this(region, new Point(u, v), new Point(width, height)) { } /// <summary> /// Creates a new texture region which is a sub-region of the given texture region /// </summary> /// <param name="region">The texture region to create a sub-region of</param> /// <param name="uv">The top left corner of this area</param> /// <param name="size">The size of this area</param> public TextureRegion(TextureRegion region, Point uv, Point size) : this(region.Texture, region.Position + uv, size) { } } /// <summary> /// This class provides a set of extension methods for dealing with <see cref="TextureRegion"/> /// </summary> public static class TextureRegionExtensions { /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { batch.Draw(texture.Texture, position, texture.Area, color, rotation, origin + texture.PivotPixels, scale, effects, layerDepth); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, Vector2 position, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { batch.Draw(texture, position, color, rotation, origin, new Vector2(scale), effects, layerDepth); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, Rectangle destinationRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) { batch.Draw(texture.Texture, destinationRectangle, texture.Area, color, rotation, origin + texture.PivotPixels, effects, layerDepth); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, RectangleF destinationRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) { batch.Draw(texture.Texture, destinationRectangle, texture.Area, color, rotation, origin + texture.PivotPixels, effects, layerDepth); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, Vector2 position, Color color) { batch.Draw(texture, position, color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, Rectangle destinationRectangle, Color color) { batch.Draw(texture, destinationRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D, Vector2, Rectangle?, Color, float, Vector2, Vector2, SpriteEffects, float)"/> public static void Draw(this SpriteBatch batch, TextureRegion texture, RectangleF destinationRectangle, Color color) { batch.Draw(texture, destinationRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0); } } }<file_sep>/MLEM/Pathfinding/AStar.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; namespace MLEM.Pathfinding { /// <summary> /// This is an abstract implementation of the A* path finding algorithm. /// This implementation is used by <see cref="AStar2"/>, a 2-dimensional A* path finding algorithm, and <see cref="AStar3"/>, a 3-dimensional A* path finding algorithm. /// </summary> /// <typeparam name="T">The type of points used for this path</typeparam> public abstract class AStar<T> { /// <summary> /// A value that represents an infinite path cost, or a cost for a location that cannot possibly be reached. /// </summary> public const float InfiniteCost = float.PositiveInfinity; /// <summary> /// The array of all directions that will be checked for path finding. /// Note that this array is only used if <see cref="DefaultAllowDiagonals"/> is true. /// </summary> public readonly T[] AllDirections; /// <summary> /// The array of all adjacent directions that will be checked for path finding. /// Note that this array is only used if <see cref="DefaultAllowDiagonals"/> is false. /// </summary> public readonly T[] AdjacentDirections; /// <summary> /// The default cost function that determines the cost for each path finding position. /// </summary> public GetCost DefaultCostFunction; /// <summary> /// The default cost for a path point. /// </summary> public float DefaultCost; /// <summary> /// The default amount of maximum tries that will be used before path finding is aborted. /// </summary> public int DefaultMaxTries; /// <summary> /// Whether or not diagonal directions are considered while finding a path. /// </summary> public bool DefaultAllowDiagonals; /// <summary> /// The amount of tries required for finding the last queried path /// </summary> public int LastTriesNeeded { get; private set; } /// <summary> /// The amount of time required for finding the last queried path /// </summary> public TimeSpan LastTimeNeeded { get; private set; } /// <summary> /// Creates a new A* pathfinder with the supplied default settings. /// </summary> /// <param name="allDirections">All directions that should be checked</param> /// <param name="adjacentDirections">All adjacent directions that should be checked</param> /// <param name="defaultCostFunction">The default function for cost determination of a path point</param> /// <param name="defaultAllowDiagonals">Whether or not diagonals should be allowed by default</param> /// <param name="defaultCost">The default cost for a path point</param> /// <param name="defaultMaxTries">The default amount of tries before path finding is aborted</param> protected AStar(T[] allDirections, T[] adjacentDirections, GetCost defaultCostFunction, bool defaultAllowDiagonals, float defaultCost = 1, int defaultMaxTries = 10000) { this.AllDirections = allDirections; this.AdjacentDirections = adjacentDirections; this.DefaultCostFunction = defaultCostFunction; this.DefaultCost = defaultCost; this.DefaultMaxTries = defaultMaxTries; this.DefaultAllowDiagonals = defaultAllowDiagonals; } /// <inheritdoc cref="FindPath"/> public Task<Stack<T>> FindPathAsync(T start, T goal, GetCost costFunction = null, float? defaultCost = null, int? maxTries = null, bool? allowDiagonals = null) { return Task.Run(() => this.FindPath(start, goal, costFunction, defaultCost, maxTries, allowDiagonals)); } /// <summary> /// Finds a path between two points using this pathfinder's default settings or, alternatively, the supplied override settings. /// </summary> /// <param name="start">The point to start path finding at</param> /// <param name="goal">The point to find a path to</param> /// <param name="costFunction">The function that determines the cost for each path point</param> /// <param name="defaultCost">The default cost for each path point</param> /// <param name="maxTries">The maximum amount of tries before path finding is aborted</param> /// <param name="allowDiagonals">If diagonals should be looked at for path finding</param> /// <returns>A stack of path points, where the top item is the first point to go to.</returns> public Stack<T> FindPath(T start, T goal, GetCost costFunction = null, float? defaultCost = null, int? maxTries = null, bool? allowDiagonals = null) { var stopwatch = Stopwatch.StartNew(); var getCost = costFunction ?? this.DefaultCostFunction; var diags = allowDiagonals ?? this.DefaultAllowDiagonals; var tries = maxTries ?? this.DefaultMaxTries; var defCost = defaultCost ?? this.DefaultCost; var open = new Dictionary<T, PathPoint<T>>(); var closed = new Dictionary<T, PathPoint<T>>(); open.Add(start, new PathPoint<T>(start, this.GetManhattanDistance(start, goal), null, 0, defCost)); var count = 0; Stack<T> ret = null; while (open.Count > 0) { PathPoint<T> current = null; foreach (var point in open.Values) { if (current == null || point.F < current.F) current = point; } if (current == null) break; open.Remove(current.Pos); closed.Add(current.Pos, current); if (current.Pos.Equals(goal)) { ret = CompilePath(current); break; } var dirsUsed = diags ? this.AllDirections : this.AdjacentDirections; foreach (var dir in dirsUsed) { var neighborPos = this.AddPositions(current.Pos, dir); var cost = getCost(current.Pos, neighborPos); if (!float.IsInfinity(cost) && cost < float.MaxValue && !closed.ContainsKey(neighborPos)) { var neighbor = new PathPoint<T>(neighborPos, this.GetManhattanDistance(neighborPos, goal), current, cost, defCost); // check if we already have a waypoint at this location with a worse path if (open.TryGetValue(neighborPos, out var alreadyNeighbor)) { if (neighbor.G < alreadyNeighbor.G) { open.Remove(neighborPos); } else { // if the old waypoint is better, we don't add ours continue; } } // add the new neighbor as a possible waypoint open.Add(neighborPos, neighbor); } } count++; if (count >= tries) break; } stopwatch.Stop(); this.LastTriesNeeded = count; this.LastTimeNeeded = stopwatch.Elapsed; return ret; } /// <summary> /// A helper method to add two positions together. /// </summary> protected abstract T AddPositions(T first, T second); /// <summary> /// A helper method to get the Manhattan Distance between two points. /// </summary> protected abstract float GetManhattanDistance(T first, T second); private static Stack<T> CompilePath(PathPoint<T> current) { var path = new Stack<T>(); while (current != null) { path.Push(current.Pos); current = current.Parent; } return path; } /// <summary> /// A cost function for a given path finding position. /// If a path point should have the default cost, <see cref="AStar{T}.DefaultCost"/> should be returned. /// If a path point should be unreachable, <see cref="AStar{T}.InfiniteCost"/> should be returned. /// </summary> /// <param name="currPos">The current position in the path</param> /// <param name="nextPos">The position we're trying to reach from the current position</param> public delegate float GetCost(T currPos, T nextPos); } /// <summary> /// A point in a <see cref="AStar{T}"/> path /// </summary> /// <typeparam name="T">The type of point used for this path</typeparam> public class PathPoint<T> { /// <summary> /// The path point that this point originated from /// </summary> public readonly PathPoint<T> Parent; /// <summary> /// The position of this path point /// </summary> public readonly T Pos; /// <summary> /// The F cost of this path point /// </summary> public readonly float F; /// <summary> /// The G cost of this path point /// </summary> public readonly float G; /// <summary> /// Creates a new path point with the supplied settings. /// </summary> /// <param name="pos">The point's position</param> /// <param name="distance">The point's manhattan distance from the start point</param> /// <param name="parent">The point's parent</param> /// <param name="terrainCostForThisPos">The point's terrain cost, based on <see cref="AStar{T}.GetCost"/></param> /// <param name="defaultCost">The default cost for a path point</param> public PathPoint(T pos, float distance, PathPoint<T> parent, float terrainCostForThisPos, float defaultCost) { this.Pos = pos; this.Parent = parent; this.G = (parent == null ? 0 : parent.G) + terrainCostForThisPos; this.F = this.G + distance * defaultCost; } /// <inheritdoc /> public override bool Equals(object obj) { if (obj == this) return true; return obj is PathPoint<T> point && point.Pos.Equals(this.Pos); } /// <inheritdoc /> public override int GetHashCode() { return this.Pos.GetHashCode(); } } }<file_sep>/MLEM/Misc/RectangleF.cs using System; using System.Runtime.Serialization; using Microsoft.Xna.Framework; using MLEM.Extensions; namespace MLEM.Misc { /// <summary> /// Represents a float-based version of <see cref="Rectangle"/> /// </summary> [DataContract] public struct RectangleF : IEquatable<RectangleF> { /// <summary> /// The empty rectangle, with an x, y, width and height of 0. /// </summary> public static RectangleF Empty => default; /// <summary> /// The x position of the top left corner of this rectangle. /// </summary> [DataMember] public float X; /// <summary> /// The y position of the top left corner of this rectangle. /// </summary> [DataMember] public float Y; /// <summary> /// The width of this rectangle. /// </summary> [DataMember] public float Width; /// <summary> /// The height of this rectangle. /// </summary> [DataMember] public float Height; /// <inheritdoc cref="X"/> public float Left => this.X; /// <summary> /// The x position of the bottom right corner of this rectangle. /// </summary> public float Right => this.X + this.Width; /// <inheritdoc cref="Y"/> public float Top => this.Y; /// <summary> /// The y position of the bottom right corner of this rectangle. /// </summary> public float Bottom => this.Y + this.Height; /// <summary> /// A boolean that is true if this rectangle is empty. /// A rectangle is considered empty if the width or height is 0. /// </summary> public bool IsEmpty => this.Width <= 0 || this.Height <= 0; /// <summary> /// The top left corner of this rectangle /// </summary> public Vector2 Location { get => new Vector2(this.X, this.Y); set { this.X = value.X; this.Y = value.Y; } } /// <summary> /// The size, that is, the width and height of this rectangle. /// </summary> public Vector2 Size { get => new Vector2(this.Width, this.Height); set { this.Width = value.X; this.Height = value.Y; } } /// <summary> /// The center of this rectangle, based on the top left corner and the size. /// </summary> public Vector2 Center => new Vector2(this.X + this.Width / 2, this.Y + this.Height / 2); /// <summary> /// Creates a new rectangle with the specified location and size /// </summary> /// <param name="x">The x coordinate of the top left corner of the rectangle</param> /// <param name="y">The y coordinate of the top left corner of the rectangle</param> /// <param name="width">The width of the rectangle</param> /// <param name="height">The height of the rectangle</param> public RectangleF(float x, float y, float width, float height) { this.X = x; this.Y = y; this.Width = width; this.Height = height; } /// <summary> /// Creates a new rectangle with the specified location and size vectors /// </summary> /// <param name="location">The top left corner of the rectangle</param> /// <param name="size">The size of the rectangle, where x represents width and the y represents height</param> public RectangleF(Vector2 location, Vector2 size) { this.X = location.X; this.Y = location.Y; this.Width = size.X; this.Height = size.Y; } /// <summary> /// Creates a new rectangle based on two corners that form a bounding box. /// The resulting rectangle will encompass both corners as well as all of the space between them. /// </summary> /// <param name="corner1">The first corner to use</param> /// <param name="corner2">The second corner to use</param> /// <returns></returns> public static RectangleF FromCorners(Vector2 corner1, Vector2 corner2) { var minX = Math.Min(corner1.X, corner2.X); var minY = Math.Min(corner1.Y, corner2.Y); var maxX = Math.Max(corner1.X, corner2.X); var maxY = Math.Max(corner1.Y, corner2.Y); return new RectangleF(minX, minY, maxX - minX, maxY - minY); } /// <summary> /// Converts a float-based rectangle to an int-based rectangle, flooring each value in the process. /// </summary> /// <param name="rect">The rectangle to convert</param> /// <returns>The resulting rectangle</returns> public static explicit operator Rectangle(RectangleF rect) { return new Rectangle(rect.X.Floor(), rect.Y.Floor(), rect.Width.Floor(), rect.Height.Floor()); } /// <summary> /// Converts an int-based rectangle to a float-based rectangle. /// </summary> /// <param name="rect">The rectangle to convert</param> /// <returns>The resulting rectangle</returns> public static explicit operator RectangleF(Rectangle rect) { return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height); } /// <inheritdoc cref="Equals(RectangleF)"/> public static bool operator ==(RectangleF a, RectangleF b) { return a.X == b.X && a.Y == b.Y && a.Width == b.Width && a.Height == b.Height; } /// <inheritdoc cref="Equals(RectangleF)"/> public static bool operator !=(RectangleF a, RectangleF b) { return !(a == b); } /// <inheritdoc cref="Rectangle.Contains(float, float)"/> public bool Contains(float x, float y) { return this.X <= x && x < this.X + this.Width && this.Y <= y && y < this.Y + this.Height; } /// <inheritdoc cref="Rectangle.Contains(Vector2)"/> public bool Contains(Vector2 value) { return this.Contains(value.X, value.Y); } /// <inheritdoc cref="Rectangle.Contains(Rectangle)"/> public bool Contains(RectangleF value) { return this.X <= value.X && value.X + value.Width <= this.X + this.Width && this.Y <= value.Y && value.Y + value.Height <= this.Y + this.Height; } /// <inheritdoc /> public override bool Equals(object obj) { return obj is RectangleF f && this == f; } /// <inheritdoc /> public bool Equals(RectangleF other) { return this == other; } /// <inheritdoc /> public override int GetHashCode() { return (((17 * 23 + this.X.GetHashCode()) * 23 + this.Y.GetHashCode()) * 23 + this.Width.GetHashCode()) * 23 + this.Height.GetHashCode(); } /// <inheritdoc cref="Rectangle.Inflate(float,float)"/> public void Inflate(float horizontalAmount, float verticalAmount) { this.X -= horizontalAmount; this.Y -= verticalAmount; this.Width += horizontalAmount * 2; this.Height += verticalAmount * 2; } /// <inheritdoc cref="Rectangle.Intersects(Rectangle)"/> public bool Intersects(RectangleF value) { return value.Left < this.Right && this.Left < value.Right && value.Top < this.Bottom && this.Top < value.Bottom; } /// <inheritdoc cref="Rectangle.Intersect(Rectangle, Rectangle)"/> public static RectangleF Intersect(RectangleF value1, RectangleF value2) { if (value1.Intersects(value2)) { var num1 = Math.Min(value1.X + value1.Width, value2.X + value2.Width); var x = Math.Max(value1.X, value2.X); var y = Math.Max(value1.Y, value2.Y); var num2 = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height); return new RectangleF(x, y, num1 - x, num2 - y); } else { return Empty; } } /// <inheritdoc cref="Rectangle.Offset(float, float)"/> public void Offset(float offsetX, float offsetY) { this.X += offsetX; this.Y += offsetY; } /// <inheritdoc cref="Rectangle.Offset(Vector2)"/> public void Offset(Vector2 amount) { this.X += amount.X; this.Y += amount.Y; } /// <inheritdoc/> public override string ToString() { return "{X:" + this.X + " Y:" + this.Y + " Width:" + this.Width + " Height:" + this.Height + "}"; } /// <inheritdoc cref="Rectangle.Union(Rectangle, Rectangle)"/> public static RectangleF Union(RectangleF value1, RectangleF value2) { var x = Math.Min(value1.X, value2.X); var y = Math.Min(value1.Y, value2.Y); return new RectangleF(x, y, Math.Max(value1.Right, value2.Right) - x, Math.Max(value1.Bottom, value2.Bottom) - y); } /// <inheritdoc cref="Rectangle.Deconstruct"/> public void Deconstruct(out float x, out float y, out float width, out float height) { x = this.X; y = this.Y; width = this.Width; height = this.Height; } } }<file_sep>/Docs/articles/text_formatting.md # Text Formatting The **MLEM** package contains a simple text formatting system that supports coloring, bold and italic font modifiers, in-text icons and text animations. Text formatting makes use of [generic fonts](font_extensions.md). It should also be noted that [MLEM.Ui](https://github.com/Ellpeck/MLEM/wiki/MLEM.Ui)'s `Paragraph`s support text formatting out of the box. *This documentation is about the new text formatting that was introduced in MLEM 3.3.1. You can see the documentation for the legacy text formatting system [here](text_formatting_legacy.md).* ## Formatting codes To format your text, you can insert *formatting codes* into it. Almost all of these codes are single letters surrounded by `<>`, and some formatting codes can accept additional parameters after their letter representation. By default, the following formatting options are available: - Colors using `<c ColorName>`. All default MonoGame colors are supported, for example `<c CornflowerBlue>`. Reset using `</c>`. - Bold and italic text using `<b>` and `<i>`, respectively. Reset using `</b>` and `</i>`. - Drop shadows using `<s>`. Optional parameters for the shadow's color and positional offset are accepted: `<s #AARRGGBB 2.5>`. Reset using `</c>`. - Underlined text using `<u>`. Reset using `</u>`. - A wobbly sine wave animation using `<a wobbly>`. Optional parameters for the wobble's intensity and height are accepted: `<a wobbly 10 0.25>`. Reset using `</a>`. ## Getting your text ready To get your text ready for rendering with formatting codes, it has to be tokenized. For that, you need to create a new text formatter first. Additionally, you need to have a [generic font](font_extensions.md) ready: ```cs var font = new GenericSpriteFont(this.Content.Load<SpriteFont>("Fonts/ExampleFont")); var formatter = new TextFormatter(); ``` You can then tokenize your string like so: ```cs var tokenizedString = formatter.Tokenize(font, "This is a <c Green>formatted</c> string!"); ``` Additionally, if you want your tokenized string to be split based on a certain maximum width automatically, you can split it like so: ```cs tokenizedString.Split(font, maxWidth, scale); ``` ## Drawing the formatted text To draw your tokenized text, all you have to do is call its `Draw` method like so: ```cs tokenizedString.Draw(gameTime, spriteBatch, position, font, color, scale, depth); ``` Note that, if your tokenized text contains any animations, you have to updated the tokenized string every `Update` call like so: ```cs tokenizedString.Update(gameTime); ``` ## Adding custom codes Adding custom formatting codes is easy! There are two things that a custom formatting code requires: - A class that extends `Code` that does what your formatting code should do (we'll use `MyCustomCode` in this case) - A regex that determines what strings your formatting code matches - A formatting code constructor that creates a new instance of your code's class You can then register your formatting code like this: ```cs formatter.Codes.Add(new Regex("<matchme>"), (form, match, regex) => new MyCustomCode(match, regex)); ``` ## Macros The text formatting system additionally supports macros: Regular expressions that cause the matched text to expand into a different string. Macros can be resolved recursively, meaning that you can have macros that resolve into other macros, and so on. By default, the following macros are available: - `~` expands into a non-breaking space, much like in LaTeX. Adding custom macros is very similar to adding custom formatting codes: ```cs formatter.Macros.Add(new Regex("matchme"), (form, match, regex) => "replacement string"); ```<file_sep>/Docs/articles/text_formatting_legacy.md # Legacy Text Formatting The **MLEM** package contains a simple text formatting system that supports coloring, bold and italic font modifiers, in-text icons and text animations. Text formatting makes use of [generic fonts](font_extensions.md). It should also be noted that [MLEM.Ui](https://github.com/Ellpeck/MLEM/wiki/MLEM.Ui)'s `Paragraph`s support text formatting out of the box. ## Formatting codes To format your text, you can insert *formatting codes* into it. These codes are surrounded by `[]` by default, however these delimiters can be changed like so: ```cs TextFormatting.SetFormatIndicators('<', '>'); ``` By default, the following formatting options are available: - All default MonoGame `Color` values, for example `[CornflowerBlue]`, `[Red]` etc. - `[Bold]` and `[Italic]` to switch to a bold or italic font (and `[Regular]` to switch back) - `[Shadow]` to add a drop shadow to the text - `[Wobbly]` for a sine wave text animation - `[Typing]` for a typewriter-style text animation - `[Unanimated]` to reset back to the default animation ## Getting your text ready To actually display the text with formatting, you first need to gather the formatting data from the text. For performance reasons, this is best done when the text changes, and not every render frame. To gather formatting data, you will need a [generic font](https://github.com/Ellpeck/MLEM/wiki/Font-Extensions). With it, you can gather the data in the form of a `FormattingCodeCollection` like so: ```cs var font = new GenericSpriteFont(this.Content.Load<SpriteFont>("Fonts/ExampleFont")); var text = "This is the [Blue]text[White] that should be [Wobbly]formatted[Unanimated]."; var data = text.GetFormattingCodes(font); ``` Additionally, you will need an *unformatted* version of the string you want to display. There are two reasons for this: - Removing formatting data from the string each frame is unnecessarily expensive - You can use generic fonts' `SplitString` method to split the text you want to display into multiple lines without the text's lengths being tainted by the formatting codes within the string. You can remove a string's formatting data like so: ```cs var unformatted = text.RemoveFormatting(font); ``` ## Drawing the formatted text Now that you have your font (`font`), the formatting data (`data`) and the unformatted string (`unformatted`), you can draw it like so: ```cs font.DrawFormattedString(this.SpriteBatch, new Vector2(10, 10), unformatted, data, Color.White, scale: 1); ``` Additionally, the `DrawFormattedString` method accepts several optional parameters, including the font to be used for bold and italic text and more. ### Time into animation If you want to display animated text, you need to pass a `TimeSpan` into `DrawFormattedString` that determines the amount of time that has passed throughout the animation. You can do this easily by passing the `GameTime`'s `TotalGameTime` span: ```cs font.DrawFormattedString(this.SpriteBatch, new Vector2(10, 10), unformatted, data, Color.White, scale: 1, timeIntoAnimation: gameTime.TotalGameTime); ``` ### Formatting settings The `FormatSettings` class contains additional information for text formatting, like the speed of predefined animations and the color and offset of the drop shadow. To change these settings, you can simply pass an instance of `FormatSettings` to `DrawFormattedString`: ```cs var settings = new FormatSettings { DropShadowColor = Color.Pink, WobbleHeightModifier = 1 }; font.DrawFormattedString(this.SpriteBatch, new Vector2(10, 10), unformatted, data, Color.White, scale: 1, formatSettings: settings); ``` ## Adding custom codes To add custom formatting codes (especially icons), you simple have to add to the `FormattingCodes` dictionary. The key is the name of the formatting code that goes between the delimiters (`[]`), and the value is an instance of `FormattingCode`: ```cs // Creating an icon TextFormatting.FormattingCodes["ExampleIcon"] = new FormattingCode(new TextureRegion(exampleTexture)); // Creating a color TextFormatting.FormattingCodes["ExampleColor"] = new FormattingCode(new Color(10, 20, 30)); ```<file_sep>/MLEM.Ui/Elements/Button.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Textures; using MLEM.Ui.Style; namespace MLEM.Ui.Elements { /// <summary> /// A button element for use inside of a <see cref="UiSystem"/>. /// A button element can be pressed, hovered over and that can be disabled. /// </summary> public class Button : Element { /// <summary> /// The button's texture /// </summary> public StyleProp<NinePatch> Texture; /// <summary> /// The color that the button draws its texture with /// </summary> public StyleProp<Color> NormalColor = Color.White; /// <summary> /// The texture that the button uses while being moused over. /// If this is null, it uses its default <see cref="Texture"/>. /// </summary> public StyleProp<NinePatch> HoveredTexture; /// <summary> /// The color that the button uses for drawing while being moused over /// </summary> public StyleProp<Color> HoveredColor; /// <summary> /// The texture that the button uses when it <see cref="IsDisabled"/>. /// If this is null, it uses its default <see cref="Texture"/>. /// </summary> public StyleProp<NinePatch> DisabledTexture; /// <summary> /// The color that the button uses for drawing when it <see cref="IsDisabled"/> /// </summary> public StyleProp<Color> DisabledColor; /// <summary> /// The <see cref="Paragraph"/> of text that is displayed on the button. /// Note that this is only nonnull by default if the constructor was passed a nonnull text. /// </summary> public Paragraph Text; /// <summary> /// The <see cref="Tooltip"/> that is displayed when hovering over the button. /// Note that this is only nonnull by default if the constructor was passed a nonnull tooltip text. /// </summary> public Tooltip Tooltip; private bool isDisabled; /// <summary> /// Set this property to true to mark the button as disabled. /// A disabled button cannot be moused over, selected or pressed. /// </summary> public bool IsDisabled { get => this.isDisabled; set { this.isDisabled = value; this.CanBePressed = !value; this.CanBeSelected = !value; } } /// <summary> /// Whether this button's <see cref="Text"/> should be truncated if it exceeds this button's width. /// Defaults to false. /// </summary> public bool TruncateTextIfLong { get => this.Text?.TruncateIfLong ?? false; set { if (this.Text != null) this.Text.TruncateIfLong = value; } } /// <summary> /// Creates a new button with the given settings /// </summary> /// <param name="anchor">The button's anchor</param> /// <param name="size">The button's size</param> /// <param name="text">The text that should be displayed on the button</param> /// <param name="tooltipText">The text that should be displayed in a <see cref="Tooltip"/> when hovering over this button</param> /// <param name="tooltipWidth">The width of this button's <see cref="Tooltip"/>, or 50 by default</param> public Button(Anchor anchor, Vector2 size, string text = null, string tooltipText = null, float tooltipWidth = 50) : base(anchor, size) { if (text != null) { this.Text = new Paragraph(Anchor.Center, 1, text, true) {Padding = new Vector2(1)}; this.AddChild(this.Text); } if (tooltipText != null) this.Tooltip = this.AddTooltip(tooltipWidth, tooltipText); } /// <inheritdoc /> public override void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { var tex = this.Texture; var color = (Color) this.NormalColor * alpha; if (this.IsDisabled) { tex = this.DisabledTexture.OrDefault(tex); color = (Color) this.DisabledColor * alpha; } else if (this.IsMouseOver) { tex = this.HoveredTexture.OrDefault(tex); color = (Color) this.HoveredColor * alpha; } batch.Draw(tex, this.DisplayArea, color, this.Scale); base.Draw(time, batch, alpha, blendState, samplerState, matrix); } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.Texture.SetFromStyle(style.ButtonTexture); this.HoveredTexture.SetFromStyle(style.ButtonHoveredTexture); this.HoveredColor.SetFromStyle(style.ButtonHoveredColor); this.DisabledTexture.SetFromStyle(style.ButtonDisabledTexture); this.DisabledColor.SetFromStyle(style.ButtonDisabledColor); } } }<file_sep>/MLEM/Pathfinding/AStar2.cs using System; using System.Linq; using Microsoft.Xna.Framework; using MLEM.Misc; namespace MLEM.Pathfinding { /// <summary> /// A 2-dimensional implementation of <see cref="AStar{T}"/> that uses <see cref="Point"/> for positions. /// </summary> public class AStar2 : AStar<Point> { private static readonly Point[] AdjacentDirs = Direction2Helper.Adjacent.Offsets().ToArray(); private static readonly Point[] AllDirs = Direction2Helper.All.Offsets().ToArray(); /// <inheritdoc /> public AStar2(GetCost defaultCostFunction, bool defaultAllowDiagonals, float defaultCost = 1, int defaultMaxTries = 10000) : base(AllDirs, AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) { } /// <inheritdoc /> protected override Point AddPositions(Point first, Point second) { return first + second; } /// <inheritdoc /> protected override float GetManhattanDistance(Point first, Point second) { return Math.Abs(second.X - first.X) + Math.Abs(second.Y - first.Y); } } }<file_sep>/Utilities/GetSupportedCharacters.py """ This script prints out a <CharacterRegions> xml element that contains efficiently calculated regions for all of the font's supported unicode characters. Pass the font file (not the spritefont xml) as an argument. This script requires FontTools. Install using: pip install fonttools """ """ The amount of characters that can be missing in a sequence to still put them in one region """ leeway = 0 from fontTools.ttLib import TTFont from sys import argv def print_region(start, end): print(f" <CharacterRegion>") print(f" <Start>&#{start};</Start>") print(f" <End>&#{end};</End>") print(f" </CharacterRegion>") # get all supported characters and sort them ttf = TTFont(argv[1]) chars = list(set(y[0] for x in ttf["cmap"].tables for y in x.cmap.items())) chars.sort() ttf.close() # split them into regions based on the leeway start = -1 last = 0 total = 0 print("<CharacterRegions>") for char in chars: if char - last > leeway + 1: if start != -1: print_region(start, last) total += last - start + 1 start = char last = char # print the remaining region print_region(start, last) total += last - start + 1 print("</CharacterRegions>") print(f"The font contains {len(chars)} characters") print(f"The spritefont will contain {total} characters")<file_sep>/MLEM.Ui/Style/UntexturedStyle.cs using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Font; namespace MLEM.Ui.Style { /// <summary> /// The default, untextured <see cref="UiStyle"/>. /// Note that, as MLEM does not provide any texture or font assets, this default style is made up of single-color textures that were generated using <see cref="SpriteBatchExtensions.GenerateTexture"/>. /// </summary> public class UntexturedStyle : UiStyle { /// <summary> /// Creates a new untextured style with textures generated by the given sprite batch /// </summary> /// <param name="batch">The sprite batch to generate the textures with</param> public UntexturedStyle(SpriteBatch batch) { this.SelectionIndicator = batch.GenerateTexture(Color.Transparent, Color.Red); this.ButtonTexture = batch.GenerateTexture(Color.CadetBlue); this.ButtonHoveredColor = Color.LightGray; this.ButtonDisabledColor = Color.Gray; this.PanelTexture = batch.GenerateTexture(Color.Gray); this.TextFieldTexture = batch.GenerateTexture(Color.MediumBlue); this.TextFieldHoveredColor = Color.LightGray; this.ScrollBarBackground = batch.GenerateTexture(Color.LightBlue); this.ScrollBarScrollerTexture = batch.GenerateTexture(Color.Blue); this.CheckboxTexture = batch.GenerateTexture(Color.LightBlue); this.CheckboxHoveredColor = Color.LightGray; this.CheckboxCheckmark = batch.GenerateTexture(Color.Blue).Region; this.RadioTexture = batch.GenerateTexture(Color.AliceBlue); this.RadioHoveredColor = Color.LightGray; this.RadioCheckmark = batch.GenerateTexture(Color.CornflowerBlue).Region; this.TooltipBackground = batch.GenerateTexture(Color.Black * 0.65F, Color.Black * 0.65F); this.TooltipOffset = new Vector2(8, 16); this.ProgressBarTexture = batch.GenerateTexture(Color.RoyalBlue); this.ProgressBarColor = Color.White; this.ProgressBarProgressPadding = new Vector2(1); this.ProgressBarProgressColor = Color.Red; this.Font = new EmptyFont(); } private class EmptyFont : GenericFont { public override GenericFont Bold => this; public override GenericFont Italic => this; public override float LineHeight => 1; protected override Vector2 MeasureChar(char c) { return Vector2.Zero; } public override void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { } public override void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { } } } }<file_sep>/MLEM.Ui/Elements/TextField.cs using System; using System.IO; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MLEM.Extensions; using MLEM.Font; using MLEM.Input; using MLEM.Misc; using MLEM.Textures; using MLEM.Ui.Style; using TextCopy; namespace MLEM.Ui.Elements { /// <summary> /// A text field element for use inside of a <see cref="UiSystem"/>. /// A text field is a selectable element that can be typed in, as well as copied and pasted from. /// If an on-screen keyboard is required, then this text field will automatically open an on-screen keyboard using <see cref="MlemPlatform.OpenOnScreenKeyboard"/>. /// </summary> public class TextField : Element { /// <summary> /// A <see cref="Rule"/> that allows any visible character and spaces /// </summary> public static readonly Rule DefaultRule = (field, add) => !add.Any(char.IsControl); /// <summary> /// A <see cref="Rule"/> that only allows letters /// </summary> public static readonly Rule OnlyLetters = (field, add) => add.All(char.IsLetter); /// <summary> /// A <see cref="Rule"/> that only allows numerals /// </summary> public static readonly Rule OnlyNumbers = (field, add) => add.All(char.IsNumber); /// <summary> /// A <see cref="Rule"/> that only allows letters and numerals /// </summary> public static readonly Rule LettersNumbers = (field, add) => add.All(c => char.IsLetter(c) || char.IsNumber(c)); /// <summary> /// A <see cref="Rule"/> that only allows characters not contained in <see cref="Path.GetInvalidPathChars"/> /// </summary> public static readonly Rule PathNames = (field, add) => add.IndexOfAny(Path.GetInvalidPathChars()) < 0; /// <summary> /// A <see cref="Rule"/> that only allows characters not contained in <see cref="Path.GetInvalidFileNameChars"/> /// </summary> public static readonly Rule FileNames = (field, add) => add.IndexOfAny(Path.GetInvalidFileNameChars()) < 0; /// <summary> /// The color that this text field's text should display with /// </summary> public StyleProp<Color> TextColor; /// <summary> /// The color that the <see cref="PlaceholderText"/> should display with /// </summary> public StyleProp<Color> PlaceholderColor; /// <summary> /// This text field's texture /// </summary> public StyleProp<NinePatch> Texture; /// <summary> /// This text field's texture while it is hovered /// </summary> public StyleProp<NinePatch> HoveredTexture; /// <summary> /// The color that this text field should display with while it is hovered /// </summary> public StyleProp<Color> HoveredColor; /// <summary> /// The scale that this text field should render text with /// </summary> public StyleProp<float> TextScale; /// <summary> /// The font that this text field should display text with /// </summary> public StyleProp<GenericFont> Font; /// <summary> /// This text field's current text /// </summary> public string Text => this.text.ToString(); /// <summary> /// The text that displays in this text field if <see cref="Text"/> is empty /// </summary> public string PlaceholderText; /// <summary> /// An event that gets called when <see cref="Text"/> changes, either through input, or through a manual change. /// </summary> public TextChanged OnTextChange; /// <summary> /// The x position that text should start rendering at, based on the x position of this text field. /// </summary> public float TextOffsetX = 4; /// <summary> /// The width that the caret should render with. /// </summary> public float CaretWidth = 0.5F; /// <summary> /// The rule used for text input. /// Rules allow only certain characters to be allowed inside of a text field. /// </summary> public Rule InputRule; /// <summary> /// The title of the <c>KeyboardInput</c> field on mobile devices and consoles /// </summary> public string MobileTitle; /// <summary> /// The description of the <c>KeyboardInput</c> field on mobile devices and consoles /// </summary> public string MobileDescription; /// <summary> /// The position of the caret within the text. /// This is always between 0 and the <see cref="string.Length"/> of <see cref="Text"/> /// </summary> public int CaretPos { get { this.CaretPos = MathHelper.Clamp(this.caretPos, 0, this.text.Length); return this.caretPos; } set { if (this.caretPos != value) { this.caretPos = value; this.HandleTextChange(false); } } } /// <summary> /// A character that should be displayed instead of this text field's <see cref="Text"/> content. /// The amount of masking characters displayed will be equal to the <see cref="Text"/>'s length. /// This behavior is useful for password fields or similar. /// </summary> public char? MaskingCharacter { get => this.maskingCharacter; set { this.maskingCharacter = value; this.HandleTextChange(false); } } private readonly StringBuilder text = new StringBuilder(); private char? maskingCharacter; private double caretBlinkTimer; private string displayedText; private int textOffset; private int caretPos; /// <summary> /// Creates a new text field with the given settings /// </summary> /// <param name="anchor">The text field's anchor</param> /// <param name="size">The text field's size</param> /// <param name="rule">The text field's input rule</param> /// <param name="font">The font to use for drawing text</param> /// <param name="text">The text that the text field should contain by default</param> public TextField(Anchor anchor, Vector2 size, Rule rule = null, GenericFont font = null, string text = null) : base(anchor, size) { this.InputRule = rule ?? DefaultRule; if (font != null) this.Font.Set(font); if (text != null) this.SetText(text, true); MlemPlatform.EnsureExists(); this.OnPressed += async e => { var title = this.MobileTitle ?? this.PlaceholderText; var result = await MlemPlatform.Current.OpenOnScreenKeyboard(title, this.MobileDescription, this.Text, false); if (result != null) this.SetText(result.Replace('\n', ' '), true); }; this.OnTextInput += (element, key, character) => { if (!this.IsSelected || this.IsHidden) return; if (key == Keys.Back) { if (this.CaretPos > 0) { this.CaretPos--; this.RemoveText(this.CaretPos, 1); } } else if (key == Keys.Delete) { this.RemoveText(this.CaretPos, 1); } else { this.InsertText(character); } }; this.OnDeselected += e => this.CaretPos = 0; this.OnSelected += e => this.CaretPos = this.text.Length; } private void HandleTextChange(bool textChanged = true) { // not initialized yet if (!this.Font.HasValue()) return; var length = this.Font.Value.MeasureString(this.text.ToString()).X * this.TextScale; var maxWidth = this.DisplayArea.Width / this.Scale - this.TextOffsetX * 2; if (length > maxWidth) { // if we're moving the caret to the left if (this.textOffset > this.CaretPos) { this.textOffset = this.CaretPos; } else { // if we're moving the caret to the right var importantArea = this.text.ToString(this.textOffset, Math.Min(this.CaretPos, this.text.Length) - this.textOffset); var bound = this.CaretPos - this.Font.Value.TruncateString(importantArea, maxWidth, this.TextScale, true).Length; if (this.textOffset < bound) { this.textOffset = bound; } } var visible = this.text.ToString(this.textOffset, this.text.Length - this.textOffset); this.displayedText = this.Font.Value.TruncateString(visible, maxWidth, this.TextScale); } else { this.displayedText = this.Text; this.textOffset = 0; } if (this.MaskingCharacter != null) this.displayedText = new string(this.MaskingCharacter.Value, this.displayedText.Length); if (textChanged) this.OnTextChange?.Invoke(this, this.Text); } /// <inheritdoc /> public override void Update(GameTime time) { base.Update(time); // handle first initialization if not done if (this.displayedText == null) this.HandleTextChange(false); if (!this.IsSelected || this.IsHidden) return; if (this.Input.IsKeyPressed(Keys.Left)) { this.CaretPos--; } else if (this.Input.IsKeyPressed(Keys.Right)) { this.CaretPos++; } else if (this.Input.IsKeyPressed(Keys.Home)) { this.CaretPos = 0; } else if (this.Input.IsKeyPressed(Keys.End)) { this.CaretPos = this.text.Length; } else if (this.Input.IsModifierKeyDown(ModifierKey.Control)) { if (this.Input.IsKeyPressed(Keys.V)) { var clip = ClipboardService.GetText(); if (clip != null) this.InsertText(clip); } else if (this.Input.IsKeyPressed(Keys.C)) { // until there is text selection, just copy the whole content ClipboardService.SetText(this.Text); } } this.caretBlinkTimer += time.ElapsedGameTime.TotalSeconds; if (this.caretBlinkTimer >= 1) this.caretBlinkTimer = 0; } /// <inheritdoc /> public override void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { var tex = this.Texture; var color = Color.White * alpha; if (this.IsMouseOver) { tex = this.HoveredTexture.OrDefault(tex); color = (Color) this.HoveredColor * alpha; } batch.Draw(tex, this.DisplayArea, color, this.Scale); if (this.displayedText != null) { var lineHeight = this.Font.Value.LineHeight * this.TextScale * this.Scale; var textPos = this.DisplayArea.Location + new Vector2(this.TextOffsetX * this.Scale, this.DisplayArea.Height / 2 - lineHeight / 2); if (this.text.Length > 0 || this.IsSelected) { var textColor = this.TextColor.OrDefault(Color.White); this.Font.Value.DrawString(batch, this.displayedText, textPos, textColor * alpha, 0, Vector2.Zero, this.TextScale * this.Scale, SpriteEffects.None, 0); if (this.IsSelected && this.caretBlinkTimer >= 0.5F) { var textSize = this.Font.Value.MeasureString(this.displayedText.Substring(0, this.CaretPos - this.textOffset)) * this.TextScale * this.Scale; batch.Draw(batch.GetBlankTexture(), new RectangleF(textPos.X + textSize.X, textPos.Y, this.CaretWidth * this.Scale, lineHeight), null, textColor * alpha); } } else if (this.PlaceholderText != null) { this.Font.Value.DrawString(batch, this.PlaceholderText, textPos, this.PlaceholderColor.OrDefault(Color.Gray) * alpha, 0, Vector2.Zero, this.TextScale * this.Scale, SpriteEffects.None, 0); } } base.Draw(time, batch, alpha, blendState, samplerState, matrix); } /// <summary> /// Replaces this text field's text with the given text. /// </summary> /// <param name="text">The new text</param> /// <param name="removeMismatching">If any characters that don't match the <see cref="InputRule"/> should be left out</param> public void SetText(object text, bool removeMismatching = false) { if (removeMismatching) { var result = new StringBuilder(); foreach (var c in text.ToString()) { if (this.InputRule(this, c.ToCachedString())) result.Append(c); } text = result.ToString(); } else if (!this.InputRule(this, text.ToString())) return; this.text.Clear(); this.text.Append(text); this.CaretPos = this.text.Length; this.HandleTextChange(); } /// <summary> /// Inserts the given text at the <see cref="CaretPos"/> /// </summary> /// <param name="text">The text to insert</param> public void InsertText(object text) { var strg = text.ToString(); if (!this.InputRule(this, strg)) return; this.text.Insert(this.CaretPos, strg); this.CaretPos += strg.Length; this.HandleTextChange(); } /// <summary> /// Removes the given amount of text at the given index /// </summary> /// <param name="index">The index</param> /// <param name="length">The amount of text to remove</param> public void RemoveText(int index, int length) { if (index < 0 || index >= this.text.Length) return; this.text.Remove(index, length); this.HandleTextChange(); } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.TextScale.SetFromStyle(style.TextScale); this.Font.SetFromStyle(style.Font); this.Texture.SetFromStyle(style.TextFieldTexture); this.HoveredTexture.SetFromStyle(style.TextFieldHoveredTexture); this.HoveredColor.SetFromStyle(style.TextFieldHoveredColor); } /// <summary> /// A delegate method used for <see cref="TextField.OnTextChange"/> /// </summary> /// <param name="field">The text field whose text changed</param> /// <param name="text">The new text</param> public delegate void TextChanged(TextField field, string text); /// <summary> /// A delegate method used for <see cref="InputRule"/>. /// It should return whether the given text can be added to the text field. /// </summary> /// <param name="field">The text field</param> /// <param name="textToAdd">The text that is tried to be added</param> public delegate bool Rule(TextField field, string textToAdd); } }<file_sep>/MLEM/Sound/SoundEffectInfo.cs using Microsoft.Xna.Framework.Audio; using MLEM.Extensions; namespace MLEM.Sound { /// <summary> /// A sound effect info is a wrapper around <see cref="SoundEffect"/> that additionally stores <see cref="Volume"/>, <see cref="Pitch"/> and <see cref="Pan"/> information. /// Additionally, a <see cref="SoundEffectInstance"/> can be created using <see cref="CreateInstance"/>. /// </summary> public class SoundEffectInfo { /// <summary> /// The <see cref="SoundEffect"/> that is played by this info. /// </summary> public readonly SoundEffect Sound; /// <summary> /// Volume, ranging from 0.0 (silence) to 1.0 (full volume). Volume during playback is scaled by SoundEffect.MasterVolume. /// </summary> public float Volume; /// <summary> /// Pitch adjustment, ranging from -1.0 (down an octave) to 0.0 (no change) to 1.0 (up an octave). /// </summary> public float Pitch; /// <summary> /// Pan value ranging from -1.0 (left speaker) to 0.0 (centered), 1.0 (right speaker). /// </summary> public float Pan; /// <summary> /// Creates a new sound effect info with the given values. /// </summary> /// <param name="sound">The sound to play</param> /// <param name="volume">The volume to play the sound with</param> /// <param name="pitch">The pitch to play the sound with</param> /// <param name="pan">The pan to play the sound with</param> public SoundEffectInfo(SoundEffect sound, float volume = 1, float pitch = 0, float pan = 0) { this.Sound = sound; this.Volume = volume; this.Pitch = pitch; this.Pan = pan; } /// <summary> /// Plays this info's <see cref="Sound"/> once. /// </summary> /// <returns>False if more sounds are currently playing than the platform allows</returns> public bool Play() { return this.Sound.Play(this.Volume, this.Pitch, this.Pan); } /// <summary> /// Creates a new <see cref="SoundEffectInstance"/> with this sound effect info's data. /// </summary> /// <param name="isLooped">The value to set the returned instance's <see cref="SoundEffectInstance.IsLooped"/> to. Defaults to false.</param> /// <returns>A new sound effect instance, with this info's data applied</returns> public SoundEffectInstance CreateInstance(bool isLooped = false) { return this.Sound.CreateInstance(this.Volume, this.Pitch, this.Pan, isLooped); } } }<file_sep>/MLEM.Ui/Elements/ScrollBar.cs using System; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using MLEM.Extensions; using MLEM.Input; using MLEM.Misc; using MLEM.Textures; using MLEM.Ui.Style; namespace MLEM.Ui.Elements { /// <summary> /// A scroll bar element to be used inside of a <see cref="UiSystem"/>. /// A scroll bar is an element that features a smaller scroller indicator inside of it that can move up and down. /// A scroll bar can be scrolled using the mouse or by using the scroll wheel while hovering over its <see cref="Element.Parent"/> or any of its siblings. /// </summary> public class ScrollBar : Element { /// <summary> /// The background texture for this scroll bar /// </summary> public StyleProp<NinePatch> Background; /// <summary> /// The texture of this scroll bar's scroller indicator /// </summary> public StyleProp<NinePatch> ScrollerTexture; /// <summary> /// The <see cref="ScrollerTexture"/>'s offset from the calculated position of the scroller. Use this to pad the scroller. /// </summary> public Vector2 ScrollerOffset; /// <summary> /// The scroller's width and height /// </summary> public Vector2 ScrollerSize; private float maxValue; /// <summary> /// The max value that this scroll bar should be able to scroll to. /// Note that the maximum value does not change the height of the scroll bar. /// </summary> public float MaxValue { get => this.maxValue; set { this.maxValue = Math.Max(0, value); // force current value to be clamped this.CurrentValue = this.CurrentValue; // auto-hide if necessary var shouldHide = this.maxValue <= 0.01F; if (this.AutoHideWhenEmpty && this.IsHidden != shouldHide) { this.IsHidden = shouldHide; this.OnAutoHide?.Invoke(this); } } } private float scrollAdded; private float currValue; /// <summary> /// The current value of the scroll bar. /// This is between 0 and <see cref="MaxValue"/> at all times. /// </summary> public float CurrentValue { get => this.currValue - this.scrollAdded; set { var val = MathHelper.Clamp(value, 0, this.maxValue); if (this.currValue != val) { if (this.SmoothScrolling) this.scrollAdded = val - this.currValue; this.currValue = val; this.OnValueChanged?.Invoke(this, val); } } } /// <summary> /// Whether this scroll bar is horizontal /// </summary> public readonly bool Horizontal; /// <summary> /// The amount added or removed from <see cref="CurrentValue"/> per single movement of the scroll wheel /// </summary> public float StepPerScroll = 1; /// <summary> /// An event that is called when <see cref="CurrentValue"/> changes /// </summary> public ValueChanged OnValueChanged; /// <summary> /// An event that is called when this scroll bar is automatically hidden from a <see cref="Panel"/> /// </summary> public GenericCallback OnAutoHide; /// <summary> /// This property is true while the user scrolls on the scroll bar using the mouse or touch input /// </summary> public bool IsBeingScrolled => this.isMouseHeld || this.isDragging || this.isTouchHeld; private bool isMouseHeld; private bool isDragging; private bool isTouchHeld; /// <summary> /// This field determines if this scroll bar should automatically be hidden from a <see cref="Panel"/> if there aren't enough children to allow for scrolling. /// </summary> public bool AutoHideWhenEmpty; /// <summary> /// Whether smooth scrolling should be enabled for this scroll bar. /// Smooth scrolling causes the <see cref="CurrentValue"/> to change gradually rather than instantly when scrolling. /// </summary> public bool SmoothScrolling; /// <summary> /// The factor with which <see cref="SmoothScrolling"/> happens. /// </summary> public float SmoothScrollFactor = 0.75F; static ScrollBar() { InputHandler.EnableGestures(GestureType.HorizontalDrag, GestureType.VerticalDrag); } /// <summary> /// Creates a new scroll bar with the given settings /// </summary> /// <param name="anchor">The scroll bar's anchor</param> /// <param name="size">The scroll bar's size</param> /// <param name="scrollerSize"></param> /// <param name="maxValue"></param> /// <param name="horizontal"></param> public ScrollBar(Anchor anchor, Vector2 size, int scrollerSize, float maxValue, bool horizontal = false) : base(anchor, size) { this.maxValue = maxValue; this.Horizontal = horizontal; this.ScrollerSize = new Vector2(horizontal ? scrollerSize : size.X, !horizontal ? scrollerSize : size.Y); this.CanBeSelected = false; } /// <inheritdoc /> public override void Update(GameTime time) { base.Update(time); // MOUSE INPUT var moused = this.Controls.MousedElement; if (moused == this && this.Controls.Input.IsMouseButtonPressed(MouseButton.Left)) { this.isMouseHeld = true; } else if (this.isMouseHeld && !this.Controls.Input.IsMouseButtonDown(MouseButton.Left)) { this.isMouseHeld = false; } if (this.isMouseHeld) this.ScrollToPos(this.Input.MousePosition.Transform(this.Root.InvTransform)); if (!this.Horizontal && moused != null && (moused == this.Parent || moused.GetParentTree().Contains(this.Parent))) { var scroll = this.Input.LastScrollWheel - this.Input.ScrollWheel; if (scroll != 0) this.CurrentValue += this.StepPerScroll * Math.Sign(scroll); } // TOUCH INPUT if (!this.Horizontal) { // are we dragging on top of the panel? if (this.Input.GetGesture(GestureType.VerticalDrag, out var drag)) { // if the element under the drag's start position is on top of the panel, start dragging var touched = this.Parent.GetElementUnderPos(Vector2.Transform(drag.Position, this.Root.InvTransform)); if (touched != null && touched != this) this.isDragging = true; // if we're dragging at all, then move the scroller if (this.isDragging) this.CurrentValue -= drag.Delta.Y / this.Scale; } else { this.isDragging = false; } } if (this.Input.TouchState.Count <= 0) { // if no touch has occured this tick, then reset the variable this.isTouchHeld = false; } else { foreach (var loc in this.Input.TouchState) { var pos = Vector2.Transform(loc.Position, this.Root.InvTransform); // if we just started touching and are on top of the scroller, then we should start scrolling if (this.DisplayArea.Contains(pos) && !loc.TryGetPreviousLocation(out _)) { this.isTouchHeld = true; break; } // scroll no matter if we're on the scroller right now if (this.isTouchHeld) this.ScrollToPos(pos.ToPoint()); } } if (this.SmoothScrolling && this.scrollAdded != 0) { this.scrollAdded *= this.SmoothScrollFactor; if (Math.Abs(this.scrollAdded) <= 0.1F) this.scrollAdded = 0; this.OnValueChanged?.Invoke(this, this.CurrentValue); } } private void ScrollToPos(Point position) { if (this.Horizontal) { var internalX = position.X - this.Area.X - this.ScrollerSize.X * this.Scale / 2; this.CurrentValue = internalX / (this.Area.Width - this.ScrollerSize.X * this.Scale) * this.MaxValue; } else { var internalY = position.Y - this.Area.Y - this.ScrollerSize.Y * this.Scale / 2; this.CurrentValue = internalY / (this.Area.Height - this.ScrollerSize.Y * this.Scale) * this.MaxValue; } } /// <inheritdoc /> public override void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { batch.Draw(this.Background, this.DisplayArea, Color.White * alpha, this.Scale); if (this.MaxValue > 0) { var scrollerPos = new Vector2(this.DisplayArea.X + this.ScrollerOffset.X, this.DisplayArea.Y + this.ScrollerOffset.Y); var scrollerOffset = new Vector2( !this.Horizontal ? 0 : this.CurrentValue / this.maxValue * (this.DisplayArea.Width - this.ScrollerSize.X * this.Scale), this.Horizontal ? 0 : this.CurrentValue / this.maxValue * (this.DisplayArea.Height - this.ScrollerSize.Y * this.Scale)); var scrollerRect = new RectangleF(scrollerPos + scrollerOffset, this.ScrollerSize * this.Scale); batch.Draw(this.ScrollerTexture, scrollerRect, Color.White * alpha, this.Scale); } base.Draw(time, batch, alpha, blendState, samplerState, matrix); } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.Background.SetFromStyle(style.ScrollBarBackground); this.ScrollerTexture.SetFromStyle(style.ScrollBarScrollerTexture); } /// <summary> /// A delegate method used for <see cref="ScrollBar.OnValueChanged"/> /// </summary> /// <param name="element">The element whose current value changed</param> /// <param name="value">The element's new <see cref="ScrollBar.CurrentValue"/></param> public delegate void ValueChanged(Element element, float value); } }<file_sep>/MLEM.Ui/Style/UiStyle.cs using System; using Microsoft.Xna.Framework; using MLEM.Font; using MLEM.Formatting; using MLEM.Misc; using MLEM.Textures; using MLEM.Ui.Elements; using SoundEffectInfo = MLEM.Sound.SoundEffectInfo; namespace MLEM.Ui.Style { /// <summary> /// The style settings for a <see cref="UiSystem"/>. /// Each <see cref="Element"/> uses these style settings by default, however you can also change these settings per element using the elements' individual style settings. /// Note that this class is a <see cref="GenericDataHolder"/>, meaning additional styles for custom components can easily be added using <see cref="GenericDataHolder.SetData"/> /// </summary> public class UiStyle : GenericDataHolder { /// <summary> /// The texture that is rendered on top of the <see cref="UiControls.SelectedElement"/> /// </summary> public NinePatch SelectionIndicator; /// <summary> /// The texture that the <see cref="Button"/> element uses /// </summary> public NinePatch ButtonTexture; /// <summary> /// The texture that the <see cref="Button"/> element uses when it is moused over (<see cref="Element.IsMouseOver"/>) /// Note that, if you just want to change the button's color when hovered, use <see cref="ButtonHoveredColor"/>. /// </summary> public NinePatch ButtonHoveredTexture; /// <summary> /// The color that the <see cref="Button"/> element renders with when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public Color ButtonHoveredColor; /// <summary> /// The texture that the <see cref="Button"/> element uses when it <see cref="Button.IsDisabled"/> /// </summary> public NinePatch ButtonDisabledTexture; /// <summary> /// The color that the <see cref="Button"/> element uses when it <see cref="Button.IsDisabled"/> /// </summary> public Color ButtonDisabledColor; /// <summary> /// The texture that the <see cref="Panel"/> element uses /// </summary> public NinePatch PanelTexture; /// <summary> /// The texture that the <see cref="TextField"/> element uses /// </summary> public NinePatch TextFieldTexture; /// <summary> /// The texture that the <see cref="TextField"/> element uses when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public NinePatch TextFieldHoveredTexture; /// <summary> /// The color that the <see cref="TextField"/> renders with when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public Color TextFieldHoveredColor; /// <summary> /// The background texture that the <see cref="ScrollBar"/> element uses /// </summary> public NinePatch ScrollBarBackground; /// <summary> /// The texture that the scroll indicator of the <see cref="ScrollBar"/> element uses /// </summary> public NinePatch ScrollBarScrollerTexture; /// <summary> /// The texture that the <see cref="Checkbox"/> element uses /// </summary> public NinePatch CheckboxTexture; /// <summary> /// The texture that the <see cref="Checkbox"/> element uses when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public NinePatch CheckboxHoveredTexture; /// <summary> /// The color that the <see cref="Checkbox"/> element renders with when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public Color CheckboxHoveredColor; /// <summary> /// The texture that the <see cref="Checkbox"/> element renders on top of its regular texture when it is <see cref="Checkbox.Checked"/> /// </summary> public TextureRegion CheckboxCheckmark; /// <summary> /// The texture that the <see cref="RadioButton"/> element uses /// </summary> public NinePatch RadioTexture; /// <summary> /// The texture that the <see cref="RadioButton"/> element uses when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public NinePatch RadioHoveredTexture; /// <summary> /// The color that the <see cref="RadioButton"/> element renders with when it is moused over (<see cref="Element.IsMouseOver"/>) /// </summary> public Color RadioHoveredColor; /// <summary> /// The texture that the <see cref="RadioButton"/> renders on top of its regular texture when it is <see cref="Checkbox.Checked"/> /// </summary> public TextureRegion RadioCheckmark; /// <summary> /// The texture that the <see cref="Tooltip"/> uses for its background /// </summary> public NinePatch TooltipBackground; /// <summary> /// The offset of the <see cref="Tooltip"/> element's top left corner from the mouse position /// </summary> public Vector2 TooltipOffset; /// <summary> /// The color that the text of a <see cref="Tooltip"/> should have /// </summary> public Color TooltipTextColor = Color.White; /// <summary> /// The amount of time that the mouse has to be over an element with a <see cref="Tooltip"/> for the tooltip to appear /// </summary> public TimeSpan TooltipDelay = TimeSpan.Zero; /// <summary> /// The texture that the <see cref="ProgressBar"/> element uses for its background /// </summary> public NinePatch ProgressBarTexture; /// <summary> /// The color that the <see cref="ProgressBar"/> element renders with /// </summary> public Color ProgressBarColor; /// <summary> /// The padding that the <see cref="ProgressBar"/> uses for its progress texture (<see cref="ProgressBarProgressTexture"/>) /// </summary> public Vector2 ProgressBarProgressPadding; /// <summary> /// The texture that the <see cref="ProgressBar"/> uses for displaying its progress /// </summary> public NinePatch ProgressBarProgressTexture; /// <summary> /// The color that the <see cref="ProgressBar"/> renders its progress texture with /// </summary> public Color ProgressBarProgressColor; /// <summary> /// The font that <see cref="Paragraph"/> and other elements should use for rendering. /// Note that, to specify a bold and italic font for <see cref="TextFormatter"/>, you should use <see cref="GenericFont.Bold"/> and <see cref="GenericFont.Italic"/>. /// </summary> public GenericFont Font; /// <summary> /// The scale that text should be rendered with in <see cref="Paragraph"/> and other elements /// </summary> public float TextScale = 1; /// <summary> /// The color that the text of a <see cref="Paragraph"/> should have /// </summary> public Color TextColor = Color.White; /// <summary> /// The <see cref="SoundEffectInfo"/> that should be played when an element's <see cref="Element.OnPressed"/> and <see cref="Element.OnSecondaryPressed"/> events are called. /// Note that this sound is only played if the callbacks have any subscribers. /// </summary> public SoundEffectInfo ActionSound; } }<file_sep>/MLEM.Ui/UiControls.cs using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using MLEM.Input; using MLEM.Misc; using MLEM.Ui.Elements; using MLEM.Ui.Style; namespace MLEM.Ui { /// <summary> /// UiControls holds and manages all of the controls for a <see cref="UiSystem"/>. /// UiControls supports keyboard, mouse, gamepad and touch input using an underlying <see cref="InputHandler"/>. /// </summary> public class UiControls { /// <summary> /// The input handler that is used for querying input /// </summary> public readonly InputHandler Input; /// <summary> /// This value ist true if the <see cref="InputHandler"/> was created by this ui controls instance, or if it was passed in. /// If the input handler was created by this instance, its <see cref="InputHandler.Update()"/> method should be called by us. /// </summary> protected readonly bool IsInputOurs; /// <summary> /// The <see cref="UiSystem"/> that this ui controls instance is controlling /// </summary> protected readonly UiSystem System; /// <summary> /// The <see cref="RootElement"/> that is currently active. /// The active root element is the one with the highest <see cref="RootElement.Priority"/> that whose <see cref="RootElement.CanSelectContent"/> property is true. /// </summary> public RootElement ActiveRoot { get; protected set; } /// <summary> /// The <see cref="Element"/> that the mouse is currently over. /// </summary> public Element MousedElement { get; protected set; } /// <summary> /// The <see cref="Element"/> that is currently touched. /// </summary> public Element TouchedElement { get; protected set; } private readonly Dictionary<string, Element> selectedElements = new Dictionary<string, Element>(); /// <summary> /// The element that is currently selected. /// This is the <see cref="RootElement.SelectedElement"/> of the <see cref="ActiveRoot"/>. /// </summary> public Element SelectedElement => this.GetSelectedElement(this.ActiveRoot); /// <summary> /// A list of <see cref="Keys"/>, <see cref="Buttons"/> and/or <see cref="MouseButton"/> that act as the buttons on the keyboard which perform the <see cref="Element.OnPressed"/> action. /// If the <see cref="ModifierKey.Shift"/> is held, these buttons perform <see cref="Element.OnSecondaryPressed"/>. /// </summary> public readonly Keybind KeyboardButtons = new Keybind().Add(Keys.Space).Add(Keys.Enter); /// <summary> /// AA <see cref="Keybind"/> that acts as the buttons on a gamepad that perform the <see cref="Element.OnPressed"/> action. /// </summary> public readonly Keybind GamepadButtons = new Keybind(Buttons.A); /// <summary> /// A <see cref="Keybind"/> that acts as the buttons on a gamepad that perform the <see cref="Element.OnSecondaryPressed"/> action. /// </summary> public readonly Keybind SecondaryGamepadButtons = new Keybind(Buttons.X); /// <summary> /// A <see cref="Keybind"/> that acts as the buttons that select a <see cref="Element"/> that is above the currently selected element. /// </summary> public readonly Keybind UpButtons = new Keybind().Add(Buttons.DPadUp).Add(Buttons.LeftThumbstickUp); /// <summary> /// A <see cref="Keybind"/> that acts as the buttons that select a <see cref="Element"/> that is below the currently selected element. /// </summary> public readonly Keybind DownButtons = new Keybind().Add(Buttons.DPadDown).Add(Buttons.LeftThumbstickDown); /// <summary> /// A <see cref="Keybind"/> that acts as the buttons that select a <see cref="Element"/> that is to the left of the currently selected element. /// </summary> public readonly Keybind LeftButtons = new Keybind().Add(Buttons.DPadLeft).Add(Buttons.LeftThumbstickLeft); /// <summary> /// A <see cref="Keybind"/> that acts as the buttons that select a <see cref="Element"/> that is to the right of the currently selected element. /// </summary> public readonly Keybind RightButtons = new Keybind().Add(Buttons.DPadRight).Add(Buttons.LeftThumbstickRight); /// <summary> /// All <see cref="Keybind"/> instances used by these ui controls. /// This can be used to easily serialize and deserialize all ui keybinds. /// </summary> public readonly Keybind[] Keybinds; /// <summary> /// The zero-based index of the <see cref="GamePad"/> used for gamepad input. /// If this index is lower than 0, every connected gamepad will trigger input. /// </summary> public int GamepadIndex = -1; /// <summary> /// Set this to false to disable mouse input for these ui controls. /// Note that this does not disable mouse input for the underlying <see cref="InputHandler"/>. /// </summary> public bool HandleMouse = true; /// <summary> /// Set this to false to disable keyboard input for these ui controls. /// Note that this does not disable keyboard input for the underlying <see cref="InputHandler"/>. /// </summary> public bool HandleKeyboard = true; /// <summary> /// Set this to false to disable touch input for these ui controls. /// Note that this does not disable touch input for the underlying <see cref="InputHandler"/>. /// </summary> public bool HandleTouch = true; /// <summary> /// Set this to false to disable gamepad input for these ui controls. /// Note that this does not disable gamepad input for the underlying <see cref="InputHandler"/>. /// </summary> public bool HandleGamepad = true; /// <summary> /// If this value is true, the ui controls are in automatic navigation mode. /// This means that the <see cref="UiStyle.SelectionIndicator"/> will be drawn around the <see cref="SelectedElement"/>. /// To set this value, use <see cref="SelectElement"/> or <see cref="RootElement.SelectElement"/> /// </summary> public bool IsAutoNavMode { get; internal set; } /// <summary> /// Creates a new instance of the ui controls. /// You should rarely have to invoke this manually, since the <see cref="UiSystem"/> handles it. /// </summary> /// <param name="system">The ui system to control with these controls</param> /// <param name="inputHandler">The input handler to use for controlling, or null to create a new one.</param> public UiControls(UiSystem system, InputHandler inputHandler = null) { this.System = system; this.Input = inputHandler ?? new InputHandler(system.Game); this.IsInputOurs = inputHandler == null; this.Keybinds = typeof(UiControls).GetFields() .Where(f => f.FieldType == typeof(Keybind)) .Select(f => (Keybind) f.GetValue(this)).ToArray(); // enable all required gestures InputHandler.EnableGestures(GestureType.Tap, GestureType.Hold); } /// <summary> /// Update this ui controls instance, causing the underlying <see cref="InputHandler"/> to be updated, as well as ui input to be queried. /// </summary> public virtual void Update() { if (this.IsInputOurs) this.Input.Update(); this.ActiveRoot = this.System.GetRootElements().FirstOrDefault(root => root.CanSelectContent && !root.Element.IsHidden); // MOUSE INPUT if (this.HandleMouse) { var mousedNow = this.GetElementUnderPos(this.Input.MousePosition.ToVector2()); this.SetMousedElement(mousedNow); if (this.Input.IsMouseButtonPressed(MouseButton.Left)) { this.IsAutoNavMode = false; var selectedNow = mousedNow != null && mousedNow.CanBeSelected ? mousedNow : null; this.SelectElement(this.ActiveRoot, selectedNow); if (mousedNow != null && mousedNow.CanBePressed) this.System.InvokeOnElementPressed(mousedNow); } else if (this.Input.IsMouseButtonPressed(MouseButton.Right)) { this.IsAutoNavMode = false; if (mousedNow != null && mousedNow.CanBePressed) this.System.InvokeOnElementSecondaryPressed(mousedNow); } } // KEYBOARD INPUT if (this.HandleKeyboard) { if (this.KeyboardButtons.IsPressed(this.Input, this.GamepadIndex)) { if (this.SelectedElement?.Root != null && this.SelectedElement.CanBePressed) { if (this.Input.IsModifierKeyDown(ModifierKey.Shift)) { // secondary action on element using space or enter this.System.InvokeOnElementSecondaryPressed(this.SelectedElement); } else { // first action on element using space or enter this.System.InvokeOnElementPressed(this.SelectedElement); } } } else if (this.Input.IsKeyPressed(Keys.Tab)) { this.IsAutoNavMode = true; // tab or shift-tab to next or previous element var backward = this.Input.IsModifierKeyDown(ModifierKey.Shift); var next = this.GetTabNextElement(backward); if (this.SelectedElement?.Root != null) next = this.SelectedElement.GetTabNextElement(backward, next); this.SelectElement(this.ActiveRoot, next); } } // TOUCH INPUT if (this.HandleTouch) { if (this.Input.GetGesture(GestureType.Tap, out var tap)) { this.IsAutoNavMode = false; var tapped = this.GetElementUnderPos(tap.Position); this.SelectElement(this.ActiveRoot, tapped); if (tapped != null && tapped.CanBePressed) this.System.InvokeOnElementPressed(tapped); } else if (this.Input.GetGesture(GestureType.Hold, out var hold)) { this.IsAutoNavMode = false; var held = this.GetElementUnderPos(hold.Position); this.SelectElement(this.ActiveRoot, held); if (held != null && held.CanBePressed) this.System.InvokeOnElementSecondaryPressed(held); } else if (this.Input.TouchState.Count <= 0) { this.SetTouchedElement(null); } else { foreach (var location in this.Input.TouchState) { var element = this.GetElementUnderPos(location.Position); if (location.State == TouchLocationState.Pressed) { // start touching an element if we just touched down on it this.SetTouchedElement(element); } else if (element != this.TouchedElement) { // if we moved off of the touched element, we stop touching this.SetTouchedElement(null); } } } } // GAMEPAD INPUT if (this.HandleGamepad) { if (this.GamepadButtons.IsPressed(this.Input, this.GamepadIndex)) { if (this.SelectedElement?.Root != null && this.SelectedElement.CanBePressed) this.System.InvokeOnElementPressed(this.SelectedElement); } else if (this.SecondaryGamepadButtons.IsPressed(this.Input, this.GamepadIndex)) { if (this.SelectedElement?.Root != null && this.SelectedElement.CanBePressed) this.System.InvokeOnElementSecondaryPressed(this.SelectedElement); } else if (this.DownButtons.IsPressed(this.Input, this.GamepadIndex)) { this.HandleGamepadNextElement(Direction2.Down); } else if (this.LeftButtons.IsPressed(this.Input, this.GamepadIndex)) { this.HandleGamepadNextElement(Direction2.Left); } else if (this.RightButtons.IsPressed(this.Input, this.GamepadIndex)) { this.HandleGamepadNextElement(Direction2.Right); } else if (this.UpButtons.IsPressed(this.Input, this.GamepadIndex)) { this.HandleGamepadNextElement(Direction2.Up); } } } /// <summary> /// Returns the <see cref="Element"/> in the underlying <see cref="UiSystem"/> that is currently below the given position. /// Throughout the ui system, this is used for mouse input querying. /// </summary> /// <param name="position">The position to query</param> /// <param name="transform">If this value is true, the <see cref="RootElement.Transform"/> will be applied.</param> /// <returns>The element under the position, or null if there isn't one</returns> public virtual Element GetElementUnderPos(Vector2 position, bool transform = true) { foreach (var root in this.System.GetRootElements()) { var pos = transform ? Vector2.Transform(position, root.InvTransform) : position; var moused = root.Element.GetElementUnderPos(pos); if (moused != null) return moused; } return null; } /// <summary> /// Selects the given element that is a child of the given root element. /// Optionally, automatic navigation can be forced on, causing the <see cref="UiStyle.SelectionIndicator"/> to be drawn around the element. /// A simpler version of this method is <see cref="RootElement.SelectElement"/>. /// </summary> /// <param name="root">The root element of the <see cref="Element"/></param> /// <param name="element">The element to select, or null to deselect the selected element.</param> /// <param name="autoNav">Whether automatic navigation should be forced on</param> public void SelectElement(RootElement root, Element element, bool? autoNav = null) { if (root == null) return; var selected = this.GetSelectedElement(root); if (selected == element) return; if (selected != null) this.System.InvokeOnElementDeselected(selected); if (element != null) { this.System.InvokeOnElementSelected(element); this.selectedElements[root.Name] = element; } else { this.selectedElements.Remove(root.Name); } this.System.InvokeOnSelectedElementChanged(element); if (autoNav != null) this.IsAutoNavMode = autoNav.Value; } /// <summary> /// Sets the <see cref="MousedElement"/> to the given value, calling the appropriate events. /// </summary> /// <param name="element">The element to set as moused</param> public void SetMousedElement(Element element) { if (element != this.MousedElement) { if (this.MousedElement != null) this.System.InvokeOnElementMouseExit(this.MousedElement); if (element != null) this.System.InvokeOnElementMouseEnter(element); this.MousedElement = element; this.System.InvokeOnMousedElementChanged(element); } } /// <summary> /// Sets the <see cref="TouchedElement"/> to the given value, calling the appropriate events. /// </summary> /// <param name="element">The element to set as touched</param> public void SetTouchedElement(Element element) { if (element != this.TouchedElement) { if (this.TouchedElement != null) this.System.InvokeOnElementTouchExit(this.TouchedElement); if (element != null) this.System.InvokeOnElementTouchEnter(element); this.TouchedElement = element; this.System.InvokeOnTouchedElementChanged(element); } } /// <summary> /// Returns the selected element for the given root element. /// A property equivalent to this method is <see cref="RootElement.SelectedElement"/>. /// </summary> /// <param name="root">The root element whose selected element to return</param> /// <returns>The given root's selected element, or null if the root doesn't exist, or if there is no selected element for that root.</returns> public Element GetSelectedElement(RootElement root) { if (root == null) return null; this.selectedElements.TryGetValue(root.Name, out var element); return element; } /// <summary> /// Returns the next element to select when pressing the <see cref="Keys.Tab"/> key during keyboard navigation. /// If the <c>backward</c> boolean is true, the previous element should be returned instead. /// </summary> /// <param name="backward">If we're going backwards (if <see cref="ModifierKey.Shift"/> is held)</param> /// <returns>The next or previous element to select</returns> protected virtual Element GetTabNextElement(bool backward) { if (this.ActiveRoot == null) return null; var children = this.ActiveRoot.Element.GetChildren(c => !c.IsHidden, true, true).Append(this.ActiveRoot.Element); if (this.SelectedElement?.Root != this.ActiveRoot) { return backward ? children.LastOrDefault(c => c.CanBeSelected) : children.FirstOrDefault(c => c.CanBeSelected); } else { var foundCurr = false; Element lastFound = null; foreach (var child in children) { if (!child.CanBeSelected) continue; if (child == this.SelectedElement) { // when going backwards, return the last element found before the current one if (backward) return lastFound; foundCurr = true; } else { // when going forwards, return the element after the current one if (!backward && foundCurr) return child; } lastFound = child; } return null; } } /// <summary> /// Returns the next element that should be selected during gamepad navigation, based on the <see cref="RectangleF"/> that we're looking for elements in. /// </summary> /// <param name="searchArea">The area that we're looking for next elements in</param> /// <returns>The first element found in that area</returns> protected virtual Element GetGamepadNextElement(RectangleF searchArea) { if (this.ActiveRoot == null) return null; var children = this.ActiveRoot.Element.GetChildren(c => !c.IsHidden, true, true).Append(this.ActiveRoot.Element); if (this.SelectedElement?.Root != this.ActiveRoot) { return children.FirstOrDefault(c => c.CanBeSelected); } else { Element closest = null; float closestDist = 0; foreach (var child in children) { if (!child.CanBeSelected || child == this.SelectedElement || !searchArea.Intersects(child.Area)) continue; var dist = Vector2.Distance(child.Area.Center, this.SelectedElement.Area.Center); if (closest == null || dist < closestDist) { closest = child; closestDist = dist; } } return closest; } } private void HandleGamepadNextElement(Direction2 dir) { this.IsAutoNavMode = true; RectangleF searchArea = default; if (this.SelectedElement?.Root != null) { searchArea = this.SelectedElement.Area; var (_, _, width, height) = this.System.Viewport; switch (dir) { case Direction2.Down: searchArea.Height += height; break; case Direction2.Left: searchArea.X -= width; searchArea.Width += width; break; case Direction2.Right: searchArea.Width += width; break; case Direction2.Up: searchArea.Y -= height; searchArea.Height += height; break; } } var next = this.GetGamepadNextElement(searchArea); if (this.SelectedElement != null) next = this.SelectedElement.GetGamepadNextElement(dir, next); if (next != null) this.SelectElement(this.ActiveRoot, next); } } }<file_sep>/Demos/GameImpl.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Font; using MLEM.Startup; using MLEM.Textures; using MLEM.Ui; using MLEM.Ui.Elements; using MLEM.Ui.Style; namespace Demos { public class GameImpl : MlemGame { private static readonly Dictionary<string, (string, Func<MlemGame, Demo>)> Demos = new Dictionary<string, (string, Func<MlemGame, Demo>)>(); private Demo activeDemo; private double fpsTime; private int lastFps; private int fpsCounter; static GameImpl() { Demos.Add("Ui", ("An in-depth demonstration of the MLEM.Ui package and its abilities", game => new UiDemo(game))); Demos.Add("Easings", ("An example of MLEM's Easings class, an adaptation of easings.net", game => new EasingsDemo(game))); Demos.Add("Pathfinding", ("An example of MLEM's A* pathfinding implementation in 2D", game => new PathfindingDemo(game))); Demos.Add("Animation and Texture Atlas", ("An example of UniformTextureAtlases, SpriteAnimations and SpriteAnimationGroups", game => new AnimationDemo(game))); Demos.Add("Auto Tiling", ("A demonstration of the AutoTiling class that MLEM provides", game => new AutoTilingDemo(game))); } public GameImpl() { this.IsMouseVisible = true; } protected override void LoadContent() { // TODO remove with MonoGame 3.8.1 https://github.com/MonoGame/MonoGame/issues/7298 this.GraphicsDeviceManager.PreferredBackBufferWidth = 1280; this.GraphicsDeviceManager.PreferredBackBufferHeight = 720; this.GraphicsDeviceManager.ApplyChanges(); base.LoadContent(); var tex = LoadContent<Texture2D>("Textures/Test"); this.UiSystem.Style = new UntexturedStyle(this.SpriteBatch) { Font = new GenericSpriteFont(LoadContent<SpriteFont>("Fonts/TestFont")), TextScale = 0.1F, PanelTexture = new NinePatch(new TextureRegion(tex, 0, 8, 24, 24), 8), ButtonTexture = new NinePatch(new TextureRegion(tex, 24, 8, 16, 16), 4), ScrollBarBackground = new NinePatch(new TextureRegion(tex, 12, 0, 4, 8), 1, 1, 2, 2), ScrollBarScrollerTexture = new NinePatch(new TextureRegion(tex, 8, 0, 4, 8), 1, 1, 2, 2) }; this.UiSystem.AutoScaleReferenceSize = new Point(1280, 720); this.UiSystem.AutoScaleWithScreen = true; this.UiSystem.GlobalScale = 5; var ui = new Group(Anchor.TopLeft, Vector2.One, false); this.UiSystem.Add("DemoUi", ui); var selection = ui.AddChild(new Panel(Anchor.Center, new Vector2(100, 80), Vector2.Zero, true)); var backButton = ui.AddChild(new Button(Anchor.TopRight, new Vector2(30, 10), "Back") { OnPressed = e => { this.activeDemo.Clear(); this.activeDemo = null; selection.IsHidden = false; e.IsHidden = true; selection.Root.SelectElement(selection.GetChildren().First(c => c.CanBeSelected)); }, IsHidden = true }); selection.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Select the demo you want to see below using your mouse, touch input, your keyboard or a controller. Check the demos' <c CornflowerBlue><l https://github.com/Ellpeck/MLEM/tree/main/Demos>source code</l></c> for more in-depth explanations of their functionality or the <c CornflowerBlue><l https://mlem.ellpeck.de/>website</l></c> for tutorials and API documentation.")); selection.AddChild(new VerticalSpace(5)); foreach (var demo in Demos) { selection.AddChild(new Button(Anchor.AutoCenter, new Vector2(1, 10), demo.Key, demo.Value.Item1) { OnPressed = e => { selection.IsHidden = true; backButton.IsHidden = false; backButton.Root.SelectElement(backButton); this.activeDemo = demo.Value.Item2.Invoke(this); this.activeDemo.LoadContent(); }, PositionOffset = new Vector2(0, 1) }); } ui.AddChild(new Paragraph(Anchor.TopLeft, 1, p => "FPS: " + this.lastFps)); } protected override void DoDraw(GameTime gameTime) { if (this.activeDemo != null) { this.activeDemo.DoDraw(gameTime); } else { this.GraphicsDevice.Clear(Color.CornflowerBlue); } base.DoDraw(gameTime); this.fpsCounter++; this.fpsTime += gameTime.ElapsedGameTime.TotalSeconds; if (this.fpsTime >= 1) { this.fpsTime -= 1; this.lastFps = this.fpsCounter; this.fpsCounter = 0; } } protected override void DoUpdate(GameTime gameTime) { base.DoUpdate(gameTime); if (this.activeDemo != null) this.activeDemo.Update(gameTime); } } }<file_sep>/Demos/UiDemo.cs using System; using System.Collections.Generic; using System.Linq; using Coroutine; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Font; using MLEM.Formatting; using MLEM.Formatting.Codes; using MLEM.Misc; using MLEM.Startup; using MLEM.Textures; using MLEM.Ui; using MLEM.Ui.Elements; using MLEM.Ui.Style; namespace Demos { public class UiDemo : Demo { private Texture2D testTexture; private NinePatch testPatch; private Panel root; public UiDemo(MlemGame game) : base(game) { } public override void LoadContent() { this.testTexture = LoadContent<Texture2D>("Textures/Test"); this.testPatch = new NinePatch(new TextureRegion(this.testTexture, 0, 8, 24, 24), 8); base.LoadContent(); // create a new style // this one derives form UntexturedStyle so that stuff like the hover colors don't have to be set again var style = new UntexturedStyle(this.SpriteBatch) { // when using a SpriteFont, use GenericSpriteFont. When using a MonoGame.Extended BitmapFont, use GenericBitmapFont. // Wrapping fonts like this allows for both types to be usable within MLEM.Ui easily // Supplying a bold and an italic version is optional Font = new GenericSpriteFont(LoadContent<SpriteFont>("Fonts/TestFont"), LoadContent<SpriteFont>("Fonts/TestFontBold"), LoadContent<SpriteFont>("Fonts/TestFontItalic")), TextScale = 0.1F, PanelTexture = this.testPatch, ButtonTexture = new NinePatch(new TextureRegion(this.testTexture, 24, 8, 16, 16), 4), TextFieldTexture = new NinePatch(new TextureRegion(this.testTexture, 24, 8, 16, 16), 4), ScrollBarBackground = new NinePatch(new TextureRegion(this.testTexture, 12, 0, 4, 8), 1, 1, 2, 2), ScrollBarScrollerTexture = new NinePatch(new TextureRegion(this.testTexture, 8, 0, 4, 8), 1, 1, 2, 2), CheckboxTexture = new NinePatch(new TextureRegion(this.testTexture, 24, 8, 16, 16), 4), CheckboxCheckmark = new TextureRegion(this.testTexture, 24, 0, 8, 8), RadioTexture = new NinePatch(new TextureRegion(this.testTexture, 16, 0, 8, 8), 3), RadioCheckmark = new TextureRegion(this.testTexture, 32, 0, 8, 8) }; var untexturedStyle = new UntexturedStyle(this.SpriteBatch); // set the defined style as the current one this.UiSystem.Style = style; // scale every ui up by 5 this.UiSystem.GlobalScale = 5; // set the ui system to automatically scale with screen size // this will cause all ui elements to be scaled based on the reference resolution (AutoScaleReferenceSize) // by default, the reference resolution is set to the initial screen size, however this value can be changed through the ui system this.UiSystem.AutoScaleWithScreen = true; // create the root panel that all the other components sit on and add it to the ui system this.root = new Panel(Anchor.Center, new Vector2(80, 100), Vector2.Zero, false, true, new Point(5, 10)); this.root.ScrollBar.SmoothScrolling = true; // add the root to the demos' ui this.UiRoot.AddChild(this.root); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "This is a small demo for MLEM.Ui, a user interface library that is part of the MLEM Library for Extending MonoGame.")); var image = this.root.AddChild(new Image(Anchor.AutoCenter, new Vector2(50, 50), new TextureRegion(this.testTexture, 0, 0, 8, 8)) {IsHidden = true, Padding = new Vector2(3)}); // Setting the x or y coordinate of the size to 1 or a lower number causes the width or height to be a percentage of the parent's width or height // (for example, setting the size's x to 0.75 would make the element's width be 0.75*parentWidth) this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(1, 10), "Toggle Grass Image", "This button shows a grass tile above it to show the automatic anchoring of objects.") { OnPressed = element => image.IsHidden = !image.IsHidden }); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Note that the default style does not contain any textures or font files and, as such, is quite bland. However, the default style is quite easy to override, as can be seen in the code for this demo.")); this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(1, 10), "Change Style") { OnPressed = element => this.UiSystem.Style = this.UiSystem.Style == untexturedStyle ? style : untexturedStyle, PositionOffset = new Vector2(0, 1), Texture = this.testPatch }); this.root.AddChild(new VerticalSpace(3)); // a paragraph with formatting codes. To see them all or to add more, check the TextFormatting class this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Paragraphs can also contain <c Blue>formatting codes</c>, including colors and <i>text styles</i>. The names of all <c Orange>MonoGame Colors</c> can be used, as well as the codes <i>Italic</i>, <b>Bold</b>, <s>Drop Shadow'd</s> and <s><c Pink>mixed formatting</s></c>. \n<i>Even <c #ff611f82>inline custom colors</c> work!</i>")); // adding some custom image formatting codes this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Additionally, you can create custom formatting codes that contain <i Grass> images and more!")); this.UiSystem.TextFormatter.AddImage("Grass", image.Texture); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Defining text animations as formatting codes is also possible, including <a wobbly>wobbly text</a> at <a wobbly 8 0.25>different intensities</a>. Of course, more animations can be added though.")); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoCenter, 1, "Text input:", true)); this.root.AddChild(new TextField(Anchor.AutoLeft, new Vector2(1, 10)) { PositionOffset = new Vector2(0, 1), PlaceholderText = "Click here to input text" }); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoCenter, 1, "Numbers-only input:", true)); this.root.AddChild(new TextField(Anchor.AutoLeft, new Vector2(1, 10), TextField.OnlyNumbers) {PositionOffset = new Vector2(0, 1)}); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoCenter, 1, "Password-style input:", true)); this.root.AddChild(new TextField(Anchor.AutoLeft, new Vector2(1, 10), text: "secret") { PositionOffset = new Vector2(0, 1), MaskingCharacter = '*' }); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Zoom in or out:")); this.root.AddChild(new Button(Anchor.AutoLeft, new Vector2(10), "+") { OnPressed = element => { if (element.Root.Scale < 2) element.Root.Scale += 0.1F; } }); this.root.AddChild(new Button(Anchor.AutoInline, new Vector2(10), "-") { OnPressed = element => { if (element.Root.Scale > 0.5F) element.Root.Scale -= 0.1F; }, PositionOffset = new Vector2(1, 0) }); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Checkbox(Anchor.AutoLeft, new Vector2(1, 10), "Checkbox 1!")); this.root.AddChild(new Checkbox(Anchor.AutoLeft, new Vector2(1, 10), "Checkbox 2!") {PositionOffset = new Vector2(0, 1)}); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new RadioButton(Anchor.AutoLeft, new Vector2(1, 10), "Radio button 1!")); this.root.AddChild(new RadioButton(Anchor.AutoLeft, new Vector2(1, 10), "Radio button 2!") {PositionOffset = new Vector2(0, 1)}); var tooltip = new Tooltip(50, "I am tooltip!") {IsHidden = true}; this.UiSystem.Add("TestTooltip", tooltip); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Button(Anchor.AutoLeft, new Vector2(1, 10), "Toggle Mouse Tooltip") { OnPressed = element => tooltip.IsHidden = !tooltip.IsHidden }); var slider = new Slider(Anchor.AutoLeft, new Vector2(1, 10), 5, 1) { StepPerScroll = 0.01F }; this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, paragraph => "Slider is at " + (slider.CurrentValue * 100).Floor() + "%") {PositionOffset = new Vector2(0, 1)}); this.root.AddChild(slider); // Check the WobbleButton method for an explanation of how this button works this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(0.5F, 10), "Wobble Me", "This button wobbles around visually when clicked, but this doesn't affect its actual size and positioning") { OnPressed = element => CoroutineHandler.Start(WobbleButton(element)), PositionOffset = new Vector2(0, 1) }); // Another button that shows animations! var fancyHoverTimer = 0D; var fancyButton = this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(0.5F, 10), "Fancy Hover") { PositionOffset = new Vector2(0, 1), OnUpdated = (e, time) => { if (e.IsMouseOver && fancyHoverTimer <= 0.5F) return; if (fancyHoverTimer > 0) { fancyHoverTimer -= time.ElapsedGameTime.TotalSeconds * 3; e.ScaleTransform(1 + (float) Math.Sin(fancyHoverTimer * MathHelper.Pi) * 0.05F); } else { e.Transform = Matrix.Identity; } } }); fancyButton.OnMouseEnter += e => fancyHoverTimer = 1; this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(0.5F, 10), "Transform Ui", "This button causes the entire ui to be transformed (both in positioning, rotation and scale)") { OnPressed = element => { if (element.Root.Transform == Matrix.Identity) { element.Root.Transform = Matrix.CreateScale(0.75F) * Matrix.CreateRotationZ(0.25F) * Matrix.CreateTranslation(50, -10, 0); } else { element.Root.Transform = Matrix.Identity; } }, PositionOffset = new Vector2(0, 1) }); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Progress bars!")); var bar1 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(1, 8), Direction2.Right, 10) {PositionOffset = new Vector2(0, 1)}); CoroutineHandler.Start(WobbleProgressBar(bar1)); var bar2 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(1, 8), Direction2.Left, 10) {PositionOffset = new Vector2(0, 1)}); CoroutineHandler.Start(WobbleProgressBar(bar2)); var bar3 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(8, 30), Direction2.Down, 10) {PositionOffset = new Vector2(0, 1)}); CoroutineHandler.Start(WobbleProgressBar(bar3)); var bar4 = this.root.AddChild(new ProgressBar(Anchor.AutoInline, new Vector2(8, 30), Direction2.Up, 10) {PositionOffset = new Vector2(1, 1)}); CoroutineHandler.Start(WobbleProgressBar(bar4)); this.root.AddChild(new VerticalSpace(3)); var dropdown = this.root.AddChild(new Dropdown(Anchor.AutoLeft, new Vector2(1, 10), "Dropdown Menu")); dropdown.AddElement("First Option"); dropdown.AddElement("Second Option"); dropdown.AddElement("Third Option"); dropdown.AddElement(new Paragraph(Anchor.AutoLeft, 1, "Dropdowns are basically just prioritized panels, so they can contain all controls, including paragraphs and")); dropdown.AddElement(new Button(Anchor.AutoLeft, new Vector2(1, 10), "Buttons")); this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Button(Anchor.AutoLeft, new Vector2(1, 10), "Disabled button", "This button can't be clicked or moved to using automatic navigation") {IsDisabled = true}).PositionOffset = new Vector2(0, 1); const string alignText = "Paragraphs can have <c CornflowerBlue><l Left>left</l></c> aligned text, <c CornflowerBlue><l Right>right</l></c> aligned text and <c CornflowerBlue><l Center>center</l></c> aligned text."; this.root.AddChild(new VerticalSpace(3)); var alignPar = this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, alignText)); alignPar.LinkAction = (l, c) => { if (Enum.TryParse<TextAlignment>(c.Match.Groups[1].Value, out var alignment)) alignPar.Alignment = alignment; }; this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "The code for this demo contains some examples for how to query element data. This is the output of that:")); var children = this.root.GetChildren(); var totalChildren = this.root.GetChildren(regardGrandchildren: true); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, $"The root has <b>{children.Count()}</b> children, but there are <b>{totalChildren.Count()}</b> when regarding children's children")); var textFields = this.root.GetChildren<TextField>(); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, $"The root has <b>{textFields.Count()}</b> text fields")); var paragraphs = this.root.GetChildren<Paragraph>(); var totalParagraphs = this.root.GetChildren<Paragraph>(regardGrandchildren: true); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, $"The root has <b>{paragraphs.Count()}</b> paragraphs, but there are <b>{totalParagraphs.Count()}</b> when regarding children's children")); var autoWidthChildren = this.root.GetChildren(e => e.Size.X == 1); var autoWidthButtons = this.root.GetChildren<Button>(e => e.Size.X == 1); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, $"The root has <b>{autoWidthChildren.Count()}</b> auto-width children, <b>{autoWidthButtons.Count()}</b> of which are buttons")); // select the first element for auto-navigation this.root.Root.SelectElement(this.root.GetChildren().First(c => c.CanBeSelected)); } // This method is used by the wobbling button (see above) // Note that this particular example makes use of the Coroutine package, which is not required but makes demonstration easier private static IEnumerator<Wait> WobbleButton(Element button) { var counter = 0F; while (counter < 4 * Math.PI) { // Every element allows the implementation of any sort of custom rendering for itself and all of its child components // This includes simply changing the transform matrix like here, but also applying custom effects and doing // anything else that can be done in the SpriteBatch's Begin call. // Note that changing visual features like this // has no effect on the ui's actual interaction behavior (mouse position interpretation, for example), but it can // be a great way to accomplish feedback animations for buttons and so on. button.Transform = Matrix.CreateTranslation((float) Math.Sin(counter / 2) * 10 * button.Scale, 0, 0); counter += 0.1F; yield return new Wait(0.01F); } button.Transform = Matrix.Identity; } private static IEnumerator<Wait> WobbleProgressBar(ProgressBar bar) { var reducing = false; while (bar.Root != null) { if (reducing) { bar.CurrentValue -= 0.1F; if (bar.CurrentValue <= 0) reducing = false; } else { bar.CurrentValue += 0.1F; if (bar.CurrentValue >= bar.MaxValue) reducing = true; } yield return new Wait(0.01F); } } public override void Clear() { this.root.Root.Element.RemoveChild(this.root); this.UiSystem.Remove("TestTooltip"); } public override void DoDraw(GameTime gameTime) { this.GraphicsDevice.Clear(Color.CornflowerBlue); base.DoDraw(gameTime); } } }<file_sep>/MLEM/Misc/GenericDataHolder.cs using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MLEM.Misc { /// <inheritdoc /> [DataContract] public class GenericDataHolder : IGenericDataHolder { [DataMember(EmitDefaultValue = false)] private Dictionary<string, object> data; /// <inheritdoc /> public void SetData(string key, object data) { if (data == default) { if (this.data != null) this.data.Remove(key); } else { if (this.data == null) this.data = new Dictionary<string, object>(); this.data[key] = data; } } /// <inheritdoc /> public T GetData<T>(string key) { if (this.data != null && this.data.TryGetValue(key, out var val)) return (T) val; return default; } /// <inheritdoc /> public IReadOnlyCollection<string> GetDataKeys() { if (this.data == null) return Array.Empty<string>(); return this.data.Keys; } } /// <summary> /// Represents an object that can hold generic key-value based data. /// A lot of MLEM components extend this class to allow for users to add additional data to them easily. /// </summary> public interface IGenericDataHolder { /// <summary> /// Store a piece of generic data on this object. /// </summary> /// <param name="key">The key to store the data by</param> /// <param name="data">The data to store in the object</param> void SetData(string key, object data); /// <summary> /// Returns a piece of generic data of the given type on this object. /// </summary> /// <param name="key">The key that the data is stored by</param> /// <typeparam name="T">The type of the data stored</typeparam> /// <returns>The data, or default if it doesn't exist</returns> T GetData<T>(string key); /// <summary> /// Returns all of the generic data that this object stores. /// </summary> /// <returns>The generic data on this object</returns> IReadOnlyCollection<string> GetDataKeys(); } }<file_sep>/Tests/DirectionTests.cs using Microsoft.Xna.Framework; using MLEM.Misc; using NUnit.Framework; using static MLEM.Misc.Direction2; namespace Tests { public class DirectionTests { [Test] public void TestDirections() { Assert.AreEqual(new Vector2(0.5F, 0.5F).ToDirection(), DownRight); Assert.AreEqual(new Vector2(0.25F, 0.5F).ToDirection(), DownRight); Assert.AreEqual(new Vector2(0.15F, 0.5F).ToDirection(), Down); } [Test] public void Test90Directions() { Assert.AreEqual(new Vector2(0.75F, 0.5F).To90Direction(), Right); Assert.AreEqual(new Vector2(0.5F, 0.5F).To90Direction(), Down); Assert.AreEqual(new Vector2(0.25F, 0.5F).To90Direction(), Down); } [Test] public void TestRotations() { // rotate cw Assert.AreEqual(Up.RotateCw(), Right); Assert.AreEqual(Up.RotateCw(true), UpRight); Assert.AreEqual(Left.RotateCw(), Up); Assert.AreEqual(UpLeft.RotateCw(), UpRight); // rotate ccw Assert.AreEqual(Up.RotateCcw(), Left); Assert.AreEqual(Up.RotateCcw(true), UpLeft); Assert.AreEqual(Left.RotateCcw(), Down); Assert.AreEqual(UpLeft.RotateCcw(), DownLeft); // rotate 360 degrees foreach (var dir in Direction2Helper.AllExceptNone) { Assert.AreEqual(RotateMultipleTimes(dir, true, false, 4), dir); Assert.AreEqual(RotateMultipleTimes(dir, true, true, 8), dir); Assert.AreEqual(RotateMultipleTimes(dir, false, false, 4), dir); Assert.AreEqual(RotateMultipleTimes(dir, false, true, 8), dir); } // rotate by with start Up Assert.AreEqual(Right.RotateBy(Right), Down); Assert.AreEqual(Right.RotateBy(Down), Left); Assert.AreEqual(Right.RotateBy(Left), Up); Assert.AreEqual(Right.RotateBy(Up), Right); // rotate by with start Left Assert.AreEqual(Up.RotateBy(Right, Left), Down); Assert.AreEqual(Up.RotateBy(Down, Left), Left); Assert.AreEqual(Up.RotateBy(Left, Left), Up); Assert.AreEqual(Up.RotateBy(Up, Left), Right); } private static Direction2 RotateMultipleTimes(Direction2 dir, bool clockwise, bool fortyFiveDegrees, int times) { for (var i = 0; i < times; i++) dir = clockwise ? dir.RotateCw(fortyFiveDegrees) : dir.RotateCcw(fortyFiveDegrees); return dir; } } }<file_sep>/MLEM.Data/RuntimeTexturePacker.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Textures; namespace MLEM.Data { /// <summary> /// A runtime texture packer provides the user with the ability to combine multiple <see cref="Texture2D"/> instances into a single texture. /// Packing textures in this manner allows for faster rendering, as fewer texture swaps are required. /// The resulting texture segments are returned as <see cref="TextureRegion"/> instances. /// </summary> public class RuntimeTexturePacker : IDisposable { private readonly List<Request> textures = new List<Request>(); private readonly bool autoIncreaseMaxWidth; private readonly bool forcePowerOfTwo; private readonly bool forceSquare; /// <summary> /// The generated packed texture. /// This value is null before <see cref="Pack"/> is called. /// </summary> public Texture2D PackedTexture { get; private set; } /// <summary> /// The time that it took to calculate the required areas the last time that <see cref="Pack"/> was called /// </summary> public TimeSpan LastCalculationTime { get; private set; } /// <summary> /// The time that it took to copy the texture data from the invidiual textures onto the <see cref="PackedTexture"/> the last time that <see cref="Pack"/> was called /// </summary> public TimeSpan LastPackTime { get; private set; } /// <summary> /// The time that <see cref="Pack"/> took the last time it was called /// </summary> public TimeSpan LastTotalTime => this.LastCalculationTime + this.LastPackTime; private int maxWidth; /// <summary> /// Creates a new runtime texture packer with the given settings /// </summary> /// <param name="maxWidth">The maximum width that the packed texture can have. Defaults to 2048.</param> /// <param name="autoIncreaseMaxWidth">Whether the maximum width should be increased if there is a texture to be packed that is wider than <see cref="maxWidth"/>. Defaults to false.</param> /// <param name="forcePowerOfTwo">Whether the resulting <see cref="PackedTexture"/> should have a width and height that is a power of two</param> /// <param name="forceSquare">Whether the resulting <see cref="PackedTexture"/> should be square regardless of required size</param> public RuntimeTexturePacker(int maxWidth = 2048, bool autoIncreaseMaxWidth = false, bool forcePowerOfTwo = false, bool forceSquare = false) { this.maxWidth = maxWidth; this.autoIncreaseMaxWidth = autoIncreaseMaxWidth; this.forcePowerOfTwo = forcePowerOfTwo; this.forceSquare = forceSquare; } /// <summary> /// Adds a new texture to this texture packer to be packed. /// The passed <see cref="Action{T}"/> is invoked in <see cref="Pack"/> and provides the caller with the resulting texture region on the <see cref="PackedTexture"/>. /// </summary> /// <param name="texture">The texture to pack</param> /// <param name="result">The result callback which will receive the resulting texture region</param> public void Add(Texture2D texture, Action<TextureRegion> result) { this.Add(new TextureRegion(texture), result); } /// <summary> /// Adds a new <see cref="TextureRegion"/> to this texture packer to be packed. /// The passed <see cref="Action{T}"/> is invoked in <see cref="Pack"/> and provides the caller with the resulting texture region on the <see cref="PackedTexture"/>. /// </summary> /// <param name="texture">The texture to pack</param> /// <param name="result">The result callback which will receive the resulting texture region</param> /// <exception cref="InvalidOperationException">Thrown when trying to add data to a packer that has already been packed, or when trying to add a texture width a width greater than the defined max width</exception> public void Add(TextureRegion texture, Action<TextureRegion> result) { if (this.PackedTexture != null) throw new InvalidOperationException("Cannot add texture to a texture packer that is already packed"); if (texture.Width > this.maxWidth) { if (this.autoIncreaseMaxWidth) { this.maxWidth = texture.Width; } else { throw new InvalidOperationException($"Cannot add texture with width {texture.Width} to a texture packer with max width {this.maxWidth}"); } } this.textures.Add(new Request(texture, result)); } /// <summary> /// Packs all of the textures and texture regions added using <see cref="Add(Microsoft.Xna.Framework.Graphics.Texture2D,System.Action{MLEM.Textures.TextureRegion})"/> into one texture. /// The resulting texture will be stored in <see cref="PackedTexture"/>. /// All of the result callbacks that were added will also be invoked. /// </summary> /// <param name="device">The graphics device to use for texture generation</param> /// <exception cref="InvalidOperationException">Thrown when calling this method on a texture packer that has already been packed</exception> public void Pack(GraphicsDevice device) { if (this.PackedTexture != null) throw new InvalidOperationException("Cannot pack a texture packer that is already packed"); // set pack areas for each request var stopwatch = Stopwatch.StartNew(); foreach (var request in this.textures.OrderByDescending(t => t.Texture.Width * t.Texture.Height)) { var area = this.FindFreeArea(new Point(request.Texture.Width, request.Texture.Height)); request.PackedArea = area; } stopwatch.Stop(); this.LastCalculationTime = stopwatch.Elapsed; // figure out texture size and generate texture var width = this.textures.Max(t => t.PackedArea.Right); var height = this.textures.Max(t => t.PackedArea.Bottom); if (this.forcePowerOfTwo) { width = ToPowerOfTwo(width); height = ToPowerOfTwo(height); } if (this.forceSquare) width = height = Math.Max(width, height); this.PackedTexture = new Texture2D(device, width, height); // copy texture data onto the packed texture stopwatch.Restart(); using (var data = this.PackedTexture.GetTextureData()) { foreach (var request in this.textures) CopyRegion(data, request); } stopwatch.Stop(); this.LastPackTime = stopwatch.Elapsed; // invoke callbacks foreach (var request in this.textures) request.Result.Invoke(new TextureRegion(this.PackedTexture, request.PackedArea)); this.textures.Clear(); } /// <summary> /// Resets this texture packer, disposing its <see cref="PackedTexture"/> and readying it to be re-used /// </summary> public void Reset() { this.PackedTexture?.Dispose(); this.PackedTexture = null; this.textures.Clear(); this.LastCalculationTime = TimeSpan.Zero; this.LastPackTime = TimeSpan.Zero; } /// <inheritdoc /> public void Dispose() { this.Reset(); } private Rectangle FindFreeArea(Point size) { var pos = new Point(0, 0); var lowestY = int.MaxValue; while (true) { var intersected = false; var area = new Rectangle(pos, size); foreach (var tex in this.textures) { if (tex.PackedArea.Intersects(area)) { pos.X = tex.PackedArea.Right; // when we move down, we want to move down by the smallest intersecting texture's height if (lowestY > tex.PackedArea.Bottom) lowestY = tex.PackedArea.Bottom; intersected = true; break; } } if (!intersected) return area; if (pos.X + size.X > this.maxWidth) { pos.X = 0; pos.Y = lowestY; lowestY = int.MaxValue; } } } private static void CopyRegion(TextureExtensions.TextureData destination, Request request) { using (var data = request.Texture.Texture.GetTextureData()) { for (var x = 0; x < request.Texture.Width; x++) { for (var y = 0; y < request.Texture.Height; y++) { var dest = request.PackedArea.Location + new Point(x, y); var src = request.Texture.Position + new Point(x, y); destination[dest] = data[src]; } } } } private static int ToPowerOfTwo(int value) { var ret = 1; while (ret < value) ret <<= 1; return ret; } private class Request { public readonly TextureRegion Texture; public readonly Action<TextureRegion> Result; public Rectangle PackedArea; public Request(TextureRegion texture, Action<TextureRegion> result) { this.Texture = texture; this.Result = result; } } } }<file_sep>/MLEM.Data/Json/RectangleFConverter.cs using System; using System.Globalization; using MLEM.Misc; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class RectangleFConverter : JsonConverter<RectangleF> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, RectangleF value, JsonSerializer serializer) { writer.WriteValue( value.X.ToString(CultureInfo.InvariantCulture) + " " + value.Y.ToString(CultureInfo.InvariantCulture) + " " + value.Width.ToString(CultureInfo.InvariantCulture) + " " + value.Height.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc /> public override RectangleF ReadJson(JsonReader reader, Type objectType, RectangleF existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = reader.Value.ToString().Split(' '); return new RectangleF( float.Parse(value[0], CultureInfo.InvariantCulture), float.Parse(value[1], CultureInfo.InvariantCulture), float.Parse(value[2], CultureInfo.InvariantCulture), float.Parse(value[3], CultureInfo.InvariantCulture)); } } }<file_sep>/Sandbox/GameImpl.cs using System; using System.IO; using System.Text.RegularExpressions; using FontStashSharp; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MLEM.Cameras; using MLEM.Data; using MLEM.Data.Content; using MLEM.Extended.Font; using MLEM.Extended.Tiled; using MLEM.Extensions; using MLEM.Formatting; using MLEM.Formatting.Codes; using MLEM.Input; using MLEM.Misc; using MLEM.Startup; using MLEM.Textures; using MLEM.Ui; using MLEM.Ui.Elements; using MLEM.Ui.Style; using MonoGame.Extended.Tiled; using Group = MLEM.Ui.Elements.Group; namespace Sandbox { public class GameImpl : MlemGame { private Camera camera; private TiledMap map; private IndividualTiledMapRenderer mapRenderer; private TiledMapCollisions collisions; private RawContentManager rawContent; private TokenizedString tokenized; public GameImpl() { this.IsMouseVisible = true; this.Window.ClientSizeChanged += (o, args) => { Console.WriteLine("Size changed"); }; } protected override void LoadContent() { // TODO remove with MonoGame 3.8.1 https://github.com/MonoGame/MonoGame/issues/7298 this.GraphicsDeviceManager.PreferredBackBufferWidth = 1280; this.GraphicsDeviceManager.PreferredBackBufferHeight = 720; this.GraphicsDeviceManager.ApplyChanges(); base.LoadContent(); this.Components.Add(this.rawContent = new RawContentManager(this.Services)); this.map = LoadContent<TiledMap>("Tiled/Map"); this.mapRenderer = new IndividualTiledMapRenderer(this.map); this.collisions = new TiledMapCollisions(this.map); this.camera = new Camera(this.GraphicsDevice) { AutoScaleWithScreen = true, Scale = 2, LookingPosition = new Vector2(25, 25) * this.map.GetTileSize(), MinScale = 0.25F, MaxScale = 4 }; var tex = this.rawContent.Load<Texture2D>("Textures/Test"); using (var data = tex.GetTextureData()) { var textureData = data; textureData[1, 9] = Color.Pink; textureData[textureData.FromIndex(textureData.ToIndex(25, 9))] = Color.Yellow; } var system = new FontSystem(this.GraphicsDevice, 1024, 1024); system.AddFont(File.ReadAllBytes("Content/Fonts/Cadman_Roman.otf")); //var font = new GenericSpriteFont(LoadContent<SpriteFont>("Fonts/TestFont")); //var font = new GenericBitmapFont(LoadContent<BitmapFont>("Fonts/Regular")); var font = new GenericStashFont(system.GetFont(32)); this.UiSystem.Style = new UntexturedStyle(this.SpriteBatch) { Font = font, TextScale = 0.1F, PanelTexture = new NinePatch(new TextureRegion(tex, 0, 8, 24, 24), 8), ButtonTexture = new NinePatch(new TextureRegion(tex, 24, 8, 16, 16), 4) }; this.UiSystem.AutoScaleReferenceSize = new Point(1280, 720); this.UiSystem.AutoScaleWithScreen = true; this.UiSystem.GlobalScale = 5; var panel = new Panel(Anchor.Center, new Vector2(0, 100), Vector2.Zero) {SetWidthBasedOnChildren = true}; panel.AddChild(new Button(Anchor.AutoLeft, new Vector2(100, 10))); panel.AddChild(new Button(Anchor.AutoCenter, new Vector2(80, 10))); //this.UiSystem.Add("Panel", panel); panel.SetData("TestKey", new Vector2(10, 2)); //Console.WriteLine(panel.GetData<Vector2>("TestKey")); var obj = new Test(Vector2.One, "test") { Vec = new Vector2(10, 20), Point = new Point(20, 30), Dir = Direction2.Left, OtherTest = new Test(Vector2.One, "other") { Vec = new Vector2(70, 30), Dir = Direction2.Right } }; Console.WriteLine(obj); for (var i = 0; i < 360; i += 45) { var rad = MathHelper.ToRadians(i); var vec = new Vector2((float) Math.Sin(rad), (float) Math.Cos(rad)); var dir = vec.ToDirection(); Console.WriteLine(vec + " -> " + dir); } var copy = obj.DeepCopy(); Console.WriteLine(copy); var intoCopy = new Test(Vector2.One, "test") {OtherTest = new Test(Vector2.One, "other")}; obj.DeepCopyInto(intoCopy); Console.WriteLine(intoCopy); var writer = new StringWriter(); this.Content.GetJsonSerializer().Serialize(writer, obj); //Console.WriteLine(writer.ToString()); // {"Vec":"10 20","Point":"20 30","Rectangle":"1 2 3 4","RectangleF":"4 5 6 7"} // Also: //this.Content.AddJsonConverter(new CustomConverter()); var res = this.Content.LoadJson<Test>("Test"); Console.WriteLine("The res is " + res); var gradient = this.SpriteBatch.GenerateGradientTexture(Color.Green, Color.Red, Color.Blue, Color.Yellow); this.OnDraw += (game, time) => { this.SpriteBatch.Begin(); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Rectangle(640 - 4, 360 - 4, 8, 8), Color.Green); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Rectangle(200, 400, 200, 400), Color.Green); font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1), new Vector2(200, 400), Color.White); font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, ellipsis: "..."), new Vector2(200, 450), Color.White); font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, true), new Vector2(200, 500), Color.White); font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, true, "..."), new Vector2(200, 550), Color.White); this.SpriteBatch.Draw(gradient, new Rectangle(300, 100, 200, 200), Color.White); this.SpriteBatch.End(); }; var sc = 4; var formatter = new TextFormatter(); formatter.AddImage("Test", new TextureRegion(tex, 0, 8, 24, 24)); formatter.Macros.Add(new Regex("<testmacro>"), (f, m, r) => "<test1>"); formatter.Macros.Add(new Regex("<test1>"), (f, m, r) => "<test2> blue"); formatter.Macros.Add(new Regex("<test2>"), (f, m, r) => "<c Blue>"); var strg = "This text uses a bunch of non-breaking~spaces to see if macros work. Additionally, it uses a macro that resolves into a bunch of other macros and then, at the end, into <testmacro> text</c>."; //var strg = "Lorem Ipsum <i Test> is simply dummy text of the <i Test> printing and typesetting <i Test> industry. Lorem Ipsum has been the industry's standard dummy text <i Test> ever since the <i Test> 1500s, when <i Test><i Test><i Test><i Test><i Test><i Test><i Test> an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; //var strg = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; //var strg = "This is <u>a test of the underlined formatting code</u>!"; this.tokenized = formatter.Tokenize(font, strg); this.tokenized.Split(font, 400, sc); var square = this.SpriteBatch.GenerateSquareTexture(Color.Yellow); var round = this.SpriteBatch.GenerateCircleTexture(Color.Green, 128); var region = new TextureRegion(round) {Pivot = new Vector2(0.5F)}; var region2 = new TextureRegion(round); var atlas = this.Content.LoadTextureAtlas("Textures/Furniture"); foreach (var r in atlas.Regions) { Console.WriteLine(r.Name + ": " + r.U + " " + r.V + " " + r.Width + " " + r.Height + " " + r.PivotPixels); foreach (var key in r.GetDataKeys()) Console.WriteLine(key + " " + r.GetData<Vector2>(key)); } this.OnDraw += (g, time) => { this.SpriteBatch.Begin(samplerState: SamplerState.PointClamp); //this.SpriteBatch.Draw(square, new Rectangle(10, 10, 400, 400), Color.White); //this.SpriteBatch.Draw(round, new Rectangle(10, 10, 400, 400), Color.White); this.SpriteBatch.Draw(region, new Vector2(50, 50), Color.White, 0, Vector2.Zero, 0.5F, SpriteEffects.None, 0); this.SpriteBatch.Draw(region2, new Vector2(50, 50), Color.Yellow * 0.5F, 0, Vector2.Zero, 0.5F, SpriteEffects.None, 0); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Vector2(50, 50), Color.Pink); //this.SpriteBatch.FillRectangle(new RectangleF(400, 20, 400, 1000), Color.Green); //font.DrawString(this.SpriteBatch, this.tokenized.DisplayString, new Vector2(400, 20), Color.White * 0.25F, 0, Vector2.Zero, sc, SpriteEffects.None, 0); //this.tokenized.Draw(time, this.SpriteBatch, new Vector2(400, 20), font, Color.White, sc, 0); //this.SpriteBatch.DrawGrid(new Vector2(30, 30), new Vector2(40, 60), new Point(10, 5), Color.Yellow, 3); this.SpriteBatch.End(); }; this.OnUpdate += (g, time) => { if (this.InputHandler.IsPressed(Keys.W)) { this.tokenized = formatter.Tokenize(font, strg); this.tokenized.Split(font, this.InputHandler.IsModifierKeyDown(ModifierKey.Shift) ? 400 : 500, sc); } this.tokenized.Update(time); }; /*var testPanel = new Panel(Anchor.Center, new Vector2(0.5F, 100), Vector2.Zero); testPanel.AddChild(new Button(Anchor.AutoLeft, new Vector2(0.25F, -1))); testPanel.AddChild(new Button(Anchor.AutoLeft, new Vector2(2500, 1)) {PreventParentSpill = true}); this.UiSystem.Add("Test", testPanel); var invalidPanel = new Panel(Anchor.Center, Vector2.Zero, Vector2.Zero) { SetWidthBasedOnChildren = true, SetHeightBasedOnChildren = true }; invalidPanel.AddChild(new Paragraph(Anchor.AutoRight, 1, "This is some test text!", true)); invalidPanel.AddChild(new VerticalSpace(1)); this.UiSystem.Add("Invalid", invalidPanel);*/ var loadGroup = new Group(Anchor.TopLeft, Vector2.One, false); var loadPanel = loadGroup.AddChild(new Panel(Anchor.Center, new Vector2(150, 150), Vector2.Zero, false, true, new Point(5, 10), false) { ChildPadding = new Padding(5, 10, 5, 5) }); for (var i = 0; i < 1; i++) { var button = loadPanel.AddChild(new Button(Anchor.AutoLeft, new Vector2(1)) { SetHeightBasedOnChildren = true, Padding = new Padding(0, 0, 0, 1), ChildPadding = new Vector2(3) }); button.AddChild(new Group(Anchor.AutoLeft, new Vector2(0.5F, 30), false) { CanBeMoused = false }); } this.UiSystem.Add("Load", loadGroup); } protected override void DoUpdate(GameTime gameTime) { base.DoUpdate(gameTime); if (this.InputHandler.IsKeyPressed(Keys.F11)) this.GraphicsDeviceManager.SetFullscreen(!this.GraphicsDeviceManager.IsFullScreen); var delta = this.InputHandler.ScrollWheel - this.InputHandler.LastScrollWheel; if (delta != 0) { this.camera.Zoom(0.1F * Math.Sign(delta), this.InputHandler.MousePosition.ToVector2()); } if (Input.InputsDown.Length > 0) Console.WriteLine("Down: " + string.Join(", ", Input.InputsDown)); if (Input.InputsPressed.Length > 0) Console.WriteLine("Pressed: " + string.Join(", ", Input.InputsPressed)); } protected override void DoDraw(GameTime gameTime) { this.GraphicsDevice.Clear(Color.Black); this.SpriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, this.camera.ViewMatrix); /*this.mapRenderer.Draw(this.SpriteBatch, this.camera.GetVisibleRectangle().ToExtended()); foreach (var tile in this.collisions.GetCollidingTiles(new RectangleF(0, 0, this.map.Width, this.map.Height))) { foreach (var area in tile.Collisions) { this.SpriteBatch.DrawRectangle(area.Position * this.map.GetTileSize(), area.Size * this.map.GetTileSize(), Color.Red); } }*/ this.SpriteBatch.End(); base.DoDraw(gameTime); } private class Test { public Vector2 Vec; public Point Point; public Direction2 Dir { get; set; } public Test OtherTest; [CopyConstructor] public Test(Vector2 test, string test2) { Console.WriteLine("Constructed with " + test + ", " + test2); } public override string ToString() { return $"{this.GetHashCode()}: {nameof(this.Vec)}: {this.Vec}, {nameof(this.Point)}: {this.Point}, {nameof(this.OtherTest)}: {this.OtherTest}, {nameof(this.Dir)}: {this.Dir}"; } } } }<file_sep>/MLEM/Formatting/TokenizedString.cs using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Font; using MLEM.Formatting.Codes; using MLEM.Misc; namespace MLEM.Formatting { /// <summary> /// A tokenized string that was created using a <see cref="TextFormatter"/> /// </summary> public class TokenizedString : GenericDataHolder { /// <summary> /// The raw string that was used to create this tokenized string. /// </summary> public readonly string RawString; /// <summary> /// The <see cref="RawString"/>, but with formatting codes stripped out. /// </summary> public readonly string String; /// <summary> /// The string that is actually displayed by this tokenized string. /// If this string has been <see cref="Split"/> or <see cref="Truncate"/> has been used, this string will contain the newline characters. /// </summary> public string DisplayString => this.modifiedString ?? this.String; /// <summary> /// The tokens that this tokenized string contains. /// </summary> public readonly Token[] Tokens; /// <summary> /// All of the formatting codes that are applied over this tokenized string. /// Note that, to get a formatting code for a certain token, use <see cref="Token.AppliedCodes"/> /// </summary> public readonly Code[] AllCodes; private string modifiedString; internal TokenizedString(GenericFont font, TextAlignment alignment, string rawString, string strg, Token[] tokens) { this.RawString = rawString; this.String = strg; this.Tokens = tokens; // since a code can be present in multiple tokens, we use Distinct here this.AllCodes = tokens.SelectMany(t => t.AppliedCodes).Distinct().ToArray(); this.RecalculateTokenData(font, alignment); } /// <summary> /// Splits this tokenized string, inserting newline characters if the width of the string is bigger than the maximum width. /// Note that a tokenized string can be re-split without losing any of its actual data, as this operation merely modifies the <see cref="DisplayString"/>. /// <seealso cref="GenericFont.SplitString"/> /// </summary> /// <param name="font">The font to use for width calculations</param> /// <param name="width">The maximum width, in display pixels based on the font and scale</param> /// <param name="scale">The scale to use for width measurements</param> /// <param name="alignment">The text alignment that should be used for width calculations</param> public void Split(GenericFont font, float width, float scale, TextAlignment alignment = TextAlignment.Left) { // a split string has the same character count as the input string but with newline characters added this.modifiedString = font.SplitString(this.String, width, scale); this.StoreModifiedSubstrings(font, alignment); } /// <summary> /// Truncates this tokenized string, removing any additional characters that exceed the length from the displayed string. /// Note that a tokenized string can be re-truncated without losing any of its actual data, as this operation merely modifies the <see cref="DisplayString"/>. /// <seealso cref="GenericFont.TruncateString"/> /// </summary> /// <param name="font">The font to use for width calculations</param> /// <param name="width">The maximum width, in display pixels based on the font and scale</param> /// <param name="scale">The scale to use for width measurements</param> /// <param name="ellipsis">The characters to add to the end of the string if it is too long</param> /// <param name="alignment">The text alignment that should be used for width calculations</param> public void Truncate(GenericFont font, float width, float scale, string ellipsis = "", TextAlignment alignment = TextAlignment.Left) { this.modifiedString = font.TruncateString(this.String, width, scale, false, ellipsis); this.StoreModifiedSubstrings(font, alignment); } /// <inheritdoc cref="GenericFont.MeasureString(string,bool)"/> public Vector2 Measure(GenericFont font) { return font.MeasureString(this.DisplayString); } /// <summary> /// Updates the formatting codes in this formatted string, causing animations to animate etc. /// </summary> /// <param name="time">The game's time</param> public void Update(GameTime time) { foreach (var code in this.AllCodes) code.Update(time); } /// <summary> /// Returns the token under the given position. /// This can be used for hovering effects when the mouse is over a token, etc. /// </summary> /// <param name="stringPos">The position that the string is drawn at</param> /// <param name="target">The position to use for checking the token</param> /// <param name="scale">The scale that the string is drawn at</param> /// <returns>The token under the target position</returns> public Token GetTokenUnderPos(Vector2 stringPos, Vector2 target, float scale) { return this.Tokens.FirstOrDefault(t => t.GetArea(stringPos, scale).Any(r => r.Contains(target))); } /// <inheritdoc cref="GenericFont.DrawString(SpriteBatch,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public void Draw(GameTime time, SpriteBatch batch, Vector2 pos, GenericFont font, Color color, float scale, float depth, TextAlignment alignment = TextAlignment.Left) { var innerOffset = new Vector2(this.GetInnerOffsetX(font, 0, 0, scale, alignment), 0); for (var t = 0; t < this.Tokens.Length; t++) { var token = this.Tokens[t]; var drawFont = token.GetFont(font) ?? font; var drawColor = token.GetColor(color) ?? color; for (var l = 0; l < token.SplitDisplayString.Length; l++) { var line = token.SplitDisplayString[l]; for (var i = 0; i < line.Length; i++) { var c = line[i]; if (l == 0 && i == 0) token.DrawSelf(time, batch, pos + innerOffset, font, color, scale, depth); var cString = c.ToCachedString(); token.DrawCharacter(time, batch, c, cString, i, pos + innerOffset, drawFont, drawColor, scale, depth); innerOffset.X += font.MeasureString(cString).X * scale; } // only split at a new line, not between tokens! if (l < token.SplitDisplayString.Length - 1) { innerOffset.X = this.GetInnerOffsetX(font, t, l + 1, scale, alignment); innerOffset.Y += font.LineHeight * scale; } } } } private void StoreModifiedSubstrings(GenericFont font, TextAlignment alignment) { if (this.Tokens.Length == 1) { // skip substring logic for unformatted text this.Tokens[0].ModifiedSubstring = this.modifiedString; } else { // this is basically a substring function that ignores added newlines for indexing var index = 0; var currToken = 0; var splitIndex = 0; var ret = new StringBuilder(); while (splitIndex < this.modifiedString.Length && currToken < this.Tokens.Length) { var token = this.Tokens[currToken]; if (token.Substring.Length > 0) { ret.Append(this.modifiedString[splitIndex]); // if the current char is not an added newline, we simulate length increase if (this.modifiedString[splitIndex] != '\n' || this.String[index] == '\n') index++; splitIndex++; } // move on to the next token if we reached its end if (index >= token.Index + token.Substring.Length) { token.ModifiedSubstring = ret.ToString(); ret.Clear(); currToken++; } } // set additional token contents beyond our string in case we truncated if (ret.Length > 0) this.Tokens[currToken++].ModifiedSubstring = ret.ToString(); while (currToken < this.Tokens.Length) this.Tokens[currToken++].ModifiedSubstring = string.Empty; } this.RecalculateTokenData(font, alignment); } private float GetInnerOffsetX(GenericFont font, int tokenIndex, int lineIndex, float scale, TextAlignment alignment) { if (alignment > TextAlignment.Left) { var rest = this.GetRestOfLineLength(font, tokenIndex, lineIndex) * scale; if (alignment == TextAlignment.Center) rest /= 2; return -rest; } return 0; } private float GetRestOfLineLength(GenericFont font, int tokenIndex, int lineIndex) { var token = this.Tokens[tokenIndex]; var ret = font.MeasureString(token.SplitDisplayString[lineIndex], true).X; if (lineIndex >= token.SplitDisplayString.Length - 1) { // the line ends somewhere in or after the next token for (var i = tokenIndex + 1; i < this.Tokens.Length; i++) { var other = this.Tokens[i]; if (other.SplitDisplayString.Length > 1) { // the line ends in this token ret += font.MeasureString(other.SplitDisplayString[0]).X; break; } else { // the line doesn't end in this token, so add it fully ret += font.MeasureString(other.DisplayString).X; } } } return ret; } private void RecalculateTokenData(GenericFont font, TextAlignment alignment) { // split display strings foreach (var token in this.Tokens) token.SplitDisplayString = token.DisplayString.Split('\n'); // token areas var innerOffset = new Vector2(this.GetInnerOffsetX(font, 0, 0, 1, alignment), 0); for (var t = 0; t < this.Tokens.Length; t++) { var token = this.Tokens[t]; var area = new List<RectangleF>(); for (var l = 0; l < token.SplitDisplayString.Length; l++) { var size = font.MeasureString(token.SplitDisplayString[l]); var rect = new RectangleF(innerOffset, size); if (!rect.IsEmpty) area.Add(rect); if (l < token.SplitDisplayString.Length - 1) { innerOffset.X = this.GetInnerOffsetX(font, t, l + 1, 1, alignment); innerOffset.Y += font.LineHeight; } else { innerOffset.X += size.X; } } token.Area = area.ToArray(); } } } }<file_sep>/MLEM.Data/Json/Direction2Converter.cs using System; using MLEM.Misc; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class Direction2Converter : JsonConverter<Direction2> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, Direction2 value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } /// <inheritdoc /> public override Direction2 ReadJson(JsonReader reader, Type objectType, Direction2 existingValue, bool hasExistingValue, JsonSerializer serializer) { Enum.TryParse<Direction2>(reader.Value.ToString(), out var dir); return dir; } } }<file_sep>/MLEM/Font/GenericFont.cs using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Misc; namespace MLEM.Font { /// <summary> /// Represents a font with additional abilities. /// <seealso cref="GenericSpriteFont"/> /// </summary> public abstract class GenericFont : GenericDataHolder { /// <summary> /// This field holds the unicode representation of a one em space. /// This is a character that isn't drawn, but has the same width as <see cref="LineHeight"/>. /// Whereas a regular <see cref="SpriteFont"/> would have to explicitly support this character for width calculations, generic fonts implicitly support it in <see cref="MeasureString"/>. /// </summary> public const char OneEmSpace = '\u2003'; /// <summary> /// This field holds the unicode representation of a non-breaking space. /// Whereas a regular <see cref="SpriteFont"/> would have to explicitly support this character for width calculations, generic fonts implicitly support it in <see cref="MeasureString"/>. /// </summary> public const char Nbsp = '\u00A0'; /// <summary> /// This field holds the unicode representation of a zero-width space. /// Whereas a regular <see cref="SpriteFont"/> would have to explicitly support this character for width calculations and string splitting, generic fonts implicitly support it in <see cref="MeasureString"/> and <see cref="SplitString"/>. /// </summary> public const char Zwsp = '\u200B'; /// <summary> /// The bold version of this font. /// </summary> public abstract GenericFont Bold { get; } /// <summary> /// The italic version of this font. /// </summary> public abstract GenericFont Italic { get; } ///<inheritdoc cref="SpriteFont.LineSpacing"/> public abstract float LineHeight { get; } ///<inheritdoc cref="SpriteFont.MeasureString(string)"/> protected abstract Vector2 MeasureChar(char c); ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public abstract void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth); ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public abstract void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth); ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public void DrawString(SpriteBatch batch, string text, Vector2 position, Color color) { this.DrawString(batch, text, position, color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0); } ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { this.DrawString(batch, text, position, color, rotation, origin, new Vector2(scale), effects, layerDepth); } ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color) { this.DrawString(batch, text, position, color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0); } ///<inheritdoc cref="SpriteBatch.DrawString(SpriteFont,string,Vector2,Color,float,Vector2,float,SpriteEffects,float)"/> public void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { this.DrawString(batch, text, position, color, rotation, origin, new Vector2(scale), effects, layerDepth); } ///<inheritdoc cref="SpriteFont.MeasureString(string)"/> public Vector2 MeasureString(string text, bool ignoreTrailingSpaces = false) { var size = Vector2.Zero; if (text.Length <= 0) return size; var xOffset = 0F; for (var i = 0; i < text.Length; i++) { switch (text[i]) { case '\n': xOffset = 0; size.Y += this.LineHeight; break; case OneEmSpace: xOffset += this.LineHeight; break; case Nbsp: xOffset += this.MeasureChar(' ').X; break; case Zwsp: // don't add width for a zero-width space break; case ' ': if (ignoreTrailingSpaces && IsTrailingSpace(text, i)) { // if this is a trailing space, we can skip remaining spaces too i = text.Length - 1; break; } xOffset += this.MeasureChar(' ').X; break; default: xOffset += this.MeasureChar(text[i]).X; break; } // increase x size if this line is the longest if (xOffset > size.X) size.X = xOffset; } // include the last line's height too! size.Y += this.LineHeight; return size; } /// <summary> /// Truncates a string to a given width. If the string's displayed area is larger than the maximum width, the string is cut off. /// Optionally, the string can be cut off a bit sooner, adding the <paramref name="ellipsis"/> at the end instead. /// </summary> /// <param name="text">The text to truncate</param> /// <param name="width">The maximum width, in display pixels based on the font and scale</param> /// <param name="scale">The scale to use for width measurements</param> /// <param name="fromBack">If the string should be truncated from the back rather than the front</param> /// <param name="ellipsis">The characters to add to the end of the string if it is too long</param> /// <returns>The truncated string, or the same string if it is shorter than the maximum width</returns> public string TruncateString(string text, float width, float scale, bool fromBack = false, string ellipsis = "") { var total = new StringBuilder(); var ellipsisWidth = this.MeasureString(ellipsis).X * scale; for (var i = 0; i < text.Length; i++) { if (fromBack) { total.Insert(0, text[text.Length - 1 - i]); } else { total.Append(text[i]); } if (this.MeasureString(total.ToString()).X * scale + ellipsisWidth >= width) { if (fromBack) { return total.Remove(0, 1).Insert(0, ellipsis).ToString(); } else { return total.Remove(total.Length - 1, 1).Append(ellipsis).ToString(); } } } return total.ToString(); } /// <summary> /// Splits a string to a given maximum width, adding newline characters between each line. /// Also splits long words and supports zero-width spaces. /// </summary> /// <param name="text">The text to split into multiple lines</param> /// <param name="width">The maximum width that each line should have</param> /// <param name="scale">The scale to use for width measurements</param> /// <returns>The split string, containing newline characters at each new line</returns> public string SplitString(string text, float width, float scale) { var ret = new StringBuilder(); var currWidth = 0F; var lastSpaceIndex = -1; var widthSinceLastSpace = 0F; for (var i = 0; i < text.Length; i++) { var c = text[i]; if (c == '\n') { // split at pre-defined new lines ret.Append(c); lastSpaceIndex = -1; widthSinceLastSpace = 0; currWidth = 0; } else { var cWidth = this.MeasureChar(c).X * scale; if (c == ' ' || c == OneEmSpace || c == Zwsp) { // remember the location of this space lastSpaceIndex = ret.Length; widthSinceLastSpace = 0; } else if (currWidth + cWidth >= width) { // check if this line contains a space if (lastSpaceIndex < 0) { // if there is no last space, the word is longer than a line so we split here ret.Append('\n'); currWidth = 0; } else { // split after the last space ret.Insert(lastSpaceIndex + 1, '\n'); // we need to restore the width accumulated since the last space for the new line currWidth = widthSinceLastSpace; } widthSinceLastSpace = 0; lastSpaceIndex = -1; } // add current character currWidth += cWidth; widthSinceLastSpace += cWidth; ret.Append(c); } } return ret.ToString(); } private static bool IsTrailingSpace(string s, int index) { for (var i = index + 1; i < s.Length; i++) { if (s[i] != ' ') return false; } return true; } } }<file_sep>/MLEM.Extended/Extensions/SpriteBatchExtensions.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MonoGame.Extended; namespace MLEM.Extended.Extensions { /// <summary> /// A set of extension methods for dealing with <see cref="SpriteBatch"/> and <see cref="RectangleF"/> in combination. /// </summary> public static class SpriteBatchExtensions { /// <inheritdoc cref="SpriteBatch.Draw(Texture2D,Rectangle,Rectangle?,Color,float,Vector2,SpriteEffects,float)"/> public static void Draw(this SpriteBatch batch, Texture2D texture, RectangleF destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) { batch.Draw(texture, destinationRectangle.ToMlem(), sourceRectangle, color, rotation, origin, effects, layerDepth); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D,Rectangle,Rectangle?,Color)"/> public static void Draw(this SpriteBatch batch, Texture2D texture, RectangleF destinationRectangle, Rectangle? sourceRectangle, Color color) { batch.Draw(texture, destinationRectangle, sourceRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0); } /// <inheritdoc cref="SpriteBatch.Draw(Texture2D,Rectangle,Color)"/> public static void Draw(this SpriteBatch batch, Texture2D texture, RectangleF destinationRectangle, Color color) { batch.Draw(texture, destinationRectangle, null, color); } /// <summary> /// Draws a grid of tile outlines reminiscent of graph paper. /// </summary> /// <param name="batch">The sprite batch to draw with</param> /// <param name="start">The top left coordinate of the grid</param> /// <param name="tileSize">The size of each tile</param> /// <param name="tileCount">The amount of tiles in the x and y axes</param> /// <param name="gridColor">The color to draw the grid outlines in</param> /// <param name="gridThickness">The thickness of each grid line. Defaults to 1.</param> public static void DrawGrid(this SpriteBatch batch, Vector2 start, Vector2 tileSize, Point tileCount, Color gridColor, float gridThickness = 1) { for (var y = 0; y < tileCount.Y; y++) { for (var x = 0; x < tileCount.X; x++) batch.DrawRectangle(start + new Vector2(x, y) * tileSize, tileSize, gridColor, gridThickness / 2); } var size = tileSize * tileCount.ToVector2() + new Vector2(gridThickness); batch.DrawRectangle(start - new Vector2(gridThickness / 2), size, gridColor, gridThickness / 2); } } }<file_sep>/Tests/DataTextureAtlasTests.cs using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Data; using MLEM.Textures; using NUnit.Framework; namespace Tests { public class TestDataTextureAtlas { [Test] public void Test() { using var game = TestGame.Create(); using var texture = new Texture2D(game.GraphicsDevice, 1, 1); var atlas = DataTextureAtlas.LoadAtlasData(new TextureRegion(texture), game.RawContent, "Texture.atlas"); Assert.AreEqual(atlas.Regions.Count(), 5); var table = atlas["LongTableUp"]; Assert.AreEqual(table.Area, new Rectangle(0, 32, 64, 48)); Assert.AreEqual(table.PivotPixels, new Vector2(16, 48 - 32)); } } }<file_sep>/MLEM/Formatting/Codes/LinkCode.cs using System; using System.Text.RegularExpressions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Font; namespace MLEM.Formatting.Codes { /// <inheritdoc /> public class LinkCode : UnderlineCode { private readonly Func<Token, bool> isSelected; /// <inheritdoc /> public LinkCode(Match match, Regex regex, float thickness, float yOffset, Func<Token, bool> isSelected) : base(match, regex, thickness, yOffset) { this.isSelected = isSelected; } /// <summary> /// Returns true if this link formatting code is currently selected or hovered over, based on the selection function. /// </summary> /// <returns>True if this code is currently selected</returns> public virtual bool IsSelected() { return this.isSelected(this.Token); } /// <inheritdoc /> public override bool DrawCharacter(GameTime time, SpriteBatch batch, char c, string cString, int indexInToken, ref Vector2 pos, GenericFont font, ref Color color, ref float scale, float depth) { // since we inherit from UnderlineCode, we can just call base if selected return this.IsSelected() && base.DrawCharacter(time, batch, c, cString, indexInToken, ref pos, font, ref color, ref scale, depth); } } }<file_sep>/MLEM.Data/Json/Vector2Converter.cs using System; using System.Globalization; using Microsoft.Xna.Framework; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class Vector2Converter : JsonConverter<Vector2> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer) { writer.WriteValue(value.X.ToString(CultureInfo.InvariantCulture) + " " + value.Y.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc /> public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = reader.Value.ToString().Split(' '); return new Vector2(float.Parse(value[0], CultureInfo.InvariantCulture), float.Parse(value[1], CultureInfo.InvariantCulture)); } } }<file_sep>/MLEM.Data/Json/PointConverter.cs using System; using System.Globalization; using Microsoft.Xna.Framework; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <inheritdoc /> public class PointConverter : JsonConverter<Point> { /// <inheritdoc /> public override void WriteJson(JsonWriter writer, Point value, JsonSerializer serializer) { writer.WriteValue(value.X.ToString(CultureInfo.InvariantCulture) + " " + value.Y.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc /> public override Point ReadJson(JsonReader reader, Type objectType, Point existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = reader.Value.ToString().Split(' '); return new Point(int.Parse(value[0], CultureInfo.InvariantCulture), int.Parse(value[1], CultureInfo.InvariantCulture)); } } }<file_sep>/MLEM/Input/Keybind.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace MLEM.Input { /// <summary> /// A keybind represents a generic way to trigger input. /// A keybind is made up of multiple key combinations, one of which has to be pressed for the keybind to be triggered. /// Note that this type is serializable using <see cref="DataContractAttribute"/>. /// </summary> [DataContract] public class Keybind { [DataMember] private Combination[] combinations = Array.Empty<Combination>(); /// <summary> /// Creates a new keybind and adds the given key and modifiers using <see cref="Add(MLEM.Input.GenericInput,MLEM.Input.GenericInput[])"/> /// </summary> /// <param name="key">The key to be pressed.</param> /// <param name="modifiers">The modifier keys that have to be held down.</param> public Keybind(GenericInput key, params GenericInput[] modifiers) { this.Add(key, modifiers); } /// <inheritdoc cref="Keybind(GenericInput, GenericInput[])"/> public Keybind(GenericInput key, ModifierKey modifier) { this.Add(key, modifier); } /// <summary> /// Creates a new keybind with no default combinations /// </summary> public Keybind() { } /// <summary> /// Adds a new key combination to this keybind that can optionally be pressed for the keybind to trigger. /// </summary> /// <param name="key">The key to be pressed.</param> /// <param name="modifiers">The modifier keys that have to be held down.</param> /// <returns>This keybind, for chaining</returns> public Keybind Add(GenericInput key, params GenericInput[] modifiers) { this.combinations = this.combinations.Append(new Combination(key, modifiers)).ToArray(); return this; } /// <inheritdoc cref="Add(MLEM.Input.GenericInput,MLEM.Input.GenericInput[])"/> public Keybind Add(GenericInput key, ModifierKey modifier) { return this.Add(key, modifier.GetKeys().Select(m => (GenericInput) m).ToArray()); } /// <summary> /// Clears this keybind, removing all active combinations. /// </summary> /// <returns>This keybind, for chaining</returns> public Keybind Clear() { this.combinations = Array.Empty<Combination>(); return this; } /// <summary> /// Removes all combinations that match the given predicate /// </summary> /// <param name="predicate">The predicate to match against</param> /// <returns>This keybind, for chaining</returns> public Keybind Remove(Func<Combination, int, bool> predicate) { this.combinations = this.combinations.Where((c, i) => !predicate(c, i)).ToArray(); return this; } /// <summary> /// Copies all of the combinations from the given keybind into this keybind. /// Note that this doesn't <see cref="Clear"/> this keybind, so combinations will be merged rather than replaced. /// </summary> /// <param name="other">The keybind to copy from</param> /// <returns>This keybind, for chaining</returns> public Keybind CopyFrom(Keybind other) { this.combinations = this.combinations.Concat(other.combinations).ToArray(); return this; } /// <summary> /// Returns whether this keybind is considered to be down. /// See <see cref="InputHandler.IsDown"/> for more information. /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether this keybind is considered to be down</returns> public bool IsDown(InputHandler handler, int gamepadIndex = -1) { return this.combinations.Any(c => c.IsDown(handler, gamepadIndex)); } /// <summary> /// Returns whether this keybind is considered to be pressed. /// See <see cref="InputHandler.IsPressed"/> for more information. /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether this keybind is considered to be pressed</returns> public bool IsPressed(InputHandler handler, int gamepadIndex = -1) { return this.combinations.Any(c => c.IsPressed(handler, gamepadIndex)); } /// <summary> /// Returns whether any of this keybind's modifier keys are currently down. /// See <see cref="InputHandler.IsDown"/> for more information. /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether any of this keyboard's modifier keys are down</returns> public bool IsModifierDown(InputHandler handler, int gamepadIndex = -1) { return this.combinations.Any(c => c.IsModifierDown(handler, gamepadIndex)); } /// <summary> /// Returns an enumerable of all of the combinations that this keybind currently contains /// </summary> /// <returns>This keybind's combinations</returns> public IEnumerable<Combination> GetCombinations() { foreach (var combination in this.combinations) yield return combination; } /// <summary> /// A key combination is a combination of a set of modifier keys and a key. /// All of the keys are <see cref="GenericInput"/> instances, so they can be keyboard-, mouse- or gamepad-based. /// </summary> [DataContract] public class Combination { /// <summary> /// The inputs that have to be held down for this combination to be valid. /// If this collection is empty, there are no required modifier keys. /// </summary> [DataMember] public readonly GenericInput[] Modifiers; /// <summary> /// The input that has to be down (or pressed) for this combination to be considered down (or pressed). /// Note that <see cref="Modifiers"/> needs to be empty, or all of its values need to be down, as well. /// </summary> [DataMember] public readonly GenericInput Key; /// <summary> /// Creates a new combination with the given settings. /// To add a combination to a <see cref="Keybind"/>, use <see cref="Keybind.Add(MLEM.Input.GenericInput,MLEM.Input.GenericInput[])"/> instead. /// </summary> /// <param name="key">The key</param> /// <param name="modifiers">The modifiers</param> public Combination(GenericInput key, GenericInput[] modifiers) { this.Modifiers = modifiers; this.Key = key; } /// <summary> /// Returns whether this combination is currently down /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether this combination is down</returns> public bool IsDown(InputHandler handler, int gamepadIndex = -1) { return this.IsModifierDown(handler, gamepadIndex) && handler.IsDown(this.Key, gamepadIndex); } /// <summary> /// Returns whether this combination is currently pressed /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether this combination is pressed</returns> public bool IsPressed(InputHandler handler, int gamepadIndex = -1) { return this.IsModifierDown(handler, gamepadIndex) && handler.IsPressed(this.Key, gamepadIndex); } /// <summary> /// Returns whether this combination's modifier keys are currently down /// </summary> /// <param name="handler">The input handler to query the keys with</param> /// <param name="gamepadIndex">The index of the gamepad to query, or -1 to query all gamepads</param> /// <returns>Whether this combination's modifiers are down</returns> public bool IsModifierDown(InputHandler handler, int gamepadIndex = -1) { return this.Modifiers.Length <= 0 || this.Modifiers.Any(m => handler.IsDown(m, gamepadIndex)); } } } }<file_sep>/MLEM/Misc/EnumHelper.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Input; namespace MLEM.Misc { /// <summary> /// A helper class that allows easier usage of <see cref="Enum"/> values. /// </summary> public static class EnumHelper { /// <summary> /// All values of the <see cref="Buttons"/> enum. /// </summary> public static readonly Buttons[] Buttons = GetValues<Buttons>().ToArray(); /// <summary> /// All values of the <see cref="Keys"/> enum. /// </summary> public static readonly Keys[] Keys = GetValues<Keys>().ToArray(); /// <summary> /// Returns all of the values of the given enum type. /// </summary> /// <typeparam name="T">The type whose enum to get</typeparam> /// <returns>An enumerable of the values of the enum, in declaration order.</returns> public static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } } }<file_sep>/MLEM/Input/InputHandler.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using MLEM.Misc; namespace MLEM.Input { /// <summary> /// An input handler is a more advanced wrapper around MonoGame's default input system. /// It includes keyboard, mouse, gamepad and touch states, as well as a new "pressed" state for keys and the ability for keyboard and gamepad repeat events. /// </summary> public class InputHandler : GameComponent { /// <summary> /// Contains the keyboard state from the last update call /// </summary> public KeyboardState LastKeyboardState { get; private set; } /// <summary> /// Contains the current keyboard state /// </summary> public KeyboardState KeyboardState { get; private set; } /// <summary> /// Set this field to false to disable keyboard handling for this input handler. /// </summary> public bool HandleKeyboard; /// <summary> /// Contains the mouse state from the last update call /// </summary> public MouseState LastMouseState { get; private set; } /// <summary> /// Contains the current mouse state /// </summary> public MouseState MouseState { get; private set; } /// <summary> /// Contains the current position of the mouse, extracted from <see cref="MouseState"/> /// </summary> public Point MousePosition => this.MouseState.Position; /// <summary> /// Contains the position of the mouse from the last update call, extracted from <see cref="LastMouseState"/> /// </summary> public Point LastMousePosition => this.LastMouseState.Position; /// <summary> /// Contains the current scroll wheel value, in increments of 120 /// </summary> public int ScrollWheel => this.MouseState.ScrollWheelValue; /// <summary> /// Contains the scroll wheel value from the last update call, in increments of 120 /// </summary> public int LastScrollWheel => this.LastMouseState.ScrollWheelValue; /// <summary> /// Set this field to false to disable mouse handling for this input handler. /// </summary> public bool HandleMouse; private readonly GamePadState[] lastGamepads = new GamePadState[GamePad.MaximumGamePadCount]; private readonly GamePadState[] gamepads = new GamePadState[GamePad.MaximumGamePadCount]; /// <summary> /// Contains the amount of gamepads that are currently connected. /// This field is automatically updated in <see cref="Update()"/> /// </summary> public int ConnectedGamepads { get; private set; } /// <summary> /// Set this field to false to disable keyboard handling for this input handler. /// </summary> public bool HandleGamepads; /// <summary> /// Contains the touch state from the last update call /// </summary> public TouchCollection LastTouchState { get; private set; } /// <summary> /// Contains the current touch state /// </summary> public TouchCollection TouchState { get; private set; } /// <summary> /// Contains all of the gestures that have finished during the last update call. /// To easily query these gestures, use <see cref="GetGesture"/> /// </summary> public readonly ReadOnlyCollection<GestureSample> Gestures; private readonly List<GestureSample> gestures = new List<GestureSample>(); /// <summary> /// Set this field to false to disable touch handling for this input handler. /// </summary> public bool HandleTouch; /// <summary> /// This is the amount of time that has to pass before the first keyboard repeat event is triggered. /// <seealso cref="KeyRepeatRate"/> /// </summary> public TimeSpan KeyRepeatDelay = TimeSpan.FromSeconds(0.65); /// <summary> /// This is the amount of time that has to pass between keyboard repeat events. /// <seealso cref="KeyRepeatDelay"/> /// </summary> public TimeSpan KeyRepeatRate = TimeSpan.FromSeconds(0.05); /// <summary> /// Set this field to false to disable keyboard repeat event handling. /// </summary> public bool HandleKeyboardRepeats = true; private DateTime heldKeyStart; private DateTime lastKeyRepeat; private bool triggerKeyRepeat; private Keys heldKey; /// <summary> /// Set this field to false to disable gamepad repeat event handling. /// </summary> public bool HandleGamepadRepeats = true; private readonly DateTime[] heldGamepadButtonStarts = new DateTime[GamePad.MaximumGamePadCount]; private readonly DateTime[] lastGamepadButtonRepeats = new DateTime[GamePad.MaximumGamePadCount]; private readonly bool[] triggerGamepadButtonRepeat = new bool[GamePad.MaximumGamePadCount]; private readonly Buttons?[] heldGamepadButtons = new Buttons?[GamePad.MaximumGamePadCount]; /// <summary> /// An array of all <see cref="Keys"/>, <see cref="Buttons"/> and <see cref="MouseButton"/> values that are currently down. /// Note that this value only gets set if <see cref="StoreAllActiveInputs"/> is true. /// </summary> public GenericInput[] InputsDown { get; private set; } = Array.Empty<GenericInput>(); /// <summary> /// An array of all <see cref="Keys"/>, <see cref="Buttons"/> and <see cref="MouseButton"/> that are currently considered pressed. /// An input is considered pressed if it was up in the last update, and is up in the current one. /// Note that this value only gets set if <see cref="StoreAllActiveInputs"/> is true. /// </summary> public GenericInput[] InputsPressed { get; private set; } = Array.Empty<GenericInput>(); private readonly List<GenericInput> inputsDownAccum = new List<GenericInput>(); /// <summary> /// Set this field to false to enable <see cref="InputsDown"/> and <see cref="InputsPressed"/> being calculated. /// </summary> public bool StoreAllActiveInputs; /// <summary> /// Creates a new input handler with optional initial values. /// </summary> /// <param name="game">The game instance that this input handler belongs to</param> /// <param name="handleKeyboard">If keyboard input should be handled</param> /// <param name="handleMouse">If mouse input should be handled</param> /// <param name="handleGamepads">If gamepad input should be handled</param> /// <param name="handleTouch">If touch input should be handled</param> /// <param name="storeAllActiveInputs">Whether all inputs that are currently down and pressed should be calculated each update</param> public InputHandler(Game game, bool handleKeyboard = true, bool handleMouse = true, bool handleGamepads = true, bool handleTouch = true, bool storeAllActiveInputs = true) : base(game) { this.HandleKeyboard = handleKeyboard; this.HandleMouse = handleMouse; this.HandleGamepads = handleGamepads; this.HandleTouch = handleTouch; this.StoreAllActiveInputs = storeAllActiveInputs; this.Gestures = this.gestures.AsReadOnly(); } /// <summary> /// Updates this input handler, querying pressed and released keys and calculating repeat events. /// Call this in your <see cref="Game.Update"/> method. /// </summary> public void Update() { var active = this.Game.IsActive; if (this.HandleKeyboard) { this.LastKeyboardState = this.KeyboardState; this.KeyboardState = active ? Keyboard.GetState() : default; var pressedKeys = this.KeyboardState.GetPressedKeys(); if (this.StoreAllActiveInputs) { foreach (var pressed in pressedKeys) this.inputsDownAccum.Add(pressed); } if (this.HandleKeyboardRepeats) { this.triggerKeyRepeat = false; if (this.heldKey == Keys.None) { // if we're not repeating a key, set the first key being held to the repeat key // note that modifier keys don't count as that wouldn't really make sense var key = pressedKeys.FirstOrDefault(k => !k.IsModifier()); if (key != Keys.None) { this.heldKey = key; this.heldKeyStart = DateTime.UtcNow; } } else { // if the repeating key isn't being held anymore, reset if (!this.IsKeyDown(this.heldKey)) { this.heldKey = Keys.None; } else { var now = DateTime.UtcNow; var holdTime = now - this.heldKeyStart; // if we've been holding the key longer than the initial delay... if (holdTime >= this.KeyRepeatDelay) { var diff = now - this.lastKeyRepeat; // and we've been holding it for longer than a repeat... if (diff >= this.KeyRepeatRate) { this.lastKeyRepeat = now; // then trigger a repeat, causing IsKeyPressed to be true once this.triggerKeyRepeat = true; } } } } } } if (this.HandleMouse) { this.LastMouseState = this.MouseState; var state = Mouse.GetState(); if (active && this.Game.GraphicsDevice.Viewport.Bounds.Contains(state.Position)) { this.MouseState = state; if (this.StoreAllActiveInputs) { foreach (var button in MouseExtensions.MouseButtons) { if (state.GetState(button) == ButtonState.Pressed) this.inputsDownAccum.Add(button); } } } else { // mouse position and scroll wheel value should be preserved when the mouse is out of bounds this.MouseState = new MouseState(state.X, state.Y, state.ScrollWheelValue, 0, 0, 0, 0, 0, state.HorizontalScrollWheelValue); } } if (this.HandleGamepads) { this.ConnectedGamepads = GamePad.MaximumGamePadCount; for (var i = 0; i < GamePad.MaximumGamePadCount; i++) { this.lastGamepads[i] = this.gamepads[i]; var state = GamePadState.Default; if (GamePad.GetCapabilities(i).IsConnected) { if (active) { state = GamePad.GetState(i); if (this.StoreAllActiveInputs) { foreach (var button in EnumHelper.Buttons) { if (state.IsButtonDown(button)) this.inputsDownAccum.Add(button); } } } } else { if (this.ConnectedGamepads > i) this.ConnectedGamepads = i; } this.gamepads[i] = state; } if (this.HandleGamepadRepeats) { for (var i = 0; i < this.ConnectedGamepads; i++) { this.triggerGamepadButtonRepeat[i] = false; if (!this.heldGamepadButtons[i].HasValue) { foreach (var b in EnumHelper.Buttons) { if (this.IsGamepadButtonDown(b, i)) { this.heldGamepadButtons[i] = b; this.heldGamepadButtonStarts[i] = DateTime.UtcNow; break; } } } else { if (!this.IsGamepadButtonDown(this.heldGamepadButtons[i].Value, i)) { this.heldGamepadButtons[i] = null; } else { var now = DateTime.UtcNow; var holdTime = now - this.heldGamepadButtonStarts[i]; if (holdTime >= this.KeyRepeatDelay) { var diff = now - this.lastGamepadButtonRepeats[i]; if (diff >= this.KeyRepeatRate) { this.lastGamepadButtonRepeats[i] = now; this.triggerGamepadButtonRepeat[i] = true; } } } } } } } if (this.HandleTouch) { this.LastTouchState = this.TouchState; this.TouchState = active ? TouchPanel.GetState() : default; this.gestures.Clear(); while (active && TouchPanel.IsGestureAvailable) this.gestures.Add(TouchPanel.ReadGesture()); } if (this.StoreAllActiveInputs) { if (this.inputsDownAccum.Count <= 0) { this.InputsPressed = Array.Empty<GenericInput>(); this.InputsDown = Array.Empty<GenericInput>(); } else { this.InputsPressed = this.inputsDownAccum.Where(i => !this.InputsDown.Contains(i)).ToArray(); this.InputsDown = this.inputsDownAccum.ToArray(); this.inputsDownAccum.Clear(); } } } /// <inheritdoc cref="Update()"/> public override void Update(GameTime gameTime) { this.Update(); } /// <summary> /// Returns the state of the <c>index</c>th gamepad from the last update call /// </summary> /// <param name="index">The zero-based gamepad index</param> /// <returns>The state of the gamepad last update</returns> public GamePadState GetLastGamepadState(int index) { return this.lastGamepads[index]; } /// <summary> /// Returns the current state of the <c>index</c>th gamepad /// </summary> /// <param name="index">The zero-based gamepad index</param> /// <returns>The current state of the gamepad</returns> public GamePadState GetGamepadState(int index) { return this.gamepads[index]; } /// <inheritdoc cref="Microsoft.Xna.Framework.Input.KeyboardState.IsKeyDown"/> public bool IsKeyDown(Keys key) { return this.KeyboardState.IsKeyDown(key); } /// <inheritdoc cref="Microsoft.Xna.Framework.Input.KeyboardState.IsKeyUp"/> public bool IsKeyUp(Keys key) { return this.KeyboardState.IsKeyUp(key); } /// <inheritdoc cref="Microsoft.Xna.Framework.Input.KeyboardState.IsKeyDown"/> public bool WasKeyDown(Keys key) { return this.LastKeyboardState.IsKeyDown(key); } /// <inheritdoc cref="Microsoft.Xna.Framework.Input.KeyboardState.IsKeyUp"/> public bool WasKeyUp(Keys key) { return this.LastKeyboardState.IsKeyUp(key); } /// <summary> /// Returns whether the given key is considered pressed. /// A key is considered pressed if it was not down the last update call, but is down the current update call. /// If <see cref="HandleKeyboardRepeats"/> is true, this method will also return true to signify a key repeat. /// </summary> /// <param name="key">The key to query</param> /// <returns>If the key is pressed</returns> public bool IsKeyPressed(Keys key) { // if the queried key is the held key and a repeat should be triggered, return true if (this.HandleKeyboardRepeats && key == this.heldKey && this.triggerKeyRepeat) return true; return this.IsKeyPressedIgnoreRepeats(key); } /// <summary> /// Returns whether the given key is considered pressed. /// This has the same behavior as <see cref="IsKeyPressed"/>, but ignores keyboard repeat events. /// If <see cref="HandleKeyboardRepeats"/> is false, this method does the same as <see cref="IsKeyPressed"/>. /// </summary> /// <param name="key">The key to query</param> /// <returns>If the key is pressed</returns> public bool IsKeyPressedIgnoreRepeats(Keys key) { return this.WasKeyUp(key) && this.IsKeyDown(key); } /// <summary> /// Returns whether the given modifier key is down. /// </summary> /// <param name="modifier">The modifier key</param> /// <returns>If the modifier key is down</returns> public bool IsModifierKeyDown(ModifierKey modifier) { return modifier.GetKeys().Any(this.IsKeyDown); } /// <summary> /// Returns whether the given mouse button is currently down. /// </summary> /// <param name="button">The button to query</param> /// <returns>Whether or not the queried button is down</returns> public bool IsMouseButtonDown(MouseButton button) { return this.MouseState.GetState(button) == ButtonState.Pressed; } /// <summary> /// Returns whether the given mouse button is currently up. /// </summary> /// <param name="button">The button to query</param> /// <returns>Whether or not the queried button is up</returns> public bool IsMouseButtonUp(MouseButton button) { return this.MouseState.GetState(button) == ButtonState.Released; } /// <summary> /// Returns whether the given mouse button was down the last update call. /// </summary> /// <param name="button">The button to query</param> /// <returns>Whether or not the queried button was down</returns> public bool WasMouseButtonDown(MouseButton button) { return this.LastMouseState.GetState(button) == ButtonState.Pressed; } /// <summary> /// Returns whether the given mouse button was up the last update call. /// </summary> /// <param name="button">The button to query</param> /// <returns>Whether or not the queried button was up</returns> public bool WasMouseButtonUp(MouseButton button) { return this.LastMouseState.GetState(button) == ButtonState.Released; } /// <summary> /// Returns whether the given mouse button is considered pressed. /// A mouse button is considered pressed if it was up the last update call, and is down the current update call. /// </summary> /// <param name="button">The button to query</param> /// <returns>Whether the button is pressed</returns> public bool IsMouseButtonPressed(MouseButton button) { return this.WasMouseButtonUp(button) && this.IsMouseButtonDown(button); } /// <inheritdoc cref="GamePadState.IsButtonDown"/> public bool IsGamepadButtonDown(Buttons button, int index = -1) { if (index < 0) { for (var i = 0; i < this.ConnectedGamepads; i++) if (this.GetGamepadState(i).IsButtonDown(button)) return true; return false; } return this.GetGamepadState(index).IsButtonDown(button); } /// <inheritdoc cref="GamePadState.IsButtonUp"/> public bool IsGamepadButtonUp(Buttons button, int index = -1) { if (index < 0) { for (var i = 0; i < this.ConnectedGamepads; i++) if (this.GetGamepadState(i).IsButtonUp(button)) return true; return false; } return this.GetGamepadState(index).IsButtonUp(button); } /// <inheritdoc cref="GamePadState.IsButtonDown"/> public bool WasGamepadButtonDown(Buttons button, int index = -1) { if (index < 0) { for (var i = 0; i < this.ConnectedGamepads; i++) if (this.GetLastGamepadState(i).IsButtonDown(button)) return true; return false; } return this.GetLastGamepadState(index).IsButtonDown(button); } /// <inheritdoc cref="GamePadState.IsButtonUp"/> public bool WasGamepadButtonUp(Buttons button, int index = -1) { if (index < 0) { for (var i = 0; i < this.ConnectedGamepads; i++) if (this.GetLastGamepadState(i).IsButtonUp(button)) return true; return false; } return this.GetLastGamepadState(index).IsButtonUp(button); } /// <summary> /// Returns whether the given gamepad button on the given index is considered pressed. /// A gamepad button is considered pressed if it was down the last update call, and is up the current update call. /// If <see cref="HandleGamepadRepeats"/> is true, this method will also return true to signify a gamepad button repeat. /// </summary> /// <param name="button">The button to query</param> /// <param name="index">The zero-based index of the gamepad, or -1 for any gamepad</param> /// <returns>Whether the given button is pressed</returns> public bool IsGamepadButtonPressed(Buttons button, int index = -1) { if (this.HandleGamepadRepeats) { if (index < 0) { for (var i = 0; i < this.ConnectedGamepads; i++) if (this.heldGamepadButtons[i] == button && this.triggerGamepadButtonRepeat[i]) return true; } else if (this.heldGamepadButtons[index] == button && this.triggerGamepadButtonRepeat[index]) { return true; } } return this.IsGamepadButtonPressedIgnoreRepeats(button, index); } /// <summary> /// Returns whether the given key is considered pressed. /// This has the same behavior as <see cref="IsGamepadButtonPressed"/>, but ignores gamepad repeat events. /// If <see cref="HandleGamepadRepeats"/> is false, this method does the same as <see cref="IsGamepadButtonPressed"/>. /// </summary> /// <param name="button">The button to query</param> /// <param name="index">The zero-based index of the gamepad, or -1 for any gamepad</param> /// <returns>Whether the given button is pressed</returns> public bool IsGamepadButtonPressedIgnoreRepeats(Buttons button, int index = -1) { return this.WasGamepadButtonUp(button, index) && this.IsGamepadButtonDown(button, index); } /// <summary> /// Queries for a gesture of a given type that finished during the current update call. /// </summary> /// <param name="type">The type of gesture to query for</param> /// <param name="sample">The resulting gesture sample, or default if there isn't one</param> /// <returns>True if a gesture of the type was found, otherwise false</returns> public bool GetGesture(GestureType type, out GestureSample sample) { foreach (var gesture in this.Gestures) { if (type.HasFlag(gesture.GestureType)) { sample = gesture; return true; } } sample = default; return false; } /// <summary> /// Returns if a given control of any kind is down. /// This is a helper function that can be passed a <see cref="Keys"/>, <see cref="Buttons"/> or <see cref="MouseButton"/>. /// </summary> /// <param name="control">The control whose down state to query</param> /// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad</param> /// <returns>Whether the given control is down</returns> /// <exception cref="ArgumentException">If the passed control isn't of a supported type</exception> public bool IsDown(GenericInput control, int index = -1) { switch (control.Type) { case GenericInput.InputType.Keyboard: return this.IsKeyDown(control); case GenericInput.InputType.Gamepad: return this.IsGamepadButtonDown(control, index); case GenericInput.InputType.Mouse: return this.IsMouseButtonDown(control); default: return false; } } /// <summary> /// Returns if a given control of any kind is up. /// This is a helper function that can be passed a <see cref="Keys"/>, <see cref="Buttons"/> or <see cref="MouseButton"/>. /// </summary> /// <param name="control">The control whose up state to query</param> /// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad</param> /// <returns>Whether the given control is down</returns> /// <exception cref="ArgumentException">If the passed control isn't of a supported type</exception> public bool IsUp(GenericInput control, int index = -1) { switch (control.Type) { case GenericInput.InputType.Keyboard: return this.IsKeyUp(control); case GenericInput.InputType.Gamepad: return this.IsGamepadButtonUp(control, index); case GenericInput.InputType.Mouse: return this.IsMouseButtonUp(control); default: return true; } } /// <summary> /// Returns if a given control of any kind is pressed. /// This is a helper function that can be passed a <see cref="Keys"/>, <see cref="Buttons"/> or <see cref="MouseButton"/>. /// </summary> /// <param name="control">The control whose pressed state to query</param> /// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad</param> /// <returns>Whether the given control is down</returns> /// <exception cref="ArgumentException">If the passed control isn't of a supported type</exception> public bool IsPressed(GenericInput control, int index = -1) { switch (control.Type) { case GenericInput.InputType.Keyboard: return this.IsKeyPressed(control); case GenericInput.InputType.Gamepad: return this.IsGamepadButtonPressed(control, index); case GenericInput.InputType.Mouse: return this.IsMouseButtonPressed(control); default: return false; } } /// <inheritdoc cref="IsDown"/> public bool IsAnyDown(params GenericInput[] control) { return control.Any(c => this.IsDown(c)); } /// <inheritdoc cref="IsUp"/> public bool IsAnyUp(params GenericInput[] control) { return control.Any(c => this.IsUp(c)); } /// <inheritdoc cref="IsPressed"/> public bool IsAnyPressed(params GenericInput[] control) { return control.Any(c => this.IsPressed(c)); } /// <summary> /// Helper function to enable gestures for a <see cref="TouchPanel"/> easily. /// Note that, if other gestures were previously enabled, they will not get overridden. /// </summary> /// <param name="gestures">The gestures to enable</param> public static void EnableGestures(params GestureType[] gestures) { foreach (var gesture in gestures) TouchPanel.EnabledGestures |= gesture; } /// <summary> /// Helper function to disable gestures for a <see cref="TouchPanel"/> easily. /// </summary> /// <param name="gestures">The gestures to disable</param> public static void DisableGestures(params GestureType[] gestures) { foreach (var gesture in gestures) TouchPanel.EnabledGestures &= ~gesture; } /// <summary> /// Helper function to enable or disable the given gestures for a <see cref="TouchPanel"/> easily. /// This method is equivalent to calling <see cref="EnableGestures"/> if the <c>enabled</c> value is true and calling <see cref="DisableGestures"/> if it is false. /// Note that, if other gestures were previously enabled, they will not get overridden. /// </summary> /// <param name="enabled">Whether to enable or disable the gestures</param> /// <param name="gestures">The gestures to enable or disable</param> public static void SetGesturesEnabled(bool enabled, params GestureType[] gestures) { if (enabled) { EnableGestures(gestures); } else { DisableGestures(gestures); } } } }<file_sep>/MLEM.Data/Json/JsonConverters.cs using System; using System.Linq; using Newtonsoft.Json; namespace MLEM.Data.Json { /// <summary> /// A helper class that stores all of the <see cref="JsonConverter"/> types that are part of MLEM.Data. /// </summary> public class JsonConverters { /// <summary> /// An array of all of the <see cref="JsonConverter"/>s that are part of MLEM.Data /// </summary> public static readonly JsonConverter[] Converters = typeof(JsonConverters).Assembly.GetExportedTypes() .Where(t => t.IsSubclassOf(typeof(JsonConverter)) && !t.IsGenericType) .Select(t => t.GetConstructor(Type.EmptyTypes).Invoke(null)).Cast<JsonConverter>().ToArray(); /// <summary> /// Adds all of the <see cref="JsonConverter"/> objects that are part of MLEM.Data to the given <see cref="JsonSerializer"/> /// </summary> /// <param name="serializer">The serializer to add the converters to</param> /// <returns>The given serializer, for chaining</returns> public static JsonSerializer AddAll(JsonSerializer serializer) { foreach (var converter in Converters) serializer.Converters.Add(converter); return serializer; } } }<file_sep>/MLEM.Ui/Elements/Tooltip.cs using System; using System.Linq; using Microsoft.Xna.Framework; using MLEM.Ui.Style; namespace MLEM.Ui.Elements { /// <summary> /// A tooltip element for use inside of a <see cref="UiSystem"/>. /// A tooltip is a <see cref="Panel"/> with a custom cursor that always follows the position of the mouse. /// Tooltips can easily be configured to be hooked onto an element, causing them to appear when it is moused, and disappear when it is not moused anymore. /// </summary> public class Tooltip : Panel { /// <summary> /// The offset that this tooltip's top left corner should have from the mouse position /// </summary> public StyleProp<Vector2> MouseOffset; /// <summary> /// The amount of time that the mouse has to be over an element before it appears /// </summary> public StyleProp<TimeSpan> Delay; /// <summary> /// The paragraph of text that this tooltip displays /// </summary> public Paragraph Paragraph; private TimeSpan delayCountdown; /// <summary> /// Creates a new tooltip with the given settings /// </summary> /// <param name="width">The width of the tooltip</param> /// <param name="text">The text to display on the tooltip</param> /// <param name="elementToHover">The element that should automatically cause the tooltip to appear and disappear when hovered and not hovered, respectively</param> public Tooltip(float width, string text = null, Element elementToHover = null) : base(Anchor.TopLeft, Vector2.One, Vector2.Zero) { if (text != null) this.Paragraph = this.AddChild(new Paragraph(Anchor.TopLeft, width, text)); this.Init(elementToHover); } /// <summary> /// Creates a new tooltip with the given settings /// </summary> /// <param name="width">The width of the tooltip</param> /// <param name="textCallback">The text to display on the tooltip</param> /// <param name="elementToHover">The element that should automatically cause the tooltip to appear and disappear when hovered and not hovered, respectively</param> public Tooltip(float width, Paragraph.TextCallback textCallback, Element elementToHover = null) : base(Anchor.TopLeft, Vector2.One, Vector2.Zero) { this.Paragraph = this.AddChild(new Paragraph(Anchor.TopLeft, width, textCallback)); this.Init(elementToHover); } /// <inheritdoc /> public override void Update(GameTime time) { base.Update(time); this.SnapPositionToMouse(); if (this.IsHidden && this.delayCountdown > TimeSpan.Zero) { this.delayCountdown -= time.ElapsedGameTime; if (this.delayCountdown <= TimeSpan.Zero) this.IsHidden = false; } } /// <inheritdoc /> public override void ForceUpdateArea() { if (this.Parent != null) throw new NotSupportedException($"A tooltip shouldn't be the child of another element ({this.Parent})"); base.ForceUpdateArea(); } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.Texture.SetFromStyle(style.TooltipBackground); this.MouseOffset.SetFromStyle(style.TooltipOffset); this.Delay.SetFromStyle(style.TooltipDelay); // we can't set from style here since it's a different element this.Paragraph?.TextColor.Set(style.TooltipTextColor); } /// <summary> /// Causes this tooltip's position to be snapped to the mouse position. /// </summary> public void SnapPositionToMouse() { var viewport = this.System.Viewport; var offset = (this.Input.MousePosition.ToVector2() + this.MouseOffset.Value) / this.Scale; if (offset.X < viewport.X) offset.X = viewport.X; if (offset.Y < viewport.Y) offset.Y = viewport.Y; if (offset.X * this.Scale + this.Area.Width >= viewport.Right) offset.X = (viewport.Right - this.Area.Width) / this.Scale; if (offset.Y * this.Scale + this.Area.Height >= viewport.Bottom) offset.Y = (viewport.Bottom - this.Area.Height) / this.Scale; this.PositionOffset = offset; } /// <summary> /// Adds this tooltip to the given <see cref="UiSystem"/> and either displays it directly or starts the <see cref="Delay"/> timer. /// </summary> /// <param name="system">The system to add this tooltip to</param> /// <param name="name">The name that this tooltip should use</param> public void Display(UiSystem system, string name) { system.Add(name, this); if (this.Delay <= TimeSpan.Zero) { this.IsHidden = false; this.SnapPositionToMouse(); } else { this.IsHidden = true; this.delayCountdown = this.Delay; } } /// <summary> /// Removes this tooltip from its <see cref="UiSystem"/> and resets the <see cref="Delay"/> timer, if there is one. /// </summary> public void Remove() { this.delayCountdown = TimeSpan.Zero; if (this.System != null) this.System.Remove(this.Root.Name); } /// <summary> /// Adds this tooltip instance to the given <see cref="Element"/>, making it display when it is moused over /// </summary> /// <param name="elementToHover">The element that should automatically cause the tooltip to appear and disappear when hovered and not hovered, respectively</param> public void AddToElement(Element elementToHover) { elementToHover.OnMouseEnter += element => { // only display the tooltip if there is anything in it if (this.Children.Any(c => !c.IsHidden)) this.Display(element.System, element.GetType().Name + "Tooltip"); }; elementToHover.OnMouseExit += element => this.Remove(); } private void Init(Element elementToHover) { if (this.Paragraph != null) this.Paragraph.AutoAdjustWidth = true; this.SetWidthBasedOnChildren = true; this.SetHeightBasedOnChildren = true; this.ChildPadding = new Vector2(2); this.CanBeMoused = false; if (elementToHover != null) this.AddToElement(elementToHover); } } }<file_sep>/Tests/NumberTests.cs using Microsoft.Xna.Framework; using MLEM.Extensions; using MLEM.Misc; using NUnit.Framework; namespace Tests { public class NumberTests { [Test] public void TestRounding() { Assert.AreEqual(1.25F.Floor(), 1); Assert.AreEqual(-1.25F.Floor(), -1); Assert.AreEqual(1.25F.Ceil(), 2); Assert.AreEqual(-1.25F.Ceil(), -2); Assert.AreEqual(new Vector2(5, 2.5F).FloorCopy(), new Vector2(5, 2)); Assert.AreEqual(new Vector2(5, 2.5F).CeilCopy(), new Vector2(5, 3)); Assert.AreEqual(new Vector2(5.25F, 2).FloorCopy(), new Vector2(5, 2)); Assert.AreEqual(new Vector2(5.25F, 2).CeilCopy(), new Vector2(6, 2)); } [Test] public void TestEquals() { Assert.IsTrue(0.25F.Equals(0.26F, 0.01F)); Assert.IsFalse(0.25F.Equals(0.26F, 0.009F)); Assert.IsTrue(new Vector2(0.25F, 0).Equals(new Vector2(0.3F, 0), 0.1F)); Assert.IsFalse(new Vector2(0.25F, 0.5F).Equals(new Vector2(0.3F, 0.25F), 0.1F)); Assert.IsTrue(new Vector3(0.25F, 0, 3.5F).Equals(new Vector3(0.3F, 0, 3.45F), 0.1F)); Assert.IsFalse(new Vector3(0.25F, 0.5F, 0).Equals(new Vector3(0.3F, 0.25F, 0), 0.1F)); Assert.IsTrue(new Vector4(0.25F, 0, 3.5F, 0.75F).Equals(new Vector4(0.3F, 0, 3.45F, 0.7F), 0.1F)); Assert.IsFalse(new Vector4(0.25F, 0.5F, 0, 1).Equals(new Vector4(0.3F, 0.25F, 0, 0.9F), 0.1F)); } [Test] public void TestPointExtensions() { Assert.AreEqual(new Point(4, 3).Multiply(3), new Point(12, 9)); Assert.AreEqual(new Point(17, 12).Divide(3), new Point(5, 4)); Assert.AreEqual(new Point(4, 12).Transform(Matrix.CreateTranslation(2, 0, 0) * Matrix.CreateScale(2, 2, 2)), new Point(12, 24)); } [Test] public void TestMatrixOps([Range(0.5F, 2, 0.5F)] float scale, [Range(-1, 1, 1F)] float rotationX) { var matrix = Matrix.CreateRotationX(rotationX) * Matrix.CreateScale(scale, scale, scale); Assert.IsTrue(matrix.Scale().Equals(new Vector3(scale), 0.001F), $"{matrix.Scale()} does not equal {new Vector2(scale)}"); Assert.AreEqual(matrix.Rotation(), Quaternion.CreateFromAxisAngle(Vector3.UnitX, rotationX)); } [Test] public void TestPenetrate() { new RectangleF(2, 2, 4, 4).Penetrate(new RectangleF(3, 2, 4, 4), out var normal, out var penetration); Assert.AreEqual(normal, new Vector2(1, 0)); Assert.AreEqual(penetration, 3); new RectangleF(-10, 10, 5, 5).Penetrate(new RectangleF(25, 25, 10, 10), out normal, out penetration); Assert.AreEqual(normal, Vector2.Zero); Assert.AreEqual(penetration, 0); } } }<file_sep>/MLEM.Data/DynamicEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Reflection; using MLEM.Data.Json; using Newtonsoft.Json; namespace MLEM.Data { /// <summary> /// A dynamic enum is a class that represents enum-like single-instance value behavior with additional capabilities, including dynamic addition of new arbitrary values. /// A dynamic enum uses <see cref="BigInteger"/> as its underlying type, allowing for an arbitrary number of enum values to be created, even when a <see cref="FlagsAttribute"/>-like structure is used that would only allow for up to 64 values in a regular enum. /// All enum operations including <see cref="And{T}"/>, <see cref="Or{T}"/>, <see cref="Xor{T}"/> and <see cref="Neg{T}"/> are supported and can be implemented in derived classes using operator overloads. /// To create a custom dynamic enum, simply create a class that extends <see cref="DynamicEnum"/>. New values can then be added using <see cref="Add{T}"/>, <see cref="AddValue{T}"/> or <see cref="AddFlag{T}"/>. /// </summary> /// <remarks> /// To include enum-like operator overloads in a dynamic enum named MyEnum, the following code can be used: /// <code> /// public static implicit operator BigInteger(MyEnum value) => GetValue(value); /// public static implicit operator MyEnum(BigInteger value) => GetEnumValue&lt;MyEnum&gt;(value); /// public static MyEnum operator |(MyEnum left, MyEnum right) => Or(left, right); /// public static MyEnum operator &amp;(MyEnum left, MyEnum right) => And(left, right); /// public static MyEnum operator ^(MyEnum left, MyEnum right) => Xor(left, right); /// public static MyEnum operator ~(MyEnum value) => Neg(value); /// </code> /// </remarks> [JsonConverter(typeof(DynamicEnumConverter))] public abstract class DynamicEnum { private static readonly Dictionary<Type, Dictionary<BigInteger, DynamicEnum>> Values = new Dictionary<Type, Dictionary<BigInteger, DynamicEnum>>(); private static readonly Dictionary<Type, Dictionary<BigInteger, DynamicEnum>> FlagCache = new Dictionary<Type, Dictionary<BigInteger, DynamicEnum>>(); private static readonly Dictionary<Type, Dictionary<string, DynamicEnum>> ParseCache = new Dictionary<Type, Dictionary<string, DynamicEnum>>(); private readonly BigInteger value; private Dictionary<DynamicEnum, bool> allFlagsCache; private Dictionary<DynamicEnum, bool> anyFlagsCache; private string name; /// <summary> /// Creates a new dynamic enum instance. /// This constructor is protected as it is only invoked via reflection. /// </summary> /// <param name="name">The name of the enum value</param> /// <param name="value">The value</param> protected DynamicEnum(string name, BigInteger value) { this.value = value; this.name = name; } /// <summary> /// Returns true if this enum value has ALL of the given <see cref="DynamicEnum"/> flags on it. /// This operation is equivalent to <see cref="Enum.HasFlag"/>. /// </summary> /// <seealso cref="HasAnyFlag"/> /// <param name="flags">The flags to query</param> /// <returns>True if all of the flags are present, false otherwise</returns> public bool HasFlag(DynamicEnum flags) { if (this.allFlagsCache == null) this.allFlagsCache = new Dictionary<DynamicEnum, bool>(); if (!this.allFlagsCache.TryGetValue(flags, out var ret)) { // & is very memory-intensive, so we cache the return value ret = (GetValue(this) & GetValue(flags)) == GetValue(flags); this.allFlagsCache.Add(flags, ret); } return ret; } /// <summary> /// Returns true if this enum value has ANY of the given <see cref="DynamicEnum"/> flags on it /// </summary> /// <seealso cref="HasFlag"/> /// <param name="flags">The flags to query</param> /// <returns>True if one of the flags is present, false otherwise</returns> public bool HasAnyFlag(DynamicEnum flags) { if (this.anyFlagsCache == null) this.anyFlagsCache = new Dictionary<DynamicEnum, bool>(); if (!this.anyFlagsCache.TryGetValue(flags, out var ret)) { // & is very memory-intensive, so we cache the return value ret = (GetValue(this) & GetValue(flags)) != 0; this.anyFlagsCache.Add(flags, ret); } return ret; } /// <inheritdoc /> public override string ToString() { if (this.name == null) { var included = new List<DynamicEnum>(); if (GetValue(this) != 0) { foreach (var v in GetValues(this.GetType())) { if (this.HasFlag(v) && GetValue(v) != 0) included.Add(v); } } this.name = included.Count > 0 ? string.Join(" | ", included) : GetValue(this).ToString(); } return this.name; } /// <summary> /// Adds a new enum value to the given enum type <typeparamref name="T"/> /// </summary> /// <param name="name">The name of the enum value to add</param> /// <param name="value">The value to add</param> /// <typeparam name="T">The type to add this value to</typeparam> /// <returns>The newly created enum value</returns> /// <exception cref="ArgumentException">Thrown if the name or value passed are already present</exception> public static T Add<T>(string name, BigInteger value) where T : DynamicEnum { if (!Values.TryGetValue(typeof(T), out var dict)) { dict = new Dictionary<BigInteger, DynamicEnum>(); Values.Add(typeof(T), dict); } // cached parsed values and names might be incomplete with new values FlagCache.Remove(typeof(T)); ParseCache.Remove(typeof(T)); if (dict.ContainsKey(value)) throw new ArgumentException($"Duplicate value {value}", nameof(value)); if (dict.Values.Any(v => v.name == name)) throw new ArgumentException($"Duplicate name {name}", nameof(name)); var ret = Construct(typeof(T), name, value); dict.Add(value, ret); return (T) ret; } /// <summary> /// Adds a new enum value to the given enum type <typeparamref name="T"/>. /// This method differs from <see cref="Add{T}"/> in that it automatically determines a value. /// The value determined will be the next free number in a sequence, which represents the default behavior in an enum if enum values are not explicitly numbered. /// </summary> /// <param name="name">The name of the enum value to add</param> /// <typeparam name="T">The type to add this value to</typeparam> /// <returns>The newly created enum value</returns> public static T AddValue<T>(string name) where T : DynamicEnum { BigInteger value = 0; if (Values.TryGetValue(typeof(T), out var defined)) { while (defined.ContainsKey(value)) value++; } return Add<T>(name, value); } /// <summary> /// Adds a new flag enum value to the given enum type <typeparamref name="T"/>. /// This method differs from <see cref="Add{T}"/> in that it automatically determines a value. /// The value determined will be the next free power of two, allowing enum values to be combined using bitwise operations to create <see cref="FlagsAttribute"/>-like behavior. /// </summary> /// <param name="name">The name of the enum value to add</param> /// <typeparam name="T">The type to add this value to</typeparam> /// <returns>The newly created enum value</returns> public static T AddFlag<T>(string name) where T : DynamicEnum { BigInteger value = 0; if (Values.TryGetValue(typeof(T), out var defined)) { while (defined.ContainsKey(value)) value <<= 1; } return Add<T>(name, value); } /// <summary> /// Returns a collection of all of the enum values that are explicitly defined for the given dynamic enum type <typeparamref name="T"/>. /// A value counts as explicitly defined if it has been added using <see cref="Add{T}"/>, <see cref="AddValue{T}"/> or <see cref="AddFlag{T}"/>. /// </summary> /// <typeparam name="T">The type whose values to get</typeparam> /// <returns>The defined values for the given type</returns> public static IEnumerable<T> GetValues<T>() where T : DynamicEnum { return GetValues(typeof(T)).Cast<T>(); } /// <summary> /// Returns a collection of all of the enum values that are explicitly defined for the given dynamic enum type <paramref name="type"/>. /// A value counts as explicitly defined if it has been added using <see cref="Add{T}"/>, <see cref="AddValue{T}"/> or <see cref="AddFlag{T}"/>. /// </summary> /// <param name="type">The type whose values to get</param> /// <returns>The defined values for the given type</returns> public static IEnumerable<DynamicEnum> GetValues(Type type) { return Values.TryGetValue(type, out var ret) ? ret.Values : Enumerable.Empty<DynamicEnum>(); } /// <summary> /// Returns the bitwise OR (|) combination of the two dynamic enum values /// </summary> /// <param name="left">The left value</param> /// <param name="right">The right value</param> /// <typeparam name="T">The type of the values</typeparam> /// <returns>The bitwise OR (|) combination</returns> public static T Or<T>(T left, T right) where T : DynamicEnum { return GetEnumValue<T>(GetValue(left) | GetValue(right)); } /// <summary> /// Returns the bitwise AND (&amp;) combination of the two dynamic enum values /// </summary> /// <param name="left">The left value</param> /// <param name="right">The right value</param> /// <typeparam name="T">The type of the values</typeparam> /// <returns>The bitwise AND (&amp;) combination</returns> public static T And<T>(T left, T right) where T : DynamicEnum { return GetEnumValue<T>(GetValue(left) & GetValue(right)); } /// <summary> /// Returns the bitwise XOR (^) combination of the two dynamic enum values /// </summary> /// <param name="left">The left value</param> /// <param name="right">The right value</param> /// <typeparam name="T">The type of the values</typeparam> /// <returns>The bitwise XOR (^) combination</returns> public static T Xor<T>(T left, T right) where T : DynamicEnum { return GetEnumValue<T>(GetValue(left) ^ GetValue(right)); } /// <summary> /// Returns the bitwise NEG (~) combination of the dynamic enum value /// </summary> /// <param name="value">The value</param> /// <typeparam name="T">The type of the values</typeparam> /// <returns>The bitwise NEG (~) value</returns> public static T Neg<T>(T value) where T : DynamicEnum { return GetEnumValue<T>(~GetValue(value)); } /// <summary> /// Returns the <see cref="BigInteger"/> representation of the given dynamic enum value /// </summary> /// <param name="value">The value whose number representation to get</param> /// <returns>The value's number representation</returns> public static BigInteger GetValue(DynamicEnum value) { return value?.value ?? 0; } /// <summary> /// Returns the defined or combined dynamic enum value for the given <see cref="BigInteger"/> representation /// </summary> /// <param name="value">The value whose dynamic enum value to get</param> /// <typeparam name="T">The type that the returned dynamic enum should have</typeparam> /// <returns>The defined or combined dynamic enum value</returns> public static T GetEnumValue<T>(BigInteger value) where T : DynamicEnum { return (T) GetEnumValue(typeof(T), value); } /// <summary> /// Returns the defined or combined dynamic enum value for the given <see cref="BigInteger"/> representation /// </summary> /// <param name="type">The type that the returned dynamic enum should have</param> /// <param name="value">The value whose dynamic enum value to get</param> /// <returns>The defined or combined dynamic enum value</returns> public static DynamicEnum GetEnumValue(Type type, BigInteger value) { // get the defined value if it exists if (Values.TryGetValue(type, out var values) && values.TryGetValue(value, out var defined)) return defined; // otherwise, cache the combined value if (!FlagCache.TryGetValue(type, out var cache)) { cache = new Dictionary<BigInteger, DynamicEnum>(); FlagCache.Add(type, cache); } if (!cache.TryGetValue(value, out var combined)) { combined = Construct(type, null, value); cache.Add(value, combined); } return combined; } /// <summary> /// Parses the given <see cref="string"/> into a dynamic enum value and returns the result. /// This method supports defined enum values as well as values combined using the pipe (|) character and any number of spaces. /// If no enum value can be parsed, null is returned. /// </summary> /// <param name="strg">The string to parse into a dynamic enum value</param> /// <typeparam name="T">The type of the dynamic enum value to parse</typeparam> /// <returns>The parsed enum value, or null if parsing fails</returns> public static T Parse<T>(string strg) where T : DynamicEnum { return (T) Parse(typeof(T), strg); } /// <summary> /// Parses the given <see cref="string"/> into a dynamic enum value and returns the result. /// This method supports defined enum values as well as values combined using the pipe (|) character and any number of spaces. /// If no enum value can be parsed, null is returned. /// </summary> /// <param name="type">The type of the dynamic enum value to parse</param> /// <param name="strg">The string to parse into a dynamic enum value</param> /// <returns>The parsed enum value, or null if parsing fails</returns> public static DynamicEnum Parse(Type type, string strg) { if (!ParseCache.TryGetValue(type, out var cache)) { cache = new Dictionary<string, DynamicEnum>(); ParseCache.Add(type, cache); } if (!cache.TryGetValue(strg, out var cached)) { BigInteger? accum = null; foreach (var val in strg.Split('|')) { foreach (var defined in GetValues(type)) { if (defined.name == val.Trim()) { accum = (accum ?? 0) | GetValue(defined); break; } } } if (accum != null) cached = GetEnumValue(type, accum.Value); cache.Add(strg, cached); } return cached; } private static DynamicEnum Construct(Type type, string name, BigInteger value) { var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] {typeof(string), typeof(BigInteger)}, null); return (DynamicEnum) constructor.Invoke(new object[] {name, value}); } } }<file_sep>/MLEM/Misc/SoundEffectInstanceHandler.cs using System; using Microsoft.Xna.Framework; namespace MLEM.Misc { /// <inheritdoc /> [Obsolete("This class has been moved to MLEM.Sound.SoundEffectInstanceHandler in 5.1.0")] public class SoundEffectInstanceHandler : Sound.SoundEffectInstanceHandler { /// <inheritdoc /> public SoundEffectInstanceHandler(Game game) : base(game) { } } }<file_sep>/MLEM.Extended/Font/GenericStashFont.cs using System.Text; using FontStashSharp; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; using MLEM.Font; namespace MLEM.Extended.Font { /// <inheritdoc/> public class GenericStashFont : GenericFont { /// <summary> /// The <see cref="SpriteFontBase"/> that is being wrapped by this generic font /// </summary> public readonly SpriteFontBase Font; /// <inheritdoc /> public override GenericFont Bold { get; } /// <inheritdoc /> public override GenericFont Italic { get; } /// <inheritdoc /> public override float LineHeight { get; } /// <summary> /// Creates a new generic font using <see cref="SpriteFontBase"/>. /// Optionally, a bold and italic version of the font can be supplied. /// </summary> /// <param name="font">The font to wrap</param> /// <param name="bold">A bold version of the font</param> /// <param name="italic">An italic version of the font</param> public GenericStashFont(SpriteFontBase font, SpriteFontBase bold = null, SpriteFontBase italic = null) { this.Font = font; // SpriteFontBase provides no line height, so we measure the height of a new line for most fonts // This doesn't work with static sprite fonts, but their size is always the one we calculate here this.LineHeight = font is StaticSpriteFont s ? s.FontSize + s.LineSpacing : font.MeasureString("\n").Y; this.Bold = bold != null ? new GenericStashFont(bold) : this; this.Italic = italic != null ? new GenericStashFont(italic) : this; } /// <inheritdoc /> public override void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { this.Font.DrawText(batch, text, position, color, scale, rotation, origin, layerDepth); } /// <inheritdoc /> public override void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { this.Font.DrawText(batch, text, position, color, scale, rotation, origin, layerDepth); } /// <inheritdoc /> protected override Vector2 MeasureChar(char c) { return this.Font.MeasureString(c.ToCachedString()); } } }<file_sep>/MLEM/Font/GenericSpriteFont.cs using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Extensions; namespace MLEM.Font { /// <inheritdoc/> public class GenericSpriteFont : GenericFont { /// <summary> /// The <see cref="SpriteFont"/> that is being wrapped by this generic font /// </summary> public readonly SpriteFont Font; /// <inheritdoc/> public override GenericFont Bold { get; } /// <inheritdoc/> public override GenericFont Italic { get; } /// <inheritdoc/> public override float LineHeight => this.Font.LineSpacing; /// <summary> /// Creates a new generic font using <see cref="SpriteFont"/>. /// Optionally, a bold and italic version of the font can be supplied. /// </summary> /// <param name="font">The font to wrap</param> /// <param name="bold">A bold version of the font</param> /// <param name="italic">An italic version of the font</param> public GenericSpriteFont(SpriteFont font, SpriteFont bold = null, SpriteFont italic = null) { this.Font = SetDefaults(font); this.Bold = bold != null ? new GenericSpriteFont(SetDefaults(bold)) : this; this.Italic = italic != null ? new GenericSpriteFont(SetDefaults(italic)) : this; } /// <inheritdoc /> protected override Vector2 MeasureChar(char c) { return this.Font.MeasureString(c.ToCachedString()); } /// <inheritdoc/> public override void DrawString(SpriteBatch batch, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { batch.DrawString(this.Font, text, position, color, rotation, origin, scale, effects, layerDepth); } /// <inheritdoc/> public override void DrawString(SpriteBatch batch, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { batch.DrawString(this.Font, text, position, color, rotation, origin, scale, effects, layerDepth); } private static SpriteFont SetDefaults(SpriteFont font) { // we copy the font here to set the default character to a space return new SpriteFont( font.Texture, font.Glyphs.Select(g => g.BoundsInTexture).ToList(), font.Glyphs.Select(g => g.Cropping).ToList(), font.Characters.ToList(), font.LineSpacing, font.Spacing, font.Glyphs.Select(g => new Vector3(g.LeftSideBearing, g.Width, g.RightSideBearing)).ToList(), ' '); } } }<file_sep>/MLEM.Ui/Elements/Paragraph.cs using System; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MLEM.Font; using MLEM.Formatting; using MLEM.Formatting.Codes; using MLEM.Misc; using MLEM.Ui.Style; namespace MLEM.Ui.Elements { /// <summary> /// A paragraph element for use inside of a <see cref="UiSystem"/>. /// A paragraph is an element that contains text. /// A paragraph's text can be formatted using the ui system's <see cref="UiSystem.TextFormatter"/>. /// </summary> public class Paragraph : Element { /// <summary> /// The font that this paragraph draws text with. /// To set its bold and italic font, use <see cref="GenericFont.Bold"/> and <see cref="GenericFont.Italic"/>. /// </summary> public StyleProp<GenericFont> RegularFont; /// <summary> /// The tokenized version of the <see cref="Text"/> /// </summary> public TokenizedString TokenizedText { get; private set; } /// <summary> /// The color that the text will be rendered with /// </summary> public StyleProp<Color> TextColor; /// <summary> /// The scale that the text will be rendered with. /// To add a multiplier rather than changing the scale directly, use <see cref="TextScaleMultiplier"/>. /// </summary> public StyleProp<float> TextScale; /// <summary> /// A multiplier that will be applied to <see cref="TextScale"/>. /// To change the text scale itself, use <see cref="TextScale"/>. /// </summary> public float TextScaleMultiplier = 1; /// <summary> /// The text to render inside of this paragraph. /// Use <see cref="GetTextCallback"/> if the text changes frequently. /// </summary> public string Text { get { this.QueryTextCallback(); return this.text; } set { if (this.text != value) { this.text = value; this.IsHidden = string.IsNullOrWhiteSpace(this.text); this.SetAreaDirty(); // force text to be re-tokenized this.TokenizedText = null; } } } /// <summary> /// If this paragraph should automatically adjust its width based on the width of the text within it /// </summary> public bool AutoAdjustWidth; /// <summary> /// Whether this paragraph should be truncated instead of split if the displayed <see cref="Text"/>'s width exceeds the provided width. /// When the string is truncated, the <see cref="Ellipsis"/> is added to its end. /// </summary> public bool TruncateIfLong; /// <summary> /// The ellipsis characters to use if <see cref="TruncateIfLong"/> is enabled and the string is truncated. /// If this is set to an empty string, no ellipsis will be attached to the truncated string. /// </summary> public string Ellipsis = "..."; /// <summary> /// An event that gets called when this paragraph's <see cref="Text"/> is queried. /// Use this event for setting this paragraph's text if it changes frequently. /// </summary> public TextCallback GetTextCallback; /// <summary> /// The action that is executed if <see cref="Link"/> objects inside of this paragraph are pressed. /// By default, <see cref="MlemPlatform.OpenLinkOrFile"/> is executed. /// </summary> public Action<Link, LinkCode> LinkAction; /// <summary> /// The <see cref="TextAlignment"/> that this paragraph's text should be rendered with /// </summary> public TextAlignment Alignment { get => this.alignment; set { this.alignment = value; this.SetAreaDirty(); this.TokenizedText = null; } } private string text; private TextAlignment alignment; /// <summary> /// Creates a new paragraph with the given settings. /// </summary> /// <param name="anchor">The paragraph's anchor</param> /// <param name="width">The paragraph's width. Note that its height is automatically calculated.</param> /// <param name="textCallback">The paragraph's text</param> /// <param name="autoAdjustWidth">Whether the paragraph's width should automatically be calculated based on the text within it.</param> public Paragraph(Anchor anchor, float width, TextCallback textCallback, bool autoAdjustWidth = false) : this(anchor, width, "", autoAdjustWidth) { this.GetTextCallback = textCallback; this.Text = textCallback(this); if (this.Text == null) this.IsHidden = true; } /// <inheritdoc cref="Paragraph(Anchor,float,TextCallback,bool)"/> public Paragraph(Anchor anchor, float width, string text, bool autoAdjustWidth = false) : base(anchor, new Vector2(width, 0)) { this.Text = text; if (this.Text == null) this.IsHidden = true; this.AutoAdjustWidth = autoAdjustWidth; this.CanBeSelected = false; this.CanBeMoused = false; } /// <inheritdoc /> protected override Vector2 CalcActualSize(RectangleF parentArea) { var size = base.CalcActualSize(parentArea); this.ParseText(size); var (w, h) = this.TokenizedText.Measure(this.RegularFont) * this.TextScale * this.TextScaleMultiplier * this.Scale; return new Vector2(this.AutoAdjustWidth ? w + this.ScaledPadding.Width : size.X, h + this.ScaledPadding.Height); } /// <inheritdoc /> public override void Update(GameTime time) { this.QueryTextCallback(); base.Update(time); if (this.TokenizedText != null) this.TokenizedText.Update(time); } /// <inheritdoc /> public override void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { var pos = this.DisplayArea.Location + new Vector2(GetAlignmentOffset(), 0); var sc = this.TextScale * this.TextScaleMultiplier * this.Scale; var color = this.TextColor.OrDefault(Color.White) * alpha; this.TokenizedText.Draw(time, batch, pos, this.RegularFont, color, sc, 0, this.Alignment); base.Draw(time, batch, alpha, blendState, samplerState, matrix); } /// <inheritdoc /> protected override void InitStyle(UiStyle style) { base.InitStyle(style); this.TextScale.SetFromStyle(style.TextScale); this.RegularFont.SetFromStyle(style.Font); this.TextColor.SetFromStyle(style.TextColor); } /// <summary> /// Parses this paragraph's <see cref="Text"/> into <see cref="TokenizedText"/>. /// Additionally, this method adds any <see cref="Link"/> elements for tokenized links in the text. /// </summary> /// <param name="size">The paragraph's default size</param> protected virtual void ParseText(Vector2 size) { if (this.TokenizedText == null) { // tokenize the text this.TokenizedText = this.System.TextFormatter.Tokenize(this.RegularFont, this.Text, this.Alignment); // add links to the paragraph this.RemoveChildren(c => c is Link); foreach (var link in this.TokenizedText.Tokens.Where(t => t.AppliedCodes.Any(c => c is LinkCode))) this.AddChild(new Link(Anchor.TopLeft, link, this.TextScale * this.TextScaleMultiplier)); } var width = size.X - this.ScaledPadding.Width; var scale = this.TextScale * this.TextScaleMultiplier * this.Scale; if (this.TruncateIfLong) { this.TokenizedText.Truncate(this.RegularFont, width, scale, this.Ellipsis, this.Alignment); } else { this.TokenizedText.Split(this.RegularFont, width, scale, this.Alignment); } } private void QueryTextCallback() { if (this.GetTextCallback != null) this.Text = this.GetTextCallback(this); } private float GetAlignmentOffset() { switch (this.Alignment) { case TextAlignment.Center: return this.DisplayArea.Width / 2; case TextAlignment.Right: return this.DisplayArea.Width; } return 0; } /// <summary> /// A delegate method used for <see cref="Paragraph.GetTextCallback"/> /// </summary> /// <param name="paragraph">The current paragraph</param> public delegate string TextCallback(Paragraph paragraph); /// <summary> /// A link is a sub-element of the <see cref="Paragraph"/> that is added onto it as a child for any tokens that contain <see cref="LinkCode"/>, to make them selectable and clickable. /// </summary> public class Link : Element { /// <summary> /// The token that this link represents /// </summary> public readonly Token Token; private readonly float textScale; /// <summary> /// Creates a new link element with the given settings /// </summary> /// <param name="anchor">The link's anchor</param> /// <param name="token">The token that this link represents</param> /// <param name="textScale">The scale that text is rendered with</param> public Link(Anchor anchor, Token token, float textScale) : base(anchor, Vector2.Zero) { this.Token = token; this.textScale = textScale; this.OnPressed += e => { foreach (var code in token.AppliedCodes.OfType<LinkCode>()) { if (this.Parent is Paragraph p && p.LinkAction != null) { p.LinkAction.Invoke(this, code); } else { MlemPlatform.Current.OpenLinkOrFile(code.Match.Groups[1].Value); } } }; } /// <inheritdoc /> public override void ForceUpdateArea() { // set the position offset and size to the token's first area var area = this.Token.GetArea(Vector2.Zero, this.textScale).FirstOrDefault(); this.PositionOffset = area.Location + new Vector2(((Paragraph) this.Parent).GetAlignmentOffset() / this.Parent.Scale, 0); this.IsHidden = area.IsEmpty; this.Size = area.Size; base.ForceUpdateArea(); } /// <inheritdoc /> public override Element GetElementUnderPos(Vector2 position) { var ret = base.GetElementUnderPos(position); if (ret != null) return ret; // check if any of our token's parts are hovered foreach (var rect in this.Token.GetArea(this.Parent.DisplayArea.Location, this.Scale * this.textScale)) { if (rect.Contains(position)) return this; } return null; } } } }<file_sep>/Tests/TexturePackerTests.cs using System; using Microsoft.Xna.Framework.Graphics; using MLEM.Data; using MLEM.Textures; using NUnit.Framework; namespace Tests { public class TexturePackerTests { private Texture2D testTexture; private TestGame game; [SetUp] public void SetUp() { this.game = TestGame.Create(); this.testTexture = new Texture2D(this.game.GraphicsDevice, 256, 256); } [TearDown] public void TearDown() { this.game?.Dispose(); this.testTexture?.Dispose(); } [Test] public void TestPacking() { using var packer = new RuntimeTexturePacker(); for (var i = 0; i < 5; i++) { var width = 16 * (i + 1); packer.Add(new TextureRegion(this.testTexture, 0, 0, width, 64), r => { Assert.AreEqual(r.Width, width); Assert.AreEqual(r.Height, 64); }); } packer.Pack(this.game.GraphicsDevice); Assert.AreEqual(packer.PackedTexture.Width, 16 + 32 + 48 + 64 + 80); Assert.AreEqual(packer.PackedTexture.Height, 64); } [Test] public void TestBounds() { // test forced max width using var packer = new RuntimeTexturePacker(128); Assert.Throws<InvalidOperationException>(() => { packer.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), StubResult); }); // test auto-expanding width using var packer2 = new RuntimeTexturePacker(128, true); Assert.DoesNotThrow(() => { packer2.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), StubResult); }); packer2.Pack(this.game.GraphicsDevice); // test power of two forcing using var packer3 = new RuntimeTexturePacker(128, forcePowerOfTwo: true); packer3.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), StubResult); packer3.Pack(this.game.GraphicsDevice); Assert.AreEqual(64, packer3.PackedTexture.Width); Assert.AreEqual(256, packer3.PackedTexture.Height); // test square forcing using var packer4 = new RuntimeTexturePacker(128, forceSquare: true); packer4.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), StubResult); packer4.Pack(this.game.GraphicsDevice); Assert.AreEqual(170, packer4.PackedTexture.Width); Assert.AreEqual(170, packer4.PackedTexture.Height); } private static void StubResult(TextureRegion region) { } } }<file_sep>/MLEM/Extensions/RandomExtensions.cs using System; using System.Collections.Generic; using System.Linq; namespace MLEM.Extensions { /// <summary> /// A set of extensions for dealing with <see cref="Random"/> /// </summary> public static class RandomExtensions { /// <summary> /// Gets a random entry from the given list with uniform chance. /// </summary> /// <param name="random">The random</param> /// <param name="entries">The entries to choose from</param> /// <typeparam name="T">The entries' type</typeparam> /// <returns>A random entry</returns> public static T GetRandomEntry<T>(this Random random, IList<T> entries) { return entries[random.Next(entries.Count)]; } /// <summary> /// Returns a random entry from the given list based on the specified weight function. /// A higher weight for an entry increases its likeliness of being picked. /// </summary> /// <param name="random">The random</param> /// <param name="entries">The entries to choose from</param> /// <param name="weightFunc">A function that applies weight to each entry</param> /// <typeparam name="T">The entries' type</typeparam> /// <returns>A random entry, based on the entries' weight</returns> /// <exception cref="IndexOutOfRangeException">If the weight function returns different weights for the same entry</exception> public static T GetRandomWeightedEntry<T>(this Random random, IList<T> entries, Func<T, int> weightFunc) { var totalWeight = entries.Sum(weightFunc); var goalWeight = random.Next(totalWeight); var currWeight = 0; foreach (var entry in entries) { currWeight += weightFunc(entry); if (currWeight >= goalWeight) return entry; } throw new IndexOutOfRangeException(); } } }<file_sep>/MLEM.Ui/Elements/Element.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MLEM.Extensions; using MLEM.Input; using MLEM.Misc; using MLEM.Textures; using MLEM.Ui.Style; using SoundEffectInfo = MLEM.Sound.SoundEffectInfo; namespace MLEM.Ui.Elements { /// <summary> /// This class represents a generic base class for ui elements of a <see cref="UiSystem"/>. /// </summary> public abstract class Element : GenericDataHolder, IDisposable { /// <summary> /// A list of all of this element's direct children. /// Use <see cref="AddChild{T}"/> or <see cref="RemoveChild"/> to manipulate this list while calling all of the necessary callbacks. /// </summary> protected readonly IList<Element> Children; private readonly List<Element> children = new List<Element>(); /// <summary> /// A sorted version of <see cref="Children"/>. The children are sorted by their <see cref="Priority"/>. /// </summary> protected IList<Element> SortedChildren { get { this.UpdateSortedChildrenIfDirty(); return this.sortedChildren; } } private bool sortedChildrenDirty; private IList<Element> sortedChildren; private UiSystem system; /// <summary> /// The ui system that this element is currently a part of /// </summary> public UiSystem System { get => this.system; internal set { this.system = value; this.Controls = value?.Controls; if (this.system != null) this.InitStyle(this.system.Style); } } /// <summary> /// The controls that this element's <see cref="System"/> uses /// </summary> public UiControls Controls; /// <summary> /// The input handler that this element's <see cref="Controls"/> use /// </summary> protected InputHandler Input => this.Controls.Input; /// <summary> /// This element's parent element. /// If this element has no parent (it is the <see cref="RootElement"/> of a ui system), this value is <c>null</c>. /// </summary> public Element Parent { get; private set; } /// <summary> /// This element's <see cref="RootElement"/>. /// Note that this value is set even if this element has a <see cref="Parent"/>. To get the element that represents the root element, use <see cref="RootElement.Element"/>. /// </summary> public RootElement Root { get; internal set; } /// <summary> /// The scale that this ui element renders with /// </summary> public float Scale => this.Root.ActualScale; private Anchor anchor; /// <summary> /// The <see cref="Anchor"/> that this element uses for positioning within its parent /// </summary> public Anchor Anchor { get => this.anchor; set { if (this.anchor == value) return; this.anchor = value; this.SetAreaDirty(); } } private Vector2 size; /// <summary> /// The size of this element, where X represents the width and Y represents the height. /// If the x or y value of the size is between 0 and 1, the size will be seen as a percentage of its parent's size rather than as an absolute value. /// If the x (or y) value of the size is negative, the width (or height) is seen as a percentage of the element's resulting height (or width). /// </summary> /// <example> /// The following example combines both types of percentage-based sizing. /// If this element is inside of a <see cref="Parent"/> whose width is 20, this element's width will be set to <c>0.5 * 20 = 10</c>, and its height will be set to <c>2.5 * 10 = 25</c>. /// <code> /// element.Size = new Vector2(0.5F, -2.5F); /// </code> /// </example> public Vector2 Size { get => this.size; set { if (this.size == value) return; this.size = value; this.SetAreaDirty(); } } /// <summary> /// The <see cref="Size"/>, but with <see cref="Scale"/> applied. /// </summary> public Vector2 ScaledSize => this.size * this.Scale; private Vector2 offset; /// <summary> /// This element's offset from its default position, which is dictated by its <see cref="Anchor"/>. /// Note that, depending on the side that the element is anchored to, this offset moves it in a different direction. /// </summary> public Vector2 PositionOffset { get => this.offset; set { if (this.offset == value) return; this.offset = value; this.SetAreaDirty(); } } /// <summary> /// The <see cref="PositionOffset"/>, but with <see cref="Scale"/> applied. /// </summary> public Vector2 ScaledOffset => this.offset * this.Scale; /// <summary> /// The padding that this element has. /// The padding is subtracted from the element's <see cref="Size"/>, and it is an area that the element does not extend into. This means that this element's resulting <see cref="DisplayArea"/> does not include this padding. /// </summary> public Padding Padding; /// <summary> /// The <see cref="Padding"/>, but with <see cref="Scale"/> applied. /// </summary> public Padding ScaledPadding => this.Padding * this.Scale; private Padding childPadding; /// <summary> /// The child padding that this element has. /// The child padding moves any <see cref="Children"/> added to this element inwards by the given amount in each direction. /// </summary> public Padding ChildPadding { get => this.childPadding; set { if (this.childPadding == value) return; this.childPadding = value; this.SetAreaDirty(); } } /// <summary> /// The <see cref="ChildPadding"/>, but with <see cref="Scale"/> applied. /// </summary> public Padding ScaledChildPadding => this.childPadding * this.Scale; /// <summary> /// This element's current <see cref="Area"/>, but with <see cref="ScaledChildPadding"/> applied. /// </summary> public RectangleF ChildPaddedArea => this.UnscrolledArea.Shrink(this.ScaledChildPadding); private RectangleF area; /// <summary> /// This element's area, without respecting its <see cref="ScrollOffset"/>. /// This area is updated automatically to fit this element's sizing and positioning properties. /// </summary> public RectangleF UnscrolledArea { get { this.UpdateAreaIfDirty(); return this.area; } } private bool areaDirty; /// <summary> /// The <see cref="UnscrolledArea"/> of this element, but with <see cref="ScaledScrollOffset"/> applied. /// </summary> public RectangleF Area => this.UnscrolledArea.OffsetCopy(this.ScaledScrollOffset); /// <summary> /// The area that this element is displayed in, which is <see cref="Area"/> shrunk by this element's <see cref="ScaledPadding"/>. /// This is the property that should be used for drawing this element, as well as mouse input handling and culling. /// </summary> public RectangleF DisplayArea => this.Area.Shrink(this.ScaledPadding); /// <summary> /// The offset that this element has as a result of <see cref="Panel"/> scrolling. /// </summary> public Vector2 ScrollOffset; /// <summary> /// The <see cref="ScrollOffset"/>, but with <see cref="Scale"/> applied. /// </summary> public Vector2 ScaledScrollOffset => this.ScrollOffset * this.Scale; private bool isHidden; /// <summary> /// Set this property to <c>true</c> to cause this element to be hidden. /// Hidden elements don't receive input events, aren't rendered and don't factor into auto-anchoring. /// </summary> public bool IsHidden { get => this.isHidden; set { if (this.isHidden == value) return; this.isHidden = value; this.SetAreaDirty(); } } private int priority; /// <summary> /// The priority of this element as part of its <see cref="Parent"/> element. /// A higher priority means the element will be drawn first and, if auto-anchoring is used, anchored higher up within its parent. /// </summary> public int Priority { get => this.priority; set { if (this.priority == value) return; this.priority = value; if (this.Parent != null) this.Parent.SetSortedChildrenDirty(); } } /// <summary> /// This element's transform matrix. /// Can easily be scaled using <see cref="ScaleTransform"/>. /// Note that, when this is non-null, a new <see cref="SpriteBatch.Begin"/> call is used for this element. /// </summary> public Matrix Transform = Matrix.Identity; /// <summary> /// The call that this element should make to <see cref="SpriteBatch"/> to begin drawing. /// Note that, when this is non-null, a new <see cref="SpriteBatch.Begin"/> call is used for this element. /// </summary> public BeginDelegate BeginImpl; /// <summary> /// Set this field to false to disallow the element from being selected. /// An unselectable element is skipped by automatic navigation and its <see cref="OnSelected"/> callback will never be called. /// </summary> public bool CanBeSelected = true; /// <summary> /// Set this field to false to disallow the element from reacting to being moused over. /// </summary> public bool CanBeMoused = true; /// <summary> /// Set this field to false to disallow this element's <see cref="OnPressed"/> and <see cref="OnSecondaryPressed"/> events to be called. /// </summary> public bool CanBePressed = true; /// <summary> /// Set this field to false to cause auto-anchored siblings to ignore this element as a possible anchor point. /// </summary> public bool CanAutoAnchorsAttach = true; /// <summary> /// Set this field to true to cause this element's width to be automatically calculated based on the area that its <see cref="Children"/> take up. /// To use this element's <see cref="Size"/>'s X coordinate as a minimum or maximum width rather than ignoring it, set <see cref="TreatSizeAsMinimum"/> or <see cref="TreatSizeAsMaximum"/> to true. /// </summary> public bool SetWidthBasedOnChildren; /// <summary> /// Set this field to true to cause this element's height to be automatically calculated based on the area that its <see cref="Children"/> take up. /// To use this element's <see cref="Size"/>'s Y coordinate as a minimum or maximum height rather than ignoring it, set <see cref="TreatSizeAsMinimum"/> or <see cref="TreatSizeAsMaximum"/> to true. /// </summary> public bool SetHeightBasedOnChildren; /// <summary> /// If this field is set to true, and <see cref="SetWidthBasedOnChildren"/> or <see cref="SetHeightBasedOnChildren"/> are enabled, the resulting width or height will always be greather than or equal to this element's <see cref="Size"/>. /// For example, if an element's <see cref="Size"/>'s Y coordinate is set to 20, but there is only one child with a height of 10 in it, the element's height would be shrunk to 10 if this value was false, but would remain at 20 if it was true. /// Note that this value only has an effect if <see cref="SetWidthBasedOnChildren"/> or <see cref="SetHeightBasedOnChildren"/> are enabled. /// </summary> public bool TreatSizeAsMinimum; /// <summary> /// If this field is set to true, and <see cref="SetWidthBasedOnChildren"/> or <see cref="SetHeightBasedOnChildren"/>are enabled, the resulting width or height weill always be less than or equal to this element's <see cref="Size"/>. /// Note that this value only has an effect if <see cref="SetWidthBasedOnChildren"/> or <see cref="SetHeightBasedOnChildren"/> are enabled. /// </summary> public bool TreatSizeAsMaximum; /// <summary> /// Set this field to true to cause this element's final display area to never exceed that of its <see cref="Parent"/>. /// If the resulting area is too large, the size of this element is shrunk to fit the target area. /// This can be useful if an element should fill the remaining area of a parent exactly. /// </summary> public bool PreventParentSpill; /// <summary> /// The transparency (alpha value) that this element is rendered with. /// Note that, when <see cref="Draw"/> is called, this alpha value is multiplied with the <see cref="Parent"/>'s alpha value and passed down to this element's <see cref="Children"/>. /// </summary> public float DrawAlpha = 1; /// <summary> /// Stores whether this element is currently being moused over or touched. /// </summary> public bool IsMouseOver { get; protected set; } /// <summary> /// Stores whether this element is its <see cref="Root"/>'s <see cref="RootElement.SelectedElement"/>. /// </summary> public bool IsSelected { get; protected set; } /// <summary> /// Event that is called after this element is drawn, but before its children are drawn /// </summary> public DrawCallback OnDrawn; /// <summary> /// Event that is called when this element is updated /// </summary> public TimeCallback OnUpdated; /// <summary> /// Event that is called when this element is pressed /// </summary> public GenericCallback OnPressed; /// <summary> /// Event that is called when this element is pressed using the secondary action /// </summary> public GenericCallback OnSecondaryPressed; /// <summary> /// Event that is called when this element's <see cref="IsSelected"/> is turned true /// </summary> public GenericCallback OnSelected; /// <summary> /// Event that is called when this element's <see cref="IsSelected"/> is turned false /// </summary> public GenericCallback OnDeselected; /// <summary> /// Event that is called when this element starts being moused over /// </summary> public GenericCallback OnMouseEnter; /// <summary> /// Event that is called when this element stops being moused over /// </summary> public GenericCallback OnMouseExit; /// <summary> /// Event that is called when this element starts being touched /// </summary> public GenericCallback OnTouchEnter; /// <summary> /// Event that is called when this element stops being touched /// </summary> public GenericCallback OnTouchExit; /// <summary> /// Event that is called when text input is made. /// When an element uses this event, it should call <see cref="MlemPlatform.EnsureExists"/> on construction to ensure that the MLEM platform is initialized. /// /// Note that this event is called for every element, even if it is not selected. /// Also note that if the active <see cref="MlemPlatform"/> uses an on-screen keyboard, this event is never called. /// </summary> public TextInputCallback OnTextInput; /// <summary> /// Event that is called when this element's <see cref="DisplayArea"/> is changed. /// </summary> public GenericCallback OnAreaUpdated; /// <summary> /// Event that is called when the element that is currently being moused changes within the ui system. /// Note that the event fired doesn't necessarily correlate to this specific element. /// </summary> public OtherElementCallback OnMousedElementChanged; /// <summary> /// Event that is called when the element that is currently being touched changes within the ui system. /// Note that the event fired doesn't necessarily correlate to this specific element. /// </summary> public OtherElementCallback OnTouchedElementChanged; /// <summary> /// Event that is called when the element that is currently selected changes within the ui system. /// Note that the event fired doesn't necessarily correlate to this specific element. /// </summary> public OtherElementCallback OnSelectedElementChanged; /// <summary> /// Event that is called when the next element to select when pressing tab is calculated. /// To cause a different element than the default one to be selected, return it during this event. /// </summary> public TabNextElementCallback GetTabNextElement; /// <summary> /// Event that is called when the next element to select when using gamepad input is calculated. /// To cause a different element than the default one to be selected, return it during this event. /// </summary> public GamepadNextElementCallback GetGamepadNextElement; /// <summary> /// Event that is called when a child is added to this element using <see cref="AddChild{T}"/> /// </summary> public OtherElementCallback OnChildAdded; /// <summary> /// Event that is called when a child is removed from this element using <see cref="RemoveChild"/> /// </summary> public OtherElementCallback OnChildRemoved; /// <summary> /// Event that is called when this element's <see cref="Dispose"/> method is called, which also happens in <see cref="Finalize"/>. /// This event is useful for unregistering global event handlers when this object should be destroyed. /// </summary> public GenericCallback OnDisposed; /// <summary> /// A style property that contains the selection indicator that is displayed on this element if it is the <see cref="RootElement.SelectedElement"/> /// </summary> public StyleProp<NinePatch> SelectionIndicator; /// <summary> /// A style property that contains the sound effect that is played when this element's <see cref="OnPressed"/> is called /// </summary> public StyleProp<SoundEffectInfo> ActionSound; /// <summary> /// A style property that contains the sound effect that is played when this element's <see cref="OnSecondaryPressed"/> is called /// </summary> public StyleProp<SoundEffectInfo> SecondActionSound; /// <summary> /// Creates a new element with the given anchor and size and sets up some default event reactions. /// </summary> /// <param name="anchor">This element's <see cref="Anchor"/></param> /// <param name="size">This element's default <see cref="Size"/></param> protected Element(Anchor anchor, Vector2 size) { this.anchor = anchor; this.size = size; this.Children = new ReadOnlyCollection<Element>(this.children); this.OnMouseEnter += element => this.IsMouseOver = true; this.OnMouseExit += element => this.IsMouseOver = false; this.OnTouchEnter += element => this.IsMouseOver = true; this.OnTouchExit += element => this.IsMouseOver = false; this.OnSelected += element => this.IsSelected = true; this.OnDeselected += element => this.IsSelected = false; this.GetTabNextElement += (backward, next) => next; this.GetGamepadNextElement += (dir, next) => next; this.SetAreaDirty(); this.SetSortedChildrenDirty(); } /// <inheritdoc /> ~Element() { this.Dispose(); } /// <summary> /// Adds a child to this element. /// </summary> /// <param name="element">The child element to add</param> /// <param name="index">The index to add the child at, or -1 to add it to the end of the <see cref="Children"/> list</param> /// <typeparam name="T">The type of child to add</typeparam> /// <returns>This element, for chaining</returns> public virtual T AddChild<T>(T element, int index = -1) where T : Element { if (index < 0 || index > this.children.Count) index = this.children.Count; this.children.Insert(index, element); element.Parent = this; element.AndChildren(e => { e.Root = this.Root; e.System = this.System; this.Root?.InvokeOnElementAdded(e); this.OnChildAdded?.Invoke(this, e); }); this.SetSortedChildrenDirty(); element.SetAreaDirty(); return element; } /// <summary> /// Removes the given child from this element. /// </summary> /// <param name="element">The child element to remove</param> public virtual void RemoveChild(Element element) { this.children.Remove(element); // set area dirty here so that a dirty call is made // upwards to us if the element is auto-positioned element.SetAreaDirty(); element.Parent = null; element.AndChildren(e => { e.Root = null; e.System = null; this.Root?.InvokeOnElementRemoved(e); this.OnChildRemoved?.Invoke(this, e); }); this.SetSortedChildrenDirty(); } /// <summary> /// Removes all children from this element that match the given condition. /// </summary> /// <param name="condition">The condition that determines if a child should be removed</param> public virtual void RemoveChildren(Func<Element, bool> condition = null) { for (var i = this.Children.Count - 1; i >= 0; i--) { var child = this.Children[i]; if (condition == null || condition(child)) { this.RemoveChild(child); } } } /// <summary> /// Causes <see cref="SortedChildren"/> to be recalculated as soon as possible. /// </summary> public void SetSortedChildrenDirty() { this.sortedChildrenDirty = true; } /// <summary> /// Updates the <see cref="SortedChildren"/> list if <see cref="SetSortedChildrenDirty"/> is true. /// </summary> public void UpdateSortedChildrenIfDirty() { if (this.sortedChildrenDirty) this.ForceUpdateSortedChildren(); } /// <summary> /// Forces an update of the <see cref="SortedChildren"/> list. /// </summary> public virtual void ForceUpdateSortedChildren() { this.sortedChildrenDirty = false; this.sortedChildren = new ReadOnlyCollection<Element>(this.Children.OrderBy(e => e.Priority).ToArray()); } /// <summary> /// Causes this element's <see cref="Area"/> to be recalculated as soon as possible. /// If this element is auto-anchored or its parent automatically changes its size based on its children, this element's parent's area is also marked dirty. /// </summary> public void SetAreaDirty() { this.areaDirty = true; if (this.Parent != null && (this.Anchor >= Anchor.AutoLeft || this.Parent.SetWidthBasedOnChildren || this.Parent.SetHeightBasedOnChildren)) this.Parent.SetAreaDirty(); } /// <summary> /// Updates this element's <see cref="Area"/> list if <see cref="areaDirty"/> is true. /// </summary> public void UpdateAreaIfDirty() { if (this.areaDirty) this.ForceUpdateArea(); } /// <summary> /// Forces this element's <see cref="Area"/> to be updated if it is not <see cref="IsHidden"/>. /// This method also updates all of this element's <see cref="Children"/>'s areas. /// </summary> public virtual void ForceUpdateArea() { this.areaDirty = false; if (this.IsHidden) return; var parentArea = this.Parent != null ? this.Parent.ChildPaddedArea : (RectangleF) this.system.Viewport; var parentCenterX = parentArea.X + parentArea.Width / 2; var parentCenterY = parentArea.Y + parentArea.Height / 2; var actualSize = this.CalcActualSize(parentArea); var recursion = 0; UpdateDisplayArea(actualSize); void UpdateDisplayArea(Vector2 newSize) { var pos = new Vector2(); switch (this.anchor) { case Anchor.TopLeft: case Anchor.AutoLeft: case Anchor.AutoInline: case Anchor.AutoInlineIgnoreOverflow: pos.X = parentArea.X + this.ScaledOffset.X; pos.Y = parentArea.Y + this.ScaledOffset.Y; break; case Anchor.TopCenter: case Anchor.AutoCenter: pos.X = parentCenterX - newSize.X / 2 + this.ScaledOffset.X; pos.Y = parentArea.Y + this.ScaledOffset.Y; break; case Anchor.TopRight: case Anchor.AutoRight: pos.X = parentArea.Right - newSize.X - this.ScaledOffset.X; pos.Y = parentArea.Y + this.ScaledOffset.Y; break; case Anchor.CenterLeft: pos.X = parentArea.X + this.ScaledOffset.X; pos.Y = parentCenterY - newSize.Y / 2 + this.ScaledOffset.Y; break; case Anchor.Center: pos.X = parentCenterX - newSize.X / 2 + this.ScaledOffset.X; pos.Y = parentCenterY - newSize.Y / 2 + this.ScaledOffset.Y; break; case Anchor.CenterRight: pos.X = parentArea.Right - newSize.X - this.ScaledOffset.X; pos.Y = parentCenterY - newSize.Y / 2 + this.ScaledOffset.Y; break; case Anchor.BottomLeft: pos.X = parentArea.X + this.ScaledOffset.X; pos.Y = parentArea.Bottom - newSize.Y - this.ScaledOffset.Y; break; case Anchor.BottomCenter: pos.X = parentCenterX - newSize.X / 2 + this.ScaledOffset.X; pos.Y = parentArea.Bottom - newSize.Y - this.ScaledOffset.Y; break; case Anchor.BottomRight: pos.X = parentArea.Right - newSize.X - this.ScaledOffset.X; pos.Y = parentArea.Bottom - newSize.Y - this.ScaledOffset.Y; break; } if (this.Anchor >= Anchor.AutoLeft) { Element previousChild; if (this.Anchor == Anchor.AutoInline || this.Anchor == Anchor.AutoInlineIgnoreOverflow) { previousChild = this.GetOlderSibling(e => !e.IsHidden && e.CanAutoAnchorsAttach); } else { previousChild = this.GetLowestOlderSibling(e => !e.IsHidden && e.CanAutoAnchorsAttach); } if (previousChild != null) { var prevArea = previousChild.GetAreaForAutoAnchors(); switch (this.Anchor) { case Anchor.AutoLeft: case Anchor.AutoCenter: case Anchor.AutoRight: pos.Y = prevArea.Bottom + this.ScaledOffset.Y; break; case Anchor.AutoInline: var newX = prevArea.Right + this.ScaledOffset.X; if (newX + newSize.X <= parentArea.Right) { pos.X = newX; pos.Y = prevArea.Y + this.ScaledOffset.Y; } else { pos.Y = prevArea.Bottom + this.ScaledOffset.Y; } break; case Anchor.AutoInlineIgnoreOverflow: pos.X = prevArea.Right + this.ScaledOffset.X; pos.Y = prevArea.Y + this.ScaledOffset.Y; break; } } } if (this.PreventParentSpill) { if (pos.X < parentArea.X) pos.X = parentArea.X; if (pos.Y < parentArea.Y) pos.Y = parentArea.Y; if (pos.X + newSize.X > parentArea.Right) newSize.X = parentArea.Right - pos.X; if (pos.Y + newSize.Y > parentArea.Bottom) newSize.Y = parentArea.Bottom - pos.Y; } this.area = new RectangleF(pos, newSize); this.System.InvokeOnElementAreaUpdated(this); foreach (var child in this.Children) child.ForceUpdateArea(); if (this.SetWidthBasedOnChildren || this.SetHeightBasedOnChildren) { Element foundChild = null; var autoSize = this.UnscrolledArea.Size; if (this.SetHeightBasedOnChildren) { var lowest = this.GetLowestChild(e => !e.IsHidden); if (lowest != null) { autoSize.Y = lowest.UnscrolledArea.Bottom - pos.Y + this.ScaledChildPadding.Bottom; foundChild = lowest; } else { if (this.Children.Count > 0) throw new InvalidOperationException($"{this} with root {this.Root.Name} sets its height based on children but it only has children anchored too low ({string.Join(", ", this.Children.Select(c => c.Anchor))})"); autoSize.Y = 0; } } if (this.SetWidthBasedOnChildren) { var rightmost = this.GetRightmostChild(e => !e.IsHidden); if (rightmost != null) { autoSize.X = rightmost.UnscrolledArea.Right - pos.X + this.ScaledChildPadding.Right; foundChild = rightmost; } else { if (this.Children.Count > 0) throw new InvalidOperationException($"{this} with root {this.Root.Name} sets its width based on children but it only has children anchored too far right ({string.Join(", ", this.Children.Select(c => c.Anchor))})"); autoSize.X = 0; } } if (this.TreatSizeAsMinimum) { autoSize = Vector2.Max(autoSize, actualSize); } else if (this.TreatSizeAsMaximum) { autoSize = Vector2.Min(autoSize, actualSize); } if (!autoSize.Equals(this.UnscrolledArea.Size, 0.01F)) { recursion++; if (recursion >= 16) { throw new ArithmeticException($"The area of {this} with root {this.Root.Name} has recursively updated too often. Does its child {foundChild} contain any conflicting auto-sizing settings?"); } else { UpdateDisplayArea(autoSize); } } } } } /// <summary> /// Calculates the actual size that this element should take up, based on the area that its parent encompasses. /// By default, this is based on the information specified in <see cref="Size"/>'s documentation. /// </summary> /// <param name="parentArea">This parent's area, or the ui system's viewport if it has no parent</param> /// <returns>The actual size of this element, taking <see cref="Scale"/> into account</returns> protected virtual Vector2 CalcActualSize(RectangleF parentArea) { var ret = new Vector2( this.size.X > 1 ? this.ScaledSize.X : parentArea.Width * this.size.X, this.size.Y > 1 ? this.ScaledSize.Y : parentArea.Height * this.size.Y); if (this.size.X < 0) ret.X = -this.size.X * ret.Y; if (this.size.Y < 0) ret.Y = -this.size.Y * ret.X; return ret; } /// <summary> /// Returns the area that should be used for determining where auto-anchoring children should attach. /// </summary> /// <returns>The area for auto anchors</returns> protected virtual RectangleF GetAreaForAutoAnchors() { return this.UnscrolledArea; } /// <summary> /// Returns this element's lowest child element (in terms of y position) that matches the given condition. /// </summary> /// <param name="condition">The condition to match</param> /// <returns>The lowest element, or null if no such element exists</returns> public Element GetLowestChild(Func<Element, bool> condition = null) { Element lowest = null; foreach (var child in this.Children) { if (condition != null && !condition(child)) continue; if (child.Anchor > Anchor.TopRight && child.Anchor < Anchor.AutoLeft) continue; if (lowest == null || child.UnscrolledArea.Bottom >= lowest.UnscrolledArea.Bottom) lowest = child; } return lowest; } /// <summary> /// Returns this element's rightmost child (in terms of x position) that matches the given condition. /// </summary> /// <param name="condition">The condition to match</param> /// <returns>The rightmost element, or null if no such element exists</returns> public Element GetRightmostChild(Func<Element, bool> condition = null) { Element rightmost = null; foreach (var child in this.Children) { if (condition != null && !condition(child)) continue; if (child.Anchor < Anchor.AutoLeft && child.Anchor != Anchor.TopLeft && child.Anchor != Anchor.CenterLeft && child.Anchor != Anchor.BottomLeft) continue; if (rightmost == null || child.UnscrolledArea.Right >= rightmost.UnscrolledArea.Right) rightmost = child; } return rightmost; } /// <summary> /// Returns this element's lowest sibling that is also older (lower in its parent's <see cref="Children"/> list) than this element that also matches the given condition. /// The returned element's <see cref="Parent"/> will always be equal to this element's <see cref="Parent"/>. /// </summary> /// <param name="condition">The condition to match</param> /// <returns>The lowest older sibling of this element, or null if no such element exists</returns> public Element GetLowestOlderSibling(Func<Element, bool> condition = null) { if (this.Parent == null) return null; Element lowest = null; foreach (var child in this.Parent.Children) { if (child == this) break; if (condition != null && !condition(child)) continue; if (lowest == null || child.UnscrolledArea.Bottom >= lowest.UnscrolledArea.Bottom) lowest = child; } return lowest; } /// <summary> /// Returns this element's first older sibling that matches the given condition. /// The returned element's <see cref="Parent"/> will always be equal to this element's <see cref="Parent"/>. /// </summary> /// <param name="condition">The condition to match</param> /// <returns>The older sibling, or null if no such element exists</returns> public Element GetOlderSibling(Func<Element, bool> condition = null) { if (this.Parent == null) return null; Element older = null; foreach (var child in this.Parent.Children) { if (child == this) break; if (condition != null && !condition(child)) continue; older = child; } return older; } /// <summary> /// Returns all of this element's siblings that match the given condition. /// Siblings are elements that have the same <see cref="Parent"/> as this element. /// </summary> /// <param name="condition">The condition to match</param> /// <returns>This element's siblings</returns> public IEnumerable<Element> GetSiblings(Func<Element, bool> condition = null) { if (this.Parent == null) yield break; foreach (var child in this.Parent.Children) { if (condition != null && !condition(child)) continue; if (child != this) yield return child; } } /// <summary> /// Returns all of this element's children of the given type that match the given condition. /// Optionally, the entire tree of children (grandchildren) can be searched. /// </summary> /// <param name="condition">The condition to match</param> /// <param name="regardGrandchildren">If this value is true, children of children of this element are also searched</param> /// <param name="ignoreFalseGrandchildren">If this value is true, children for which the condition does not match will not have their children searched</param> /// <typeparam name="T">The type of children to search for</typeparam> /// <returns>All children that match the condition</returns> public IEnumerable<T> GetChildren<T>(Func<T, bool> condition = null, bool regardGrandchildren = false, bool ignoreFalseGrandchildren = false) where T : Element { foreach (var child in this.Children) { var applies = child is T t && (condition == null || condition(t)); if (applies) yield return (T) child; if (regardGrandchildren && (!ignoreFalseGrandchildren || applies)) { foreach (var cc in child.GetChildren(condition, true, ignoreFalseGrandchildren)) yield return cc; } } } /// <inheritdoc cref="GetChildren{T}"/> public IEnumerable<Element> GetChildren(Func<Element, bool> condition = null, bool regardGrandchildren = false, bool ignoreFalseGrandchildren = false) { return this.GetChildren<Element>(condition, regardGrandchildren, ignoreFalseGrandchildren); } /// <summary> /// Returns the parent tree of this element. /// The parent tree is this element's <see cref="Parent"/>, followed by its parent, and so on, up until the <see cref="RootElement"/>'s <see cref="RootElement.Element"/>. /// </summary> /// <returns>This element's parent tree</returns> public IEnumerable<Element> GetParentTree() { if (this.Parent == null) yield break; yield return this.Parent; foreach (var parent in this.Parent.GetParentTree()) yield return parent; } /// <summary> /// Returns a subset of <see cref="Children"/> that are currently relevant in terms of drawing and input querying. /// A <see cref="Panel"/> only returns elements that are currently in view here. /// </summary> /// <returns>This element's relevant children</returns> protected virtual IList<Element> GetRelevantChildren() { return this.SortedChildren; } /// <summary> /// Updates this element and all of its <see cref="GetRelevantChildren"/> /// </summary> /// <param name="time">The game's time</param> public virtual void Update(GameTime time) { this.System.InvokeOnElementUpdated(this, time); foreach (var child in this.GetRelevantChildren()) if (child.System != null) child.Update(time); } /// <summary> /// Draws this element by calling <see cref="Draw"/> internally. /// If <see cref="Transform"/> or <see cref="BeginImpl"/> is set, a new <see cref="SpriteBatch.Begin"/> call is also started. /// </summary> /// <param name="time">The game's time</param> /// <param name="batch">The sprite batch to use for drawing</param> /// <param name="alpha">The alpha to draw this element and its children with</param> /// <param name="blendState">The blend state that is used for drawing</param> /// <param name="samplerState">The sampler state that is used for drawing</param> /// <param name="matrix">The transformation matrix that is used for drawing</param> public void DrawTransformed(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { var customDraw = this.BeginImpl != null || this.Transform != Matrix.Identity; var mat = this.Transform * matrix; if (customDraw) { // end the usual draw so that we can begin our own batch.End(); // begin our own draw call if (this.BeginImpl != null) { this.BeginImpl(this, time, batch, alpha, blendState, samplerState, mat); } else { batch.Begin(SpriteSortMode.Deferred, blendState, samplerState, null, null, null, mat); } } // draw content in custom begin call this.Draw(time, batch, alpha, blendState, samplerState, mat); if (customDraw) { // end our draw batch.End(); // begin the usual draw again for other elements batch.Begin(SpriteSortMode.Deferred, blendState, samplerState, null, null, null, matrix); } } /// <summary> /// Draws this element and all of its children. Override this method to draw the content of custom elements. /// Note that, when this is called, <see cref="SpriteBatch.Begin"/> has already been called with custom <see cref="Transform"/> etc. applied. /// </summary> /// <param name="time">The game's time</param> /// <param name="batch">The sprite batch to use for drawing</param> /// <param name="alpha">The alpha to draw this element and its children with</param> /// <param name="blendState">The blend state that is used for drawing</param> /// <param name="samplerState">The sampler state that is used for drawing</param> /// <param name="matrix">The transformation matrix that is used for drawing</param> public virtual void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { this.System.InvokeOnElementDrawn(this, time, batch, alpha); if (this.IsSelected) this.System.InvokeOnSelectedElementDrawn(this, time, batch, alpha); foreach (var child in this.GetRelevantChildren()) { if (!child.IsHidden) child.DrawTransformed(time, batch, alpha * child.DrawAlpha, blendState, samplerState, matrix); } } /// <summary> /// Draws this element and all of its <see cref="GetRelevantChildren"/> early. /// Drawing early involves drawing onto <see cref="RenderTarget2D"/> instances rather than onto the screen. /// Note that, when this is called, <see cref="SpriteBatch.Begin"/> has not yet been called. /// </summary> /// <param name="time">The game's time</param> /// <param name="batch">The sprite batch to use for drawing</param> /// <param name="alpha">The alpha to draw this element and its children with</param> /// <param name="blendState">The blend state that is used for drawing</param> /// <param name="samplerState">The sampler state that is used for drawing</param> /// <param name="matrix">The transformation matrix that is used for drawing</param> public virtual void DrawEarly(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) { foreach (var child in this.GetRelevantChildren()) { if (!child.IsHidden) child.DrawEarly(time, batch, alpha * child.DrawAlpha, blendState, samplerState, matrix); } } /// <summary> /// Returns the element under the given position, searching the current element and all of its <see cref="GetRelevantChildren"/>. /// </summary> /// <param name="position">The position to query</param> /// <returns>The element under the position, or null if no such element exists</returns> public virtual Element GetElementUnderPos(Vector2 position) { if (this.IsHidden) return null; if (this.Transform != Matrix.Identity) position = Vector2.Transform(position, Matrix.Invert(this.Transform)); var relevant = this.GetRelevantChildren(); for (var i = relevant.Count - 1; i >= 0; i--) { var element = relevant[i].GetElementUnderPos(position); if (element != null) return element; } return this.CanBeMoused && this.DisplayArea.Contains(position) ? this : null; } /// <inheritdoc /> public virtual void Dispose() { this.OnDisposed?.Invoke(this); GC.SuppressFinalize(this); } /// <summary> /// Performs the specified action on this element and all of its <see cref="Children"/> /// </summary> /// <param name="action">The action to perform</param> public void AndChildren(Action<Element> action) { action(this); foreach (var child in this.Children) child.AndChildren(action); } /// <summary> /// Sorts this element's <see cref="Children"/> using the given comparison. /// </summary> /// <param name="comparison">The comparison to sort by</param> public void ReorderChildren(Comparison<Element> comparison) { this.children.Sort(comparison); } /// <summary> /// Reverses this element's <see cref="Children"/> list in the given range. /// </summary> /// <param name="index">The index to start reversing at</param> /// <param name="count">The amount of elements to reverse</param> public void ReverseChildren(int index = 0, int? count = null) { this.children.Reverse(index, count ?? this.Children.Count); } /// <summary> /// Scales this element's <see cref="Transform"/> matrix based on the given scale and origin. /// </summary> /// <param name="scale">The scale to use</param> /// <param name="origin">The origin to use for scaling, or null to use this element's center point</param> public void ScaleTransform(float scale, Vector2? origin = null) { this.Transform = Matrix.CreateScale(scale, scale, 1) * Matrix.CreateTranslation(new Vector3((1 - scale) * (origin ?? this.DisplayArea.Center), 0)); } /// <summary> /// Initializes this element's <see cref="StyleProp{T}"/> instances using the ui system's <see cref="UiStyle"/>. /// </summary> /// <param name="style">The new style</param> protected virtual void InitStyle(UiStyle style) { this.SelectionIndicator.SetFromStyle(style.SelectionIndicator); this.ActionSound.SetFromStyle(style.ActionSound); this.SecondActionSound.SetFromStyle(style.ActionSound); } /// <summary> /// A delegate used for the <see cref="Element.OnTextInput"/> event. /// </summary> /// <param name="element">The current element</param> /// <param name="key">The key that was pressed</param> /// <param name="character">The character that was input</param> public delegate void TextInputCallback(Element element, Keys key, char character); /// <summary> /// A generic element-specific delegate. /// </summary> /// <param name="element">The current element</param> public delegate void GenericCallback(Element element); /// <summary> /// A generic element-specific delegate that includes a second element. /// </summary> /// <param name="thisElement">The current element</param> /// <param name="otherElement">The other element</param> public delegate void OtherElementCallback(Element thisElement, Element otherElement); /// <summary> /// A delegate used inside of <see cref="Element.Draw"/> /// </summary> /// <param name="element">The element that is being drawn</param> /// <param name="time">The game's time</param> /// <param name="batch">The sprite batch used for drawing</param> /// <param name="alpha">The alpha this element is drawn with</param> public delegate void DrawCallback(Element element, GameTime time, SpriteBatch batch, float alpha); /// <summary> /// A generic delegate used inside of <see cref="Element.Update"/> /// </summary> /// <param name="element">The current element</param> /// <param name="time">The game's time</param> public delegate void TimeCallback(Element element, GameTime time); /// <summary> /// A delegate used by <see cref="Element.GetTabNextElement"/>. /// </summary> /// <param name="backward">If this value is true, <see cref="ModifierKey.Shift"/> is being held</param> /// <param name="usualNext">The element that is considered to be the next element by default</param> public delegate Element TabNextElementCallback(bool backward, Element usualNext); /// <summary> /// A delegate used by <see cref="Element.GetGamepadNextElement"/>. /// </summary> /// <param name="dir">The direction of the gamepad button that was pressed</param> /// <param name="usualNext">The element that is considered to be the next element by default</param> public delegate Element GamepadNextElementCallback(Direction2 dir, Element usualNext); /// <summary> /// A delegate method used for <see cref="BeginImpl"/> /// </summary> /// <param name="element">The custom draw group</param> /// <param name="time">The game's time</param> /// <param name="batch">The sprite batch used for drawing</param> /// <param name="alpha">This element's draw alpha</param> /// <param name="blendState">The blend state used for drawing</param> /// <param name="samplerState">The sampler state used for drawing</param> /// <param name="matrix">The transform matrix used for drawing</param> public delegate void BeginDelegate(Element element, GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix); } }
82eb1f4cac1c57d02a07e36e7f3b85a08ba9cc52
[ "Markdown", "C#", "Python", "Lua" ]
77
C#
AtomicBlom/MLEM
bb189261d7e301da78ac3c5a78bb66aa8a50b629
fba53dccf9498cb612a0fb19e5c8443d9bc64b15
refs/heads/master
<file_sep># MSHS-Department-Volumes Processing Department Volume Data for Labor Productivity report generation <file_sep>library(dplyr) #-----------ED Hours Hours <- function(){ #aggregate ED Hour file by day to get total daily ed hours raw <- readxl::read_excel(file.choose()) Date <- as.Date(raw$`ED Arrival Time`, format = "%m/%d/%Y") raw <- cbind(raw,Date) daily <- aggregate(`ED LOS`~Date,raw,sum) daily <- daily %>% filter(Date >= as.Date(start, format = "%m/%d/%Y"), Date <= as.Date(end, format = "%m/%d/%Y")) return(daily) } Trend <- function(){ #append master file with the daily ed hour trend library(openxlsx) setwd("J:/deans/Presidents/SixSigma/MSHS Productivity/Productivity/Volume - Data/MSH Data/ED Hours/Calculation Worksheets") Master <- read.xlsx(xlsxFile = "ED Hours Daily Trend.xlsx", sheet = 1, detectDates = T) #Master$Date <- as.Date(Master$Date, origin = "1899-12-30") colnames(Master) <- c("Date","ED LOS") current <<- rbind(Master,daily) tail(current,29) } Save <- function(){ #overwrite the master file and save the daily trend for the PP setwd("J:/deans/Presidents/SixSigma/MSHS Productivity/Productivity/Volume - Data/MSH Data/ED Hours/Calculation Worksheets") library(openxlsx) write.xlsx(current, file = "ED Hours Daily Trend.xlsx", row.names = F, overwrite = T) start <- min(daily$Date) end <- max(daily$Date) library(lubridate) smonth <- month(start) smonth <- toupper(month.abb[month(start)]) emonth <- toupper(month.abb[month(end)]) sday <- format(as.Date(start, format="%Y-%m-%d"), format="%d") eday <- format(as.Date(end, format="%Y-%m-%d"), format="%d") syear <- substr(start, start=1, stop=4) eyear <- substr(end, start=1, stop=4) name <- paste0("MSH_ED Hours_",sday,smonth,syear," to ",eday,emonth,eyear,".xlsx") write.xlsx(daily, file=name, row.names=F) } #gives a daily ED hour total for the PP start <- "12/19/2021" end <- "01/15/2022" daily <- Hours() #appends the "daily" dataframe to the master Trend() #gives ED Hour sum for the PP. Input this into the upload tracker EDHours1 <- sum(daily$`ED LOS`[1:14]) EDHours2 <- sum(daily$`ED LOS`[15:28]) #If both the daily and new master (current) look good then run this to save all necessary files Save() rm(daily,current,EDHours) <file_sep>#---------Art 28 Visits #First save raw file #Create Art 28 function Art28 <- function(YYYYMM){ #Read the raw excel file from Doran raw <- readxl::read_excel(file.choose()) #assign column names colnames(raw) <- c("YearMo","Clinic Group","Clinic Group Description","Clinic Code","Attending MD","Payor Group","Encounters") #filter on the month and year raw <- raw[raw$YearMo == YYYYMM,] #Create vector for all departments recieving volumes cc <<- c(01040170,01040185,01040388,01040404,01040407,01040409,01040411, 01040426,01040436,01040435,01040438,01040441,01040447,01040458, 01040460,01040464,01040473,01040477) #Create each specific volume dataframe volume1 <- raw[raw$`Clinic Code` %in% c("HI196","HI198","RE930","RE994"),] volume2 <- raw[raw$`Clinic Code` %in% c("MH349", "MH346"),] volume3 <- raw[raw$`Clinic Code` %in% c("MH348", "MH363"),] volume4 <- raw volume5 <- raw[raw$`Clinic Code` %in% c("CL678","CL679","CL681","CL688"),] volume6 <- raw[raw$`Clinic Code` %in% c("CL647","CL651","CL652","CL653","CL654","CL657","CL660"),] volume7 <- raw[raw$`Clinic Code` %in% c("CL641","CL644","CL646","CL638"),] volume8 <- raw[raw$`Clinic Code` %in% c("GV475","GV476"),] volume9 <- raw[raw$`Clinic Code` %in% c("SB411","SB412","SB413","SB414"),] volume10 <- raw[raw$`Clinic Code` %in% c("CL101","CL103","CL106","CL270","CL271","CL642","CL191","CL197","CL155","CL194","CL193","CL265","CL280","CL160","CL107","CL297","CL294","CL435","CL201","CL202","CL206","CL208","CL205","CL203","CL140","CL147","CL285","CL212","CL213","PD230","PD240"),] volume11 <- raw[raw$`Clinic Code` %in% c("AH379","AH401","DE125","AH402","AH549"),] volume12 <- raw[raw$`Clinic Code` %in% c("CL194"),] volume13 <- raw[raw$`Clinic Code` %in% c("HE307","HE309"),] volume14 <- raw[raw$`Clinic Code` %in% c("DI622"),] volume15 <- raw[raw$`Clinic Code` %in% c("CV260"),] volume16 <- raw[raw$`Clinic Code` %in% c("CL188"),] volume17 <- raw[raw$`Clinic Code` %in% c("MH330"),] volume18 <- raw[raw$`Clinic Code` %in% c("ER494"),] #create a vecotr of each departments volume vol <- c(sum(volume1$Encounters),sum(volume2$Encounters),sum(volume3$Encounters), sum(volume4$Encounters),sum(volume5$Encounters),sum(volume6$Encounters), sum(volume7$Encounters),sum(volume8$Encounters),sum(volume9$Encounters), sum(volume10$Encounters),sum(volume11$Encounters),sum(volume12$Encounters), sum(volume13$Encounters),sum(volume14$Encounters),sum(volume15$Encounters), sum(volume16$Encounters),sum(volume17$Encounters),sum(volume18$Encounters)) #output each department with its associated volume volume <<- cbind(cc,vol) colnames(volume) <- c("cc",YYYYMM) setwd("J:/deans/Presidents/SixSigma/MSHS Productivity/Productivity/Volume - Data/MSH Data/Art 28 Visits/Calculation Worksheet") #Read Master Art28 file master <- read.csv("Art28_Master.csv",check.names=F) #append master file and save it back master <<- merge(master,volume,by="cc") write.csv(master,"Art28_Master.csv",row.names=F) } #enter year and month in YYYYMM format #for example 201802 would represent February 2018 Art28("202201") <file_sep>#--------RETU Observation Days #Sums the # of observation days by year and month RETUdays <- function(start, pp1, pp2, pp3 = "1/1/2050"){ #select most recent raw RETU Visits file RETU <- readxl::read_excel(file.choose()) #use difftime function to calculate the number of days between two POSIXct timestamps RETU <- cbind(RETU,difftime(RETU$`RETU DISCHARGE TIME`, RETU$`RETU ROOMED (ARRIVAL) TIME`, units = "days")) colnames(RETU)[16] <- "DAYS" #Convert data parameters to correct format start <- as.POSIXct(as.character(start), format = "%m/%d/%Y") pp1 <- as.POSIXct(as.character(pp1), format = "%m/%d/%Y") pp2 <- as.POSIXct(as.character(pp2), format = "%m/%d/%Y") pp3 <- as.POSIXct(as.character(pp3), format = "%m/%d/%Y") #Filter RETU file for both pay perids RETU1 <- RETU[RETU$`RETU ROOMED (ARRIVAL) TIME`>=start & RETU$`RETU ROOMED (ARRIVAL) TIME`<=pp1,] RETU2 <- RETU[RETU$`RETU ROOMED (ARRIVAL) TIME`>pp1 & RETU$`RETU ROOMED (ARRIVAL) TIME`<=pp2,] RETU3 <- RETU[RETU$`RETU ROOMED (ARRIVAL) TIME`>pp2 & RETU$`RETU ROOMED (ARRIVAL) TIME`<=pp3,] #Get patient days for both pay periods pp1days <<- sum(RETU1$DAYS) pp2days <<- sum(RETU2$DAYS) pp3days <<- sum(RETU3$DAYS) } #start is the first day of the first pp. pp1 is end date of first pp. pp2 is end date of second pp RETUdays(start="11/21/2021", pp1="12/4/2021", pp2="12/18/2021", pp3 = "01/01/2022") #Outputs pateint day totals for pp1 and pp2 pp1days pp2days pp3days
1be49d31e89e709c3c555e3dca6fc6f39c3ffe2b
[ "Markdown", "R" ]
4
Markdown
MSHS-OAO/MSHS-Department-Volumes
1e43b9ac22d00a712685900443901cb1bc9f5514
4c902860f183ba1e771ae3ba21d1ec97358510e7
refs/heads/master
<file_sep>package com.zamkovenko.time4child; import android.Manifest; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import com.zamkovenko.time4child.activity.EnterParentPhoneActivity; import com.zamkovenko.time4child.utils.SmsUtils; import com.zamkovenko.utils.model.Message; import com.zamkovenko.utils.model.serializer.MessageSerializer; import com.zamkovenko.utils.model.serializer.SmsMessageSerializer; /** * User: <NAME> * Date: 09.01.2018 */ public class SendMessageTask extends AsyncTask<Message, Void, Void> { private Context m_context; public SendMessageTask(Context context) { this.m_context = context; } @Override protected Void doInBackground(Message... messages) { Message message = messages[0]; Log.d(SendMessageTask.class.getSimpleName(), "Start to send message: " + message); MessageSerializer<String> messageSerializer = new SmsMessageSerializer(); // SocketClientManager.getInstance().sendMessage(messageSerializer.serialize(message)); if (ContextCompat.checkSelfPermission(m_context, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { Log.d(SendMessageTask.class.getSimpleName(),"Need SEND_SMS permission"); return null; } else{ Log.d(SendMessageTask.class.getSimpleName(),"SEND_SMS permission is OK"); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(m_context); String parentPhone = prefs.getString(EnterParentPhoneActivity.PARAM_PARENT_PHONE, ""); SmsUtils.sendSMS(parentPhone, messageSerializer.serialize(message), m_context); return null; } } <file_sep>include ':time4parent', ':time4child', ':utils' <file_sep>package com.zamkovenko.time4child.utils; import android.app.PendingIntent; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.telephony.SmsManager; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.util.Log; import android.widget.Toast; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; /** * User: <NAME> * Date: 15.05.2018 */ public class SmsUtils { private static final String PARAM_SIM_CARD = "sim_card"; public static void sendSMS(String phoneNo, String msg, Context context) { try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int simId = prefs.getInt(SmsUtils.PARAM_SIM_CARD, -1); if (simId != -1) { sendSMS(context, simId, phoneNo, null, msg, null, null); } else { Log.d("SmsUtils", "simId != -1"); } } catch (Exception ex) { ex.printStackTrace(); } } private static boolean sendSMS(final Context ctx, int simID, String toNum, String centerNum, String smsText, PendingIntent sentIntent, PendingIntent deliveryIntent) { Log.d("sendSMS", "try to send sms from simID " + simID); try { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { SubscriptionManager subscriptionManager = SubscriptionManager.from(ctx); List<SubscriptionInfo> subscriptionInfoList = subscriptionManager.getActiveSubscriptionInfoList(); for (SubscriptionInfo subscriptionInfo : subscriptionInfoList) { int subscriptionId = subscriptionInfo.getSubscriptionId(); int simSlotIndex = subscriptionInfo.getSimSlotIndex(); Log.d("apipas", "subscriptionId:" + subscriptionId + ", simSlotIndex: " + simSlotIndex); if (simID == simSlotIndex) { SmsManager.getSmsManagerForSubscriptionId(subscriptionId).sendTextMessage(toNum, centerNum, smsText,sentIntent, deliveryIntent); System.out.println("sms is OK"); } } } else { String name; if (simID == 0) { name = "isms"; // for model : "Philips T939" name = "isms0" } else if (simID == 1) { name = "isms2"; } else { throw new Exception("can not get service which for sim '" + simID + "', only 0,1 accepted as values"); } Log.d("sendSMS", "name: " + name); Method method = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String.class); method.setAccessible(true); Object param = method.invoke(null, name); method = Class.forName("com.android.internal.telephony.ISms$Stub").getDeclaredMethod("asInterface", IBinder.class); method.setAccessible(true); Object stubObj = method.invoke(null, param); if (Build.VERSION.SDK_INT < 18) { method = stubObj.getClass().getMethod("sendText", String.class, String.class, String.class, PendingIntent.class, PendingIntent.class); method.invoke(stubObj, toNum, centerNum, smsText, sentIntent, deliveryIntent); } else { method = stubObj.getClass().getMethod("sendText", String.class, String.class, String.class, String.class, PendingIntent.class, PendingIntent.class); method.invoke(stubObj, ctx.getPackageName(), toNum, centerNum, smsText, sentIntent, deliveryIntent); } System.out.println("sms is OK"); return true; } } catch (ClassNotFoundException e) { Log.e("apipas", "ClassNotFoundException:" + e.getMessage()); } catch (NoSuchMethodException e) { Log.e("apipas", "NoSuchMethodException:" + e.getMessage()); } catch (InvocationTargetException e) { Log.e("apipas", "InvocationTargetException:" + e.getMessage()); } catch (IllegalAccessException e) { Log.e("apipas", "IllegalAccessException:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(System.out); } return false; } } <file_sep>package com.zamkovenko.utils; /** * User: <NAME> * Date: 11.02.2018 */ public interface OnMessageRefreshListener { void OnRefresh(); } <file_sep>package com.zamkovenko.time4parent.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.SmsMessage; import com.zamkovenko.time4parent.activity.EnterParentPhoneActivity; import com.zamkovenko.time4parent.service.SmsProcessorService; import com.zamkovenko.utils.ParseUtils; /** * User: <NAME> * Date: 10.12.2017 */ public class SmsReceiver extends BroadcastReceiver { private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; private Context context; @Override public void onReceive(Context context, Intent intent) { this.context = context; if (intent.getAction().equals(SMS_RECEIVED)) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); if (pdus.length == 0) { return; } SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } dispatchMessage(messages); } } } private void dispatchMessage(SmsMessage[] messages) { String from = ParseUtils.GetClearNumer(messages[0].getDisplayOriginatingAddress()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String parentPhone = prefs.getString(EnterParentPhoneActivity.PARAM_PARENT_PHONE, ""); boolean isOk = from.contains(parentPhone); if (isOk) { StringBuilder bodyText = new StringBuilder(); for (SmsMessage message : messages) { bodyText.append(message.getMessageBody()); } String body = bodyText.toString(); Intent smsServiceIntent = new Intent(context, SmsProcessorService.class); smsServiceIntent.putExtra(SmsProcessorService.PARAM_FROM, from); smsServiceIntent.putExtra(SmsProcessorService.PARAM_BODY, body); context.startService(smsServiceIntent); abortBroadcast(); } } } <file_sep>package com.zamkovenko.time4parent.activity; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.zamkovenko.time4parent.R; import com.zamkovenko.time4parent.Utils.NetworkUtils; /** * User: <NAME> * Date: 31.12.2017 */ public class CheckIpActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_ip); TextView ip = (TextView) findViewById(R.id.txt_ip); Button ok = (Button) findViewById(R.id.btn_ok); if(Build.VERSION.SDK_INT < 21){ ok.setBackgroundResource(R.drawable.btn_style); }else { ok.setBackgroundResource(R.drawable.btn_ripple); } ip.setText(NetworkUtils.getIPAddress(true)); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } } <file_sep>package com.zamkovenko.utils.model; /** * Author: <NAME> * Date: 09.01.2018 */ public enum MessageState { NOT_DONE, DONE } <file_sep>package com.zamkovenko.time4parent.activity; import android.Manifest; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import com.zamkovenko.utils.model.Message; import com.zamkovenko.time4parent.R; import com.zamkovenko.time4parent.fragment.DatePickerFragment; import com.zamkovenko.time4parent.fragment.TimePickerFragment; import com.zamkovenko.time4parent.manager.MessageManager; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; /** * User: <NAME> * Date: 10.12.2017 */ public class TaskEditActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener{ private static final int PERMISSION_SEND_SMS = 123; private static final int PERMISSION_READ_PHONE_STATE = 1234; private short m_id = -1; public static String PARAM_TASK_ID = "_id"; private static Calendar calendar; private Switch m_switchIsBlink; private Switch m_switchIsVibration; private TextView txtCurrentTime; private TextView txtCurrentDate; private TextView txtTitle; private Locale locale; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_edit); locale = new Locale("uk","UA"); calendar = new GregorianCalendar(locale); calendar.setTime(Calendar.getInstance(locale).getTime()); m_switchIsBlink = findViewById(R.id.switch_blinking); m_switchIsVibration = findViewById(R.id.switch_vibration); Button btnSetDate = findViewById(R.id.btn_setDate); Button btnSetTime = findViewById(R.id.btn_setTime); Button btnAccept = findViewById(R.id.btn_accept); if(Build.VERSION.SDK_INT < 21){ btnAccept.setBackgroundResource(R.drawable.btn_style); }else { btnAccept.setBackgroundResource(R.drawable.btn_ripple); } txtTitle = findViewById(R.id.txt_title); txtCurrentTime = findViewById(R.id.txt_currentTime); txtCurrentDate = findViewById(R.id.txt_currentDate); btnSetDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Locale.setDefault(new Locale("uk","UA")); DatePickerFragment newFragment = new DatePickerFragment(); newFragment.setListener(TaskEditActivity.this); newFragment.show(getSupportFragmentManager(), "datePicker"); } }); btnSetTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TimePickerFragment newFragment = new TimePickerFragment(); newFragment.setListener(TaskEditActivity.this); newFragment.show(getSupportFragmentManager(), "timePicker"); } }); btnAccept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!CheckPermissionSendSms()) { ActivityCompat.requestPermissions(TaskEditActivity.this, new String[]{Manifest.permission.SEND_SMS}, PERMISSION_SEND_SMS); } else if (!CheckPermissionGrantedReadPhoneState()) { ActivityCompat.requestPermissions(TaskEditActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_PHONE_STATE); } else { SendSms(); } } }); CheckForEdit(); OnCalendarChanged(); } private boolean CheckPermissionSendSms() { return ContextCompat.checkSelfPermission(TaskEditActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED; } private boolean CheckPermissionGrantedReadPhoneState() { return ContextCompat.checkSelfPermission(TaskEditActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED; } private void CheckForEdit(){ final short id = getIntent().getShortExtra(PARAM_TASK_ID, (short) -1); if (id != -1) { List<Message> all = MessageManager.getInstance().GetAll(); for (Message message : all) { if(message.getId() == id){ SetMessageForEdit(message); m_id = id; } } } } private void SetMessageForEdit(Message message) { txtTitle.setText(message.getTitle()); calendar.setTime(message.getOnDate()); m_switchIsBlink.setChecked(message.isBlinking()); m_switchIsVibration.setChecked(message.isVibro()); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); OnCalendarChanged(); } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); OnCalendarChanged(); } public void OnCalendarChanged() { calendar.set(Calendar.SECOND, 0); SimpleDateFormat formatDate = new SimpleDateFormat("MMM d, yyyy", locale); SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm"); txtCurrentDate.setText(formatDate.format(calendar.getTime())); txtCurrentTime.setText(formatTime.format(calendar.getTime())); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSION_SEND_SMS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && CheckPermissionGrantedReadPhoneState()) { SendSms(); } } case PERMISSION_READ_PHONE_STATE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && CheckPermissionSendSms()) { SendSms(); } } } } private void SendSms(){ Message newMessage = new Message() .getBuilder() .setId(m_id) .setTitle(txtTitle.getText().toString()) .setIsBlinking(m_switchIsBlink.isChecked()) .setIsVibro(m_switchIsVibration.isChecked()) .setOnDate(calendar.getTime()).build(); MessageManager messageManager = MessageManager.getInstance(); if (m_id != -1) { messageManager.updateMessage(newMessage); } else { messageManager.addMessage(newMessage); } onBackPressed(); } } <file_sep>package com.zamkovenko.utils.model.serializer; import com.zamkovenko.utils.model.Message; import com.zamkovenko.utils.model.MessageState; import java.util.Date; /** * Author: <NAME> * Date: 26.11.2017 */ public class SmsMessageSerializer implements MessageSerializer<String> { @Override public String serialize(Message message) { StringBuilder stringMessage = new StringBuilder(); long time; if (message.getOnDate() != null) { time = message.getOnDate().getTime(); } else { time = 0; } stringMessage.append(time); stringMessage.append("."); stringMessage.append(message.getVolume()); stringMessage.append("."); stringMessage.append(message.getDuration()); stringMessage.append("."); stringMessage.append(message.getRepeatingDelay()); stringMessage.append("."); stringMessage.append(message.getId()); stringMessage.append("."); stringMessage.append(message.isVibro() ? 1 : 0); stringMessage.append("."); stringMessage.append(message.isBlinking() ? 1 : 0); stringMessage.append("."); stringMessage.append(message.getMessageState() == MessageState.DONE ? 1 : 0); stringMessage.append("."); stringMessage.append(message.getTitle()); stringMessage.append("."); return stringMessage.toString(); } @Override public Message deserizlize(String stringMessage) { String[] parts = stringMessage.split("\\."); assert (parts.length > INDICES.COUNT); return new Message().getBuilder() .setOnDate(new Date(Long.valueOf(parts[INDICES.DATE]))) .setDuration(Short.valueOf(parts[INDICES.DURATION])) .setVolume(Short.valueOf(parts[INDICES.VOLUME])) .setRepeatingDelay(Short.valueOf(parts[INDICES.REPEATING_DELAY])) .setId(Short.valueOf(parts[INDICES.ID])) .setIsVibro(parts[INDICES.IS_VIBRO].equals("1")) .setIsBlinking(parts[INDICES.IS_BLINKING].equals("1")) .setMessageState(parts[INDICES.IS_DONE].equals("1") ? MessageState.DONE : MessageState.NOT_DONE) .setTitle(String.valueOf(parts[INDICES.TITLE])) .build(); } } interface INDICES { int DATE = 0; int VOLUME = DATE + 1; int DURATION = VOLUME + 1; int REPEATING_DELAY = DURATION + 1; int ID = REPEATING_DELAY + 1; int IS_VIBRO = ID + 1; int IS_BLINKING = IS_VIBRO + 1; int IS_DONE = IS_BLINKING + 1; int TITLE = IS_DONE + 1; int COUNT = IS_BLINKING + 1; }<file_sep>package com.zamkovenko.time4child.manager; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.zamkovenko.time4child.receiver.ClientMessageReceiver; import com.zamkovenko.time4child.activity.EnterParentIpActivity; import com.zamkovenko.utils.Connection; import com.zamkovenko.utils.Constants; import java.io.IOException; import java.net.Socket; /** * User: <NAME> * Date: 18.12.2017 */ public class SocketClientManager implements Runnable { @SuppressLint("StaticFieldLeak") private static SocketClientManager instance; public static SocketClientManager getInstance() { return instance; } private Context context; private Connection connection; public SocketClientManager(Context context) { this.context = context; instance = this; } public void sendMessage(String message) { if (connection != null) { connection.sendMessage(message); } } @Override public void run() { try { while (true) { if (connection != null) { continue; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String ip = prefs.getString(EnterParentIpActivity.PARAM_PARENT_IP, ""); String tempUrl = "10.0.2.2"; // tempUrl = Constants.LOCALHOST; // tempUrl = "localhost"; // String url = ip.equals("") ? tempUrl : ip; Log.d(getClass().getSimpleName(),("url: " + tempUrl + ":" + Constants.SERVER_PORT)); Socket socket = new Socket(tempUrl, 5554); Log.d(getClass().getSimpleName(), ("socket accept")); connection = new Connection(socket); connection.setRecievedListener(new ClientMessageReceiver(context)); } } catch (IOException e) { context.startActivity(new Intent(context, EnterParentIpActivity.class)); if (connection != null) { connection.clear(); } } } } <file_sep>package com.zamkovenko.time4child.receiver; import android.content.Context; import android.content.Intent; import com.zamkovenko.time4child.service.SmsProcessorService; import com.zamkovenko.utils.Constants; import com.zamkovenko.utils.MessageReceiver; /** * User: <NAME> * Date: 31.12.2017 */ public class ClientMessageReceiver extends MessageReceiver { private Context context; public ClientMessageReceiver(Context context) { this.context = context; } @Override public void processMessage(String message) { Intent smsServiceIntent = new Intent(context, SmsProcessorService.class); smsServiceIntent.putExtra(SmsProcessorService.PARAM_FROM, Constants.DEFAULT_PHONE_NUMBER); smsServiceIntent.putExtra(SmsProcessorService.PARAM_BODY, message); context.startService(smsServiceIntent); } } <file_sep>package com.zamkovenko.utils; import com.zamkovenko.utils.model.Message; /** * User: <NAME> * Date: 17.12.2017 */ public interface MessageSender { void sendMessage(Message message); } <file_sep>package com.zamkovenko.time4child.activity; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.Telephony; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Window; import com.zamkovenko.time4child.R; import com.zamkovenko.time4child.receiver.NotificationReceiver; import com.zamkovenko.time4child.utils.SimUtils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; public class MainActivity extends AppCompatActivity { private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SetupLog(); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); RequestPermission(); receiver = new NotificationReceiver(); registerReceiver(receiver, new IntentFilter(NotificationReceiver.ACTION)); CheckForSimSettings(); CheckForParentNumber(); finish(); } private void CheckForSimSettings() { if (!SimUtils.IsSimChosen(this)) { Intent chooseSimIntent = new Intent(getApplicationContext(), ChooseSimCardActivity.class); startActivity(chooseSimIntent); } } private void CheckForParentNumber() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String parentPhone = prefs.getString(EnterParentPhoneActivity.PARAM_PARENT_PHONE, ""); if (parentPhone.equals("")) { Intent parentPhoneIntent = new Intent(this, EnterParentPhoneActivity.class); startActivity(parentPhoneIntent); } } private void RequestPermission() { // Request the permission immediately here for the first time run if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{ Manifest.permission_group.SMS, Manifest.permission_group.STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.SEND_SMS, Manifest.permission.BROADCAST_SMS, Manifest.permission.RECEIVE_SMS, }, 0); } } private void SetupLog() { if ( isExternalStorageWritable() ) { File logFile = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { logFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + String.valueOf(new Date(System.currentTimeMillis())).replace(" ", "_") + "_log.txt"); } Log.d(getClass().getSimpleName(),("LOGGING: " + logFile)); // clear the previous logcat and then write the new one to the file try { Runtime.getRuntime().exec( "logcat -c"); Runtime.getRuntime().exec( "logcat -f " + logFile); } catch ( IOException e ) { e.printStackTrace(); } } } public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if ( Environment.MEDIA_MOUNTED.equals( state ) ) { return true; } return false; } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } private void SetupSmsReceiver(){ final String myPackageName = getPackageName(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) { Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName); startActivity(intent); } } } } <file_sep>package com.zamkovenko.utils; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class Connection { private OnMessageRecievedListener recievedListener; private DataInputStream in; private DataOutputStream out; private Socket socket; public Connection(Socket socket) { this.socket = socket; try { in = new DataInputStream(this.socket.getInputStream()); out = new DataOutputStream(this.socket.getOutputStream()); new Thread(new ListeningRunnable()).start(); } catch (IOException e) { e.printStackTrace(); } } public void sendMessage(String message) { new Thread(new SenderRunnable(message)).start(); } public void clear() { try { in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } public void setRecievedListener(OnMessageRecievedListener recievedListener) { this.recievedListener = recievedListener; } class ListeningRunnable implements Runnable { @Override public void run() { try { while (true) { String line = in.readUTF(); recievedListener.OnMessageReceive(line); } } catch (IOException e) { e.printStackTrace(); } } } class SenderRunnable implements Runnable { private String message; SenderRunnable(String message) { this.message = message; } @Override public void run() { try { out.writeUTF(message); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
6a91609fef48366da16c636a21b76ad8c411702e
[ "Java", "Gradle" ]
14
Java
YuliyaSubbotovskaya/app
3a738abbfcf7dbf93fe9a6dc42d843d4ed301b6c
243db0e787af2904d13a68b06bbe5d16317b334d
refs/heads/master
<file_sep><img alt="React Native Map Card View" src="assets/logo.png" width="1050"/> [![Battle Tested ✅](https://img.shields.io/badge/-Battle--Tested%20%E2%9C%85-03666e?style=for-the-badge)](https://github.com/Paraboly/react-native-map-card-view) [![Map based list card view for React Native via Paraboly.](https://img.shields.io/badge/-Map%20based%20list%20card%20view%20for%20React%20Native%20via%20Paraboly.-lightgrey?style=for-the-badge)](https://github.com/Paraboly/react-native-map-card-view) [![npm version](https://img.shields.io/npm/v/@paraboly/react-native-map-card-view.svg?style=for-the-badge)](https://www.npmjs.com/package/@paraboly/react-native-map-card-view) [![npm](https://img.shields.io/npm/dt/@paraboly/react-native-map-card-view.svg?style=for-the-badge)](https://www.npmjs.com/package/react-native-map-card-view) ![Platform - Android and iOS](https://img.shields.io/badge/platform-Android%20%7C%20iOS-blue.svg?style=for-the-badge) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](https://opensource.org/licenses/MIT) [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg?style=for-the-badge)](https://github.com/prettier/prettier) <p align="center"> <img alt="React Native Map Card View" src="assets/Screenshots/example.png" width="49%" /> <img alt="React Native Map Card View" src="assets/Screenshots/example2.png" width="49%" /> </p> # Installation Add the dependency: ```ruby npm i @paraboly/react-native-map-card-view ``` ## Peer Dependencies ###### IMPORTANT! You need install them ```js "react": ">= 16.x.x", "react-native": ">= 0.55.x", "react-native-maps": ">= 0.26.1", "react-native-androw": ">= 0.0.34", "react-native-user-avatar": ">= 1.0.4", "@freakycoder/react-native-helpers": "^0.1.0" ``` # Usage ## Import ```jsx import MapCardView from "@paraboly/react-native-map-card-view"; ``` ## Usage (IMPORTANT! READ IT BEFORE USE) To fill the list data. You **HAVE TO** use this format: **Updated:** "source" is optional now :) ```json [ { "name": "<NAME>", "source": "https://images.unsplash.com/photo-1566807810030-3eaa60f3e670?ixlib=rb-1.2.1&auto=format&fit=crop&w=3334&q=80" }, { "name": "<NAME>", "source": "https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3000&q=80" } ] ``` ```jsx <MapCardView data={data} title="Testimonial" colors={["red", "black", "gray"]} /> ``` # Configuration - Props | Property | Type | Default | Description | | ---------------- | :------------: | :-----------------------: | --------------------------------------------------------------------------------- | | width | number, string | ScreenWidth \* 0.9 | change the width of the card view | | height | number, string | 150 | change the height of the card view | | title | string | Testimonial | change the title | | data | array | dummyData(check the code) | set your own data array however you **HAVE TO** fill the array with above format! | | markers | <Marker> | default marker | set your own Marker JSX Object | | styles | style | default | change the container's style | | mapStyle | style | default | change the map's style | | titleStyle | style | default | change the title's style | | shadowStyle | style | default | change the shadow's style | | shadowColor | string | #ccc | change the shadow color | | borderColor | string | #f54242 | change the border color | | backgroundColor | string | #fff | change the background color | | borderLeftWidth | number | 5 | change the left sided border width | | markerLat | number | 37.78825 | change the default marker latitude | | markerLng | number | -122.4324 | change the default marker longitude | | mapInitialRegion | lat,lng | INITIAL_REGION | change the map initial region | | colors | array | colors | change the background color of text avatar | | size | string | "30" | change the size of avatar(image)'s size | | listHeight | number, string | 85 | change list height dynamically | ## Future Plans - [x] ~~LICENSE~~ ## Author FreakyCoder, <EMAIL> | <EMAIL> ## License React Native Map Card View is available under the MIT license. See the LICENSE file for more info. <file_sep>export default { container: { flexDirection: "row", alignItems: "center", justifyContent: "flex-start" }, imageStyle: { width: 30, height: 30 }, textStyle: { marginLeft: 8, color: "#757575" } }; <file_sep>import React from "react"; import PropTypes from "prop-types"; import { Text, View, Image } from "react-native"; import styles from "./ListItem.style"; import UserAvatar from "react-native-user-avatar"; const ListItem = props => { const { name, source, size, colors, imageStyle, textStyle } = props; return ( <View style={styles.container}> <UserAvatar size={size} name={name} src={source} colors={colors} style={imageStyle || styles.imageStyle} /> <Text numberOfLines={1} style={textStyle || styles.textStyle}> {name} </Text> </View> ); }; ListItem.propTypes = { size: PropTypes.string, colors: PropTypes.array }; ListItem.defaultProps = { size: "30", colors: ["#b888a0", "#ccc", "#e36259", "#ccaabb", "#b888a0"] }; export default ListItem; <file_sep>import React from "react"; import PropTypes from "prop-types"; import { Text, View, FlatList, Dimensions } from "react-native"; import Androw from "react-native-androw"; import MapView, { Marker } from "react-native-maps"; import ListItem from "./components/ListItem/ListItem"; import _styles, { _shadowStyle, _container, _listStyle } from "./MapCardView.style"; const { width: ScreenWidth, height: ScreenHeight } = Dimensions.get("window"); const ASPECT_RATIO = ScreenWidth / ScreenHeight; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const INITIAL_REGION = { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA }; const MapCardView = props => { const { data, width, title, height, styles, markers, mapStyle, markerLat, markerLng, titleStyle, listHeight, borderColor, shadowStyle, shadowColor, borderLeftWidth, backgroundColor, mapInitialRegion } = props; renderListItem = (list, index) => { const { item } = list; return ( <View key={index} style={{ marginTop: 3 }}> <ListItem name={item.name} source={item.source} {...props} /> </View> ); }; return ( <Androw style={shadowStyle || _shadowStyle(shadowColor)}> <View style={ styles || _container( height, width, borderColor, borderLeftWidth, backgroundColor ) } > <Androw style={_styles.mapContainer}> <MapView liteMode initialRegion={mapInitialRegion} style={mapStyle || _styles.mapStyle} > {markers || ( <Marker coordinate={{ latitude: markerLat, longitude: markerLng }} /> )} </MapView> </Androw> <View style={_styles.listContainer}> <Text style={titleStyle || _styles.titleStyle}>{title}</Text> <View style={_styles.listContainerGlue}> <FlatList style={_listStyle(listHeight)} renderItem={renderListItem} keyExtractor={(item, index) => item.name} data={data && data.length > 0 && data} /> </View> </View> </View> </Androw> ); }; MapCardView.propTypes = { title: PropTypes.string, shadowColor: PropTypes.string, borderColor: PropTypes.string, borderLeftWidth: PropTypes.number, backgroundColor: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }; MapCardView.defaultProps = { height: 150, listHeight: 85, shadowColor: "#ccc", borderLeftWidth: 5, markerLat: LATITUDE, markerLng: LONGITUDE, title: "Testimonial", borderColor: "#f54242", backgroundColor: "#fff", width: ScreenWidth * 0.9, mapInitialRegion: INITIAL_REGION }; export default MapCardView;
8fe67b7ebcf23e628329dd02d3a87eeab17bb07e
[ "Markdown", "JavaScript" ]
4
Markdown
Paraboly/react-native-map-card-view
7bd955bb71ebd4cc5099b292c67bb43b869769b9
f2d007942a8b7cbb7bfefe865667fbbd5137d426
refs/heads/master
<file_sep>platform :ios, '7.0' pod 'Dropbox-Sync-API-SDK', '~> 3.1.2' pod 'UIAlertView+Blocks', '~> 0.8.1' pod 'libextobjc/EXTScope', '~> 0.4.1' pod 'CocoaSecurity', '~> 1.2.2' pod 'SWTableViewCell', '~> 0.3.7' pod 'NYXImagesKit', '~> 2.3' pod 'Appirater', '~> 2.0.4' pod 'CrashlyticsFramework', '~> 2.2.5.2' pod 'MBProgressHUD', '~> 0.8' <file_sep>Idea Zone ========= Idea Zone is an iPhone application that lets you jot down notes and have them immediately synced to Dropbox. App URL: https://itunes.apple.com/us/app/idea-zone/id795927539 Open Source ----------- I've scrubbed the credentials from "AIBConstants.cpp" - you'll have to create your own Dropbox app and plop them in. This project also uses Cocoapods for dependency management. Use `pod install` to install everything required. License ------- Copyright 2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
765cc309aab2d6d413ab0ad90b2a7a0d5d053ae3
[ "Markdown", "Ruby" ]
2
Ruby
turtlesoupy/Idea-Zone
2e04a3d32eb16cfc1e5f2d3af4f5bcf2b87a1950
edef25eab44ec0eaea39b486e756388cf7141f0d
refs/heads/master
<file_sep><?php require 'configuration.php'; require 'personne.php'; require 'formulaire.php'; if (!($_SESSION)) { echo "<script>window.location.href = 'devoir (2).php';</script>"; } ?> <!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="UTF-8" /> <title>Login and Registration Form with HTML5 and CSS3</title> <link rel="stylesheet" href="https://bootswatch.com/5/solar/bootstrap.min.css"> </head> <body> <div class="col-md-4 mx-auto p-5"> <div class="card text-white bg-success mb-6" style="max-width: 20rem;"> <div class="card-header">Connection reussit</div> <div class="card-body"> <h4 class="card-title">Bienvenue </h4> <p class="card-text"><?= $_SESSION['username'] ?> <?= $_SESSION['email'] ?> </p> </div> <a href="Acceuil.php" class="btn btn-info" role="button" aria-pressed="true">All User</a> <a href="Deconnexion.php" class="btn btn-secondary" role="button" aria-pressed="true">Deconnexion</a> </div> </div> </body> </html><file_sep><?php require 'configuration.php'; require 'personne.php'; require 'formulaire.php'; if (isset($_POST['inscription'])) { if (!empty($_POST['nom']) && !empty($_POST['prenom']) && !empty($_POST['password']) && !empty($_POST['adress'])) { $obj = new db; $personne = new Personne($_POST['prenom'], $_POST['nom'], $_POST['bday'], $_POST['adress'], $_POST['mail'], $_POST['flexRadioDefault'], $_POST['password']); $obj->connect(); var_dump($obj->controleMail($_POST['mail'])); if ($obj->controlAge() != true) { echo "<script>alert('Interdit au moins de 18 ans ');</script>"; echo "<script>window.location.href = 'devoir (2).php';</script>"; } elseif ($obj->controleMail($_POST['mail']) != true) { echo "<script>alert('cette email est deja dans notre base de donnée');</script>"; echo "<script>window.location.href ='devoir (2).php';</script>"; } else $obj->addPerson($personne); echo "<script>alert('records added successfully');</script>"; echo "<script>window.location.href = 'devoir (2).php';</script>"; } } if (isset($_POST['connexion'])) { $obj = new db(); $obj->connect(); $emailid = $_POST['username']; $password = $_POST['<PASSWORD>']; $user = $obj->login($emailid, $password); if ($user) // Registration Success header("location:home.php"); else // Registration Failed echo "<script>alert('Emailid / Password Not Match')</script>"; echo "<script>window.location.href = 'devoir (2).php';</script>"; } if (isset($_GET['idD']) && !empty($_GET['idD'])) { $obj = new db(); $obj->connect(); $deleteId = $_GET['idD']; $obj->deletePerson($deleteId); } if (isset($_GET['idM']) && !empty($_GET['idM'])) { $name = $_POST['nom']; $firstName = $_POST['prenom']; $mail = $_POST['mail']; $password = $_POST['password']; $bday = $_POST['bday']; $adresse = $_POST['adress']; $obj = new db(); $obj->connect(); $ModifId = $_GET['idM']; $obj->upgrade($ModifId, $name, $firstName, $bday, $password, $mail, $adresse); } if (isset($_POST['modifier'])) { echo "<script>alert('mangui ci biir mais dess na na ')</script>"; if (isset($_GET['idM']) && !empty($_GET['idM'])) { echo "<script>alert('mangui ci biir')</script>"; $ModifId = $_GET['idM']; $name = $_POST['nom']; $firstName = $_POST['prenom']; $mail = $_POST['mail']; $password = $_POST['<PASSWORD>']; $bday = $_POST['bday']; $adresse = $_POST['adress']; $obj = new db(); $obj->connect(); $obj->upgrade($ModifId, $name, $firstName, $bday, $password, $mail, $adresse); } } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <link href="joua3.css" rel="stylesheet"> <title>Membre</title> </head> <?php require 'configuration.php'; require 'formulaire.php'; require 'personne.php'; $mysqli = new mysqli('localhost', 'root', '', 'evaluation'); $mysqli->set_charset("utf8"); $requete = 'SELECT * FROM user'; $resultat = $mysqli->query($requete); $obj = new db(); $obj->connect(); if (isset($_GET['idL']) && !empty($_GET['idL'])) { $detail = $_GET['idL']; $detaili = $obj->detail($detail); ?> <table class="table table-success table-striped"> <thead> <tr> <th> id </th> <th> Prenom </th> <th> Nom </th> <th> email </th> <th> dateNaissance </th> <th> adresse </th> <th> sexe </th> </tr> </thead> <tr> <th><?php if (isset($detaili)) echo $detaili['id']; ?></th> <th><?php echo $detaili['Prenom']; ?></th> <th><?php echo $detaili['nom']; ?></th> <th><?php echo $detaili['email']; ?></th> <th><?php echo $detaili['date_naissance']; ?></th> <th><?php echo $detaili['adresse']; ?></th> <th><?php echo $detaili['sexe']; ?></th> </tr> <?php } ?> <table class="table table-success table-striped"> <thead> <tr> <th> id </th> <th> Prenom </th> <th> Nom </th> <th class="text-center">action</th> </tr> </thead> <?php while ($donnees = mysqli_fetch_array($resultat)) { ?> <tr> <th><?php if (isset($donnees)) echo $donnees['id']; ?></th> <th><?php echo $donnees['Prenom']; ?></th> <th><?php echo $donnees['nom']; ?></th> <td class="text-center"> <a class='btn btn-success btn-xs' href="Acceuil.php?idL=<?php if (isset($donnees)) echo $donnees['id']; ?>"><span class="glyphicon glyphicon-edit"></span> Details</a> <a class='btn btn-info btn-xs' href="modification.php?idM=<?php if (isset($donnees)) echo $donnees['id']; ?>"><span class="glyphicon glyphicon-edit"></span> modifier</a> <a href="traitement.php?idD=<?php if (isset($donnees)) echo $donnees['id']; ?>" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> supprimer</a> </td> </tr> <?php } $mysqli->close(); ?> <table> </body> </html><file_sep><!DOCTYPE html> <html lang="en" dir="ltr"> <head> <script type="text/javascript"></script> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js></script> <link rel="stylesheet" href="modification.css"> <title>Devoir </title> </head> <?php ?> <body> <div class="container mt-5"> <div class="row d-flex justify-content-center align-items-center"> <div class="col-md-8"> <form id="regForm" method="POST" action="traitement.php?idM=<?php echo $_GET['idM']; ?>"> <h1 id="register">modification </h1> <div class="all-steps" id="all-steps"> <span class="step"><i class="fa fa-user"></i></span> <span class="step"><i class="fa fa-map-marker"></i></span> <span class="step"><i class="fa fa-shopping-bag"></i></span> <span class="step"><i class="fa fa-car"></i></span> <span class="step"><i class="fa fa-spotify"></i></span> <span class="step"><i class="fa fa-mobile-phone"></i></span> </div> <div class="tab"> <h6> le prenom stp</h6> <p> <input placeholder="prénom" oninput="this.className = ''" name="prenom"></p> </div> <div class="tab"> <h6> le nom </h6> <p><input placeholder="nom de famile" oninput="this.className = ''" name="nom"></p> </div> <div class="tab"> <h6>ton mail?</h6> <p><input placeholder="ton mail stp " oninput="this.className = ''" name="mail"></p> </div> <div class="tab"> <h6>Ton mot de passe </h6> <p><input placeholder="mot de passe " oninput="this.className = ''" name="password"></p> </div> <div class="tab"> <h6>date d'anniversaire</h6> <p><input placeholder="your birthdate" oninput="this.className = ''" name="bday"></p> </div> <div class="tab"> <h6>ton adresse</h6> <p><input placeholder="your adresse" oninput="this.className = ''" name="adress"></p> </div> <div class="thanks-message text-center" id="text-message"> <img src="https://i.imgur.com/O18mJ1K.png" width="100" class="mb-4"> <h3>modification reussit !</h3> <span> Merci pour la confiance a la prochaine !</span> <input type="submit" name="modifier" id="inscription" class="button" value="enregistrer"> </div> <div style="overflow:auto;" id="nextprevious"> <div style="float:right;"> <di> <button type="button" id="prevBtn" onclick="nextPrev(-1)"><i class="fa fa-angle-double-left"></i></button> <button type="button" id="nextBtn" onclick="nextPrev(1)"><i class="fa fa-angle-double-right"></i></button> </div> </div> </form> </div> </div> </div> <script type="text/javascript"> var currentTab = 0; document.addEventListener("DOMContentLoaded", function(event) { showTab(currentTab); }); function showTab(n) { var x = document.getElementsByClassName("tab"); x[n].style.display = "block"; if (n == 0) { document.getElementById("prevBtn").style.display = "none"; } else { document.getElementById("prevBtn").style.display = "inline"; } if (n == (x.length - 1)) { document.getElementById("nextBtn").innerHTML = '<i class="fa fa-angle-double-right"></i>'; } else { document.getElementById("nextBtn").innerHTML = '<i class="fa fa-angle-double-right"></i>'; } fixStepIndicator(n) } function nextPrev(n) { var x = document.getElementsByClassName("tab"); if (n == 1 && !validateForm()) return false; x[currentTab].style.display = "none"; currentTab = currentTab + n; if (currentTab >= x.length) { document.getElementById("nextprevious").style.display = "none"; document.getElementById("all-steps").style.display = "none"; document.getElementById("register").style.display = "none"; document.getElementById("text-message").style.display = "block"; } showTab(currentTab); } function validateForm() { var x, y, i, valid = true; x = document.getElementsByClassName("tab"); y = x[currentTab].getElementsByTagName("input"); for (i = 0; i < y.length; i++) { if (y[i].value == "") { y[i].className += " invalid"; valid = false; } } if (valid) { document.getElementsByClassName("step")[currentTab].className += " finish"; } return valid; } function fixStepIndicator(n) { var i, x = document.getElementsByClassName("step"); for (i = 0; i < x.length; i++) { x[i].className = x[i].className.replace(" active", ""); } x[n].className += " active"; } </script> </body> </html><file_sep><?php class config { //Declaration des variables private $servername; private $username; private $password; private $dbname; private $charset; //Connexion a la base de donnees public function connect() { $this->servername = 'localhost'; $this->username = 'root'; $this->password = ''; $this->dbname = 'evaluation'; $this->charset = 'utf8mb4'; try { $db = "mysql:host=" . $this->servername . ";dbname=" . $this->dbname . ";password=" . $this->password . ";charset=" . $this->charset; $pdo = new PDO($db, $this->username, $this->password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } } <file_sep><?php session_start(); session_destroy(); echo "<script>window.location.href = 'devoir (2).php';</script>"; exit; <file_sep> <?php session_start(); class db extends config { public function controlAge() { $dateNaissance = $_POST['bday']; $aujourdhui = date("Y-m-d"); $diff = date_diff(date_create($dateNaissance), date_create($aujourdhui)); $ageInYears = $diff->format('%y'); if ($ageInYears < 18) return false; else return true; } public function controleMail($email) { $sql_e = "SELECT * FROM user WHERE email='$email'"; $db = mysqli_connect('localhost', 'root', '', 'evaluation'); $res_e = mysqli_query($db, $sql_e); if (mysqli_num_rows($res_e) > 0) return false; else return true; } public function Login($emailid, $password) { $res = "SELECT * FROM user WHERE email = '" . $emailid . "' AND mot_de_pass = '" . md5($password) . "'"; $db = mysqli_connect('localhost', 'root', '', 'evaluation'); $res_e = mysqli_query($db, $res); $user_data = mysqli_fetch_array($res_e); if (mysqli_num_rows($res_e) > 0) { $_SESSION['login'] = true; $_SESSION['username'] = $user_data['Prenom']; $_SESSION['email'] = $user_data['nom']; return TRUE; } else return FALSE; } public function addPerson(Personne $personne) { try { $nom = $personne->getNom(); $prenom = $personne->getPrenom(); $datedeNaiss = $personne->getDateNaissance(); $email = $personne->getEmail(); $adresse = $personne->getAdresse(); $sexe = $personne->getSexe(); $mdp = $personne->getPassword(); $hash = md5($mdp); $sql = "INSERT INTO user (prenom,nom,email,mot_de_pass,date_naissance,adresse,sexe) VALUES (?,?,?,?,?,?,?)"; $res = $this->connect()->prepare($sql); $res->execute(array($prenom, $nom, $email, $hash, $datedeNaiss, $adresse, $sexe)); echo 'Bien sa marche'; } catch (Exception $e) { echo "Erreur" . $e->getMessage(); } } public function deletePerson($id) { $sql_e = "DELETE FROM user WHERE id ='$id'"; $db = mysqli_connect('localhost', 'root', '', 'evaluation'); if (mysqli_query($db, $sql_e)) header("Location:Acceuil.php"); else echo " on a un probléme "; // header("location:Acceuil.php"); } public function detail($id) { $sql = "SELECT * FROM user WHERE id = '$id'"; $res = $this->connect()->query($sql); $row = $res->fetch(); return $row; } public function upgrade($id, $prenom, $nom, $dateNaissance, $password, $email, $adresse) { $sql_e = "UPDATE user SET Prenom = '$prenom', nom ='$nom', email='$email',mot_de_pass='$password', date_naissance='$dateNaissance', adresse='$adresse' WHERE id = '$id'"; $db = mysqli_connect('localhost', 'root', '', 'evaluation'); if (mysqli_query($db, $sql_e)) header("Location:Acceuil.php"); else echo " on a un probléme "; } }
51aa837b5dd1c5d3f046d7d186f784f1480b2747
[ "PHP" ]
7
PHP
jouahibou/evaluation
da7e241392f3f9839253bd341c6c804a741cbdd5
a67e3d2d2e8ec7dc35acd8c57450c81c2854abb0
refs/heads/master
<repo_name>enricorusso/sha2017-abusemail<file_sep>/script.sh declare -i pos pos=5 tshark -r file2.pcap -T fields -e usb.capdata | cut -d: -f1,3 | while read a do if [ "$a" != "" ]; then h1=`echo $a | cut -d: -f1` h2=`echo $a | cut -d: -f2` if [ "$h2" == "38" ]; then echo -n "/" fi if [ "$h2" != "00" ]; then IFS="/" tokens=( `grep 0x$h2 keycodes | grep -i keyboard` ) ret=`echo ${tokens[2]} | cut -b11-` if [[ $ret == *"and"* ]]; then r1=`echo $ret | cut -b1` r2=`echo $ret | rev | cut -b1` if [ "$h1" == "02" ]; then echo -n "$r2" else echo -n "$r1" fi else case $h2 in "28") echo ;; "2c") echo -n " " ;; "*") echo -n "?$h2" ;; esac #if [ "$h2" == "28" ]; then # echo # else # if [ "$h2" == "2c" ]; then # echo -n " " # else # fi fi fi fi done <file_sep>/decode.py import base64 import sys import time import subprocess import threading from Crypto import Random from Crypto.Cipher import AES from scapy.all import * BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-ord(s[-1])] magic = "SHA2017" class AESCipher: def __init__( self, key ): self.key = key def encrypt( self, raw ): raw = pad(raw) iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key, AES.MODE_CBC, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ) def decrypt( self, enc ): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(self.key, AES.MODE_CBC, iv ) return unpad(cipher.decrypt( enc[16:] )) def run_command(cmd): ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = ps.communicate()[0] return output def send_ping(host, magic, data): data = cipher.encrypt(data) load = "{}:{}".format(magic, data) time.sleep(1) sr(IP(dst=host)/ICMP()/load, timeout=1, verbose=0) def chunks(L, n): for i in xrange(0, len(L), n): yield L[i:i+n] def get_file(host, magic, fn): time.sleep(1) data = base64.urlsafe_b64encode(open(fn, "rb").read()) cnt = 0 icmp_threads = [] for line in chunks(data, 500): t = threading.Thread(target = send_ping, args = (host,magic, "getfile:{}:{}".format(cnt,line))) t.daemon = True t.start() icmp_threads.append(t) cnt += 1 for t in icmp_threads: t.join() cipher = AESCipher('K8djhaIU8H2d1jNb') f = sys.argv[1] pkts = rdpcap(f) chunks = {} i = 0 fname = "" def save_chunks(): global chunks, i, fname print("save " + fname) result = '' for x in sorted(chunks.keys()): result += chunks[x] b = base64.urlsafe_b64decode(result) open(fname, 'wb').write(b) chunks = {} for packet in pkts: input = packet[IP].load if input[0:len(magic)] == magic: input = input.split(":") data = cipher.decrypt(input[1]).split(":") if data[0]=='command': print(data[1]) if data[0]=='getfile': if len(data)>=3: #print("2: " + data[2]) chunks[int(data[1])] = data[2] else: i += 1 if i == 3: print("save array: " + str(len(chunks))) fname = "file1.pcap" save_chunks() i=0 print("save array: " + str(len(chunks))) fname = "file2.pcap" save_chunks()
825d5b5e3950318597e9a5eb914a76510c1e9c9a
[ "Python", "Shell" ]
2
Shell
enricorusso/sha2017-abusemail
b67b0ef12e65e5a48511b210101126fadc5766ce
0c69ac2bd1b587879580c6bd31e58e0301d286c0
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SampleWebBlog.Models; namespace SampleWebBlog.Controllers { public class MahasiswaController : Controller { static List<Mahasiswa> lstMhs = new List<Mahasiswa>() { new Mahasiswa{Nim="77889911",Nama="<NAME>", Email ="<EMAIL>",IPK=3.2}, new Mahasiswa{Nim="77889912",Nama="Bambang", Email="<EMAIL>",IPK=3.5}, new Mahasiswa{Nim="77889913",Nama="Alex", Email="<EMAIL>",IPK=3.1} }; // GET: Mahasiswa public ActionResult Index(string keyword="") { List<Mahasiswa> results = lstMhs.OrderBy(m => m.Nama).ToList(); if (keyword != string.Empty) results = lstMhs.Where(m => m.Nama.ToLower() .Contains(keyword.ToLower()) || m.Nim.Contains(keyword)).ToList(); return View(results); } // GET: Mahasiswa/Details/5 public ActionResult Details(int id) { return View(); } // GET: Mahasiswa/Create public ActionResult Create() { return View(); } // POST: Mahasiswa/Create [HttpPost] public ActionResult Create(Mahasiswa mahasiswa) { try { if (ModelState.IsValid) { lstMhs.Add(mahasiswa); return RedirectToAction("Index"); } // TODO: Add insert logic here else { return View(); } } catch { return View(); } } // GET: Mahasiswa/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Mahasiswa/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Mahasiswa/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Mahasiswa/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } } <file_sep># ASPMVCBootcamp Training ASP .NET MVC
bbf097937c5decc53909c661f693b9948bd4f647
[ "Markdown", "C#" ]
2
C#
ilhamfn4/ASPMVCBootcamp
c4664b82446d8994d6c0e5303f707ce97f475dda
bf5fce702a0c796815be6c4e9f6d2668f4cd8ea9
refs/heads/master
<repo_name>jabouzi/MovieListMVVM<file_sep>/app/src/main/java/com/raywenderlich/wewatch/component/AppComponent.kt package com.raywenderlich.wewatch.component interface AppComponent { }<file_sep>/app/src/main/java/com/raywenderlich/wewatch/viewmodel/MovieViewModel.kt package com.raywenderlich.wewatch.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.raywenderlich.wewatch.data.MovieRepository import com.raywenderlich.wewatch.data.MovieRepositoryImpl import com.raywenderlich.wewatch.data.model.details.MovieDetails class MovieViewModel(private val repository: MovieRepository = MovieRepositoryImpl()): ViewModel() { fun getMovie(movieId: Int): LiveData<MovieDetails?>{ return repository.getMovieDetails(movieId) } }<file_sep>/app/src/main/java/com/raywenderlich/wewatch/listener/MovieClickListener.kt package com.raywenderlich.wewatch.listener import android.view.View interface MovieClickListener { fun onItemClick(id: Int) }<file_sep>/app/src/main/java/com/raywenderlich/wewatch/view/activities/MovieDetailsActivity.kt package com.raywenderlich.wewatch.view.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.raywenderlich.wewatch.R import com.raywenderlich.wewatch.data.model.details.MovieDetails import com.raywenderlich.wewatch.data.net.RetrofitClient import com.raywenderlich.wewatch.viewModelFactory import com.raywenderlich.wewatch.viewmodel.MovieViewModel import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_main.progressBar import kotlinx.android.synthetic.main.activity_movie_details.* import kotlinx.android.synthetic.main.toolbar_view_custom_layout.* import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class MovieDetailsActivity : BaseActivity() { private val toolbar: Toolbar by lazy { toolbar_toolbar_view as Toolbar } private lateinit var viewModel: MovieViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_movie_details) setSupportActionBar(toolbar) getSupportActionBar()?.setDisplayHomeAsUpEnabled(true); getSupportActionBar()?.setDisplayShowHomeEnabled(true); val movieId = intent.extras.getInt("id") viewModel = ViewModelProviders.of(this, viewModelFactory).get(MovieViewModel::class.java) showLoading() viewModel.getMovie(movieId).observe(this, Observer { movie -> hideLoading() movie?.let { showMovieDetails(movie) } }) } private fun showLoading() { progressBar.visibility = View.VISIBLE } private fun hideLoading() { progressBar.visibility = View.GONE } private fun showMovieDetails(movieDetails: MovieDetails) { movieDetails?.let { if (it.posterPath != null) Picasso.get().load(RetrofitClient.TMDB_IMAGEURL + it.posterPath).into(movieImageView) else { movieImageView.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_local_movies_gray, null)) } movieTitleTextView.setText(movieDetails.title) movieReleaseDateTextView.setText(movieDetails.releaseDate) movieDetails.voteAverage?.let { it -> movieReviewsTextView.setText(it.toString()) } movieoverviewTextView.setText(movieDetails.overview) } } override fun getToolbarInstance(): Toolbar? = toolbar fun goToAddActivity(view: View) = startActivity<AddMovieActivity>() } <file_sep>/app/src/main/java/com/raywenderlich/wewatch/viewmodel/WeWatchViewModelFactory.kt package com.raywenderlich.wewatch.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class WeWatchViewModelFactory: ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return modelClass.newInstance() as T } }<file_sep>/README.md # Movie List MVVM MVVM with architecture components example of a Movie list from RW Book
7e2e29f8accd34cf203a0c162d555277e0c5b455
[ "Markdown", "Kotlin" ]
6
Kotlin
jabouzi/MovieListMVVM
2d89ca0cd56a965a71ced74d83dcdd5006a98481
b54eb6634519a8993cc7bfc5e7f5f47b86b1ef4e
refs/heads/master
<file_sep>"""Discover Cambridge Audio network audio player.""" from . import MDNSDiscoverable # pylint: disable=too-few-public-methods class Discoverable(MDNSDiscoverable): """Add support for Cambridge Audio service.""" def __init__(self, nd): """Initialize the Cast discovery.""" super(Discoverable, self).__init__(nd, '_stream-magic._tcp.local.')
4ba252839bfc6bac5d010ea6033580305bdafb4b
[ "Python" ]
1
Python
ChristianKuehnel/netdisco
983ad164d1dde438c512aa99f3f4271abd81392e
8659d3e1a34ea5c5ba9ecf3b177d4a7907055888
refs/heads/master
<file_sep>instabackup is a quick hack to back up your instagram stream. I put it together in 20 mins. It's raw. I don't care. Run it, and it'll download all the photos from yuor instagram feed into the current directory, named with the upload date and title. It won't re-download files that already exist, so you can safely run it nightly and just download new photos if you want to do that. The first time you run it, it'll need authentication. OAuth2 doesn't seem to have a pure desktop flow, so you'll end up on a page on movieos.org that will give you a token to cut and paste back to the command line. Not the best of solutions, but it'll do. It'll cache the token in a file called `.instabackup.token` in your home directory, and subsequent runs won't need authenticating. I think that's it. Tell me (<EMAIL>) if it breaks. ## TODO list (that probably won't get done) * Write out a local HTML file that embeds the images and has comments / tags, so you get a pretty HTML file like the Tumblr backup tool provides. * Write out the full backed up metadata as JSON or something so in extremis you can recover everything about a file. * Take the file output directory as a command-line param so things don't just get spewed into the current directory. * It's probably got unicode bugs in it. Everything always does. ## Flickr support The vague long-term aim of this tool was a bulk-import-into-flickr-from-instagram-history tool. Maybe I want to do this. It should do tags and comments and things, and properly set the taken-date, and all that stuff. Not sure if I really care enough about that, though. It's enoguh to just have an automatable backup tool. <file_sep>import urllib, urllib2 import os import json import datetime API_KEY = "6e3014faf9dc441b84e69ac0fa94f6fa" API_SECRET = "<KEY>" TOKEN_FILE = os.path.expandvars("$HOME/.instabackup.token") def main(): # look for existing token try: with file(TOKEN_FILE) as f: token = f.read().strip() except IOError: # ok, we don't have a token redirect = "http://movieos.org/toys/instabackup/" auth = "https://instagram.com/oauth/authorize/?client_id=%s&redirect_uri=%s&response_type=token"%(API_KEY, urllib.quote(redirect)) print "Open\n\n%s\n\nin a web browser, then paste the token (bit after the # in the landing page) here:"%(auth) token = raw_input("--> ") with file(TOKEN_FILE, "w") as f: f.write(token) url = "https://api.instagram.com/v1/users/self/media/recent?access_token=%s"%token while url: print "fetching page.." conn = urllib2.urlopen(url) raw = conn.read() data = json.loads(raw) for photo in data["data"]: image = photo["images"]["standard_resolution"]["url"] try: title = photo["caption"]["text"] except (KeyError, TypeError): title = "untitled" print u"..%s"%title dt = datetime.datetime.utcfromtimestamp(float(photo["created_time"])) # can't use colons in time because macos gets whiny. filename = u"%s %s.jpg"%(dt.strftime("%Y-%m-%dT%H-%M-%S"), title) if not os.path.exists(filename): u = urllib2.urlopen(image) with open(filename, 'w') as f: f.write(u.read()) try: url = data["pagination"]["next_url"] except KeyError: break print "All done!" if __name__ == "__main__": main()
b3b6bdcc2bea5bf3245f3e00a94c8078828bd62c
[ "Markdown", "Python" ]
2
Markdown
tominsam/instabackup
0c1c3ac50cb992d541fb4cbfda16877879323954
122291a99b83f116909fcc2ff6d4f28587c8d82c
refs/heads/master
<repo_name>dcchivian/kb_mash<file_sep>/lib/src/us/kbase/kbmash/MashSketchResults.java package us.kbase.kbmash; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * <p>Original spec-file type: MashSketchResults</p> * <pre> * * * * Returns the local scratch file path of the generated sketch file. * * Will have the extension '.msh' * </pre> * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("com.googlecode.jsonschema2pojo") @JsonPropertyOrder({ "sketch_path" }) public class MashSketchResults { @JsonProperty("sketch_path") private String sketchPath; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("sketch_path") public String getSketchPath() { return sketchPath; } @JsonProperty("sketch_path") public void setSketchPath(String sketchPath) { this.sketchPath = sketchPath; } public MashSketchResults withSketchPath(String sketchPath) { this.sketchPath = sketchPath; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return ((((("MashSketchResults"+" [sketchPath=")+ sketchPath)+", additionalProperties=")+ additionalProperties)+"]"); } } <file_sep>/lib/kb_mash/mash_utils/MashUtils.py import time import os # import errno import json import subprocess import csv import requests def log(message, prefix_newline=False): """ Logging function, provides a hook to suppress or redirect log messages. """ print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message)) mash_bin = '/kb/module/mash-Linux64-v2.0/mash' # ahs_url = 'https://homology.kbase.us/namespace/%s/search' class MashUtils: def __init__(self, config, auth_token): self.scratch = os.path.abspath(config['scratch']) self.sw_url = config['srv-wiz-url'] if config.get('id-mapper-url'): self.id_mapper_url = config['id-mapper-url'] else: self.id_mapper_url = config['kbase-endpoint'] + "/idmapper/api/v1" self.auth_token = auth_token endpoint = config['kbase-endpoint'].split('/services')[0] if 'appdev' in endpoint: endpoint = endpoint.replace("appdev", "narrative") elif '/kbase' in endpoint: endpoint = endpoint.replace("kbase", "narrative.kbase") self.endpoint = endpoint def mash_sketch(self, genome_file_path, paired_ends=False): """ Generate a sketch file for a given fasta/fastq file path, saving the output to a tempfile. Documentation: http://mash.readthedocs.io/en/latest/tutorials.html """ assert os.path.exists(genome_file_path), 'genome_file_path must exist' output_path = genome_file_path + '.msh' args = [mash_bin, 'sketch', genome_file_path, '-o', output_path] if paired_ends: # Sketch the reads using `-m 2` to improve results by ignoring single-copy k-mers, which # are more likely to be erroneous: args = args + ['-m', '2'] self._run_command(' '.join(args)) return output_path def get_sketch_service_url_with_service_wizard(self): ''' ''' payload = { "method":"ServiceWizard.get_service_status", "id":'', "params":[{"module_name":"sketch_service","version":"beta"}], "version":"1.1" } sw_resp = requests.post(url=self.sw_url, data=json.dumps(payload)) sketch_resp = sw_resp.json() if sketch_resp.get('error'): raise RuntimeError("ServiceWizard Error: "+ str(sketch_resp['error'])) sketch_url = sketch_resp['result'][0]['url'] return sketch_url def sketch_service_query(self, input_upas, n_max_results, search_db): '''Query assembly homology service to leverage its caching and mash implementation params: input_upa - reference to assembly or genome n_max_results - number of results to return search_db - string to specify search database ''' # get current sketch_service url from service wizard sketch_url = self.get_sketch_service_url_with_service_wizard() results = [] for upa in input_upas: payload = { "method":"get_homologs", "params":{ 'ws_ref':upa, 'n_max_results':n_max_results, 'search_db': search_db } } resp = requests.post(url=sketch_url, data=json.dumps(payload),headers={ 'content-type':"application/json-rpc",'Authorization':self.auth_token}) if len(input_upas) == 1: results = self.parse_results(resp.json()) else: curr = self.parse_results(resp.json(), input_name=upa) results += curr return results def parse_results(self, results_data, input_name=None): ''' params: results_data: dictionary response from sketch_service ''' if results_data.get('error'): raise RuntimeError("Sketch_service Error: " + str(results_data['error'])) if not results_data.get('result'): raise ValueError("No results or results empty in JSON response body") if not results_data['result'].get('distances'): raise ValueError("No Distances in results JSON response") results = [] distances = results_data['result']['distances'] # id_to_similarity, id_to_upa, id_to_sciname, id_to_strain = {}, {}, {}, {} for d in distances: curr = {} curr['Id'] = d['sourceid'] sciname = "" if d.get('sciname'): sciname += d['sciname'] if d.get('kbase_id'): curr['item_link'] = self.endpoint + "/#dataview/" + d['kbase_id'] if d.get('strain'): sciname = sciname + " " + d['strain'] curr['sciname'] = sciname curr['dist'] = float(d['dist']) if input_name != None: curr['input_name'] = input_name results.append(curr) # id_to_similarity[d['sourceid']] = float(d['dist']) # if d.get('sciname'): # id_to_sciname[d['sourceid']] = d['sciname'] # if d.get('kbase_id'): # id_to_upa[d['sourceid']] = d['kbase_id'] # if d.get('strain'): # id_to_strain[d['sourceid']] = d['strain'] return results def id_mapping_query(self, ids): """ """ payload = { "ids":ids } id_mapper_url = self.id_mapper_url + '/mapping/RefSeq' resp = requests.get(url=id_mapper_url, data=json.dumps(payload),\ headers={'content-type':"application/json-rpc",'Authorization':self.auth_token}) return self.parse_mapper_response(resp.json()) def parse_mapper_response(self, resp): """ """ if resp.get('error'): raise RuntimeError("ID Mapper Error: "+ str(resp.get('error', "unknown error"))) id_to_upa = {} for id_ in resp: mappings = resp[id_]["mappings"] # default upa is no upa id_to_upa[id_] = "" for mapping in mappings: if mapping['ns'] == "KBase": id_to_upa[id_] = mapping['id'] return id_to_upa def _run_command(self, command): """ _run_command: run command and print result """ log('Start executing command:\n{}'.format(command)) pipe = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) output = pipe.communicate()[0] exitCode = pipe.returncode if (exitCode == 0): log('Executed command:\n{}\n'.format(command) + 'Exit Code: {}\nOutput:\n{}'.format(exitCode, output)) else: error_msg = 'Error running command:\n{}\n'.format(command) error_msg += 'Exit Code: {}\nOutput:\n{}'.format(exitCode, output) raise ValueError(error_msg) <file_sep>/lib/src/us/kbase/kbmash/MashSketchParams.java package us.kbase.kbmash; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * <p>Original spec-file type: MashSketchParams</p> * <pre> * * * * Pass in **one of** input_path, assembly_ref, or reads_ref * * input_path - string - local file path to an input fasta/fastq * * assembly_ref - string - workspace reference to an Assembly type * * reads_ref - string - workspace reference to a Reads type * * Optionally, pass in a boolean indicating whether you are using paired-end reads. * * paired_ends - boolean - whether you are passing in paired ends * </pre> * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("com.googlecode.jsonschema2pojo") @JsonPropertyOrder({ "input_path", "assembly_ref", "reads_ref", "paired_ends" }) public class MashSketchParams { @JsonProperty("input_path") private String inputPath; @JsonProperty("assembly_ref") private String assemblyRef; @JsonProperty("reads_ref") private String readsRef; @JsonProperty("paired_ends") private Long pairedEnds; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("input_path") public String getInputPath() { return inputPath; } @JsonProperty("input_path") public void setInputPath(String inputPath) { this.inputPath = inputPath; } public MashSketchParams withInputPath(String inputPath) { this.inputPath = inputPath; return this; } @JsonProperty("assembly_ref") public String getAssemblyRef() { return assemblyRef; } @JsonProperty("assembly_ref") public void setAssemblyRef(String assemblyRef) { this.assemblyRef = assemblyRef; } public MashSketchParams withAssemblyRef(String assemblyRef) { this.assemblyRef = assemblyRef; return this; } @JsonProperty("reads_ref") public String getReadsRef() { return readsRef; } @JsonProperty("reads_ref") public void setReadsRef(String readsRef) { this.readsRef = readsRef; } public MashSketchParams withReadsRef(String readsRef) { this.readsRef = readsRef; return this; } @JsonProperty("paired_ends") public Long getPairedEnds() { return pairedEnds; } @JsonProperty("paired_ends") public void setPairedEnds(Long pairedEnds) { this.pairedEnds = pairedEnds; } public MashSketchParams withPairedEnds(Long pairedEnds) { this.pairedEnds = pairedEnds; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return ((((((((((("MashSketchParams"+" [inputPath=")+ inputPath)+", assemblyRef=")+ assemblyRef)+", readsRef=")+ readsRef)+", pairedEnds=")+ pairedEnds)+", additionalProperties=")+ additionalProperties)+"]"); } } <file_sep>/lib/kb_mash/kb_object_utils/KBObjectUtils.py import time import os import uuid import errno import operator from jinja2 import Environment, PackageLoader, select_autoescape from KBaseReport.KBaseReportClient import KBaseReport from KBaseReport.baseclient import ServerError as _RepError from AssemblyUtil.AssemblyUtilClient import AssemblyUtil from AssemblyUtil.baseclient import ServerError as AssemblyUtilError from Workspace.WorkspaceClient import Workspace as _Workspace from DataFileUtil.DataFileUtilClient import DataFileUtil as _DFUClient from DataFileUtil.baseclient import ServerError as _DFUError def log(message, prefix_newline=False): """ Logging function, provides a hook to suppress or redirect log messages. """ print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message)) env = Environment(loader=PackageLoader('kb_mash','kb_object_utils/templates'), autoescape=select_autoescape(['html'])) class KBObjectUtils: KBASE_DBS = {'KBaseRefseq'} def __init__(self, config): self.scratch = os.path.abspath(config['scratch']) self.tmp = os.path.join(self.scratch, str(uuid.uuid4())) self._mkdir_p(self.tmp) self.callbackURL = os.environ['SDK_CALLBACK_URL'] self.ws_url = config['workspace-url'] self.dfu = _DFUClient(self.callbackURL) def _mkdir_p(self, path): """ _mkdir_p: make directory for given path """ # https://stackoverflow.com/a/600612/643675 if not path: return try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def input_upa_parse(self, upa): obj_data = self.dfu.get_objects({"object_refs":[upa]})['data'][0] obj_type = obj_data['info'][2] gs_obj = obj_data['data'] if 'KBaseSets.GenomeSet' in obj_type: upas = [gsi['ref'] for gsi in gs_obj['items']] elif 'KBaseSearch.GenomeSet' in obj_type: upas = [gse['ref'] for gse in gs_obj['elements'].values()] elif "KBaseGenomes.ContigSet" in obj_type or "KBaseGenomeAnnotations.Assembly" in obj_type or "KBaseGenomes.Genome" in obj_type: upas = [upa] else: raise TypeError("provided input must of type 'KBaseSets.GenomeSet','KBaseSearch.GenomeSet','KBaseGenomes.ContigSet','KBaseGenomeAnnotations.Assembly' or 'KBaseGenomes.Genome' not " +str(obj_type)) return upas # def _create_link_mapping(self, id_to_upa): # idmap = {} # log('Looking up object names and scientific names in KBase data stores') # ws_refs = [] # for x in id_to_upa.values(): # if x != "": # ws_refs.append(x) # if len(ws_refs) > 0: # # should really catch error and log here, later. Same below for taxa lookup # objs = self.dfu.get_objects({'object_refs': ws_refs})['data'] # upa_to_name = {} # upa_to_taxon_upa = {} # for o in objs: # upa_ = self._to_upa(o['info']) # upa_to_name[upa_] = o['info'][1] # # check to see if this object has a taxon_upa # if o.get('refs'): # upa_to_taxon_upa[upa_] = o['refs'][0] # taxrefs = upa_to_taxon_upa.values() # # 1) Really should use a reference path here, but since the taxons are public skip # # 2) The taxon objects should have the scientific name in the metadata so the entire # # object doesn't need to be fetched. At least the taxa objects are small. # # 3) Should use DFU for getting objects # # 4) This code is a Very Bad Example of how to do things, basically # upa_to_sci_name = {} # if len(taxrefs) > 0: # taxobjs = self.dfu.get_objects({'object_refs': taxrefs})['data'] # for t in taxobjs: # upa = self._to_upa(t['info']) # upa_to_sci_name[upa] = t['data']['scientific_name'] # for id_, upa in id_to_upa.items(): # upa = upa.replace('_','/') # if upa != "" and upa_to_name.get(upa) and upa_to_taxon_upa.get(upa): # idmap[id_] = {'id': '{} ({})'.format(upa_to_name[upa], # upa_to_sci_name[upa_to_taxon_upa[upa]]), # 'link': '/#dataview/' + upa} # elif upa != "" and upa_to_name.get(upa): # idmap[id_] = {'id': '{}'.format(upa_to_name[upa]), 'link':'/#dataview/' + upa} # return idmap def _to_upa(self, objinfo, sep='/'): return str(objinfo[6]) + sep + str(objinfo[0]) + sep + str(objinfo[4]) # def _write_search_results(self, outfile, id_to_similarity, id_to_link, id_to_strain): # # change to mustache or something later. Or just rewrite this whole thing since this is # # a demo # with open(outfile, 'w') as html_file: # html_file.write('<html><body>\n') # html_file.write('<div>Showing {} matches</div>\n' # .format(len(id_to_similarity))) # html_file.write('<table>\n') # html_file.write('<tr><th>ID</th><th>Minhash distance</th></tr>\n') # for id_, similarity in sorted( # id_to_similarity.items(), key=operator.itemgetter(1), reverse=False): # if id_ in id_to_link: # html_file.write( # '<tr><td><a href="{}" target="_blank">{}</a></td><td>{}</td>\n'.format( # id_to_link[id_]['link'], id_to_link[id_]['id'], similarity)) # else: # html_file.write('<tr><td>{}</td><td>{}</td>\n'.format(id_, similarity)) # html_file.write('</table>\n') # html_file.write('</body></html>\n') # def create_search_report(self, wsname, id_to_similarity, id_to_upa, id_to_sciname, id_to_strain): def create_search_report(self, wsname, query_results, multi): outdir = os.path.join(self.tmp, 'search_report') self._mkdir_p(outdir) # id_to_link = self._create_link_mapping(query_results) if multi: template = env.get_template("index_multi.html") else: template = env.get_template("index.html") html_output = template.render(results=query_results) with open(os.path.join(outdir,'index.html'), 'w') as f: f.write(html_output) # self._write_search_results( # os.path.join(outdir, 'index.html'), id_to_similarity, id_to_link, id_to_strain) log('Saving Mash search report') html_link = { 'path':outdir, 'name':'index.html', 'description': 'Mash html report' } try: report = KBaseReport(self.callbackURL) return report.create_extended_report({ 'direct_html_link_index':0, 'html_links':[html_link], 'workspace_name': wsname, 'report_object_name':'kb_mash_report_' + str(uuid.uuid4()) }) except _RepError as re: log('Logging exception from creating report object') log(str(re)) # TODO delete shock node raise def stage_assembly_files(self, object_list): """ _stage_assembly_files: download the fasta files to the scratch area return list of file names """ log('Processing assembly object list: {}'.format(object_list)) auc = AssemblyUtil(self.callbackURL) staged_file_list = [] for assembly_upa in object_list: try: filename = auc.get_assembly_as_fasta({'ref': assembly_upa})['path'] except AssemblyUtilError as assembly_error: print(str(assembly_error)) raise staged_file_list.append(filename) log('Created file list: {}'.format(staged_file_list)) return staged_file_list
c52a3b40747be70de5662fee27c86280c93edfba
[ "Java", "Python" ]
4
Java
dcchivian/kb_mash
acba9d72dbf7e5a35ae5ea4abaef34ad22c6826b
0803f6a4721d83819d3670b3f0e0ecc306f58d65
refs/heads/master
<file_sep># Cache Simulator Assembler for the Mano Machine designed in Cedarville's Computer Architecture class. ## Hardware Requirements Your system must support at minumum version 4.3 of OpenGL. To see if your computer is supported, check your hardware and driver version using the following links: - [Intel](https://www.intel.com/content/www/us/en/support/articles/000005524/graphics.html) - [NVIDIA](https://developer.nvidia.com/opengl-driver) ## Environment Setup ### Install vcpkg Install [vcpkg](https://github.com/microsoft/vcpkg), and follow the instructions to integrate it with Visual Studio. After it is installed, run the following commands: ``` vcpkg install glfw3 vcpkg install glew vcpkg install glm ``` If you integrated vcpkg with Visual Studio, the libraries will be automatically added to your projects. ### Compile NFD Next, download [Native File Dialogue](https://github.com/mlabbe/nativefiledialog) and compile it using Visual Studio. The .sln file can be found in `build/vs2010`. Make sure to use the same compiler versionas you plan on using for this project! Once compilation of NFD is finished, you will need to tell this project where to find the files for NFD. Under project properties, add `(NFD)/src/include` to Additional Include Directories and `(NFD)/build/lib/Debug/x86/`to Additional Library Dependencies under the Debug configuration, and `(NFD)/build/lib/Release/x86/` under the Release configuration (optional). # How to Use Load a .csv file using the "Load File" button. The expected format for the .csv is for the address, in binary, to be the first column, and for the second column to be the data. To load a line into RAM, type in the address (in binary) and click Load Memory. If the line is cached, a message will say that there was a cache hit. If the line was not cached, it will be loaded into the cache and highlighted red, and a message will appear saying that there was a cache miss. ## Known Bugs If cancel is pressed when selecting a file, main memory is given a single line of memory with no data, but will not be displayed. To fix, simply load another file. <file_sep>#include "TextBox.h" #include <glm/gtc/type_ptr.hpp> TextBox::TextBox(std::shared_ptr<GLRenderingProgram> prog, std::shared_ptr<GLRenderingProgram> textBox, glm::vec2 topLeft, glm::vec2 bottomRight) : _left(topLeft), _right(bottomRight), RenderObject(textBox), _enabled(true), _str(prog), _scrolled(0.0f) { _str.setPosition(_left - glm::vec2(0.0f, _str.getFontSize())); _textColor = glm::vec3(1.0f, 1.0f, 1.0f); _centered = false; _backColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); p_verts = { _left.x, _left.y, _left.x, _right.y, _right.x, _left.y, _right.x, _left.y, _left.x, _right.y, _right.x, _right.x }; } void TextBox::draw(const glm::mat4 & matrix) { if (_enabled) { RenderObject::draw(matrix); p_verts = { _left.x, _left.y, _left.x, _right.y, _right.x, _left.y, _right.x, _left.y, _left.x, _right.y, _right.x, _right.y }; glBindBuffer(GL_ARRAY_BUFFER, p_vbos[0]); glBufferSubData(GL_ARRAY_BUFFER, 0, p_verts.size() * sizeof(p_verts[0]), &p_verts[0]); glUniform4fv(p_prog->getUniformLoc("backgroundColor"), 1, glm::value_ptr(_backColor)); glUniformMatrix4fv(p_prog->getUniformLoc("mat"), 1, GL_FALSE, glm::value_ptr(matrix)); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(0); glFrontFace(GL_CCW); glDisable(GL_DEPTH_TEST); glDrawArrays(GL_TRIANGLES, 0, 6); glm::vec2 pos = _left - glm::vec2(0.0f, _str.getFontSize()); if (_centered) pos += glm::vec2((_right.x - _left.x - _str.getWidth()) / 2.0f, 0.0f); _str.setPosition(pos); _str.setColor(_textColor); _str.draw(matrix); } } void TextBox::setup() { glBindVertexArray(p_vao); p_vbos.push_back(GLuint()); glGenBuffers(1, &p_vbos[0]); glBindBuffer(GL_ARRAY_BUFFER, p_vbos[0]); glBufferData(GL_ARRAY_BUFFER, p_verts.size() * sizeof(p_verts[0]), &p_verts[0], GL_DYNAMIC_DRAW); } void TextBox::setEnabled(bool en) { _enabled = en; if (_enabled) { _left.y += _scrolled; _scrolled = 0.0f; } } void TextBox::charCallback(GLFWwindow * win, unsigned int codepoint) { if (_str.getWidth() < _right.x - _str.getFontSize() && _enabled) _str.push_back((char)codepoint); } void TextBox::keyCallback(GLFWwindow * win, int key, int scancode, int action, int mods) { if (_enabled) { if (key == GLFW_KEY_ENTER) { if (action == GLFW_PRESS || action == GLFW_REPEAT) { _str.push_back('\n'); } } else if (key == GLFW_KEY_BACKSPACE && !_str.empty()) { if (action == GLFW_PRESS || action == GLFW_REPEAT) { _str.pop_back(); } } } } void TextBox::scrollCallback(GLFWwindow * win, double x, double y) { if (_enabled) { float scrollAmount = y * Character::getAdvanceY() * 2; _left.y -= scrollAmount; _scrolled += scrollAmount; } } <file_sep>#include <iostream> #include <Windows.h> #include <string> #include "GLWindow.h" #include "OpenGLFailure.h" //Request use of high performace graphics cards extern "C" { //Select NVIDIA card if avaible _declspec (dllexport) DWORD NvOptimusEnablement = 1; //Select AMD card if available _declspec (dllexport) DWORD AmdPowerXpressRequestHighPerformance = 1; } int main() { try { GLWindow window("Cache Simulator", 1280, 720); window.start(); } catch (const OpenGLFailure& er) { std::cerr << er.what(); return -1; } return 0; } <file_sep>#pragma once #include <gl/glew.h> #include <GLFW/glfw3.h> #include <string> #include <vector> #include <glm/glm.hpp> #include <map> #include "RenderObject.h" #include "TextBox.h" #include "Button.h" #include "OpenFile.h" #include "SaveFileController.h" constexpr unsigned SET_NUM = 4; constexpr unsigned FIELDS = 5; class GLWindow { public: GLWindow(std::string title, unsigned width, unsigned height); ~GLWindow(); void start(); private: unsigned _windowWidth; unsigned _windowHeight; std::string _windowTitle; GLFWwindow* _window; std::vector<RenderObject*> _objs; glm::mat4 _mat; struct glfwPointers { TextBox* mainMem[2]; TextBox* location; Button* file; Button* simulate; } _ptrs; OpenFileController* of; TextBox* holder; TextBox* _location; TextBox* _msg; TextBox* _RAMTextBoxes[SET_NUM][FIELDS]; std::vector<std::string> _memory; bool _oldest[SET_NUM]; glm::ivec2 _lastUsed; void onGLFWError(int error, const char* description); }; <file_sep>#include "GLWindow.h" #include <memory> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <sstream> #include <iomanip> #include <Windows.h> #undef _DEBUG #include "OpenGLFailure.h" #include "Character.h" #include "RenderString.h" #include "Button.h" #include "Debug.h" GLWindow::GLWindow(std::string title, unsigned width, unsigned height) : _windowWidth(width), _windowHeight(height), _windowTitle(title), _window(nullptr) { #ifndef _DEBUG FreeConsole(); #endif // _DEBUG if (!glfwInit()) throw OpenGLFailure("Failed to initialize glfw"); glfwSetErrorCallback((GLFWerrorfun)&[this](int error, const char* description) { onGLFWError(error, description); }); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); #endif // _DEBUG _window = glfwCreateWindow(_windowWidth, _windowHeight, _windowTitle.c_str(), nullptr, nullptr); glfwMakeContextCurrent(_window); GLenum glewError = glewInit(); if (glewError != GLEW_OK) throw OpenGLFailure((char*)glewGetErrorString(glewError)); #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(glDebugOutput, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); #endif // _DEBUG glfwSwapInterval(1); glm::mat4 proj = glm::ortho(0.0f, (float)_windowWidth, 0.0f, (float)_windowHeight, -1.0f, 1.0f); glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -1.0f)); _mat = proj * view; std::shared_ptr<GLRenderingProgram> characterProg = std::make_shared<GLRenderingProgram>("charVert.glsl", "charFrag.glsl"); Character::generateLookupTable(24); std::shared_ptr<GLRenderingProgram> textboxProg = std::make_shared<GLRenderingProgram>("textboxVert.glsl", "textboxFrag.glsl"); std::shared_ptr<GLRenderingProgram> buttonProg = std::make_shared<GLRenderingProgram>("btnVert.glsl", "btnFrag.glsl"); glm::vec3 h1Title = glm::vec3(124 / 255.0f, 252 / 255.0f, 0.0f); glm::vec3 h2Title = glm::vec3(1.0f, 1.0f, 0.0f); TextBox* memTitle = new TextBox(characterProg, textboxProg, glm::vec2(_windowWidth / 2.0f, _windowHeight), glm::vec2(_windowWidth, _windowHeight - 30.0f)); memTitle->setString("Main Memory"); memTitle->setTextColor(h1Title); memTitle->setCentered(true); TextBox* mainAddrTitle = new TextBox(characterProg, textboxProg, glm::vec2(_windowWidth / 2.0f, _windowHeight - 30), glm::vec2(3.0f * _windowWidth / 4.0f, _windowHeight - 60.0f)); TextBox* mainDataTitle = new TextBox(characterProg, textboxProg, glm::vec2(3.0f * _windowWidth / 4.0f, _windowHeight - 30), glm::vec2(_windowWidth, _windowHeight - 60.0f)); mainAddrTitle->setString("Address"); mainDataTitle->setString("Data"); mainAddrTitle->setTextColor(h2Title); mainDataTitle->setTextColor(h2Title); mainAddrTitle->setCentered(true); mainDataTitle->setCentered(true); TextBox* mainAddr = new TextBox(characterProg, textboxProg, glm::vec2(_windowWidth / 2.0f, _windowHeight - 60), glm::vec2( 3.0f * _windowWidth / 4.0f, 0.0f)); TextBox* mainData = new TextBox(characterProg, textboxProg, glm::vec2( 3 * _windowWidth / 4.0f, _windowHeight - 60), glm::vec2(_windowWidth, 0.0f)); mainAddr->setCentered(true); mainData->setCentered(true); _ptrs.mainMem[0] = mainAddr; _ptrs.mainMem[1] = mainData; glfwSetScrollCallback(_window, [](GLFWwindow* window, double x, double y) { glfwPointers* ptrs = (glfwPointers*)glfwGetWindowUserPointer(window); ptrs->mainMem[0]->scrollCallback(window, x, y); ptrs->mainMem[1]->scrollCallback(window, x, y); }); glm::vec2 RAMtop = glm::vec2(0.0f, _windowHeight / 2.0f); float lineHeight = -30.0f; TextBox* RAMtitle = new TextBox(characterProg, textboxProg, RAMtop, RAMtop + glm::vec2(_windowWidth / 2.0f, lineHeight)); RAMtitle->setString("2-Way Set Associative RAM"); RAMtitle->setCentered(true); RAMtitle->setTextColor(h1Title); TextBox* setTitle = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(0.0f, lineHeight), RAMtop + glm::vec2(_windowWidth / 10.0f, 2 * lineHeight)); setTitle->setString("Set"); setTitle->setTextColor(h2Title); setTitle->setCentered(true); TextBox* tagTitle1 = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(_windowWidth / 10.0f, lineHeight), RAMtop + glm::vec2(2 * _windowWidth / 10.0f, 2 * lineHeight)); tagTitle1->setString("Tag"); tagTitle1->setTextColor(h2Title); tagTitle1->setCentered(true); TextBox* dataTitle1 = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(2 * _windowWidth / 10.0f, lineHeight), RAMtop + glm::vec2(3 * _windowWidth / 10.0f, 2 * lineHeight)); dataTitle1->setString("Data"); dataTitle1->setTextColor(h2Title); dataTitle1->setCentered(true); TextBox* tagTitle2 = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(3 * _windowWidth / 10.0f, lineHeight), RAMtop + glm::vec2(4 * _windowWidth / 10.0f, 2 * lineHeight)); tagTitle2->setString("Tag"); tagTitle2->setTextColor(h2Title); tagTitle2->setCentered(true); TextBox* dataTitle2 = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(4 * _windowWidth / 10.0f, lineHeight), RAMtop + glm::vec2(5 * _windowWidth / 10.0f, 2 * lineHeight)); dataTitle2->setString("Data"); dataTitle2->setTextColor(h2Title); dataTitle2->setCentered(true); for (unsigned i = 0; i < SET_NUM; i++) { for (unsigned j = 0; j < FIELDS; j++) { TextBox* box = new TextBox(characterProg, textboxProg, RAMtop + glm::vec2(j * _windowWidth / 10.0f, (2 + i) * lineHeight), RAMtop + glm::vec2((1 + j) * _windowWidth / 10.0f, (3 + i) * lineHeight)); box->setCentered(true); if (j == 0) { std::stringstream str; str << i; box->setString(str.str()); box->setTextColor(glm::vec3(0.5f, 0.5f, 0.5f)); } _RAMTextBoxes[i][j] = box; _objs.push_back(box); } } memset(_oldest, false, SET_NUM); holder = new TextBox(characterProg, textboxProg, { 0.0f, 0.0f }, { 0.0f, 0.0f }); holder->setEnabled(false); of = new OpenFileController(holder); Button* loadFile = new Button(characterProg, buttonProg, _windowWidth / 5.0f, 40.0f, "Load File", glm::vec2(10.0f, _windowHeight - 55.0f)); loadFile->setCallbackFunc([this]() { of->operator()(); std::string str = holder->getString(); std::stringstream stream; stream << str; _memory.clear(); std::string addr = ""; std::string data = ""; while (!stream.eof()) { std::string line = ""; stream >> line; auto delim = line.find(","); addr.append(line.substr(0, delim)); addr.append("\n"); data.append(line.substr(delim + 1, line.length() - delim)); data.append("\n"); _memory.push_back(line.substr(delim + 1, line.length() - delim)); } _ptrs.mainMem[0]->setString(addr); _ptrs.mainMem[1]->setString(data); }); _ptrs.file = loadFile; _location = new TextBox(characterProg, textboxProg, glm::vec2(10.0f, _windowHeight - 60.0f), glm::vec2(10.0f + _windowWidth / 5.0f, _windowHeight - 100.0f)); _location->setBackgroundColor(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); _location->setTextColor(glm::vec3(0.0f, 0.0f, 0.0f)); _ptrs.location = _location; glfwSetCharCallback(_window, [](GLFWwindow* win, unsigned int codepoint) { glfwPointers* ptrs = (glfwPointers*)glfwGetWindowUserPointer(win); ptrs->location->charCallback(win, codepoint);; }); glfwSetKeyCallback(_window, [](GLFWwindow* win, int key, int scancode, int action, int mods) { glfwPointers* ptrs = (glfwPointers*)glfwGetWindowUserPointer(win); ptrs->location->keyCallback(win, key, scancode, action, mods); }); _msg = new TextBox(characterProg, textboxProg, glm::vec2(10.0f, _windowHeight - 105.0f), glm::vec2(10.0f + 2 * _windowHeight / 5.0f, _windowHeight - 145.0f)); Button* sim = new Button(characterProg, buttonProg, _windowWidth / 5.0f, 40.0f, "Load Address", glm::vec2(20.0f + _windowWidth / 5.0f, _windowHeight - 100.0f)); sim->setCallbackFunc([this]() { if (_memory.empty()) { _msg->setString("Load a file into main memory"); _msg->setTextColor(glm::vec3(1.0f, 0.2f, 0.5f)); return; } if (_lastUsed.y != 0) { _RAMTextBoxes[_lastUsed.x][_lastUsed.y]->setTextColor(glm::vec3(1.0f, 1.0f, 1.0f)); _RAMTextBoxes[_lastUsed.x][_lastUsed.y + 1]->setTextColor(glm::vec3(1.0f, 1.0f, 1.0f)); } std::string memLocStr = _location->getString(); bool isBinary = std::find_if_not(memLocStr.begin(), memLocStr.end(), [](auto c) {return c == '0' || c == '1'; }) == memLocStr.end(); if (!isBinary || memLocStr.empty()) { _msg->setString("Memory Address must be in binary"); _msg->setTextColor(glm::vec3(1.0f, 0.2f, 0.5f)); return; } int memLoc = strtol(memLocStr.c_str(), nullptr, 2); int set = memLoc % 4; std::string tagStr = ""; if (memLoc < 4) tagStr = "0"; else tagStr = memLocStr.substr(0, memLocStr.length() - 2); int tag = strtol(tagStr.c_str(), nullptr, 2); int location1 = -1; int location2 = -1; if (_RAMTextBoxes[set][1]->getString().length() != 0) location1 = strtol(_RAMTextBoxes[set][1]->getString().c_str(), nullptr, 2); if (_RAMTextBoxes[set][3]->getString().length() != 0) location2 = strtol(_RAMTextBoxes[set][3]->getString().c_str(), nullptr, 2); if (location1 == tag || location2 == tag) { _msg->setString("Cache Hit"); _msg->setTextColor(glm::vec3(0.0f, 1.0f, 0.0f)); return; } _msg->setString("Cache Miss"); _msg->setTextColor(glm::vec3(1.0f, 0.0f, 0.0f)); auto fillRAM = [this, &tagStr, &memLoc, &set](bool first) { int bitwidth = std::ceil(std::log2(_memory.size())) - 2; if (tagStr.length() < bitwidth) { std::string padding = ""; while (padding.length() + tagStr.length() != bitwidth) padding.append("0"); tagStr = padding + tagStr; } if (memLoc < _memory.size()) { int tagIndex = !first * 2 + 1; _RAMTextBoxes[set][tagIndex]->setString(tagStr); _RAMTextBoxes[set][tagIndex + 1]->setString(_memory[memLoc]); _RAMTextBoxes[set][tagIndex]->setTextColor(glm::vec3(1.0f, 0.0f, 0.0f)); _RAMTextBoxes[set][tagIndex + 1]->setTextColor(glm::vec3(1.0f, 0.0f, 0.0f)); _lastUsed = glm::vec2(set, tagIndex); } else { _msg->setString("Invalid Memory Address"); _msg->setTextColor(glm::vec3(1.0f, 0.2f, 0.5f)); } }; if (location1 == -1 || _oldest[set]) { fillRAM(true); _oldest[set] = false; return; } if (location2 == -1 || !_oldest[set]) { fillRAM(false); _oldest[set] = true; return; } }); _ptrs.simulate = sim; glfwSetCursorPosCallback(_window, [](GLFWwindow* win, double x, double y) { glfwPointers* ptrs = (glfwPointers*)glfwGetWindowUserPointer(win); ptrs->file->cursorMoveCallback(win, x, y); ptrs->simulate->cursorMoveCallback(win, x, y); }); glfwSetMouseButtonCallback(_window, [](GLFWwindow* win, int button, int action, int mods) { glfwPointers* ptrs = (glfwPointers*)glfwGetWindowUserPointer(win); ptrs->file->mouseCallback(win, button, action, mods); ptrs->simulate->mouseCallback(win, button, action, mods); }); _objs.push_back(mainAddr); _objs.push_back(mainData); _objs.push_back(memTitle); _objs.push_back(mainAddrTitle); _objs.push_back(mainDataTitle); _objs.push_back(RAMtitle); _objs.push_back(setTitle); _objs.push_back(tagTitle1); _objs.push_back(dataTitle1); _objs.push_back(tagTitle2); _objs.push_back(dataTitle2); _objs.push_back(loadFile); _objs.push_back(_location); _objs.push_back(sim); _objs.push_back(_msg); _lastUsed = glm::vec2(0.0f, 0.0f); glfwSetWindowUserPointer(_window, &_ptrs); } GLWindow::~GLWindow() { for (auto i : _objs) { delete i; } delete holder; delete of; glfwDestroyWindow(_window); glfwTerminate(); } void GLWindow::start() { for (auto i : _objs) { i->setup(); } while (!glfwWindowShouldClose(_window)) { double currentTime = glfwGetTime(); glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); for (auto i : _objs) i->update(currentTime); //Draw all objects for (auto i : _objs) i->draw(_mat); glfwSwapBuffers(_window); glfwPollEvents(); } glCheckError(); } void GLWindow::onGLFWError(int error, const char * description) { std::cerr << description << std::endl; }
41ab4fa2006eca91d40997a8e7fcb3d64fd2f004
[ "Markdown", "C++" ]
5
Markdown
Jaynard2/CacheSimulator
16fb6dcb70e63ceadbd3701a20c8e1bd6c818db9
838be2c63fcf498fe9a9d40ef76796d0d3c6ad62
refs/heads/main
<repo_name>xadorfr/bind9-to-cloudflare<file_sep>/env.sample.php <?php $cfEmail = ''; // account cloudflare email $cfKey = ''; // global api key : https://dash.cloudflare.com/profile/api-tokens $cfAccountId = ''; // visible in the url of account homepage https://dash.cloudflare.com/56465416841... => take the 56465416841... part <file_sep>/delete-pending-zones.php #!/usr/bin/env php <?php require __DIR__ . '/env.php'; function errorHandler($errno, $errstr, $errfile, $errline) { if (error_reporting() == 0) { return; } throw new Exception("ERROR l.$errline ($errfile) : $errstr\n"); } set_error_handler('errorHandler'); chdir(__DIR__); $authHeaders = "-H \"X-Auth-Key: $cfKey\" -H \"X-Auth-Email: $cfEmail\""; $cmd = "curl -s -X GET $authHeaders -H \"Content-Type: application/json\" \"https://api.cloudflare.com/client/v4/zones?per_page=50\""; $raw = shell_exec($cmd); $zones = json_decode($raw); //$zones = json_decode(file_get_contents(__DIR__ . '/zones.json')); //echo 'nb domaines : ' . count($zones->result); foreach($zones->result as $zone) { // echo $zone->name . ' : ' . implode(' ', $zone->name_servers) . "\n"; if($zone->status !== 'pending') continue; // only delete pending domains echo $zone->name . "\n"; /* DANGER ZONE ! */ $cmd = "curl -s -X DELETE $authHeaders -H \"Content-Type: application/json\" \"https://api.cloudflare.com/client/v4/zones/{$zone->id}\""; $raw = shell_exec($cmd); $res = json_decode($raw); if(count($res->errors) > 0) { echo " failed\n"; } else { echo " deleted\n"; } sleep(5); } <file_sep>/list-dns.php #!/usr/bin/env php <?php $domains = file('jobs/domains.txt'); foreach ($domains as $line) { $domain = trim($line); echo "$domain..."; $cmd = "whois $domain|grep -i '^Name Server:'|awk '{print $3}'"; $res = shell_exec($cmd); if(empty($res)) { $cmd = "whois $domain|grep -i '^nserver:'|awk '{print $2}'"; $res = shell_exec($cmd); } echo str_replace("\n", ' ', $res) . "\n"; } <file_sep>/README.md BIND9 to Cloudflare === PHP script wrapping curl calls to the v4 API of Cloudflare to import a list of domain with their records (BIND zone file). - Populate `job/domains.txt` with one domain per line - Copy/Paste the zone files into `jobs/` (the script awaits that zones file names are in the shape `[domain].host`) - `./import.php` <file_sep>/import.php #!/usr/bin/env php <?php require __DIR__ . '/env.php'; function errorHandler($errno, $errstr, $errfile, $errline) { if (error_reporting() == 0) { return; } throw new Exception("ERROR l.$errline ($errfile) : $errstr\n"); } set_error_handler('errorHandler'); chdir(__DIR__); $domains = file('jobs/domains.txt'); try { foreach ($domains as $line) { $domain = trim($line); echo "import $domain..."; $authHeaders = "-H \"X-Auth-Key: $cfKey\" -H \"X-Auth-Email: $cfEmail\""; $cmd = "curl -s -X POST $authHeaders -H \"Content-Type: application/json\" \"https://api.cloudflare.com/client/v4/zones\""; $cmd .= " --data '{\"account\": {\"id\": \"$cfAccountId\"}, \"name\":\"$domain\",\"jump_start\":false}'"; $resp = json_decode(shell_exec($cmd)); if(count($resp->errors) > 0) { echo "errors : \n"; foreach($resp->errors as $err) { echo $err->message . "\n"; } continue; } sleep(2); // rate-limit CF $idZone = $resp->result->id; $zoneFile = "jobs/$domain.hosts"; while(true) { $cmd = "curl -s -X POST $authHeaders \"https://api.cloudflare.com/client/v4/zones/$idZone/dns_records/import\""; $cmd .= " --form 'file=@$zoneFile' --form 'proxied=false'"; $raw = shell_exec($cmd); $resp = json_decode($raw); if($resp == false) { // usually 429 => rate-limit CF echo $raw . "\n"; sleep(10); continue; } break; } if(count($resp->errors) > 0) { echo "errors : \n"; foreach($resp->errors as $err) { echo $err->message . "\n"; } continue; } echo "ok ! ({$resp->result->total_records_parsed} records)\n"; sleep(2); // rate-limit CF } } catch (Exception $e) { echo (string) $e; exit(1); }
760538e26e6ffa2461cb46d82c804f118dfb1c84
[ "Markdown", "PHP" ]
5
PHP
xadorfr/bind9-to-cloudflare
d8c201866edfa400d8125e3e03db37b85f14061f
f7a9976a74352b18f52835c732d0427200b6aad6
refs/heads/master
<repo_name>AlaaAlsayyed/UserManagement<file_sep>/UserManagement/Models/SearchUserModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UserManagement.Models { public class SearchUserModel { public string name { get; set; } public string username { get; set; } public string addressZipcode { get; set; } public string companyName { get; set; } } }<file_sep>/UserManagement/Controllers/UsersController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using UserManagement.Models; using UserManagement.Services; namespace UserManagement.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly UserService _usersService; public UsersController(UserService userService) { _usersService = userService; } /// <summary> /// List all users in mongo db /// </summary> /// <returns></returns> [HttpGet] public ActionResult<List<User>> Get() { return _usersService.Get(); } /// <summary> /// Get user by id /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id:length(24)}", Name = "GetUser")] public ActionResult<User> Get(string id) { var User = _usersService.Get(id); if (User == null) { return NotFound(); } return User; } /// <summary> /// insert new user in Users collection /// </summary> /// <param name="user"></param> /// <returns></returns> [HttpPost] public ActionResult<User> Create(User user) { _usersService.Create(user); return CreatedAtRoute("GetUser", new { id = user.Id.ToString() }, user); } /// <summary> /// get users who are matching the filter criteria /// </summary> /// <param name="search"></param> /// <returns></returns> [HttpPost("search")] public ActionResult<List<User>> Search(SearchUserModel search) { var matchingUsers = _usersService.Get(); if (!string.IsNullOrEmpty(search.name)) matchingUsers = matchingUsers.Where(k => k.name.Contains(search.name)).ToList(); if (!string.IsNullOrEmpty(search.username)) matchingUsers = matchingUsers.Where(k => k.username.Contains(search.username)).ToList(); if (!string.IsNullOrEmpty(search.companyName)) matchingUsers = matchingUsers.Where(k => k.company != null && k.company.name.Contains(search.companyName)).ToList(); if (!string.IsNullOrEmpty(search.addressZipcode)) matchingUsers = matchingUsers.Where(k => k.address != null && k.address.zipcode.Contains(search.addressZipcode)).ToList(); return matchingUsers; } /// <summary> /// replace user who has this id with current current users /// </summary> /// <param name="id"></param> /// <param name="UserIn"></param> /// <returns></returns> [HttpPut("{id:length(24)}")] public IActionResult Update(string id, User UserIn) { var User = _usersService.Get(id); if (User == null) { return NotFound(); } _usersService.Update(id, UserIn); return NoContent(); } /// <summary> /// Delete user who has this id /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id:length(24)}")] public IActionResult Delete(string id) { var User = _usersService.Get(id); if (User == null) { return NotFound(); } _usersService.Remove(User.Id); return NoContent(); } } }<file_sep>/UserManagement/Services/UserService.cs using Microsoft.Extensions.Configuration; using MongoDB.Driver; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using UserManagement.Models; namespace UserManagement.Services { public class UserService { private readonly IMongoCollection<User> _users; public UserService(IConfiguration config) { var client = new MongoClient(config.GetConnectionString("UsersDb")); var database = client.GetDatabase("UsersDb"); _users = database.GetCollection<User>("Users"); } public List<User> Get() { var users = _users.Find(k => true).ToList(); if(users.Count == 0) { using (WebClient httpClient = new WebClient()) { var jsonData = httpClient.DownloadString("https://jsonplaceholder.typicode.com/users"); var data = JsonConvert.DeserializeObject<IEnumerable<User>>(jsonData); foreach( var user in data) { Create(user); } users = _users.Find(k => true).ToList(); } } return users; } public User Get(string id) { return _users.Find<User>(k => k.Id == id).FirstOrDefault(); } public User Create(User user) { user.Id = null; _users.InsertOne(user); return user; } public void Update(string id, User userIn) { _users.ReplaceOne(k => k.Id == id, userIn); } public void Remove(User userIn) { _users.DeleteOne(k => k.Id == userIn.Id); } public void Remove(string id) { _users.DeleteOne(k => k.Id == id); } } }
02c0534cfecbc2da803611daaeab9eee3885d81c
[ "C#" ]
3
C#
AlaaAlsayyed/UserManagement
4d6114380d2d4837c321704beac3ed14e897ae0a
4c0f75a2a39dd9302c506a87b8a1c80ba888aa63
refs/heads/master
<file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Runtime; using NUnit.Framework; namespace TestDs3.Runtime { [TestFixture] public class TestHttpHelper { [Test] public void TestUrlEncode() { Assert.AreEqual("abc%20/%E4%BB%BD", HttpHelper.PercentEncodePath("abc /份")); } } } <file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using System.Collections.Generic; using System.Linq; namespace TestDs3.Lang { internal class LangTestHelpers { public static IEnumerable<string> RandomStrings(int stringCount, int stringSizes) { var chars = Enumerable.Range(0, 26).Select(i => (char)('a' + i)).ToArray(); return RandomStrings(new Random(), stringCount, stringSizes, chars).ToArray(); } public static IEnumerable<string> RandomStrings(Random rand, int stringCount, int stringSizes, char[] chars) { var buffer = new char[stringSizes]; for (int i = 0; i < stringCount; i++) { PopulateWithRandom(rand, buffer, chars); yield return new String(buffer); } } private static void PopulateWithRandom<T>(Random rand, T[] dest, T[] allowed) { for (int i = 0; i < dest.Length; i++) { dest[i] = allowed[rand.Next(allowed.Length)]; } } } } <file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using System.Collections.Generic; using System.IO; using Ds3.Models; using Ds3.Runtime; namespace Ds3.Helpers.Transferrers { internal class PartialDataTransferrerDecorator : ITransferrer { private readonly int _retries; private readonly ITransferrer _transferrer; internal PartialDataTransferrerDecorator(ITransferrer transferrer, int retries = 5) { _transferrer = transferrer; _retries = retries; } public void Transfer(IDs3Client client, string bucketName, string objectName, long blobOffset, Guid jobId, IEnumerable<Range> ranges, Stream stream, IMetadataAccess metadataAccess, Action<string, IDictionary<string, string>> metadataListener, int objectTransferAttempts) { var currentTry = 0; var transferrer = _transferrer; var tRanges = ranges; while (true) { try { transferrer.Transfer(client, bucketName, objectName, blobOffset, jobId, tRanges, stream, metadataAccess, metadataListener, objectTransferAttempts); return; } catch (Ds3ContentLengthNotMatch ex) { BestEffort.ModifyForRetry(stream, objectTransferAttempts, ref currentTry, objectName, blobOffset, ref tRanges, ref transferrer, ex); } catch (Exception ex) { if (ExceptionClassifier.IsRecoverableException(ex)) { BestEffort.ModifyForRetry(stream, _retries, ref currentTry, objectName, blobOffset, ex); } else { throw; } } } } } }<file_sep>using System.IO; using System.Text; using Ds3.Lang; using NUnit.Framework; using TestDs3.Helpers; namespace TestDs3.Lang { [TestFixture] internal class TestStreamsUtil { [Test] public void TestBufferedCopyTo() { const string message = "This is a test string to make sure we are buffering correctly"; var messageStream = new MockStream(message); var dstStream = new MemoryStream(); StreamsUtil.BufferedCopyTo(messageStream, dstStream, 10); var testMessage = new UTF8Encoding(false).GetString(dstStream.GetBuffer(), 0, (int) dstStream.Length); Assert.AreEqual(message, testMessage); } } }<file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Calls; using Ds3.Helpers.Jobs; using Ds3.Helpers.Transferrers; using Ds3.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Ds3.Helpers.Strategies; using Ds3.Runtime; namespace Ds3.Helpers { public class Ds3ClientHelpers : IDs3ClientHelpers { private readonly IDs3Client _client; private const JobRequestType JobTypePut = JobRequestType.PUT; private const JobRequestType JobTypeGet = JobRequestType.GET; private readonly int _retryAfter; //Negative represent infinite number private readonly int _objectTransferAttempts; //Negative number represents infinite number of retries private readonly int _jobRetries; private readonly int _jobWaitTime; //in minutes private readonly long? _maximumFileSizeForAggregating; public Ds3ClientHelpers(IDs3Client client, int retryAfter = -1, int objectTransferAttempts = 5, int jobRetries = -1, int jobWaitTime = 5, long? maximumFileSizeForAggregating = null) { this._client = client; this._retryAfter = retryAfter; this._objectTransferAttempts = objectTransferAttempts; this._jobRetries = jobRetries; this._jobWaitTime = jobWaitTime; this._maximumFileSizeForAggregating = maximumFileSizeForAggregating; } public IJob StartWriteJob(string bucket, IEnumerable<Ds3Object> objectsToWrite, long? maxBlobSize = null, IHelperStrategy<string> helperStrategy = null) { var withAggregation = false; var request = new PutBulkJobSpectraS3Request( bucket, VerifyObjectCount(objectsToWrite) ); if (maxBlobSize.HasValue) { request.WithMaxUploadSize(maxBlobSize.Value); } if (_maximumFileSizeForAggregating.HasValue && GetJobSize(objectsToWrite) <= _maximumFileSizeForAggregating.Value) { withAggregation = true; request.Aggregating = true; } PutBulkJobSpectraS3Response jobResponse = null; var retriesLeft = this._jobRetries; do { try { jobResponse = this._client.PutBulkJobSpectraS3(request); } catch (Ds3MaxJobsException) { if (retriesLeft == 0) { throw; } retriesLeft--; Thread.Sleep(this._jobWaitTime*1000*60); } } while (jobResponse == null); if (helperStrategy == null) { helperStrategy = new WriteRandomAccessHelperStrategy(this._retryAfter, withAggregation); } return FullObjectJob.Create( this._client, jobResponse.ResponsePayload, helperStrategy, new WriteTransferrer(), _objectTransferAttempts ); } private static long GetJobSize(IEnumerable<Ds3Object> objectsToWrite) { return objectsToWrite.Where(objectToWrite => objectToWrite.Size != null) .Sum(objectToWrite => objectToWrite.Size.Value); } public IJob StartReadJob(string bucket, IEnumerable<Ds3Object> objectsToRead, IHelperStrategy<string> helperStrategy = null) { if (helperStrategy == null) { helperStrategy = new ReadRandomAccessHelperStrategy<string>(this._retryAfter); } var processingOrder = JobChunkClientProcessingOrderGuarantee.NONE; if (helperStrategy.GetType() == typeof(ReadStreamHelperStrategy)) { processingOrder = JobChunkClientProcessingOrderGuarantee.IN_ORDER; } var jobResponse = this._client.GetBulkJobSpectraS3( new GetBulkJobSpectraS3Request(bucket, VerifyObjectCount(objectsToRead)) .WithChunkClientProcessingOrderGuarantee(processingOrder) ); return FullObjectJob.Create( this._client, jobResponse.ResponsePayload, helperStrategy, new PartialDataTransferrerDecorator(new ReadTransferrer(), _objectTransferAttempts) ); } public IPartialReadJob StartPartialReadJob( string bucket, IEnumerable<string> fullObjects, IEnumerable<Ds3PartialObject> partialObjects, IHelperStrategy<Ds3PartialObject> helperStrategy = null ) { var partialObjectList = new SortedSet<Ds3PartialObject>(partialObjects); var fullObjectList = fullObjects.ToList(); if (partialObjectList.Count + fullObjectList.Count == 0) { throw new InvalidOperationException(Resources.NoObjectsToTransferException); } if (helperStrategy == null) { helperStrategy = new ReadRandomAccessHelperStrategy<Ds3PartialObject>(this._retryAfter); } var processingOrder = JobChunkClientProcessingOrderGuarantee.NONE; if (helperStrategy.GetType() == typeof(ReadStreamHelperStrategy)) { processingOrder = JobChunkClientProcessingOrderGuarantee.IN_ORDER; } var jobResponse = this._client.GetBulkJobSpectraS3( new GetBulkJobSpectraS3Request(bucket, fullObjectList, partialObjectList) .WithChunkClientProcessingOrderGuarantee(processingOrder) ); return PartialReadJob.Create( this._client, jobResponse.ResponsePayload, fullObjectList, partialObjectList, helperStrategy, _objectTransferAttempts ); } private static List<T> VerifyObjectCount<T>(IEnumerable<T> objects) { var objectList = objects.ToList(); if (objectList.Count == 0) { throw new InvalidOperationException(Resources.NoObjectsToTransferException); } return objectList; } public IJob StartReadAllJob(string bucket, IHelperStrategy<string> helperStrategy = null) { return this.StartReadJob(bucket, this.ListObjects(bucket), helperStrategy); } public IEnumerable<Ds3Object> ListObjects(string bucketName) { return ListObjects(bucketName, null); } public IEnumerable<Ds3Object> ListObjects(string bucketName, string keyPrefix) { var isTruncated = false; string marker = null; do { var request = new GetBucketRequest(bucketName) { Marker = marker, Prefix = keyPrefix }; var response = _client.GetBucket(request).ResponsePayload; isTruncated = response.Truncated; marker = response.NextMarker; var responseObjects = response.Objects.ToList() as IList<Contents> ?? response.Objects.ToList(); foreach (var ds3Object in responseObjects) { yield return new Ds3Object(ds3Object.Key, ds3Object.Size); } } while (isTruncated); } public static readonly Func<Ds3Object, bool> FolderFilterPredicate = obj => !obj.Name.EndsWith("/"); public static readonly Func<Ds3Object, bool> ZeroLengthFilterPredicate = obj => obj.Size != 0; public static IEnumerable<Ds3Object> FilterDs3Objects(IEnumerable<Ds3Object> objects, params Func<Ds3Object, bool>[] predicates) { if (predicates == null) return objects; var result = objects; for (var i = 0; i < predicates.Length; i++) { var predicate = predicates[i]; if (predicate == null) continue; result = result.Where(obj => predicate.Invoke(obj)); } return result; } public void EnsureBucketExists(string bucketName) { var headResponse = _client.HeadBucket(new HeadBucketRequest(bucketName)); if (headResponse.Status == HeadBucketResponse.StatusType.DoesntExist) { _client.PutBucket(new PutBucketRequest(bucketName)); } } public IJob RecoverWriteJob(Guid jobId, IHelperStrategy<string> helperStrategy = null) { var jobResponse = this._client.ModifyJobSpectraS3(new ModifyJobSpectraS3Request(jobId)).ResponsePayload; if (jobResponse.Status == JobStatus.COMPLETED) { throw new InvalidOperationException(Resources.JobCompletedException); } if (jobResponse.RequestType != JobTypePut) { throw new InvalidOperationException(Resources.ExpectedPutJobButWasGetJobException); } if (helperStrategy == null) { helperStrategy = new WriteRandomAccessHelperStrategy(this._retryAfter, false); } return FullObjectJob.Create( this._client, jobResponse, helperStrategy, new WriteTransferrer() ); } public IJob RecoverReadJob(Guid jobId, IHelperStrategy<string> helperStrategy = null) { var jobResponse = this._client.ModifyJobSpectraS3(new ModifyJobSpectraS3Request(jobId)).ResponsePayload; if (jobResponse.Status == JobStatus.COMPLETED) { throw new InvalidOperationException(Resources.JobCompletedException); } if (jobResponse.RequestType != JobTypeGet) { throw new InvalidOperationException(Resources.ExpectedGetJobButWasPutJobException); } if (helperStrategy == null) { helperStrategy = new ReadRandomAccessHelperStrategy<string>(this._retryAfter); } return FullObjectJob.Create( this._client, jobResponse, helperStrategy, new ReadTransferrer() ); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ds3.Calls; using Moq; namespace TestDs3.Helpers.Strategies.ChunkStrategies { public static class AllocateMock { public static AllocateJobChunkSpectraS3Request Allocate(Guid chunkId) { return Match.Create( r => r.JobChunkId == chunkId.ToString(), () => new AllocateJobChunkSpectraS3Request(chunkId) ); } public static GetJobChunksReadyForClientProcessingSpectraS3Request AvailableChunks(Guid jobId) { return Match.Create( r => r.Job == jobId.ToString(), () => new GetJobChunksReadyForClientProcessingSpectraS3Request(jobId) ); } } } <file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using System.Collections.Generic; using System.IO; using Ds3.Models; namespace Ds3.Helpers.Transferrers { internal interface ITransferrer { void Transfer(IDs3Client client, string bucketName, string objectName, long blobOffset, Guid jobId, IEnumerable<Range> ranges, Stream stream, IMetadataAccess metadataAccess, Action<string, IDictionary<string, string>> metadataListener, int objectTransferAttempts); } }<file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Collections.Generic; using Ds3.Helpers; using NUnit.Framework; namespace TestDs3.Helpers { [TestFixture] public class TestMetadataUtils { [Test] public void TestGetUriEscapeMetadataWithEmptyDic() { var emptyMetadata = new Dictionary<string, string>(); CollectionAssert.AreEqual(emptyMetadata, MetadataUtils.GetUriEscapeMetadata(new Dictionary<string, string>())); } [Test] public void TestGetUriEscapeMetadataWithEnglishDic() { var metadata = new Dictionary<string, string> { {"key1", "value1"}, {"key 2", "value 2"} }; var expected = new Dictionary<string, string> { {"key1", "value1"}, {"key%202", "value%202"} }; CollectionAssert.AreEqual(expected, MetadataUtils.GetUriEscapeMetadata(metadata)); } [Test] public void TestGetUriEscapeMetadataWithHebrewDic() { var metadata = new Dictionary<string, string> { {"מפתח 1", "ערך 1"}, {"מפתח 2", "ערך 2"} }; var expected = new Dictionary<string, string> { {"%D7%9E%D7%A4%D7%AA%D7%97%201", "%D7%A2%D7%A8%D7%9A%201"}, {"%D7%9E%D7%A4%D7%AA%D7%97%202", "%D7%A2%D7%A8%D7%9A%202"} }; CollectionAssert.AreEqual(expected, MetadataUtils.GetUriEscapeMetadata(metadata)); } [Test] public void TestGetUriUnEscapeMetadataWithEmptyDic() { var emptyMetadata = new Dictionary<string, string>(); CollectionAssert.AreEqual(emptyMetadata, MetadataUtils.GetUriUnEscapeMetadata(new Dictionary<string, string>())); } [Test] public void TestGetUriUnEscapeMetadataWithEnglishDic() { var expected = new Dictionary<string, string> { {"key1", "value1"}, {"key 2", "value 2"} }; var metadata = new Dictionary<string, string> { {"key1", "value1"}, {"key%202", "value%202"} }; CollectionAssert.AreEqual(expected, MetadataUtils.GetUriUnEscapeMetadata(metadata)); } [Test] public void TestGetUriUnEscapeMetadataWithHebrewDic() { var expected = new Dictionary<string, string> { {"מפתח 1", "ערך 1"}, {"מפתח 2", "ערך 2"} }; var metadata = new Dictionary<string, string> { {"%D7%9E%D7%A4%D7%AA%D7%97%201", "%D7%A2%D7%A8%D7%9A%201"}, {"%D7%9E%D7%A4%D7%AA%D7%97%202", "%D7%A2%D7%A8%D7%9A%202"} }; CollectionAssert.AreEqual(expected, MetadataUtils.GetUriUnEscapeMetadata(metadata)); } } } <file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using System.Collections.Generic; using System.IO; using Ds3.Calls; using Ds3.Models; namespace Ds3.Helpers.Transferrers { internal class WriteTransferrer : ITransferrer { public void Transfer(IDs3Client client, string bucketName, string objectName, long blobOffset, Guid jobId, IEnumerable<Range> ranges, Stream stream, IMetadataAccess metadataAccess, Action<string, IDictionary<string, string>> metadataListener, int objectTransferAttempts) { var currentTry = 0; while (true) { var request = new PutObjectRequest(bucketName, objectName, stream) .WithJob(jobId) .WithOffset(blobOffset); if (blobOffset == 0 && metadataAccess != null) { request.WithMetadata(MetadataUtils.GetUriEscapeMetadata(metadataAccess.GetMetadataValue(objectName))); } try { client.PutObject(request); return; } catch (Exception ex) { if (ExceptionClassifier.IsRecoverableException(ex)) { BestEffort.ModifyForRetry(stream, objectTransferAttempts, ref currentTry, request.ObjectName, request.Offset.Value, ex); } else { throw; } } } } } }<file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Collections.Generic; using System.IO; using NUnit.Framework; using Moq; using Ds3; using Ds3.Runtime; using Ds3.Helpers.Transferrers; using Range = Ds3.Models.Range; namespace TestDs3.Helpers.Transferrers { [TestFixture] internal class TestPartialDataTransferrerDecorator { [Test] public void TestZeroRetries() { var client = new Mock<IDs3Client>(MockBehavior.Strict); MockHelpers.SetupGetObjectWithContentLengthMismatchException(client, "bar", 0L, "ABCDEFGHIJ", 20L, 10L); // The initial request is for all 20 bytes, but only the first 10 will be sent try { var stream = new MemoryStream(200); var exceptionTransferrer = new ReadTransferrer(); var decorator = new PartialDataTransferrerDecorator(exceptionTransferrer, 0); decorator.Transfer(client.Object, JobResponseStubs.BucketName, "bar", 0, JobResponseStubs.JobId, new List<Range>(), stream, null, null, 0); Assert.Fail(); } catch (Ds3NoMoreRetransmitException ex) { var expectedMessage = string.Format(Resources.NoMoreRetransmitException, "0", "bar", "0"); Assert.AreEqual(expectedMessage, ex.Message); Assert.AreEqual(0, ex.Retries); } } [Test] public void Test1Retries() { var client = new Mock<IDs3Client>(MockBehavior.Strict); MockHelpers.SetupGetObjectWithContentLengthMismatchException(client, "bar", 0L, "ABCDEFGHIJ", 20L, 10L); MockHelpers.SetupGetObjectWithContentLengthMismatchException(client, "bar", 0L, "ABCDEFGHIJ", 20L, 10L, Range.ByPosition(9, 19)); try { var stream = new MemoryStream(200); var exceptionTransferrer = new ReadTransferrer(); var retries = 1; var decorator = new PartialDataTransferrerDecorator(exceptionTransferrer, retries); decorator.Transfer(client.Object, JobResponseStubs.BucketName, "bar", 0, JobResponseStubs.JobId, new List<Range>(), stream, null, null, retries); Assert.Fail(); } catch (Ds3NoMoreRetransmitException ex) { var expectedMessage = string.Format(Resources.NoMoreRetransmitException, "1", "bar", "0"); Assert.AreEqual(expectedMessage, ex.Message); Assert.AreEqual(1, ex.Retries); } } } } <file_sep>/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Text; using NUnit.Framework; using Ds3.Helpers.Streams; using System.IO; namespace TestDs3.Helpers.Streams { [TestFixture] class TestPutObjectRequestStream { const int CopyBufferSize = 1; byte[] byteStringSize26 = Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyz"); byte[] first10Bytes = Encoding.UTF8.GetBytes("abcdefghij"); byte[] second10Bytes = Encoding.UTF8.GetBytes("klmnopqrst"); byte[] last6Bytes = Encoding.UTF8.GetBytes("uvwxyz"); [Test] public void TestCopyToInOrder() { var stream = new MemoryStream(byteStringSize26); Assert.AreEqual( GetRequestedStream(stream, 0, 10), new MemoryStream(first10Bytes)); Assert.AreEqual( GetRequestedStream(stream, 10, 10), new MemoryStream(second10Bytes)); Assert.AreEqual( GetRequestedStream(stream, 20, 6), new MemoryStream(last6Bytes)); } [Test] public void TestCopyToNotInOrder() { var stream = new MemoryStream(byteStringSize26); Assert.AreEqual( GetRequestedStream(stream, 10, 10), new MemoryStream(second10Bytes)); Assert.AreEqual( GetRequestedStream(stream, 20, 6), new MemoryStream(last6Bytes)); Assert.AreEqual( GetRequestedStream(stream, 0, 10), new MemoryStream(first10Bytes)); } private Stream GetRequestedStream(Stream source, long offset, long lenght) { var putObjectRequestStream = new ObjectRequestStream(source, offset, lenght); var requestStream = new MemoryStream(); if (putObjectRequestStream.Position != 0) { putObjectRequestStream.Seek(0, SeekOrigin.Begin); } putObjectRequestStream.CopyTo(requestStream, CopyBufferSize); return requestStream; } } }
72054e57148f6c4fd7c2e82edde33a0b1e94f2a7
[ "C#" ]
11
C#
rpmoore/ds3_net_sdk
73a754e7db2e4007600665b0d568fec47ed074dc
4a8d31c7e4fba231eab644929635fbc571947bcc
refs/heads/master
<repo_name>boyInFocus/faceDetector<file_sep>/FaceDetector/DLog.h /*! * @file DLog.h * @author <NAME> <<EMAIL>> * @version 1.0 * @Created by Justin on 2017/1/11. * @section DESCRIPTION * Define the log format */ //#ifndef UvcTest_DLog_h //#define UvcTest_DLog_h // DLog(@"here"); or DLog(@"value: %d", x); #ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif
fdf36991026ddb1b4436ba87fa20433fff3208af
[ "C" ]
1
C
boyInFocus/faceDetector
3e40bf07f8f6ff0a5e13a1f585ade5f9005e8716
1f4796f19b30b66015cc95955aed7af47ba48c3c
refs/heads/master
<file_sep>computer_please_do_you_happen_to_know_the_time_please_thank_you_meow ========== Aliases "computer_please_do_you_happen_to_know_the_time_please_thank_you_meow" to "now" in the Time and DateTime classes. Examples: Time.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow => the current time DateTime.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow => the current date and time computer_please_hold_on_could_you_please_wait_this_many_seconds_for_me(2) => sleeps for two seconds [![Build Status](https://travis-ci.org/coleww/computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.svg?branch=master)](https://travis-ci.org/coleww/computer_please_do_you_happen_to_know_the_time_please_thank_you_meow) <file_sep>require 'bundler/setup' Bundler.setup require 'computer_please_do_you_happen_to_know_the_time_please_thank_you_meow' describe 'right_computer_please_do_you_happen_to_know_the_time_please_thank_you_meow' do describe "Time#computer_please_do_you_happen_to_know_the_time_please_thank_you_meow" do it "matches at the same instant" do computer_please_do_you_happen_to_know_the_time_please_thank_you_meow = Time.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow now = Time.now expect(now.to_i).to eq(computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.to_i) end it "does not match at a different instant" do computer_please_do_you_happen_to_know_the_time_please_thank_you_meow = Time.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow sleep(1) now = Time.now expect(now.to_i).not_to eq(computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.to_i) end end describe "DateTime#computer_please_do_you_happen_to_know_the_time_please_thank_you_meow" do it "matches at the same instant" do computer_please_do_you_happen_to_know_the_time_please_thank_you_meow = DateTime.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow now = DateTime.now expect(now.to_time.to_i).to eq(computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.to_time.to_i) end it "does not match at a different instant" do computer_please_do_you_happen_to_know_the_time_please_thank_you_meow = DateTime.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow sleep(1) now = DateTime.now expect(now.to_time.to_i).not_to eq(computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.to_time.to_i) end end describe "#computer_please_hold_on_could_you_please_wait_this_many_seconds_for_me" do it "sleeps n seconds" do pre = Time.now computer_please_hold_on_could_you_please_wait_this_many_seconds_for_me(1) post = Time.now expect(post.to_i).to eq(pre.to_i + 1) end end describe "#computer_please_cease_all_operations_something_terrible_has_occurred_in_regard_to_the" do it "raises an error" do expect {computer_please_cease_all_operations_something_terrible_has_occurred_in_regard_to_the('test') }.to raise_error('test') end end end<file_sep>Gem::Specification.new do |s| s.name = 'computer_please_do_you_happen_to_know_the_time_please_thank_you_meow' s.version = '0.1.0' s.date = '2014-09-02' s.summary = "Time.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow" s.description = "Aliases .computer_please_do_you_happen_to_know_the_time_please_thank_you_meow to .now, computer_please_hold_on_could_you_please_wait_this_many_seconds_for_me to sleep." s.authors = ["<NAME>", "<NAME>", "<NAME>"] s.email = "<EMAIL>" s.files = ["lib/computer_please_do_you_happen_to_know_the_time_please_thank_you_meow.rb"] s.homepage = 'https://github.com/coleww/computer_please_do_you_happen_to_know_the_time_please_thank_you_meow' s.license = 'MIT' s.add_development_dependency "rspec" end<file_sep>require 'date' class Time def self.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow self.now end end class DateTime def self.computer_please_do_you_happen_to_know_the_time_please_thank_you_meow self.now end end alias computer_please_cease_all_operations_something_terrible_has_occurred_in_regard_to_the raise alias computer_please_hold_on_could_you_please_wait_this_many_seconds_for_me sleep
42f249dada700627d1a36fc613dae35ff9095e29
[ "Markdown", "Ruby" ]
4
Markdown
coleww/computer_please_do_you_happen_to_know_the_time_please_thank_you_meow
659a01f112b961852b32cb42b0f763d7966909d1
5b03ea83df53da71ff991dc9fcf165e59b59d1a0
refs/heads/master
<repo_name>storify/sweetpotato<file_sep>/static/js/script.js /* Author: */ var pFilters = []; function getDate(dateStr) { var d; dateStr = (typeof dateStr == 'undefined') ? '' : ''+dateStr; // Make sure it is a string if(dateStr.length > 3 && dateStr.substr(10,1)=="T") { dateStr = dateStr.substring(0,19).replace('T',' ').replace(/\-/g,'/'); d = new Date(dateStr); d = Math.round((d.getTime() - (d.getTimezoneOffset()*60*1000)) /1000); } else { d = (dateStr.length > 0) ? new Date(dateStr) : new Date(); // Math.round((new Date(tweet.created_at)).getTime()/1000); d = Math.round((d.getTime()) /1000); } return d; }; function displayDate(date,relative) { var date = ''+date; if(parseInt(date,10) > 0) { if(date.length==10) { date = parseInt(date,10)*1000; } } else { // Date string are not as flexible on Webkit than Gecko... if(date.substr(10,1)=='T') { if(date.substr(date.length-1,1)=='Z') { date = Date.UTC(parseInt(date.substr(0,4),10),parseInt(date.substr(5,2),10)-1,parseInt(date.substr(8,2),10),parseInt(date.substr(11,2),10),parseInt(date.substr(14,2),10),parseInt(date.substr(17,2),10)); } else { date = (date.substr(16,1)==':') ? date.substr(0,19) : date.substr(0,16); date = date.replace('T',' ').replace(/\-/g,'/'); } } } var j=new Date(); var f=new Date(date); //if(B.ie) { f = Date.parse(h.replace(/( \+)/," UTC$1")) } if(relative) { var i=j-f; var c=1000,d=c*60,e=d*60,g=e*24,b=g*7; if(isNaN(i)||i<0){return"";} if(i<c*7){return"right now";} if(i<d){return Math.floor(i/c)+" seconds ago";} if(i<d*2){return"about 1 minute ago";} if(i<e){return Math.floor(i/d)+" minutes ago";} if(i<e*2){return"about 1 hour ago";} if(i<g){return Math.floor(i/e)+" hours ago";} //if(i>g&&i<g*2){return"yesterday"} //if(i<g*365){return Math.floor(i/g)+" days ago"} } var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var curr_date = f.getDate(); var curr_month = f.getMonth(); var curr_year = f.getFullYear(); var curr_minutes = f.getMinutes(); if(curr_minutes<10) curr_minutes = '0'+curr_minutes; return m_names[curr_month] + " "+curr_date+", " + curr_year + ' at '+f.getHours()+':'+curr_minutes; }; function togglePotatoes(pType) { if (pFilters.indexOf(pType) > -1) { pFilters.splice(pFilters.indexOf(pType),1); } else { pFilters.push(pType); } console.log(pFilters.join(",")); $(pFilters.join(",")).hide('slow'); $("#potatoes li").not($(pFilters.join(","))).show('slow'); } $(document).ready(function() { $('#bugs').live('click',function(e){ $(this).toggleClass('selected'); togglePotatoes('.bug'); return false; }); $('#features').live('click',function(e){ $(this).toggleClass('selected'); togglePotatoes('.feature'); return false; }); $('#todos').live('click',function(e){ $(this).toggleClass('selected'); togglePotatoes('.todo'); return false; }); $('#to-users').live('click',function(e){ $('#to-users-list').toggle('fast'); return false; }); $('#from-users').live('click',function(e){ $('#from-users-list').toggle('fast'); return false; }); $('.user').live('click',function(e){ var thisUser = $(this).attr('id'); $(this).toggleClass('selected'); togglePotatoes("."+thisUser); return false; }); $('#potatoes li').live('hover',function(e){ $(this).find('.bake').toggle(); }); io.setPath('/client/'); socket = new io.Socket(null, { port: 8081 ,transports: ['websocket', 'htmlfile', 'xhr-multipart', 'xhr-polling'] }); socket.connect(); $('.bake').live('click', function(e) { e.preventDefault(); socket.send('{"bake_potato":true,"potato_id":'+$(this).parents('li').attr('id')+'}'); $(this).parents('li').remove(); return false; }); socket.on('message', function(data){ var potato = $.parseJSON( data ); if(potato.bake_potato) { $('#'+potato.potato_id).remove(); } else { var classString = "to-" + potato.to.replace("@",'') + " " + potato.category.replace("#",'') + " from-" + potato.from.replace("@",''); $('#potatoes').prepend('<li id="'+potato.id+'" class="'+classString+'"><h3>' + potato.to + ": " + potato.category + ' <a class="bake" href="#">Bake it</a></h3><span class="task">' + potato.msg +"</span><h6> Assigned by " + potato.from + " on " + displayDate(potato.created_at) + '</h6></li>'); } }); socket.on('connect', function(data){ console.log(data); }); }); <file_sep>/server.js // setup Dependencies require(__dirname + "/lib/setup").ext( __dirname + "/lib").ext( __dirname + "/lib/express/support"); var connect = require('connect') , express = require('express') , sys = require('sys') , io = require('Socket.IO-node') , hbs = require('hbs') , _ = require('underscore').underscore , OAuth = require('oauth').OAuth , mongoose = require('mongoose').Mongoose , fs = require('fs') , config = JSON.parse(fs.readFileSync("./config.json","utf8")) , max_id = 0 , port = 8081 ; // Setup Mongoose // Connect to the Mongo Server var db = mongoose.connect('mongodb://localhost:27017/SweetPotato'); // Create the Potato model mongoose.model('Potato', { collection : 'potatoes', properties : ['id','msg','to','from','hashtag','category','created_at','completed_at','yam'], indexes : ['id','to','completed_at','created_at','category'] }); db.potatoes = db.model('Potato'); // Connect to Yammer using oAuth var oauth_credentials = config.oauth_credentials || {}; var oa = new OAuth( 'https://www.yammer.com/oauth/request_token', 'https://www.yammer.com/oauth/access_token', config.CONSUMER_KEY, config.CONSUMER_SECRET, '1.0',null,'HMAC-SHA1' ); // Setup Express var server = express.createServer(); server.configure(function(){ server.set('views', __dirname + '/views'); server.use(connect.bodyDecoder()); server.use(connect.staticProvider(__dirname + '/static')); server.use(server.router); server.set("view engine", "hbs"); }); // setup the errors server.error(function(err, req, res, next){ if (err instanceof NotFound) { res.render('404.hbs', { locals: { title : 'SweetPotato - 404' ,description: 'Bake your to do\'s' ,author: 'Storify' },status: 404 }); } else { res.render('500.hbs', { locals: { title : 'SweetPotato - Server Error' ,description: 'Bake your to do\'s' ,author: 'Storify' ,error: err },status: 500 }); } }); // Listen on the port assigned above server.listen(port); /////////////////////////////////////////// // Utils // /////////////////////////////////////////// /////// ADD ALL YOUR UTILITY FUNCTIONS HERE ///////// // A util function to help output strings and variables to the console var debug = function(str,obj) { var r = (obj) ? str+' '+sys.inspect(obj) : str; console.log(r); } function linkify(text) { if( !text ) return text; text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){ nice = url; if( url.match('^https?:\/\/') ) { nice = nice.replace(/^https?:\/\//i,'') } else url = 'http://'+url; return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>'; }); return text; } // A function to find all stored Potatoes and send them via Socket.io to the client function sendStoredPotatoes(client){ db.potatoes.find({'completed_at':null}).sort([['created_at','ascending']]).all(function(potatoes){ for (p in potatoes) { potatoes[p].msg = potatoes[p].yam.body.plain.replace(potatoes[p].to,'').replace(potatoes[p].category,''); client.send(JSON.stringify({ to : potatoes[p].to, from : potatoes[p].from, msg : linkify(potatoes[p].msg), category : potatoes[p].category, created_at: potatoes[p].created_at, completed_at: potatoes[p].completed_at, hashtag : potatoes[p].hashtag, id : potatoes[p].id })); } }); } function bakePotato(client, id){ db.potatoes.find({"id":id}).first(function(potato){ potato.completed_at = new Date(); potato.save(); client.broadcast({"potato_deleted":id}); }); } /////////////////////////////////////////// // Socket.io // /////////////////////////////////////////// // Setup Socket.IO and send all stored Potatoes upon connection var io = io.listen(server); io.on('connection', function(client){ debug('Client Connected'); sendStoredPotatoes(client); client.on('message', function(message){ message = JSON.parse(message); if(message.bake_potato){ bakePotato(client, message.potato_id); } client.broadcast(message); }); client.on('disconnect', function(){ debug('Client Disconnected.'); }); }); /////////////////////////////////////////// // Routes // /////////////////////////////////////////// /////// ADD ALL YOUR ROUTES HERE ///////// // Our one and only user facing route, this sets up the filter menu, gets us hooked into Socket.io and listens for new Potatoes server.get('/', function(req,res){ db.potatoes._collection.distinct("to",function(err,toUsers){ for (var i in toUsers) { toUsers[i] = toUsers[i].replace("@",''); } db.potatoes._collection.distinct("from",function(err,fromUsers){ for (var i in fromUsers) { fromUsers[i] = fromUsers[i].replace("@",''); } res.render('index.hbs', { locals : { to_users : toUsers ,from_users : fromUsers ,title : 'SweetPotato' ,description : 'Bake your to do list.' ,author : 'Storify' } }); }); }); }); // TODO @xdamman || @dshaw: Please document this route server.get('/auth',function(req,res) { oa.getOAuthRequestToken(function(error,oauth_token,oauth_token_secret,results) { if(error) { debug('error:',error); } else { oauth_credentials = {token: oauth_token, secret: oauth_token_secret}; var endpoint = 'https://www.yammer.com/oauth/authorize?oauth_token='+oauth_token; debug('redirecting to '+endpoint); res.redirect(endpoint); } }); }); // TODO @xdamman || @dshaw: Please document this route server.get('/oauth/access_token',function(req,res) { var oauth_verifier = req.param('oauth_verifier'); debug('Using oauth_verifier: '+oauth_verifier,oauth_credentials); oa.getOAuthAccessToken(oauth_credentials.token,oauth_credentials.secret,oauth_verifier,function(error, oauth_access_token, oauth_access_token_secret,results) { if(error) { debug('error: ',error); } else { oauth_credentials.access_token = oauth_access_token; oauth_credentials.access_token_secret = oauth_access_token_secret; debug('Yeah: ',oauth_credentials); } }) }); // TODO @xdamman || @dshaw: Please document this function get_latest_yams = function(newer_than_id,callback) { oa.get('https://www.yammer.com/api/v1/messages.json?newer_than='+max_id,oauth_credentials.access_token,oauth_credentials.access_token_secret,function(err,json) { var feed = JSON.parse(json); var references = feed.references; var userInfo = {}; for (var i in references) { if(references[i].type=='user') { userInfo[references[i].id] = references[i]; } } var r = []; for (var i in feed.messages) { var result = feed.messages[i]; max_id = (result.id > max_id) ? result.id : max_id; result.from = '@'+userInfo[result.sender_id].name; r.push(result); } return callback(r); }); } // Check Yammer for new Yams every 30 seconds, if there are any, check to see if they are Potatoes // If they are a Potatoes, save them to mongo and broadcast them to the clients db.potatoes.find().sort([['id','descending']]).first(function(p) { max_id = (p && p.id > 0) ? p.id : 0; debug('max_id: '+max_id); setInterval(function() { get_latest_yams(max_id,function(yams) { for (var i=0, len=yams.length; i < len; i++) { var msg = yams[i].body.plain; var to = msg.match(/(@[a-z0-9]{1,15})/i) || ["","@unassigned"]; if((category=msg.match(/(#(feature|bug|todo))/i))) { debug('Adding message :\t'+msg); var plainPotato = { id : yams[i].id, yam : yams[i], to : to[1], from : yams[i].from, category : category[1], created_at : new Date(yams[i].created_at), completed_at: null, msg : yams[i].body.plain }; var potato = new db.potatoes(plainPotato); potato.save(); plainPotato.msg = linkify(plainPotato.msg.replace(plainPotato.to,'').replace(plainPotato.category,'')); io.broadcast(JSON.stringify(plainPotato)); } }; }); },1000*10); }); // A Route for Creating a 500 Error (Useful to keep around) server.get('/500', function(req, res){ throw new Error('This is a 500 Error'); }); // The 404 Route (ALWAYS Keep this as the last route) server.get('/*', function(req, res){ throw new NotFound; }); // Create the not found error function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } debug('Listening on :' + port ); <file_sep>/README.md Sweet Potato ------------------ Simple bug and feature tracking with Yammer. #Install npm install oauth mongoose
cf7f101c6a682ba0a95cb49dd121819cb1b3c7ad
[ "JavaScript", "Markdown" ]
3
JavaScript
storify/sweetpotato
a565afce565707ad53f01388848b7901092f0c80
b07cdee5bab0e064e5d1f3a8fc35d6944846fa39
refs/heads/master
<file_sep>import Vue from "vue"; new Vue({ })
d4b2740a04cd8242eafaa513815377e8aeb45484
[ "JavaScript" ]
1
JavaScript
FarinaYasmin/laravelvue_authentication
14b65d3d9b855ce3780145f13dc37368208c841e
67a75a852beccd945f51683893ac08c6d0213bcc
refs/heads/master
<repo_name>iRaphi/Tr0llCMD<file_sep>/src/me/iRaphi/tr0ll/tr0ll.java package me.iRaphi.tr0ll; import java.io.IOException; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Creeper; import org.bukkit.entity.Enderman; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.kitteh.tag.TagAPI; import Listener.FallListener; import Listener.FreezeListener; import Listener.IAListener; import Listener.TagListener; import Metrics.Metrics; @SuppressWarnings({ "deprecation", "unused", "unchecked", "rawtypes" }) public class tr0ll extends JavaPlugin { public void onDisable() { System.out.println("[Tr0llCMD] Tr0llCMD Disabled!"); } public void onEnable() { try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( } loadConfig(); PluginDescriptionFile info = getDescription(); System.out.println("[Tr0llCMD] You are using Version " + info.getVersion()); registerEvents(); System.out.println("[Tr0llCMD] was Enabled."); } String updatemsg = "§3Theres a new §eTr0llCMD §3at BukkitDev! Get it now!"; String cmd1 = "trollcmd.cmd"; String no = "§cError: Player not found / not Online."; String title = "§f=§c=§f=§c=§f=§c=§f=§c=§f=§c= §6Tr0llCMD §f=§c=§f=§c=§f=§c=§f=§c=§f=§c="; public ArrayList<String> fall = new ArrayList(); public ArrayList<String> freezed = new ArrayList(); private TagListener tagl; private IAListener ial; private FallListener fl; private FreezeListener frl; public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { Player p = (Player)sender; if ((cmd.getName().equalsIgnoreCase("tr0llcmd"))){ if (p.hasPermission(this.cmd1)) { if (args.length == 0) { p.sendMessage(title); p.sendMessage("§6/troll §ckill §e[player]"); p.sendMessage("§6/troll §cop §e[player]"); p.sendMessage("§6/troll §cdeop §e[player]"); p.sendMessage("§6/troll §cslow §e[player]"); p.sendMessage("§6/troll §crandom §e[player]"); p.sendMessage("§6/troll §crocket §e[player]"); p.sendMessage("§6/troll §cpumpkin §e[player]"); p.sendMessage("§6/troll §chelp §e<1|2>"); p.sendMessage(title); } if (args.length == 1) { if ((args[0].equalsIgnoreCase("kill")) || (args[0].equalsIgnoreCase("random")) || (args[0].equalsIgnoreCase("boss")) || (args[0].equalsIgnoreCase("slenderman")) || (args[0].equalsIgnoreCase("explode")) || (args[0].equalsIgnoreCase("creep")) || (args[0].equalsIgnoreCase("slow")) || (args[0].equalsIgnoreCase("op")) || (args[0].equalsIgnoreCase("deop")) || (args[0].equalsIgnoreCase("pumpkin")) || (args[0].equalsIgnoreCase("rocket"))) { p.sendMessage("§cError: You have to put in a player."); } else if (args[0].equalsIgnoreCase("showtroll")) { p.sendMessage("§cError: Not enough arguments."); } else if (args[0].equalsIgnoreCase("help")) { p.sendMessage(title); p.sendMessage("§6/troll §ckill §e[player]"); p.sendMessage("§6/troll §cop §e[player]"); p.sendMessage("§6/troll §cdeop §e[player]"); p.sendMessage("§6/troll §cslow §e[player]"); p.sendMessage("§6/troll §crandom §e[player]"); p.sendMessage("§6/troll §crocket §e[player]"); p.sendMessage("§6/troll §cpumpkin §e[player]"); p.sendMessage("§6/troll §chelp §e<1|2>"); p.sendMessage(title); } else { p.sendMessage("§cError: That Argument was not found for §6/troll"); } } if (args.length == 2) { if (args[0].equalsIgnoreCase("help")) { if (args[1].equalsIgnoreCase("1")) { p.sendMessage(title); p.sendMessage("§6/troll §ckill §e[player]"); p.sendMessage("§6/troll §cop §e[player]"); p.sendMessage("§6/troll §cdeop §e[player]"); p.sendMessage("§6/troll §cslow §e[player]"); p.sendMessage("§6/troll §crandom §e[player]"); p.sendMessage("§6/troll §crocket §e[player]"); p.sendMessage("§6/troll §cpumpkin §e[player]"); p.sendMessage("§6/troll §chelp §e<1|2>"); p.sendMessage(title); } else if (args[1].equalsIgnoreCase("2")) { p.sendMessage(title); p.sendMessage("§6/troll §cexplode §e[player]"); p.sendMessage("§6/troll §ccreep §e[player]"); p.sendMessage("§6/troll §cburn §e[player] §7// Player may die due to burn damage"); p.sendMessage("§6/troll §cfreeze §e[player]"); p.sendMessage("§6/troll §cshowtroll §a[on|off] §7// Shows that this was a troll."); p.sendMessage(title); } else { p.sendMessage("§cError: That argument was not found for §6/troll help"); } } if(args[0].equalsIgnoreCase("freeze")){ Player o = Bukkit.getPlayer(args[1]); if(o != null && o.isOnline()){ freezed.add(o.getName()); p.sendMessage("Troll sent to §e"+o.getName()); final Player pp = p; final Player oo = o; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { freezed.remove(pp.getName()); pp.sendMessage("§e"+oo.getName()+"§f is no longer freezed."); } }, 100L); }else{ p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if(args[0].equalsIgnoreCase("burn")){ Player o = Bukkit.getPlayer(args[1]); if(o != null && o.isOnline()){ o.getWorld().strikeLightning(o.getLocation()); o.setFireTicks(100); p.sendMessage("Troll sent to §e"+o.getName()); }else{ p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("creep")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { World w = o.getWorld(); Creeper creeper = (Creeper)w.spawnEntity(o.getLocation(), EntityType.CREEPER); creeper.setPowered(true); Creeper creeper2 = (Creeper)w.spawnEntity(o.getLocation(), EntityType.CREEPER); creeper2.setPowered(true); creeper2.setMaxHealth(100); creeper2.setHealth(100); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("explode")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { TNTPrimed tnt = (TNTPrimed)o.getWorld().spawn(o.getEyeLocation(), TNTPrimed.class); tnt.setVelocity(o.getLocation().getDirection().multiply(0)); tnt.setFuseTicks(10); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("kill")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { o.setHealth(0); o.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("Messages.kill"))); p.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("Messages.killsender") + " " + o.getName())); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("slow")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { o.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 200, 1)); o.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 1)); o.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, 200, 4)); o.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 200, 4)); o.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 200, 2)); p.sendMessage("Troll sent to §e" + o.getName()); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("rocket")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { //o.sendMessage("§7God: §oWhat are you doing up here?"); -- Removed it temp. because it look more of a bug now. p.sendMessage("Troll sent to §e" + o.getName()); World w = o.getLocation().getWorld(); double x = o.getLocation().getX(); double y = 255.0; double z = o.getLocation().getZ(); o.teleport(new Location(w, x, y, z)); o.getWorld().playEffect(new Location(w, x, y, z), Effect.MOBSPAWNER_FLAMES, 10); //Playing Effects for the World now. fall.add(o.getName()); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("pumpkin")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { //o.sendMessage("§6§o§lHappy Halloween!"); -- Removed the Halloween text because.. its not halloween anymore :) p.sendMessage("Troll sent to §e" + o.getName()); if(o.getInventory().getHelmet() != null){ ItemStack a = o.getInventory().getHelmet(); o.getWorld().dropItem(o.getLocation(), a); o.getInventory().setHelmet(new ItemStack(Material.PUMPKIN, 1)); o.playSound(o.getLocation(), Sound.CHICKEN_EGG_POP, 10, 10); }else{ o.getInventory().setHelmet(new ItemStack(Material.PUMPKIN, 1)); } } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("op")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { o.sendMessage("§7§o[CONSOLE: Opped " + o.getDisplayName() + "]"); p.sendMessage("Troll sent to §e" + o.getName()); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("deop")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { o.sendMessage("§eYou are no longer OP!"); p.sendMessage("Troll sent to §e" + o.getName()); } else { p.sendMessage(this.no); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } if (args[0].equalsIgnoreCase("random")) { Player o = Bukkit.getPlayer(args[1]); if ((o != null) && (o.isOnline())) { int r1 = (int)(Math.random() * 9 + 1); if (r1 == 1) { o.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 200, 1)); o.sendMessage("§7Can you see me?"); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cBLINDNESS"); } else if (r1 == 2) { o.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, 200, 1)); o.sendMessage("§7From Heaven."); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cABSORPTION"); } else if (r1 == 3) { o.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 1)); o.sendMessage("§7Catfood is so bad.."); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cCONFUSION"); } else if (r1 == 4) { o.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 1)); o.sendMessage("§7I feel like Chuck Norris..!"); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cDMG_RESTITANCE"); } else if (r1 == 5) { o.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, 200, 1)); o.sendMessage("§7I'm so hungry.."); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cHUNGER"); } else if (r1 == 6) { o.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 200, 1)); o.sendMessage("§7IM ON SPEED."); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cSPEED"); } else if (r1 == 7) { o.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 200, 1)); o.sendMessage("§7Am I Spiderman?"); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cPOISON"); } else if (r1 == 8) { o.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 200, 1)); o.sendMessage("§7FIRE ON MY HAND"); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cFAST_DIGGING"); } else if (r1 == 9) { o.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20, 1)); o.sendMessage("§7Healed"); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cHEAL"); } else if (r1 == 10) { o.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 200, 1)); o.sendMessage("§7I feel so much stronger now."); p.sendMessage("Troll sent to §e" + o.getName() + " §fEffect: §cSTRENGTH"); } if (getConfig().getString("troll.showtroll").contentEquals("on")) { o.sendMessage("You just got trolled by §e" + p.getName() + "§f!"); } } else { p.sendMessage(this.no); } } if (args[0].equalsIgnoreCase("showtroll")) { if (args[1].equalsIgnoreCase("on")) { getConfig().set("troll.showtroll", "on"); saveConfig(); p.sendMessage("Now, the player gets informed that he was trolled."); } else if (args[1].equalsIgnoreCase("off")) { getConfig().set("troll.showtroll", "off"); saveConfig(); p.sendMessage("Now, the player no longer gets informed that he was trolled."); } else { p.sendMessage("§cError: Unknown Arguments given."); } } } } else { p.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("Messages.noperm"))); } } if (cmd.getName().equalsIgnoreCase("trollnick")) { if (args.length == 0) { p.sendMessage(title); p.sendMessage("§6/trollnick §e[name|off]"); p.sendMessage("§c§oTo use the full Nick System, you have to"); p.sendMessage("§c§oInstall '§cTagAPI§c§o'."); p.sendMessage(title); } if (args.length == 1) { if (args[0].equalsIgnoreCase("off")) { p.setDisplayName(p.getName()); p.setPlayerListName(p.getName()); TagAPI.refreshPlayer(p); p.sendMessage("§eYour new Name is: §b" + p.getName()); } else if (args[0].equalsIgnoreCase("name")) { p.sendMessage("§eYou can't use the Name 'name'."); } else if (p.hasPermission("troll.nick")) { try { p.setPlayerListName(ChatColor.translateAlternateColorCodes('&', "&f" + args[0])); p.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&f" + args[0])); p.setCustomName(ChatColor.translateAlternateColorCodes('&', "&f" + args[0])); TagAPI.refreshPlayer(p); p.sendMessage("§eYour new name is now: §b" + args[0]); } catch (Exception e) { p.sendMessage("§eUser '§c" + args[0] + "§e' already online."); p.setPlayerListName(p.getName()); } } else { p.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("Messages.noperm"))); } } } return false; } public void loadConfig() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } getConfig().addDefault("cfgver", "1"); getConfig().addDefault("troll.showtroll", "on"); getConfig().addDefault("Messages.kill", "&fYou got killed by &eHerobrine"); getConfig().addDefault("Messages.killsender", "&fYou Killed:"); getConfig().addDefault("Messages.noperm", "&cYou are not allowed to do this."); getConfig().options().copyDefaults(true); saveConfig(); } public void registerEvents() { this.ial = new IAListener(this); this.tagl = new TagListener(this); this.fl = new FallListener(this); this.frl = new FreezeListener(this); } } <file_sep>/README.md Tr0llCMD ======== Tr0llCMD Plugin for Bukkit ======== Welcome to my Project page. What you see here is my project Tr0llCMD. Have fun looking at the code. <file_sep>/src/Listener/FallListener.java package Listener; import me.iRaphi.tr0ll.tr0ll; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; public class FallListener implements Listener { private tr0ll plugin; public FallListener(tr0ll plugin) { this.plugin = plugin; plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler public void onEntityDamage(EntityDamageEvent event) { if ((event.getEntity() instanceof Player)) { Player player = (Player)event.getEntity(); if ((plugin.fall.contains(player.getName())) && (event.getCause().equals(EntityDamageEvent.DamageCause.FALL))) { event.setCancelled(true); plugin.fall.remove(player.getName()); } } } } <file_sep>/src/Listener/FreezeListener.java package Listener; import me.iRaphi.tr0ll.tr0ll; import org.bukkit.Effect; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; public class FreezeListener implements Listener { private tr0ll plugin; public FreezeListener(tr0ll plugin) { this.plugin = plugin; plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler public void onWalk(PlayerMoveEvent e){ Player p = e.getPlayer(); if(plugin.freezed.contains(p.getName())){ e.setCancelled(true); p.getWorld().playEffect(p.getLocation().add(0.0D, 1.0D, 0.0D), Effect.STEP_SOUND, 79); } } }
0a65f096b94d9d1e44b646f20c84dc085a35a610
[ "Markdown", "Java" ]
4
Java
iRaphi/Tr0llCMD
e13b08789c849e30213ac25463f53694ba40b3ce
90f0cb949bd0aaf991e1da666e15a9e76f95b315
refs/heads/master
<file_sep><?php namespace Hiraeth\Sentry; use Hiraeth; use SlashTrace\Sentry\SentryHandler; /** * {@inheritDoc} */ class SentryHandlerDelegate implements Hiraeth\Delegate { /** * {@inheritDoc} */ static public function getClass(): string { return SentryHandler::class; } /** * {@inheritDoc} */ public function __invoke(Hiraeth\Application $app): object { return new SentryHandler($app->getEnvironment('SENTRY.DSN')); } } <file_sep><?php namespace Hiraeth\Sentry; use Hiraeth; use SlashTrace\Sentry\SentryHandler; /** * {@inheritDoc} */ class ApplicationProvider implements Hiraeth\Provider { /** * {@inheritDoc} */ static public function getInterfaces(): array { return [ Hiraeth\Application::class ]; } /** * {@inheritDoc} */ public function __invoke($instance, Hiraeth\Application $app): object { if ($app->getEnvironment('SENTRY.DSN', NULL)) { $app->setHandler(SentryHandler::class); } return $instance; } } <file_sep>This package provides Sentry support for the Hiraeth nano Framework. ## Setup In order to register the sentry handler, you'll have to add it to your environment: ```js [SENTRY] DSN = <your sentry dsn> ```
4ca6a170e1537a18467c1bafcdf2bea113296743
[ "Markdown", "PHP" ]
3
PHP
hiraeth-php/sentry
c789c4163e10ec00c14bdbf7a4916811ce5a8630
20efd5eebb1ea63353b93b33968787e11bc8523b
refs/heads/master
<repo_name>Youssouf/statsbibliotek<file_sep>/src/com/company/Main.java package com.company; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // write your code here int[] tenInteger = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[][] hoursWork = {{3, 2, 5, 6, 8}, {3, 2, 1, 6, 8}, {3, 2, 5, 6, 4}}; ArrayList<String> myStringOne = new ArrayList<>(); List<Integer> myStringTwo = new ArrayList<>(); for (int s : tenInteger) { myStringTwo.add(s); } for (int v : myStringTwo) { System.out.println(v); } int mySum = 0; for (int i = 0; i < 5; i++) { mySum = mySum + i; } System.out.println("The sum is " + mySum); System.out.println("The size or rows of Array is " + hoursWork.length); System.out.println("The number og colunms are " + hoursWork[0].length); System.out.println("The size or row of tenInteger is " + tenInteger.length); myStringOne.add("The new String is not good for me "); Person person = new Person(); Person person1 = new Person(); Person p1 = new Person(); Person person2 = new Person(1,"you", "souare", "Wondy"); Person person3 = new Person(); Person p5 = new Person(); Person p6 = new Person(2, "Youssouf", "Souare", "Denmark"); List<Person> newPerson = new ArrayList<Person>(); newPerson.add(p6); newPerson.add(person2); for (Person p : newPerson) { System.out.println(p.toString()); } } }
91a6bc7bb380e4fab2932fe5ced3a388e2da56d1
[ "Java" ]
1
Java
Youssouf/statsbibliotek
e0986fb22f13158db3b3f62670cb840973cb5942
af03ed121e685ba672b06760ca10cd93b0caf904
refs/heads/master
<repo_name>Charlene717/Getting-and-Cleaning-Data-Course-Project<file_sep>/run_analysis.R #FINAL PROYECT # -------- Step1 ---------------- #Merges the training and the test sets to create one data set. ## Fist we have to download the zip file an then unzip it. if(!file.exists("./data")){dir.create("./data")} #We create a new directory if doesn´t exist called data where we will save the files tf <-"./data/dataset.zip" ; td <- "./data" Urlzip<- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file( Urlzip , tf , mode = "wb" ) files.data <- unzip( tf , exdir = td ) ## Now we are going to read each txt file listed and paste them to build a single data setwd("./data/UCI HAR Dataset") namestrain<-list.files( "train", full.names = TRUE )[-1] namestest<-list.files( "test" , full.names = TRUE )[-1] Train<-lapply(namestrain,read.table,header=FALSE ) Test<-lapply(namestest,read.table,header=FALSE ) data1<- mapply ( rbind, Train, Test )#Paste below the train dat, the test data data<-cbind(data1[[1]],data1[[2]],data1[[3]]) #Unique data # ------ Step2 ------------------ #Extracts only the measurements on the mean and standard deviation for each measurement. ## First we have to name each column between 2:562 because the fisrt one is the subject column and the last one is the activity ## The names of these columns is in is alredy part of a list so we only have to assign them to the column library(data.table) columnsnames <- fread( list.files()[2], header = FALSE, stringsAsFactor = FALSE ) setnames(data,c(1:563),c("subject", columnsnames$V2,"activity")) ## We use regular expression to extract the columns that contains the word std or mean followed by (), nad we start in teh second column, because the first one is alredy taken dataf<-data[,c(1,grep( "std|mean\\(\\)", columns$V2 ) + 1,563)] str(dataf) # Chhecking the data # ------ Step3 ---------- #Uses descriptive activity names to name the activities in the data set namesact <- fread( list.files()[1], header = FALSE, stringsAsFactor = FALSE ) dataf$activity <- namesact$V2[ match( dataf$activity, namesact$V1 ) ] # ------ Step4 -------- #From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. tidydata<-aggregate(dataf[,2:67],by=list(dataf$subject,dataf$activity),FUN=mean) # ----- Step5 ------ #Write the new data in a txt file write.table(tidydata,"tidydat.txt",row.name=FALSE) #Extraemos los datos del zip file <file_sep>/README.md # Getting-and-Cleaning-Data-Course-Project This is the final proyect to pass the course Getting and Cleaning Data from Coursera This repository has three main parts that work together in order to complete the final task that is getting a clean data that can be used in deeper analysis. **CODE BOOK** This part describes the variables, the data, and any transformations or work that I performed to clean up the data. **run anslysis.R** This contains the script to run the code and obtain the final data that its called tidy data **tidy data** Final data, alredy clean and understandable.
29da45123ade533d02e4d8fea601866895d8f3af
[ "Markdown", "R" ]
2
R
Charlene717/Getting-and-Cleaning-Data-Course-Project
a159d118a23ced4ac99d5fd6fbfdeadd07c8bad0
35ce9308aa6db2823902cc698fba42329983ba65
refs/heads/master
<repo_name>Auston/codeeval<file_sep>/Split_The_Number.py import sys def split_the_number(text): if '+' in text: n_str, s_str = text.split(' ') index = s_str.find('+') return int(n_str[:index]) + int(n_str[index:]) elif '-' in text: n_str, s_str = text.split(' ') index = s_str.find('-') return int(n_str[:index]) - int(n_str[index:]) def main(): with open(sys.argv[1]) as f: for line in f: print split_the_number(line.strip()) if __name__ == '__main__': main() <file_sep>/Roman_Numerals.py import sys coding = zip( [1000,900,500,400,100,90,50,40,10,9,5,4,1], ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] ) def roman_numerals(text): res = '' num = int(text) for d, r in coding: while num >= d: res += r num -= d return res def main(): with open(sys.argv[1]) as f: for line in f: print roman_numerals(line.strip()) if __name__ == '__main__': main() <file_sep>/Hex_to_Decimal.py import sys def hex_to_decimal(text): return int(text, 16) def main(): with open(sys.argv[1]) as f: for line in f: print hex_to_decimal(line.strip()) if __name__ == '__main__': main() <file_sep>/Query_Board.py import sys def query_board(action_list): board = [[0]*256]*256 for action in action_list: l = action.split(' ') if l[0] == 'SetCol': c = int(l[1]) for i in xrange(256): board[i][c] = int(l[2]) elif l[0] == 'SetRow': r = int(l[1]) board[r] = [int(l[2])] * 256 if 'QueryCol' in action_list[-1]: c = action_list[-1].split(' ')[-1] return sum([board[i][int(c)] for i in xrange(256)]) elif 'QueryRow' in action_list[-1]: r = action_list[-1].split(' ')[-1] return sum(board[int(r)]) def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() query = False action_list = [] for i in all_text: action = i.strip().split(' ')[0] action_list.append(i.strip()) if 'Query' in action: print query_board(action_list) if __name__ == '__main__': main() <file_sep>/Swap_Case.py import sys def swap_case(text): return ''.join([i.lower() if i.isupper() else i.upper() for i in text]) def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print swap_case(i.strip()) if __name__ == '__main__': main() <file_sep>/Beautiful_Strings.py import sys import collections import string def beautiful_strings(text): line = text.lower() l = collections.Counter(line) add = 26 beauty = 0 for key,value in l.most_common(): if key in string.letters[:26]: beauty += value*add add -= 1 return beauty def main(): with open(sys.argv[1]) as f: for line in f: print beautiful_strings(line.strip()) if __name__ == '__main__': main() <file_sep>/Sum_of_Primes.py def is_prime(n): if n < 2: return False elif n == 2: return True else: for j in range(2, n): if (n % j) == 0: return False return True prime_sum = 0 i = 2 count = 0 while True: if is_prime(i): count += 1 prime_sum += i i += 1 if count == 1000: break print prime_sum <file_sep>/Swap_Elements.py import sys def swap_list(a, b, l): l[a], l[b] = l[b], l[a] return l def swap_elements(text): squ, action = text.split(':') s_list = squ.strip().split(' ') #print 'list', s_list a_list = action.strip().split(',') #print 'action', a_list for action in a_list: s, e = (int(i) for i in action.split('-')) s_list = swap_list(s, e, s_list) #print s, e #print '' #print s_list res = ' '.join(s_list) return res def main(): with open(sys.argv[1]) as f: for line in f: print swap_elements(line.strip()) if __name__ == '__main__': main() <file_sep>/Shortest_Repetition.py import sys def shortest_repetition(text): x = '' for i in xrange(len(text)): x+=text[i] res = text.split(x) if filter(None, res) == []: return i+1 break def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print shortest_repetition(i.strip()) if __name__ == '__main__': main() <file_sep>/file_size.py import os import sys print os.stat(sys.argv[1])[6] <file_sep>/Reverse_Words.py import sys def reverse_words(text): return ' '.join(list(reversed(text.split(' ')))) def main(): with open(sys.argv[1]) as f: for line in f: print reverse_words(line.strip()) if __name__ == '__main__': main() <file_sep>/Data_Recovery.py import sys def data_recovery(text): words, numbers = text.split(';') word_list = words.split(' ') res = word_list[:] for n, i in enumerate(numbers.split(' ')): res[int(i)-1] = word_list[n] return ' '.join(res) def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print data_recovery(i.strip()) if __name__ == '__main__': main() <file_sep>/Compressed_Sequence.py import sys def compressed_sequence(text): s_list = text.split(' ') res = [] i = [0, s_list[0]] for s in s_list: if s == i[1]: i[0] += 1 else: res.extend([str(i[0]), i[1]]) i[1] = s i[0] = 1 res.extend([str(i[0]), i[1]]) return ' '.join(res) def main(): with open(sys.argv[1]) as f: for line in f: print compressed_sequence(line.strip()) if __name__ == '__main__': main() <file_sep>/Bit_Positions.py import sys def bit_positions(text): l = text.split(',') n, a, b = [int(i) for i in l] s = str(bin(n)) if s[-a] == s[-b]: return 'true' else: return 'false' return text def main(): with open(sys.argv[1]) as f: for line in f: print bit_positions(line.strip()) if __name__ == '__main__': main() <file_sep>/Minimum_Path_Sum.py import sys def minimum_path_sum(text): n = len(text[0]) res = [] for i in range(n): res.append(list(0 for i in range(n))) res[0][0] = text[0][0] for n in range(1, n): res[0][n] = sum(text[0][:n+1]) col = [text[i][0] for i in range(n+1)] for n in range(n+1): res[n][0] = sum(col[:n+1]) for i in range(1, n+1): for j in range(1, n+1): hoz = text[i][j] + res[i-1][j] ver = text[i][j] + res[i][j-1] res[i][j] = min(hoz, ver) return res[-1][-1] def main(): with open(sys.argv[1]) as f: l = 0 for line in f: if l == 0: l = int(line.strip()) matrix = [] continue row = line.strip().split(',') matrix.append([int(i) for i in row]) l -= 1 if l == 0: print minimum_path_sum(matrix) if __name__ == '__main__': main() <file_sep>/Simple_Sorting.py import sys def simple_sorting(text): l = [float(v) for v in text.split(' ')] return ' '.join([str(v) for v in sorted(l)]) def main(): with open(sys.argv[1]) as f: for line in f: print simple_sorting(line.strip()) if __name__ == '__main__': main() <file_sep>/Penultimate_Word.py import sys def penultimate_word(text): l = text.split(' ') if len(l)>=2: return text.split(' ')[-2] else: return None def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print penultimate_word(i.strip()) if __name__ == '__main__': main() <file_sep>/Find_a_Writer.py import sys def find_a_writer(text): s_list, n_list = text.split('|') number_list = [int(i) for i in n_list.strip().split(' ')] return ''.join([s_list[i-1] for i in number_list]) def main(): with open(sys.argv[1]) as f: for line in f: print find_a_writer(line.strip()) if __name__ == '__main__': main() <file_sep>/Set_Intersection.py import sys def set_intersection(text): a, b = text.split(';') l_a = a.split(',') l_b = b.split(',') l = list(set(l_a).intersection(set(l_b))) return ','.join(sorted(l)) def main(): with open(sys.argv[1]) as f: for line in f: print set_intersection(line.strip()) if __name__ == '__main__': main() <file_sep>/Find_Min.py import sys def calc_lower(m, b, c, r): return (b * m + c) % r def calc_higher(m,j,k): for i in range(max(m)+1): if i not in m[j-k:j]: return i return max(m)+1 def find_min(text): m = [] n, k, a, b, c, r = [int(i) for i in text.split(',')] m.append(a) for i in xrange(1, k): m.append(calc_lower(m[i-1], b, c, r)) for j in xrange(int(k), int(n)): m.append(calc_higher(m, int(j), int(k))) return m[-1] def main(): with open(sys.argv[1]) as f: for line in f: print find_min(line.strip()) if __name__ == '__main__': main() <file_sep>/Self_Describing_Numbers.py import collections, sys def is_self_describing_number(number): d = collections.Counter(str(number)) l = len(number) c = 0 for j in xrange(l): if d[str(j)] == int(number[j]): c += 1 if c == l: return 1 else: return 0 def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print is_self_describing_number(i.strip()) if __name__ == '__main__': main() <file_sep>/Hidden_Digits.py import sys def pick_hidden(w, letter): if w in letter: return str(letter.find(w)) elif w.isdigit(): return w else: return '' def hidden_digits(text): letter = 'abcdefjhij' res = ''.join([pick_hidden(i, letter) for i in text]) return res if res else 'NONE' def main(): with open(sys.argv[1]) as f: for line in f: print hidden_digits(line.strip()) if __name__ == '__main__': main() <file_sep>/Calculate_Distance.py import sys from math import sqrt def calculate_distance(text): x = text.split(' ') point_a_x = int(x[0][1:-1]) point_a_y = int(x[1][:-1]) point_b_x = int(x[2][1:-1]) point_b_y = int(x[3][:-1]) x = point_a_x - point_b_x y = point_a_y - point_b_y return int(sqrt(x*x + y*y)) def main(): with open(sys.argv[1]) as f: for line in f: print calculate_distance(line.strip()) if __name__ == '__main__': main() <file_sep>/Longest_Word.py import sys def longest_word(text): word_list = text.split(' ') num_list = [len(word) for word in word_list] return word_list[num_list.index(max(num_list))] def main(): if len(sys.argv) != 2: return file_name = sys.argv[1] all_text = [] with open(file_name, 'r') as f: all_text = f.readlines() for i in all_text: print longest_word(i.strip()) if __name__ == '__main__': main() <file_sep>/Happy_Numbers.py import sys def calculate_sum(num): return sum(int(i)*int(i) for i in num) def happy_numbers(text): n_list = [] while True: r = calculate_sum(text) if r == 1: return 1 if r in n_list: return 0 n_list.append(r) text = str(r) def main(): with open(sys.argv[1]) as f: for line in f: print happy_numbers(line.strip()) if __name__ == '__main__': main()
c3f47209c6dec4ae6fd683e191630207e5b0c437
[ "Python" ]
25
Python
Auston/codeeval
996a18c33f54fd212915f82daf51874a20029207
5ac8be78e696aaa6fd58065d2ccded9dec872fea
refs/heads/master
<file_sep># Jogo da velha em React Projeto acadêmico <file_sep>class Quadrado extends React.Component { constructor (props){ super (props); this.state = { value: props.value, }; console.log(props) } render (){ return ( <button className="quadrado" onClick={this.props.onClick} > {this.props.value} </button> ); } } function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } var temVazio = false; squares.forEach((quadrado) => { if (!quadrado) { temVazio = true; } }) if (!temVazio) { return 'Ninguém'; } return null; } class Tabuleiro extends React.Component{ constructor (props){ super (props); this.state = { quadrados: Array(9).fill(null), xIsNext: true }; } handleClick(i) { //faz uma cópia do vetor const quadrados = this.state.quadrados.slice(); if (calculateWinner (quadrados)){ alert ('Jogo já acabou'); return; } if (quadrados[i]){ alert ('Quadrado ocupado!') return; } quadrados[i] = this.state.xIsNext ? 'X' : '0'; this.setState ({ quadrados: quadrados, xIsNext: !this.state.xIsNext, }); } renderizarQuadrado (i){ return ( <Quadrado value={this.state.quadrados[i]} onClick={() => this.handleClick(i)} /> ); } render (){ const vencedor = calculateWinner (this.state.quadrados); let status; if (vencedor) { status = 'Vencedor: ' + vencedor; } else { status = 'Jogador: ' + (this.state.xIsNext ? 'X' : 'O'); } return ( <div> <br /> <button onClick={() => {location.reload();}}>Reiniciar</button><br /><br /> <button onClick={() => { if (!vencedor) { var ganhou = false; this.state.quadrados.forEach((quadrado, index) => { var quadradosSupostos = [...this.state.quadrados]; if (!quadrado) { quadradosSupostos[index] = this.state.xIsNext ? 'X' : '0'; if (calculateWinner(quadradosSupostos)) { this.handleClick(index); ganhou = true; } } }) if (!ganhou) { var selected = false; while (!selected) { var randomNumber = (Math.random() * 10).toFixed(); if (typeof this.state.quadrados[randomNumber] == "object" && !this.state.quadrados[randomNumber]) { this.handleClick(randomNumber); selected = true } } } } else { alert('jogo já acabou!') } }}>Jogada aleatória</button> <br /> <br /> <div className="status">{status}</div> <div className="board-row"> {this.renderizarQuadrado(0)} {this.renderizarQuadrado(1)} {this.renderizarQuadrado(2)} </div> <div className="board-row"> {this.renderizarQuadrado(3)} {this.renderizarQuadrado(4)} {this.renderizarQuadrado(5)} </div> <div className="board-row"> {this.renderizarQuadrado(6)} {this.renderizarQuadrado(7)} {this.renderizarQuadrado(8)} </div> </div> ); } } class Jogo extends React.Component { render () { return ( <div className="game"> <div className="game-board"> <Tabuleiro quadrados={Array(9).fill().map((value, pos) => pos)}/> </div> </div> ); } } ReactDOM.render ( <Jogo />, document.getElementById("root") );
dbebc1cac578bd3d31c0cc04900cc803b3397e9d
[ "Markdown", "JavaScript" ]
2
Markdown
leandrosabatini/jogoDaVelhaReact
eba18179005e0584ce390ebf0706d745595eb9be
cef1461b508fbc65db5382d2b41ba8680b1f8b55
refs/heads/master
<file_sep>// ConsoleApplication15.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <locale.h> using namespace std; int main() { setlocale(LC_ALL, "rus"); int n; do { cout << "Введите номер задания = "; cin >> n; if (n == 1) { cout << "1. Написать программу, которая вводит с клавиатуры одномерный массив из 5 целых чисел, после чего выводит количество ненулевых элементов. Перед вводом каждого элемента должна выводиться подсказка с номером элемента.\n\n"; int a[5], s = 0; for (int i = 0; i < 5; i++) { cout << "a[" << i + 1 << "] = "; cin >> a[i]; if (a[i] != 0) s++; } cout << "не нулевых элементов = " << s << endl << endl; } else if (n == 2) { cout << "2. Написать программу, которая выводит минимальный элемент введенного с клавиатуры массива целых чисел. Ниже приведен рекомендуемый вид экрана во время работы программы.\n\n"; cout << "Поиск минимального элемента массива.\nВведите в одной строке элементы массива через пробел (5 целых чисел)\nи нажмите <Enter>\n\n"; cout << "a[5] = "; int a[5]; int min_v = INT_MAX; for (int i = 0; i < 5; i++) { cin >> a[i]; if (a[i] < min_v) min_v = a[i]; } cout << "\nmin = " << min_v << endl << endl; } else if (n == 3) { cout << "3. Написать программу, которая вычисляет среднее арифметическое ненулевых элементов введенного с клавиатуры массива целых чисел.\n\n"; int a[10], s1 = 0, s = 0; float sr; cout << "Введите элементы массива (10 целых чисел черех пробел) в одной строке и нажмите <Enter>.\na[10] = "; for (int i = 0; i < 10; i++) { cin >> a[i]; if (a[i] != 0) { s++; s1 += a[i]; } } cout << "Сумма элементов массива = " << s1 << endl; cout << "Количество ненулевых элементов = " << s << endl; cout << "Среднее арифметическое ненулевых элементов = " << (float)s1 / s << endl << endl; } else if (n == 4) { cout << "4. Написать программу, которая вычисляет среднее арифметическое элементов массива без учета минимального и максимального элементов массива.\n\n"; cout << "Введите массив (10 целых чисел в одной строке)\na[10] = "; int a[10]; int min_v = INT_MAX; int max_v = INT_MIN; float res = 0; for (int i = 0; i < 10; i++) { cin >> a[i]; if (a[i] < min_v) min_v = a[i]; if (a[i] > max_v) max_v = a[i]; res += a[i]; } res = (res - min_v - max_v) / 8; cout << "min = " << min_v << endl; cout << "max = " << max_v << endl; cout << "среднее арифметическое = = " << res << endl; } else if (n == 5) { cout << "5. Написать программу, которая проверяет, находится ли введенное с клавиатуры число в массиве. Массив должен вводиться во время работы программы.\n\n"; int a[10] = { 5, 55, 66, 12, 7, 33, 22, 1, 99, 53 }; int x, y = 0; //cout << "Введите 10 элементов массива в строку\na[10] = "; cout << "введите число для проверки\n"; do { cout << "x = "; cin >> x; for (int i = 0; i < 10; i++) { if (x == a[i]) { y = 1; break; } else y = 0; } if (y == 1) cout << "данное число находится в массиве\n"; else cout << "данное число не находится в массиве\nвведите другое число!\n"; } while (y != 1); cout << endl; } else if (n == 6) { cout << "6. Написать программу, которая вычисляет, сколько раз введенное с клавиатуры число встречается в массиве.\n\n"; int x, a[10], sum = 0; cout << "заполните массив 10 значениями через пробел\na[10] = "; for (int i = 0; i < 10; i++) { cin >> a[i]; } cout << "Введите число\nx = "; cin >> x; for (int i = 0; i < 10; i++) { if (a[i] == x) sum++; } cout << "числел <" << x << "> в строке = " << sum << endl << endl; } else if (n == 7) { cout << "7. Написать программу, которая проверяет, есть ли во введенном с клавиатуры массиве элементы с одинаковым значением\n\n"; int a[10], x = 0; cout << "\nВведите 10 чисел массива\na[10] = "; for (int i = 0; i < 10; i++) { cin >> a[i]; } for (int i = 0; i < 10; i++) { for (int j = i + 1; j < 10; j++) { if (a[i] == a[j]) { x = 1; break; } } if (x == 1) { cout << "в данном массиве имеются повторяющиеся элементы\n\n"; break; } } if (x == 0) cout << "повторяющиеся элементы отсутсвуют!\n\n"; } else if (n == 8) { cout << "Написать программу, которая определяет количество учеников в классе, чей рост превышает средний.\n\n"; int a[100], s = 0, sum = 0, x = 0; float res; cout << "*** Анализ роста учеников ***\nВведите рост (см) и нажмите <Enter>.\nДля завершения введите 0 и нажмите <Enter>\n"; for (int i = 0; i < 100; i++) { cout << "--> "; cin >> a[i]; if (a[i] > 0) { s++; sum += a[i]; } else break; } res = sum / s; for (int i = 0; i < s; i++) { if (a[i] > res) x++; } cout << "\nсредний рост = " << res << endl; cout << "У " << x << " человек рост превышает средний!\n\n"; } else if (n == 9) { cout << "Написать программу, которая обрабатывает результаты экзамена. Для каждой оценки программа должна вычислить процент от общего количества оценок.\n\n"; int a[4]; int s = 0; float prc1; for (int i = 0; i < 4; i++) { switch (i) { case 0: cout << "Пятерок = "; break; case 1: cout << "Четверок = "; break; case 2: cout << "Троек = "; break; case 3: cout << "Двоек = "; break; } cin >> a[i]; s += a[i]; } prc1 = 100.0 / s; for (int i = 0; i < 4; i++) { switch (i) { case 0: cout << "Пятерок = "; break; case 1: cout << "Четверок = "; break; case 2: cout << "Троек = "; break; case 3: cout << "Двоек = "; break; } cout << prc1*a[i] << "%\n"; } cout << endl; } else if (n == 10) { cout << "Дан массив символов s1,..sn.Подсчитать сколько раз встречается в массиве символ К.\n\n"; char a[10]; char str = 'k'; int s = 0; int b = 0; cout << endl; cout << "Введите 10 символов\n"; for (char i = 0; i < 10; i++) { cout << "a[" << b << "] = "; cin >> a[i]; if (a[i] == str) { s++; } b++; } cout << "Символ <К> встречается " << s << " раз" << endl; } else if (n == 11) { cout << "Дан массив символов S1,...,Sn. Распечатать все буквы, непосредственно перед которыми находится буква С.\n\n"; char a[10], z; int b = 0; cout << "\nВведите 10 символов\n" << endl; for (char i = 0; i < 10; i++) { cout << "a[" << b << "] = "; cin >> a[i]; if (a[i] == 'c') { z = i; } b++; } cout << z << endl; for (char i = z + 1; i < 10; i++) { cout << a[i] << " "; } cout << endl << endl; } else if (n == 12) { cout << "Даны действительные числа а1,..a16. Получить min(a1*a9,a2*a10,...,a8*a16).\n\n"; int a[16], min_v = INT_MAX, min; for (int i = 0; i < 16; i++) { cout << "a[" << i << "] = "; cin >> a[i]; } cout << endl; for (int i = 0; i < 16/2; i++) { cout << "a[" << i << "] * a[" << i + 8 << "]\n"; a[i] = a[i] * a[i + 8]; if (a[i] < min_v) { min = i; min_v = a[i]; } } cout << "\nmin = " << min_v << "\t a[" << min << "] * a[" << min + 8 << "]" << endl << endl; } } while (true); return 0; }
cfa2560f4fcba3068d0e50e70f309300987547a8
[ "C++" ]
1
C++
MeushRoman/array1ht
a566b4d3d94713d0a8883e26335c906889432814
c7f10440d71b358f0cea3ce2d06738ffff058bcd
refs/heads/master
<file_sep>package com.example.arturmusayelyan.swipetabs; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class MainActivity extends AppCompatActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private ViewPager pager; private ActionBar actionBar; @SuppressLint("WrongConstant") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pager = findViewById(R.id.pager); pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager())); pager.setOnPageChangeListener(this); actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab1 = actionBar.newTab(); tab1.setText("Tab 1"); tab1.setTabListener(this); ActionBar.Tab tab2 = actionBar.newTab(); tab2.setText("Tab 2"); tab2.setTabListener(this); ActionBar.Tab tab3 = actionBar.newTab(); tab3.setText("Tab 3"); tab3.setTabListener(this); actionBar.addTab(tab1); actionBar.addTab(tab2); actionBar.addTab(tab3); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { Log.d("Art", "onTabSelected at position " + tab.getPosition() + " name+ " + tab.getText()); pager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { Log.d("Art", "onTabUnSelected at position " + tab.getPosition() + " name+ " + tab.getText()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { Log.d("Art", "onTabReSelected at position " + tab.getPosition() + " name+ " + tab.getText()); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { Log.d("Art", "onPageScrolled at " + position); } @Override public void onPageSelected(int position) { Log.d("Art", "onPageSelected at " + position); actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { Log.d("Art", "onPageScrollStateChanged IDLE"); } else if (state == ViewPager.SCROLL_STATE_DRAGGING) { Log.d("Art", "onPageScrollStateChanged Dragging"); } else if (state == ViewPager.SCROLL_STATE_SETTLING) { Log.d("Art", "onPageScrollStateChanged Settling"); } } }
da8de694656b60d38f70e4bbf1ba2e42b889f11f
[ "Java" ]
1
Java
musayelyan/SwipeTabs
4cdeae7e76496f5608603f7da780c035a7c61aae
df49f110763f844e2fc4227162364ffe61d9aa0a
refs/heads/master
<repo_name>lindsaywilhelm11/FS1000_Exercises<file_sep>/scripts/provincePageContentScript.js //this script serves up the appropriate content depending on which province the user decides to browse //finds all the tags I'd want to change with this script let dynamicElementsp = []; function findAllTags (){ dynamicElementsp[0] = document.getElementById("provinceName"); dynamicElementsp[1] = document.getElementById("expensiveRestaurants"); dynamicElementsp[2] = document.getElementById("midrangeRestaurants"); dynamicElementsp[3] = document.getElementById("cheapRestaurants"); } //this function will be triggered onclick --- it takes the elements id as param to know what content to serve function newContentOnClick(event) { event = event || window.event; //IE let target = event.target || event.srcElement; //IE let id = target.id; alert("you clicked on " + id); } //finds all links that will change content and adds an onclick event to them function addOnclickForEach(item, index, arr){ item.setAttribute("onclick","newContentOnClick(event)"); //_*_*_*_*_*_*__*_ this next line is just to make sure that everything works console.log(item.id); } let contentLinks = []; function findAllLinks() { let contentLinks = Array.from(document.getElementById("provinceNav").children); contentLinks.forEach(addOnclickForEach); } //waits till the document is loaded so I can find elements by id window.onload = function() { findAllTags(); findAllLinks(); };
79ec9dd484654fda76d3a90b16a544926bbb759d
[ "JavaScript" ]
1
JavaScript
lindsaywilhelm11/FS1000_Exercises
b14c113fadfcdae19340abe894f832924f7af36e
5bd90f00bf96e417b9775e7793c6e6e2b9c8d041
refs/heads/master
<file_sep>package assign3; import static org.junit.Assert.*; import org.junit.Test; public class SudokuTest { @Test public void testToString() { Sudoku sudoku = new Sudoku(Sudoku.mediumGrid); String mediumGrid = "5 3 0 0 7 0 0 0 0" + System.lineSeparator() + "6 0 0 1 9 5 0 0 0" + System.lineSeparator() + "0 9 8 0 0 0 0 6 0" + System.lineSeparator() + "8 0 0 0 6 0 0 0 3" + System.lineSeparator() + "4 0 0 8 0 3 0 0 1" + System.lineSeparator() + "7 0 0 0 2 0 0 0 6" + System.lineSeparator() + "0 6 0 0 0 0 2 8 0" + System.lineSeparator() + "0 0 0 4 1 9 0 0 5" + System.lineSeparator() + "0 0 0 0 8 0 0 7 9"; assertEquals(sudoku.toString(), mediumGrid); } @Test public void testSolve() { Sudoku sudoku = new Sudoku(Sudoku.easyGrid); String easyGridSolution = "1 6 4 7 9 5 3 8 2" + System.lineSeparator() + "2 8 7 4 6 3 9 1 5" + System.lineSeparator() + "9 3 5 2 8 1 4 6 7" + System.lineSeparator() + "3 9 1 8 7 6 5 2 4" + System.lineSeparator() + "5 4 6 1 3 2 7 9 8" + System.lineSeparator() + "7 2 8 9 5 4 1 3 6" + System.lineSeparator() + "8 1 9 6 4 7 2 5 3" + System.lineSeparator() + "6 7 3 5 2 9 8 4 1" + System.lineSeparator() + "4 5 2 3 1 8 6 7 9"; int count = sudoku.solve(); assertEquals(sudoku.getSolutionText(), easyGridSolution); } @Test public void testSolve2() { Sudoku sudoku = new Sudoku(Sudoku.arbitraryGrid); assertEquals(sudoku.solve(), Sudoku.MAX_SOLUTIONS); } } <file_sep>package assign4; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; public class Bank { public static final int NUM_ACCOUNTS = 20; public static final int INIT_BALANCE = 1000; private Account[] accounts; private BlockingQueue<Transaction> transactionQueue = new ArrayBlockingQueue<>( 100); private CountDownLatch latch; /** * A Worker processes transactions. Worker communicates with Bank via * BlockingQueue. * * @author WEIYUNSHENG * */ class Worker implements Runnable { @Override public void run() { try { Transaction transaction; while ((transaction = transactionQueue.take()) != Transaction.nullTransaction) { int from = transaction.from; int to = transaction.to; int amount = transaction.amount; accounts[from].cutBalance(amount); accounts[to].addBalance(amount); } } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); } } public void start(String transactionFile, int numWorkers) { latch = new CountDownLatch(numWorkers); accounts = new Account[Bank.NUM_ACCOUNTS]; for (int i = 0; i < accounts.length; i++) { accounts[i] = new Account(i, Bank.INIT_BALANCE); } for (int i = 0; i < numWorkers; i++) { new Thread(new Worker()).start(); } try (Scanner in = new Scanner(new BufferedReader(new FileReader( new File(transactionFile))))) { while (in.hasNext()) { int from = in.nextInt(); int to = in.nextInt(); int amount = in.nextInt(); try { transactionQueue.put(new Transaction(from, to, amount)); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < accounts.length; i++) { try { transactionQueue.put(Transaction.nullTransaction); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } try { latch.await(); for (Account acc : accounts) { System.out.println(acc); } } catch (InterruptedException e) { } } public static void main(String[] args) { String transactionFile = args[0]; int numWorkers = Integer.parseInt(args[1]); Bank bank = new Bank(); bank.start(transactionFile, numWorkers); } } /** * An Account represents a bank account. * * @author WEIYUNSHENG * */ class Account { private final int id; private int balance; private int numTransactions; public Account(int id, int balance) { this.id = id; this.balance = balance; numTransactions = 0; } public synchronized int getBalance() { return balance; } public synchronized void addBalance(int amount) { balance += amount; numTransactions++; } public synchronized void cutBalance(int amount) { balance -= amount; numTransactions++; } // getId() doesn't need to be synchronized, because id is never changed, so it will not expose so-called middle state. public int getId() { return id; } public synchronized int getNumTransactions() { return numTransactions; } @Override public synchronized String toString() { return String.format("acct:%s bal:%s trans:%s", id, balance, numTransactions); } } /** * A Transaction is an immutable class that stores information about a * transaction. * * @author WEIYUNSHENG * */ class Transaction { public final int from; public final int to; public final int amount; public static final Transaction nullTransaction = new Transaction(-1, 0, 0); public Transaction(int from, int to, int amount) { this.from = from; this.to = to; this.amount = amount; } } <file_sep>package assign3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Encapsulates a Sudoku grid to be solved. * CS108 Stanford. */ public class Sudoku { // Provided grid data for main/testing // The instance variable strategy is up to you. // Provided easy 1 6 grid // (can paste this text into the GUI too) public static final int[][] easyGrid = Sudoku.stringsToGrid( "1 6 4 0 0 0 0 0 2", "2 0 0 4 0 3 9 1 0", "0 0 5 0 8 0 4 0 7", "0 9 0 0 0 6 5 0 0", "5 0 0 1 0 2 0 0 8", "0 0 8 9 0 0 0 3 0", "8 0 9 0 4 0 2 0 0", "0 7 3 5 0 9 0 0 1", "4 0 0 0 0 0 6 7 9"); // Provided medium 5 3 grid public static final int[][] mediumGrid = Sudoku.stringsToGrid("530070000", "600195000", "098000060", "800060003", "400803001", "700020006", "060000280", "000419005", "000080079"); // Provided hard 3 7 grid // 1 solution this way, 6 solutions if the 7 is changed to 0 public static final int[][] hardGrid = Sudoku.stringsToGrid( "3 7 0 0 0 0 0 8 0", "0 0 1 0 9 3 0 0 0", "0 4 0 7 8 0 0 0 3", "0 9 3 8 0 0 0 1 2", "0 0 0 0 4 0 0 0 0", "5 2 0 0 0 6 7 9 0", "6 0 0 0 2 1 0 4 0", "0 0 0 5 3 0 9 0 0", "0 3 0 0 0 0 0 5 1"); // Added an unconstrained grid for testing public static final int[][] arbitraryGrid = Sudoku.stringsToGrid( "0 0 0 0 0 0 0 8 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"); public static final int SIZE = 9; // size of the whole 9x9 puzzle public static final int PART = 3; // size of each 3x3 part public static final int MAX_SOLUTIONS = 100; // Provided various static utility methods to // convert data formats to int[][] grid. /** * Returns a 2-d grid parsed from strings, one string per row. The "..." is * a Java 5 feature that essentially makes "rows" a String[] array. * (provided utility) * * @param rows * array of row strings * @return grid */ public static int[][] stringsToGrid(String... rows) { int[][] result = new int[rows.length][]; for (int row = 0; row < rows.length; row++) { result[row] = stringToInts(rows[row]); } return result; } /** * Given a single string containing 81 numbers, returns a 9x9 grid. Skips * all the non-numbers in the text. (provided utility) * * @param text * string of 81 numbers * @return grid */ public static int[][] textToGrid(String text) { int[] nums = stringToInts(text); if (nums.length != SIZE * SIZE) { throw new RuntimeException("Needed 81 numbers, but got:" + nums.length); } int[][] result = new int[SIZE][SIZE]; int count = 0; for (int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { result[row][col] = nums[count]; count++; } } return result; } /** * Given a string containing digits, like "1 23 4", returns an int[] of * those digits {1 2 3 4}. (provided utility) * * @param string * string containing ints * @return array of ints */ public static int[] stringToInts(String string) { int[] a = new int[string.length()]; int found = 0; for (int i = 0; i < string.length(); i++) { if (Character.isDigit(string.charAt(i))) { a[found] = Integer.parseInt(string.substring(i, i + 1)); found++; } } int[] result = new int[found]; System.arraycopy(a, 0, result, 0, found); return result; } // Provided -- the deliverable main(). // You can edit to do easier cases, but turn in // solving hardGrid. public static void main(String[] args) { Sudoku sudoku; sudoku = new Sudoku(Sudoku.hardGrid); System.out.println(sudoku); // print the raw problem int count = sudoku.solve(); System.out.println("solutions:" + count); System.out.println("elapsed:" + sudoku.getElapsed() + "ms"); System.out.println(sudoku.getSolutionText()); } // My code begins here. /** * Given a 2D array, return its string representation. * * @param ints */ public static String intsToString(int[][] ints) { StringBuilder sb = new StringBuilder(); for (int[] row : ints) { for (int ele : row) { sb.append(ele).append(" "); } sb.deleteCharAt(sb.length() - 1).append(System.lineSeparator()); } sb.delete(sb.lastIndexOf(System.lineSeparator()), sb.length()); return sb.toString(); } /** * A Spot represents a spot in Sudoku grid. * * @author WEIYUNSHENG * */ private class Spot { // Represent the coordinate of the Spot in grid final int x; final int y; Set<Integer> rowCand, colCand, neighborCand; Spot(int x, int y) { this.x = x; this.y = y; } void set(int value) { tempSolution[x][y] = value; rowCand.removeAll(Collections.singleton(value)); colCand.removeAll(Collections.singleton(value)); neighborCand.removeAll(Collections.singleton(value)); } void clear() { int value = tempSolution[x][y]; if (value != 0) { rowCand.add(value); colCand.add(value); neighborCand.add(value); tempSolution[x][y] = 0; } } int getCandSize() { return getCandidates().size(); } Set<Integer> getCandidates() { Set<Integer> candidates = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); candidates.retainAll(rowCand); candidates.retainAll(colCand); candidates.retainAll(neighborCand); return candidates; } } /** * * @param grid * 9 * 9 2D int array * @return a list of 81 Spots with constraints contained in the Spot itself */ private List<Spot> getSpotList(int[][] grid) { List<Spot> spotList = new ArrayList<>(); Set<Integer>[] rowCandArray = new Set[Sudoku.SIZE]; Set<Integer>[] colCandArray = new Set[Sudoku.SIZE]; Set<Integer>[] neighborCandArray = new Set[Sudoku.SIZE]; for (int i = 0; i < Sudoku.SIZE; i++) { rowCandArray[i] = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); colCandArray[i] = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); neighborCandArray[i] = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { int value = grid[i][j]; int neighcandIndex = (i / Sudoku.PART) * 3 + j / 3; if (value == 0) { Spot spot = new Spot(i, j); spot.rowCand = rowCandArray[i]; spot.colCand = colCandArray[j]; spot.neighborCand = neighborCandArray[neighcandIndex]; spotList.add(spot); } else { rowCandArray[i].removeAll(Collections.singleton(value)); colCandArray[j].removeAll(Collections.singleton(value)); neighborCandArray[neighcandIndex].removeAll(Collections.singleton(value)); } } } return spotList; } // grid should never be changed (include its content). private final int[][] grid; private int[][] tempSolution; private int[][] firstSolution; private int countSolutions = 0; private long elapsedTime; /** * Sets up Sudoku based on the given 2-D array. Require ints to be a legal 9 * * 9 grid. Empty spots are represented by 0. * * @param ints */ public Sudoku(int[][] ints) { grid = ints; } /** * Sets up Sudoku based on the given string. * * @param puzzle * string of 81 numbers */ public Sudoku(String puzzle) { int[][] ints = Sudoku.textToGrid(puzzle); grid = ints; } @Override public String toString() { return Sudoku.intsToString(grid); } /** * Detect whether the given grid has conflicts. * * @param grid * the grid to check * @return <code>true</code> if has conflict otherwise <code>false</code> */ private boolean detectConflicts(int[][] grid) { // Check rows for (int[] row : grid) { boolean[] used = new boolean[Sudoku.SIZE + 1]; for (int ele : row) { if (ele != 0 && used[ele]) { return true; } used[ele] = true; } } // Check columns for (int j = 0; j < Sudoku.SIZE; j++) { boolean[] used = new boolean[Sudoku.SIZE + 1]; for (int i = 0; i < Sudoku.SIZE; i++) { int ele = grid[i][j]; if (ele != 0 && used[ele]) { return true; } used[ele] = true; } } // Check 3 * 3 neighborhoods for (int i = 0; i < Sudoku.SIZE / Sudoku.PART; i++) { for (int j = 0; j < Sudoku.SIZE / Sudoku.PART; j++) { boolean[] used = new boolean[Sudoku.SIZE + 1]; for (int ix = i * Sudoku.PART; ix < i * Sudoku.PART + Sudoku.PART; ix++) { for (int jy = j * Sudoku.PART; jy < j * Sudoku.PART + Sudoku.PART; jy++) { int ele = grid[ix][jy]; if (ele != 0 && used[ele]) { return true; } used[ele] = true; } } } } return false; } /** * Solve the Sudoku problem recursively. Current partial solution is in * partialSol, empty Spot is in in spotList[listIndex .. end - 1] * * @param partialSol * @param spotList * @param listIndex * @return whether to continue searching or not */ private boolean solveRec(int[][] partialSol, List<Spot> spotList, int listIndex) { if (listIndex >= spotList.size()) { countSolutions += 1; if (firstSolution == null) { firstSolution = new int[tempSolution.length][tempSolution[0].length]; for (int i = 0; i < firstSolution.length; i++) { System.arraycopy(tempSolution[i], 0, firstSolution[i], 0, tempSolution[0].length); } } if (countSolutions >= Sudoku.MAX_SOLUTIONS) { return false; } else { return true; } } else { Spot curSpot = spotList.get(listIndex++); for (int val: curSpot.getCandidates()) { curSpot.set(val); if (!solveRec(partialSol, spotList, listIndex)) { return false; } curSpot.clear(); } return true; } } /** * Solves the puzzle, invoking the underlying recursive search. * * @return the number of solutions (max 100) */ public int solve() { long startTime = System.currentTimeMillis(); countSolutions = 0; if (!detectConflicts(grid)) { List<Spot> spotList = getSpotList(grid); Collections.sort(spotList, new Comparator<Spot>() { @Override public int compare(Spot lhs, Spot rhs) { return lhs.getCandSize() - rhs.getCandSize(); } }); // Initialize tempSolution with grid tempSolution = new int[grid.length][grid[0].length]; for (int i = 0; i < tempSolution.length; i++) { System.arraycopy(grid[i], 0, tempSolution[i], 0, grid[0].length); } solveRec(tempSolution, spotList, 0); assert !detectConflicts(firstSolution); } elapsedTime = System.currentTimeMillis() - startTime; return countSolutions; } /** * Get the solution text. * * @return the first found solution if any, otherwise an empty string */ public String getSolutionText() { if (0 == countSolutions) { return ""; } else { return Sudoku.intsToString(firstSolution); } } /** * * @return the elapsed time for the last call of <code>solve()</code>, * measured in milliseconds */ public long getElapsed() { return elapsedTime; } }
8a723dbda1be8f2576fc3f2ad94d8e4a5b3428db
[ "Java" ]
3
Java
bbeltran1234/Stanford-CS-108
8023b57d839052f7a7500b7dcb7abc9656dedb60
7d69ecf16b6033395b242b7c6379797b93d1bd90
refs/heads/master
<file_sep>#include "Ray.h" // Default Constructor Ray::Ray() { } // Constructor Ray::Ray(const Vector3& a, const Vector3& b) { A = a; B = b; } // Get Origin Vector3 Ray::origin() const { return A; } // Get Direction of Ray Vector3 Ray::direction() const { return B; } Vector3 Ray::pointAtParameter(float t) const { return A + t * B; } // Destructor Ray::~Ray() { } <file_sep>#include "SurfaceList.h" // Constructor SurfaceList::SurfaceList(){ listSize = 0; list = nullptr; } // Constructor with values SurfaceList::SurfaceList(Surface** l, int n){ list = l; listSize = n; } // Hit everything in list bool SurfaceList::hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const{ // Temporary HitRecord HitRecord tempRec; // Bool if it hit anything bool hitAnything = false; // Closest value found double closestSoFar = tMax; // Loop through each element of the list for (int i = 0; i < listSize; i++) { // Check if element is hit if (list[i]->hit(r, tMin, closestSoFar, tempRec)) { hitAnything = true; closestSoFar = tempRec.t; rec = tempRec; } } // Return if it hit anything return hitAnything; } // Destructor SurfaceList::~SurfaceList(){ } <file_sep>#include "Sphere.h" // Constructor Sphere::Sphere(){ center = Vector3(0, 0, 0); radius = 0; material = nullptr; } // Constructor with Initialisation Sphere::Sphere(Vector3 cen, float r, Material* mat) { center = cen; radius = r; material = mat; } // Sphere Hit Function bool Sphere::hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const { // Vector from ray origin to center Vector3 oc = r.origin() - center; // Solving for discriminant float a = dot(r.direction(), r.direction()); float b = dot(oc, r.direction()); float c = dot(oc, oc) - radius * radius; float discriminant = b * b - a * c; // Check if positive discriminant if (discriminant > 0) { // Find result 1 to equation float temp = (-b - sqrt(b * b - a * c)) / a; // Check if temp is between min and max, update HitRecord if (temp > tMin && temp < tMax) { rec.t = temp; rec.p = r.pointAtParameter(rec.t); rec.normal = (rec.p - center) / radius; rec.mat = material; return true; } // Find result 2 to equation temp = (-b + sqrt(b * b - a * c)) / a; // Check if temp is between min and max, update HitRecord if (temp > tMin && temp < tMax) { rec.t = temp; rec.p = r.pointAtParameter(rec.t); rec.normal = (rec.p - center) / radius; rec.mat = material; return true; } } // If not positive return false return false; } // Destructor Sphere::~Sphere(){ } <file_sep>#pragma once #include "Ray.h" class Camera { public: // Constructor Camera(); // Ray Function Ray getRay(float u, float v); // Destructor ~Camera(); // Variables Vector3 origin; Vector3 lowerLeftCorner; Vector3 horizontal; Vector3 vertical; }; <file_sep>#pragma once #include "Vector3.h" class Ray { public: // Default Constructor Ray(); // Contructor Ray(const Vector3& a, const Vector3& b); // Origin of Ray Vector3 origin() const; // Direction of Ray Vector3 direction() const; // Return A + Bt for Given t Vector3 pointAtParameter(float t) const; // Destructor ~Ray(); // Vectors for Ray Vector3 A; Vector3 B; }; <file_sep># RayTracingTutorial Learning Some Ray Tracing in C++ <file_sep>#include <iostream> #include <string> #include <fstream> #include <float.h> #include <stdlib.h> #include <time.h> #include <iomanip> #include "SurfaceList.h" #include "Sphere.h" #include "Camera.h" #include "Metal.h" #include "Lambertian.h" #include "Dielectric.h" // Function Predeclarations Vector3 colour(const Ray& r, Surface* world, int depth); // Main Function int main() { // Get Desired File Name std::string fileName; std::cout << "Enter File Name: "; std::cin >> fileName; // Open Output File std::ofstream outputFile; outputFile.open("images/" + fileName + ".ppm"); // Height and Width of Image int nx = 800; int ny = 400; // Number of samples for antialiasing int ns = 100; // Total number of runs float total = float(nx) * float(ny); // Progress variable float progress = 0.0; // Reset random seed srand(time(NULL)); // Define Important Vector 3s Vector3 lowerLeftCorner(-2.0, -1.0, -1.0); Vector3 horizontal(4.0, 0.0, 0.0); Vector3 vertical(0.0, 2.0, 0.0); Vector3 origin(0.0, 0.0, 0.0); // Initialise PPM outputFile << "P3\n" << nx << " " << ny << "\n255\n"; // Set output format std::cout << std::fixed; std::cout << std::setprecision(1); // List of Surfaces Surface* list[4]; // Populate list list[0] = new Sphere(Vector3(0, 0, -1), 0.5, new Lambertian(Vector3(0.8, 0.3, 0.3))); list[1] = new Sphere(Vector3(0, -100.5, -1), 100.0, new Lambertian(Vector3(0.8, 0.8, 0.0))); list[2] = new Sphere(Vector3(1, 0, -1), 0.5, new Metal(Vector3(0.8, 0.6, 0.2), 0.3)); list[3] = new Sphere(Vector3(-1, 0, -1), 0.5, new Dielectric(1.5)); // SurfaceList Surface* world = new SurfaceList(list, 4); // Create main camera Camera cam; // Fill PPM Image for (int j = ny - 1; j >= 0; j--) { for (int i = 0; i < nx; i++) { // Initialise colour to 0, 0, 0 Vector3 col(0, 0, 0); // Loop through for antialiasing for (int s = 0; s < ns; s++) { // Coordinates float u = float(i + ((float)rand() / (RAND_MAX))) / float(nx); float v = float(j + ((float)rand() / (RAND_MAX))) / float(ny); // Create ray Ray r = cam.getRay(u, v); // Find point at ray Vector3 p = r.pointAtParameter(2.0); // Add to colour col += colour(r, world, 0); } // Get average of colour col /= float(ns); // Fix gamma col = Vector3(sqrt(col[0]), sqrt(col[1]), sqrt(col[2])); // Converted RGB Values 0-255 int ir = int(255.99 * col[0]); int ig = int(255.99 * col[1]); int ib = int(255.99 * col[2]); // Add to PPM outputFile << ir << " " << ig << " " << ib << "\n"; // Print progress progress += 1.0; float percent = 100 * progress / total; std::cout << "Progress: " << percent << "%" << "\r"; } } // Add newline std::cout << "\nCompleted!\n"; // Cleanup outputFile.close(); return 0; } // Colour Function Vector3 colour(const Ray& r, Surface* world, int depth) { // HitRecord to check HitRecord rec; // Check if hit if (world->hit(r, 0.001, FLT_MAX, rec)) { // Holders of information Ray scattered; Vector3 attenuation; // Check if within depth and other stuff if (depth < 50 && rec.mat->scatter(r, rec, attenuation, scattered)) { return attenuation * colour(scattered, world, depth + 1); } // Else return default colour else { return Vector3(0, 0, 0); } } // Otherwise return background gradient else { // Initial and final colours Vector3 initColour = Vector3(1.0, 1.0, 1.0); Vector3 finalColour = Vector3(0.5, 0.7, 1.0); // Unit y direction Vector3 unitDirection = unitVector(r.direction()); // Gradient variable float t = 0.5 * (unitDirection.y() + 1.0); // Return gradient return (1.0 - t) * initColour + t * finalColour; } }<file_sep>#pragma once #include "Material.h" class Dielectric : public Material { public: // Constructor Dielectric(float ri) { refIndex = ri; } // Override Scatter Function virtual bool scatter(const Ray& rIn, const HitRecord& rec, Vector3& attenuation, Ray& scattered) const { // Variable for normal Vector3 outwardNormal; // Reflected variable Vector3 reflected = reflect(rIn.direction(), rec.normal); // ni / nt float niOverNt; // Colour value attenuation = Vector3(1.0, 1.0, 1.0); // Refracted Vector3 Vector3 refracted; // if outside the surface if (dot(rIn.direction(), rec.normal) > 0) { // Set outward normal and ni / nt outwardNormal = -rec.normal; niOverNt = refIndex; } else { outwardNormal = rec.normal; niOverNt = 1.0 / refIndex; } // Check if refracts if (refract(rIn.direction(), outwardNormal, niOverNt, refracted)) { scattered = Ray(rec.p, refracted); } // Else reflect else { scattered = Ray(rec.p, reflected); return false; } // Return from function return true; } // Variables float refIndex; }; <file_sep>#pragma once #include "Surface.h" class Material { public: // Constructor Material(){} // Ray scattering virtual bool scatter(const Ray& rIn, const HitRecord& rec, Vector3& attenuation, Ray& scattered) const = 0; // Destructor ~Material(){} }; // Reflect ray Vector3 reflect(const Vector3& v, const Vector3& n) { // Return reflection return v - 2 * dot(v, n) * n; } // Return random point in unit circle Vector3 randomInUnitSphere() { // Point Vector3 p; // Try getting random point do { p = 2.0 * Vector3(((float)rand() / (RAND_MAX)), ((float)rand() / (RAND_MAX)), ((float)rand() / (RAND_MAX))) - Vector3(1, 1, 1); } while (p.squaredLength() >= 1.0); // Return point return p; } // Refract bool refract(const Vector3& v, const Vector3& n, float niOverNt, Vector3& refracted) { // Create unit vector from v Vector3 uv = unitVector(v); // Find dot product with normal float dt = dot(uv, n); // Get discriminant of equation float discriminant = 1.0 - niOverNt * niOverNt * (1.0 - (dt * dt)); // Check if discriminant is larger than 0 if (discriminant > 0) { refracted = niOverNt * (uv - (n * dt)) - n * sqrt(discriminant); return true; } // Else didn't hit else { return false; } }<file_sep>#pragma once #include "Material.h" class Metal : public Material{ public: // Constructor Metal(const Vector3& a, float f) { albedo = a; fuzz = f; } // Override Scatter Function virtual bool scatter(const Ray& rIn, const HitRecord& rec, Vector3& attenuation, Ray& scattered) const { // Reflected ray Vector3 reflected = reflect(unitVector(rIn.direction()), rec.normal); // Scattered ray scattered = Ray(rec.p, reflected + fuzz * randomInUnitSphere()); // Colour data attenuation = albedo; // Exit function return (dot(scattered.direction(), rec.normal) > 0); } // Destructor ~Metal(){} // Variables Vector3 albedo; float fuzz; }; <file_sep>#pragma once #include "Surface.h" class Sphere : public Surface { public: // Constructors Sphere(); Sphere(Vector3 cen, float r, Material* mat); // Hit Function virtual bool hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const; // Destructor ~Sphere(); // Variables Vector3 center; float radius; Material* material; }; <file_sep>#include "Surface.h" // Constructor Surface::Surface() { } // Destructor Surface::~Surface() { } <file_sep>#pragma once #include <math.h> #include <stdlib.h> #include <iostream> class Vector3{ public: // Default Constructor Vector3(){} // Constructor Vector3(float e0, float e1, float e2); // X, Y, Z getters inline float x() const { return e[0]; } inline float y() const { return e[1]; } inline float z() const { return e[2]; } // R, G, B getters inline float r() const { return e[0]; } inline float g() const { return e[1]; } inline float b() const { return e[2]; } // Basic Operator Overloads inline const Vector3& operator+() const { return *this; } inline Vector3 operator-() const { return Vector3(-e[0], -e[1], -e[2]); } inline float operator[](int i) { return e[i]; } // Other Operator Overloads inline Vector3& operator+=(const Vector3& v2); inline Vector3& operator-=(const Vector3& v2); inline Vector3& operator*=(const Vector3& v2); inline Vector3& operator/=(const Vector3& v2); inline Vector3& operator*=(const float t); inline Vector3& operator/=(const float t); // Vector3 Methods inline float length() const { return sqrt(e[0] * e[0] + e[1] * e[1] + e[2] * e[2]); } inline float squaredLength() const { return e[0] * e[0] + e[1] * e[1] + e[2] * e[2]; } inline void makeUnitVector(); // Destructor ~Vector3(); // Holds Values float e[3]; }; // Other Functions // Operator Overloads inline std::istream& operator>>(std::istream& is, Vector3& v) { is >> v.e[0] >> v.e[1] >> v.e[2]; return is; } inline std::ostream& operator<<(std::ostream& os, const Vector3& v) { os << v.e[0] << ", " << v.e[1] << ", " << v.e[2]; return os; } inline Vector3 operator+(const Vector3& v1, const Vector3& v2) { return Vector3(v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]); } inline Vector3 operator-(const Vector3 & v1, const Vector3 & v2) { return Vector3(v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]); } inline Vector3 operator*(const Vector3 & v1, const Vector3 & v2) { return Vector3(v1.e[0] * v2.e[0], v1.e[1] * v2.e[1], v1.e[2] * v2.e[2]); } inline Vector3 operator/(const Vector3 & v1, const Vector3 & v2) { return Vector3(v1.e[0] / v2.e[0], v1.e[1] / v2.e[1], v1.e[2] / v2.e[2]); } inline Vector3 operator*(const float t, const Vector3 & v) { return Vector3(t * v.e[0], t * v.e[1], t * v.e[2]); } inline Vector3 operator*(const Vector3 & v, const float t) { return Vector3(t * v.e[0], t * v.e[1], t * v.e[2]); } inline Vector3 operator/(const Vector3 & v, const float t) { return Vector3(v.e[0] / t, v.e[1] / t, v.e[2] / t); } // Dot Product inline float dot(const Vector3 & v1, const Vector3 & v2) { return v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2]; } // Cross Product inline Vector3 cross(const Vector3 & v1, const Vector3 & v2) { return Vector3((v1.e[1] * v2.e[2] - v1.e[2] * v2.e[1]), (v1.e[2] * v2.e[0] - v1.e[0] * v2.e[2]), (v1.e[0] * v2.e[1] - v1.e[1] * v2.e[0])); } // Unit Vector inline Vector3 unitVector(Vector3 v) { return v / v.length(); } // Operator Overloads inline Vector3& Vector3::operator+=(const Vector3& v2) { e[0] += v2.e[0]; e[1] += v2.e[1]; e[2] += v2.e[2]; return *this; } inline Vector3& Vector3::operator-=(const Vector3& v2) { e[0] -= v2.e[0]; e[1] -= v2.e[1]; e[2] -= v2.e[2]; return *this; } inline Vector3& Vector3::operator*=(const Vector3& v2) { e[0] *= v2.e[0]; e[1] *= v2.e[1]; e[2] *= v2.e[2]; return *this; } inline Vector3& Vector3::operator/=(const Vector3& v2) { e[0] /= v2.e[0]; e[1] /= v2.e[1]; e[2] /= v2.e[2]; return *this; } inline Vector3& Vector3::operator*=(const float t) { e[0] *= t; e[1] *= t; e[2] *= t; return *this; } inline Vector3& Vector3::operator/=(const float t) { float k = 1.0 / t; e[0] *= k; e[1] *= k; e[2] *= k; return *this; }<file_sep>#pragma once #include "Ray.h" class Material; struct HitRecord { float t; Vector3 p; Vector3 normal; Material* mat; }; class Surface { public: // Constructor Surface(); virtual bool hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const = 0; // Destructor ~Surface(); }; <file_sep>#pragma once #include "Sphere.h" class SurfaceList : public Surface { public: // Constructors SurfaceList(); SurfaceList(Surface** l, int n); // Hit function virtual bool hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const; // Destructor ~SurfaceList(); // Variables Surface** list; int listSize; }; <file_sep>#include "Vector3.h" // Constructor Vector3::Vector3(float e0, float e1, float e2){ e[0] = e0; e[1] = e1; e[2] = e2; } // Vector3 Methods // Make Unit Vector inline void Vector3::makeUnitVector() { // Find Multiplier float k = 1.0 / length(); // Apply Multiplier e[0] *= k; e[1] *= k; e[2] *= k; } // Destructor Vector3::~Vector3(){ }<file_sep>#pragma once #include "Material.h" class Lambertian : public Material{ public: // Constructor Lambertian(const Vector3 a) { albedo = a; } // Overloaded Scatter Function virtual bool scatter(const Ray& rIn, const HitRecord& rec, Vector3& attenuation, Ray& scattered) const { // Target Scattering Vector3 target = rec.p + rec.normal + randomInUnitSphere(); // Scattered ray scattered = Ray(rec.p, target - rec.p); // Colour information attenuation = albedo; // Exit function return true; } // Destructor ~Lambertian(){} // Variables Vector3 albedo; };<file_sep>#include "Camera.h" // Constructor Camera::Camera() { lowerLeftCorner = Vector3(-2.0, -1.0, -1.0); horizontal = Vector3(4.0, 0.0, 0.0); vertical = Vector3(0.0, 2.0, 0.0); origin = Vector3(0.0, 0.0, 0.0); } // Ray function Ray Camera::getRay(float u, float v) { return Ray(origin, lowerLeftCorner + u * horizontal + v * vertical - origin); } // Destructor Camera::~Camera() { }
ada24f137b3f28923c8724c97adf77c90d52129c
[ "Markdown", "C++" ]
18
C++
Torquelus/RayTracingTutorial
1a8aa5c477fdc4463644654e8f3761ed2aa2fbd7
685bbc2da53efbeb9033ac6dcb8915c7e9dfc809
refs/heads/master
<repo_name>banyancheung/ibos-linux-install<file_sep>/ibos_install_sh/res/extra.php <?php if (isset($_SERVER['argv'])) { $params = $_SERVER['argv']; array_shift($params); $shellScript = $params[0]; $mysqlPassword = $params[1]; list($execId,) = explode('_', $shellScript); if (!empty($execId)){ markComplete($execId,$mysqlPassword); } } function markComplete($id,$mysqlPassword){ $url = 'http://worker.ibos.cn/?r=onekeydeploy/complete&id='.$id.'&pwd='.$mysqlPassword; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, 'spider'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $data = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return ($httpcode>=200 && $httpcode<300) ? true : false; } <file_sep>/ibos_install_sh/install.sh #!/bin/bash ####---- global variables ----begin#### export nginx_version=1.4.4 export mysql_version=5.6.21 export php_version=5.3.29 export ibos_version=4.1.0 ####---- global variables ----end#### web=nginx install_log=/ibos/website-info.log echo "" echo "version :" echo "web : $web" echo "nginx : $nginx_version" echo "php : $php_version" echo "mysql : $mysql_version" ####---- Clean up the environment ----begin#### echo "will be installed, wait ..." ./uninstall.sh in &> /dev/null ####---- Clean up the environment ----end#### web_dir=nginx-${nginx_version} php_dir=php-${php_version} if [ `uname -m` == "x86_64" ];then machine=x86_64 else machine=i686 fi ####---- global variables ----begin#### export web export web_dir export php_dir export mysql_dir=mysql-${mysql_version} ####---- global variables ----end#### ifredhat=$(cat /proc/version | grep redhat) ifcentos=$(cat /proc/version | grep centos) ifubuntu=$(cat /proc/version | grep ubuntu) ifdebian=$(cat /proc/version | grep -i debian) ifgentoo=$(cat /proc/version | grep -i gentoo) ifsuse=$(cat /proc/version | grep -i suse) ifAliCloud=$(cat /proc/version | grep AliCloud) ####---- install dependencies ----begin#### if [ "$ifcentos" != "" ] || [ "$machine" == "i686" ];then rpm -e httpd-2.2.3-31.el5.centos gnome-user-share &> /dev/null fi \cp /etc/rc.local /etc/rc.local.bak > /dev/null if [ "$ifredhat" != "" ];then rpm -e --allmatches mysql MySQL-python perl-DBD-MySQL dovecot exim qt-MySQL perl-DBD-MySQL dovecot qt-MySQL mysql-server mysql-connector-odbc php-mysql mysql-bench libdbi-dbd-mysql mysql-devel-5.0.77-3.el5 httpd php mod_auth_mysql mailman squirrelmail php-pdo php-common php-mbstring php-cli &> /dev/null fi if [ "$ifAliCloud" != "" ];then rpm -e --allmatches mysql MySQL-python perl-DBD-MySQL dovecot exim qt-MySQL perl-DBD-MySQL dovecot qt-MySQL mysql-server mysql-connector-odbc php-mysql mysql-bench libdbi-dbd-mysql mysql-devel-5.0.77-3.el5 httpd php mod_auth_mysql mailman squirrelmail php-pdo php-common php-mbstring php-cli &> /dev/null fi if [ "$ifredhat" != "" ];then \mv /etc/yum.repos.d/rhel-debuginfo.repo /etc/yum.repos.d/rhel-debuginfo.repo.bak &> /dev/null \cp ./res/rhel-debuginfo.repo /etc/yum.repos.d/ yum makecache yum -y remove mysql MySQL-python perl-DBD-MySQL dovecot exim qt-MySQL perl-DBD-MySQL dovecot qt-MySQL mysql-server mysql-connector-odbc php-mysql mysql-bench libdbi-dbd-mysql mysql-devel-5.0.77-3.el5 httpd php mod_auth_mysql mailman squirrelmail php-pdo php-common php-mbstring php-cli &> /dev/null yum -y install gcc gcc-c++ gcc-g77 make libtool autoconf patch unzip automake fiex* libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl libmcrypt libmcrypt-devel libpng libpng-devel libjpeg-devel openssl openssl-devel curl curl-devel libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl autoconf automake libaio* iptables -F elif [ "$ifAliCloud" != "" ];then yum makecache yum -y remove mysql MySQL-python perl-DBD-MySQL dovecot exim qt-MySQL perl-DBD-MySQL dovecot qt-MySQL mysql-server mysql-connector-odbc php-mysql mysql-bench libdbi-dbd-mysql mysql-devel-5.0.77-3.el5 httpd php mod_auth_mysql mailman squirrelmail php-pdo php-common php-mbstring php-cli &> /dev/null yum -y install gcc gcc-c++ gcc-g77 make libtool autoconf patch unzip automake fiex* libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl libmcrypt libmcrypt-devel libpng libpng-devel libjpeg-devel openssl openssl-devel curl curl-devel libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl autoconf automake libaio* iptables -F elif [ "$ifcentos" != "" ];then rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5 &> /dev/null sed -i 's/^exclude/#exclude/' /etc/yum.conf yum makecache yum -y remove mysql MySQL-python perl-DBD-MySQL dovecot exim qt-MySQL perl-DBD-MySQL dovecot qt-MySQL mysql-server mysql-connector-odbc php-mysql mysql-bench libdbi-dbd-mysql mysql-devel-5.0.77-3.el5 httpd php mod_auth_mysql mailman squirrelmail php-pdo php-common php-mbstring php-cli &> /dev/null yum -y install gcc gcc-c++ make libtool autoconf patch unzip automake libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl libmcrypt libmcrypt-devel libpng libpng-devel libjpeg-devel openssl openssl-devel curl curl-devel libxml2 libxml2-devel ncurses ncurses-devel libtool-ltdl-devel libtool-ltdl autoconf automake libaio* yum -y update bash iptables -F elif [ "$ifubuntu" != "" ];then apt-get -y update \mv /etc/apache2 /etc/apache2.bak &> /dev/null \mv /etc/nginx /etc/nginx.bak &> /dev/null \mv /etc/php5 /etc/php5.bak &> /dev/null \mv /etc/mysql /etc/mysql.bak &> /dev/null apt-get -y autoremove apache2 nginx php5 mysql-server &> /dev/null apt-get -y install unzip build-essential libncurses5-dev libfreetype6-dev libxml2-dev libssl-dev libcurl4-openssl-dev libjpeg62-dev libpng12-dev libfreetype6-dev libsasl2-dev libpcre3-dev autoconf libperl-dev libtool libaio* apt-get -y install --only-upgrade bash iptables -F elif [ "$ifdebian" != "" ];then apt-get -y update \mv /etc/apache2 /etc/apache2.bak &> /dev/null \mv /etc/nginx /etc/nginx.bak &> /dev/null \mv /etc/php5 /etc/php5.bak &> /dev/null \mv /etc/mysql /etc/mysql.bak &> /dev/null apt-get -y autoremove apache2 nginx php5 mysql-server &> /dev/null apt-get -y install unzip psmisc build-essential libncurses5-dev libfreetype6-dev libxml2-dev libssl-dev libcurl4-openssl-dev libjpeg62-dev libpng12-dev libfreetype6-dev libsasl2-dev libpcre3-dev autoconf libperl-dev libtool libaio* apt-get -y install --only-upgrade bash iptables -F elif [ "$ifgentoo" != "" ];then emerge net-misc/curl elif [ "$ifsuse" != "" ];then zypper install -y libxml2-devel libopenssl-devel libcurl-devel fi ####---- install dependencies ----end#### ####---- install software ----begin#### rm -f tmp.log echo tmp.log ./env/install_set_sysctl.sh ./env/install_set_ulimit.sh if [ -e /dev/xvdb ] && [ "$ifsuse" == "" ] ;then ./env/install_disk.sh fi ./env/install_dir.sh echo "---------- make dir ok ----------" >> tmp.log ./env/install_env.sh echo "---------- env ok ----------" >> tmp.log ./mysql/install_${mysql_dir}.sh echo "---------- ${mysql_dir} ok ----------" >> tmp.log ./nginx/install_nginx-${nginx_version}.sh echo "---------- ${web_dir} ok ----------" >> tmp.log ./php/install_nginx_php-${php_version}.sh echo "---------- ${php_dir} ok ----------" >> tmp.log ./php/install_php_extension.sh echo "---------- php extension ok ----------" >> tmp.log ./res/install_soft.sh echo "---------- IBOS-$ibos_version ok ----------" >> tmp.log ####---- install software ----end#### cat /etc/redhat-release |grep 7\..*|grep -i centos>/dev/null if [ ! $? -ne 0 ] ;then systemctl stop firewalld.service systemctl disable firewalld.service cp /etc/rc.local /etc/rc.local.bak > /dev/null cp /etc/rc.d/rc.local /etc/rc.d/rc.local.bak > /dev/null chmod u+x /etc/rc.local chmod u+x /etc/rc.d/rc.local else echo "it is not centos7" fi ####---- Start command is written to the rc.local ----begin#### if [ "$ifgentoo" != "" ];then if ! cat /etc/local.d/sysctl.start | grep "/etc/init.d/mysqld" > /dev/null;then echo "/etc/init.d/mysqld start" >> /etc/local.d/sysctl.start fi if ! cat /etc/local.d/sysctl.start | grep "/etc/init.d/nginx" > /dev/null;then echo "/etc/init.d/nginx start" >> /etc/local.d/sysctl.start fi if ! cat /etc/local.d/sysctl.start |grep "/etc/init.d/php-fpm" > /dev/null;then echo "/etc/init.d/php-fpm start" >> /etc/local.d/sysctl.start fi elif [ "$ifsuse" != "" ];then if ! cat /etc/rc.d/boot.local | grep "/etc/init.d/mysqld" > /dev/null;then echo "/etc/init.d/mysqld start" >> /etc/rc.d/boot.local fi if ! cat /etc/rc.d/boot.local | grep "/etc/init.d/nginx" > /dev/null;then echo "/etc/init.d/nginx start" >> /etc/rc.d/boot.local fi if ! cat /etc/rc.d/boot.local |grep "/etc/init.d/php-fpm" > /dev/null;then echo "/etc/init.d/php-fpm start" >> /etc/rc.d/boot.local fi else cat /etc/issue |grep 14\..* >/dev/null if [ ! $? -ne 0 ] ;then if ! cat /etc/init.d/rc.local | grep "/etc/init.d/mysqld" > /dev/null;then echo "/etc/init.d/mysqld start" >> /etc/init.d/rc.local fi if ! cat /etc/rc.local | grep "/etc/init.d/nginx" > /dev/null;then echo "/etc/init.d/nginx start" >> /etc/init.d/rc.local fi if ! cat /etc/rc.local |grep "/etc/init.d/php-fpm" > /dev/null;then echo "/etc/init.d/php-fpm start" >> /etc/init.d/rc.local fi else echo "it is not ubuntu 14" if ! cat /etc/rc.local | grep "/etc/init.d/mysqld" > /dev/null;then echo "/etc/init.d/mysqld start" >> /etc/rc.local fi if ! cat /etc/rc.local | grep "/etc/init.d/nginx" > /dev/null;then echo "/etc/init.d/nginx start" >> /etc/rc.local fi if ! cat /etc/rc.local |grep "/etc/init.d/php-fpm" > /dev/null;then echo "/etc/init.d/php-fpm start" >> /etc/rc.local fi fi fi ####---- Start command is written to the rc.local ----end#### ####---- centos yum configuration----begin#### if [ "$ifcentos" != "" ] && [ "$machine" == "x86_64" ];then sed -i 's/^#exclude/exclude/' /etc/yum.conf fi if [ "$ifubuntu" != "" ] || [ "$ifdebian" != "" ];then mkdir -p /var/lock sed -i 's#exit 0#touch /var/lock/local#' /etc/rc.local else mkdir -p /var/lock/subsys/ fi ####---- centos yum configuration ----end#### ####---- mysql password initialization ----begin#### echo "---------- rc init ok ----------" >> tmp.log TMP_PASS=$(date | md5sum |head -c 10) /ibos/server/mysql/bin/mysqladmin -u root password "$<PASSWORD>" cp /ibos/www/system/config/configDefault.php /ibos/www/system/config/config.php sed -i s/'mysql_password'/${TMP_PASS}/g account.log sed -i s/'{host}'/127.0.0.1/g /ibos/www/system/config/config.php sed -i s/'{port}'/3306/g /ibos/www/system/config/config.php sed -i s/'{dbname}'/ibos/g /ibos/www/system/config/config.php sed -i s/'{username}'/root/g /ibos/www/system/config/config.php sed -i s/'{tableprefix}'/ibos_/g /ibos/www/system/config/config.php sed -i s/'{password}'/${TMP_PASS}/g /ibos/www/system/config/config.php sed -i s/'{charset}'/utf_8/g /ibos/www/system/config/config.php chown www:www /ibos/www/system/config/config.php echo "---------- mysql init ok ----------" >> tmp.log ####---- mysql password initialization ----end#### ####---- Environment variable settings ----begin#### if [ "$ifsuse" != "" ];then \cp /etc/profile.d/profile.sh /etc/profile.d/profile.sh.bak echo 'export PATH=$PATH:/ibos/server/mysql/bin:/ibos/server/nginx/sbin:/ibos/server/php/sbin:/ibos/server/php/bin' >> /etc/profile.d/profile.sh export PATH=$PATH:/ibos/server/mysql/bin:/ibos/server/nginx/sbin:/ibos/server/php/sbin:/ibos/server/php/bin else \cp /etc/profile /etc/profile.bak echo 'export PATH=$PATH:/ibos/server/mysql/bin:/ibos/server/nginx/sbin:/ibos/server/php/sbin:/ibos/server/php/bin' >> /etc/profile export PATH=$PATH:/ibos/server/mysql/bin:/ibos/server/nginx/sbin:/ibos/server/php/sbin:/ibos/server/php/bin fi ####---- Environment variable settings ----end#### ####---- restart ----begin#### /etc/init.d/php-fpm restart &> /dev/null /etc/init.d/nginx restart &> /dev/null ####---- restart ----end#### ####---- notify begin ----#### php ./res/extra.php $exeid $TMP_PASS echo "---------- notify ok ----------" >> tmp.log ####---- notify end----#### ####---- log ----begin#### \cp tmp.log $install_log cat $install_log bash source /etc/profile &> /dev/null source /etc/profile.d/profile.sh &> /dev/null bash ####---- log ----end#### <file_sep>/ibos_install_sh/php/install_php_extension.sh #!/bin/bash ifsuse=$(cat /proc/version | grep -i suse) if [ `uname -m` == "x86_64" ];then machine=x86_64 else machine=i686 fi #memcache if [ ! -f memcache-3.0.6.tgz ];then wget http://oss.aliyuncs.com/aliyunecs/onekey/php_extend/memcache-3.0.6.tgz fi rm -rf memcache-3.0.6 tar -xzvf memcache-3.0.6.tgz cd memcache-3.0.6 /ibos/server/php/bin/phpize ./configure --enable-memcache --with-php-config=/ibos/server/php/bin/php-config CPU_NUM=$(cat /proc/cpuinfo | grep processor | wc -l) if [ $CPU_NUM -gt 1 ];then make -j$CPU_NUM else make fi make install cd .. echo "extension=memcache.so" >> /ibos/server/php/etc/php.ini #zend mkdir -p /ibos/server/php/lib/php/extensions/no-debug-non-zts-20090626/ if [ $machine == "x86_64" ];then if [ ! -f ZendGuardLoader-php-5.3-linux-glibc23-x86_64.tar.gz ];then wget http://oss.aliyuncs.com/aliyunecs/onekey/php_extend/ZendGuardLoader-php-5.3-linux-glibc23-x86_64.tar.gz fi tar zxvf ZendGuardLoader-php-5.3-linux-glibc23-x86_64.tar.gz mv ./ZendGuardLoader-php-5.3-linux-glibc23-x86_64/php-5.3.x/ZendGuardLoader.so /ibos/server/php/lib/php/extensions/no-debug-non-zts-20090626/ else if [ ! -f ZendGuardLoader-php-5.3-linux-glibc23-i386.tar.gz ];then wget http://oss.aliyuncs.com/aliyunecs/onekey/php_extend/ZendGuardLoader-php-5.3-linux-glibc23-i386.tar.gz fi tar zxvf ZendGuardLoader-php-5.3-linux-glibc23-i386.tar.gz mv ./ZendGuardLoader-php-5.3-linux-glibc23-i386/php-5.3.x/ZendGuardLoader.so /ibos/server/php/lib/php/extensions/no-debug-non-zts-20090626/ fi echo "zend_extension=/ibos/server/php/lib/php/extensions/no-debug-non-zts-20090626/ZendGuardLoader.so" >> /ibos/server/php/etc/php.ini echo "zend_loader.enable=1" >> /ibos/server/php/etc/php.ini echo "zend_loader.disable_licensing=0" >> /ibos/server/php/etc/php.ini echo "zend_loader.obfuscation_level_support=3" >> /ibos/server/php/etc/php.ini echo "zend_loader.license_path=" >> /ibos/server/php/etc/php.ini <file_sep>/ibos_install_sh/res/install_soft.sh #!/bin/bash #IBOS cd /ibos/www/ if [ ! -f iboscode.zip ];then wget -O iboscode.zip http://ibosupgrade.oss-cn-hangzhou.aliyuncs.com/release/pro/v4.1.0/IBOS_4.1.0%20Pro_20170117203637_virtual.zip fi unzip iboscode.zip chmod -R 777 /ibos/www/system/config chmod -R 777 /ibos/www/data chmod -R 777 /ibos/www/static find ./ -type f | xargs chmod 644 find ./ -type d | xargs chmod 755 chmod -R 777 system/config/ static/ data/ cd - chown -R www:www /ibos/www/<file_sep>/install_ibos.sh #!/bin/bash wget -O iboslinux.zip http://ibosupgrade.oss-cn-hangzhou.aliyuncs.com/linux-one-key/ibos_install_sh.zip rm -rf ibos_install_sh ifredhat=$(cat /proc/version | grep redhat) ifcentos=$(cat /proc/version | grep centos) ifubuntu=$(cat /proc/version | grep ubuntu) ifdebian=$(cat /proc/version | grep -i debian) if [ "$ifredhat" != "" ];then yum install -y zip unzip elif [ "$ifubuntu" != "" ];then apt-get -y install unzip elif [ "$ifdebian" != "" ];then apt-get install -y unzip elif [ "$ifcentos" != "" ];then yum install -y zip unzip fi; unzip iboslinux.zip rm -rf iboslinux.zip chmod -R 777 ./ibos_install_sh/ cd ./ibos_install_sh/ filepath=$(basename "$0") export exeid=$filepath ./install.sh<file_sep>/ibos_install_sh/env/install_dir.sh #!/bin/bash ifubuntu=$(cat /proc/version | grep ubuntu) userdel www groupadd www if [ "$ifubuntu" != "" ];then useradd -g www -M -d /ibos/www -s /usr/sbin/nologin www &> /dev/null else useradd -g www -M -d /ibos/www -s /sbin/nologin www &> /dev/null fi mkdir -p /ibos mkdir -p /ibos/server mkdir -p /ibos/www mkdir -p /ibos/log mkdir -p /ibos/log/php mkdir -p /ibos/log/mysql mkdir -p /ibos/log/nginx mkdir -p /ibos/log/nginx/access chown -R www:www /ibos/log mkdir -p /ibos/server/${mysql_dir} ln -s /ibos/server/${mysql_dir} /ibos/server/mysql mkdir -p /ibos/server/${php_dir} ln -s /ibos/server/${php_dir} /ibos/server/php mkdir -p /ibos/server/${web_dir} mkdir -p /ibos/log/nginx mkdir -p /ibos/log/nginx/access ln -s /ibos/server/${web_dir} /ibos/server/nginx
5f3122d2772f1902c36f890c9c71170f440ea230
[ "PHP", "Shell" ]
6
PHP
banyancheung/ibos-linux-install
e19d6621c90a3be1edd68c8d7ca9d853d9cecfec
1495f3fd3d50d8b33dd2051501b338c704fe28de
refs/heads/master
<repo_name>DrMegahertz/pygments-style-railscasts<file_sep>/pygments_style_railscasts/__init__.py # -*- coding: utf-8 -*- """ railscasts ~~~~~~~~~~ Port of the railscasts color scheme for Vim. Based upon the work of <NAME> and <NAME>. :copyright: Copyright 2011 <NAME> :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Text class RailscastsStyle(Style): """ Port of the railscasts color scheme for Vim. """ default_style = '' background_color = '#222' highlight_color = '#e6e1dc' styles = { Comment: 'italic #bc9458', Error: '#ffc66d', Keyword: '#cc7833', Keyword.Reserved: '#da4939', Keyword.Type: '#5a647e', Name: '#fff', Name.Attribute: '#da4939', Name.Builtin: '#6d9cbe', Name.Builtin.Pseudo: '#fff', Name.Class: '#ffc66d', Name.Constant: '#6d9cbe', Name.Decorator: '#da4939', Name.Function: '#ffc66d', Name.Tag: '#e8bf6a', Number: '#a5c261', Operator: '#fff', Operator.Word: '#cc7833', Punctuation: '#fff', String: '#a5c261', String.Escape: '#da4939', Text: '#fff', }
60c8a8b963bd17a77e1b5f10a6ccd19c4249ff9b
[ "Python" ]
1
Python
DrMegahertz/pygments-style-railscasts
0d6c21acbe98cd63a5d26c567973f5340f556436
cbf05ed27a838f84967be3a9df11595322e329f9
refs/heads/master
<repo_name>lucascr91/nabokov_0.0.1<file_sep>/nabokov.py import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk root = tk.Tk() root.geometry('600x400') root.resizable(False, False) root.title('Nabokov 0.0.1') root.mainloop()<file_sep>/README.md # Nabokov 0.0.1 ![alt text](https://github.com/lucascr91/nabokov_0.0.1/blob/master/nabokovanddimitri.jpeg?raw=true) <NAME> was a Russian novelist born into a vastly wealthy family and who had a first-class education under the instructions of a multitude of tutors. As he claims in his famous autobiography ["Speak, memory"](https://www.amazon.com/Speak-Memory-Autobiography-Revisited-International-ebook/dp/B004KABDWA), he learns to read in English before learning to read in Russian and was common to him hear stories narrated in English by his mother before going to bed. In a family that spoke Russian, English, and French in their daily life, Nabokov was - not surprisingly - already trilingual by the age of 12. Unfortunately, not all children in the world can have access to an education like that enjoyed by Vladimir Nabokov. However, with modern computers, we can build tools that can effectively democratize access to learn. This program is a project that I have been developing to help Brazilian children to learn how to read. In fact, in this first version, my goal is much more humble and very narrowly defined: I want to develop a tool to help my niece to learn how to read. However, the overall principles and the code produced within this project might be useful for someone interested in the development of a similar tool or in going ahead by improving this one. Besides this README file, this repository contains a TASKS file that summarizes the project's goals and lays down the tasks whose completion is necessary to create the program. <file_sep>/TASKS.md # Tasks This first version consists just on a digital implementation of all activities in the book [Alfabetização Fônica](https://www.amazon.com.br/s?i=stripbooks&rh=p_27%3AAlessandra+Gotuzo+Seabra+Capovilla&ref=dp_byline_sr_book_1) by <NAME>. See below the task table: | Task | Status | | ------------------- | ------------------- | | book upload | to be done | | First program: Implement one activity | to be done |
a14f079f96f21328d3adb55fa5770e2c85d9de17
[ "Markdown", "Python" ]
3
Python
lucascr91/nabokov_0.0.1
d1ef58e407a32cd0e7d63b0efb36d42013137752
df327015531e4c72037e2bb5dd55de3180507cc3
refs/heads/master
<repo_name>mrsauravsahu/TicTacToe<file_sep>/README.md # TicTacToe Solution for Tic Tac Toe Console game. <file_sep>/TicTacToe/TicTacToe/TicTacToe.c #define _CRT_SECURE_NO_WARNINGS //Preprocessor Directives #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define SIZE 3 //Data Structures enum Bool { false, true }; typedef enum Bool bool; enum Character { X=88, O=79 }; typedef enum Character character; struct Cell { bool isOccupied; int position; character character; }; typedef struct Cell cell; //Function Prototypes void Initialize(cell [SIZE][SIZE], int, int); bool IsValid(cell[SIZE][SIZE], int); void ReadUserName(char[], int); void Input(cell[SIZE][SIZE], int); void WriteLine(int); void Display(cell[SIZE][SIZE], char); int Toss(); int IsGameOver(cell[SIZE][SIZE]); int next(cell grid[SIZE][SIZE]); //The main Function int main() { //Variable Declaration cell grid[SIZE][SIZE]; char user1[40], user2[40], temp[40], playAgain, symbol; int firstUser, count, isItOver, position; bool aiWon; character enumSymbol; //Game Logic while (1) { Initialize(grid, SIZE, SIZE); count = 0; ReadUserName(user1, 1); strcpy(user2, "AI"); firstUser = Toss(); switch (firstUser) { case 0: printf("%s won the toss.", user1); aiWon = false; break; case 1: printf("%s won the toss.", user2); aiWon = true; strcpy(temp, user1); strcpy(user1, user2); strcpy(user2, temp); } printf("\nPLAYERS"); printf("\nPlayer 1: %s: Assigned piece: X", user1); printf("\nPlayer 2: %s: Assigned piece: O", user2); while (count < (SIZE*SIZE)) { Display(grid, 'P'); //system("cls"); if(aiWon ==true) { if(count%2 == 0) { position = next(grid); if (count % 2 == 0) { symbol = 'X'; enumSymbol = X; } else { symbol = 'O'; enumSymbol = O; } grid[(position - 1) / SIZE][(position - 1) % SIZE].isOccupied = true; grid[(position - 1) / SIZE][(position - 1) % SIZE].character = enumSymbol; } else { Input(grid, count); } } else { if(count%2 == 1) { position = next(grid); if (count % 2 == 0) { symbol = 'X'; enumSymbol = X; } else { symbol = 'O'; enumSymbol = O; } grid[(position - 1) / SIZE][(position - 1) % SIZE].isOccupied = true; grid[(position - 1) / SIZE][(position - 1) % SIZE].character = enumSymbol; } else { Input(grid, count); } } Display(grid, 'M'); if (count >= (2 * SIZE - 2)) { isItOver = IsGameOver(grid); if (isItOver != -1) { if (isItOver == 79) strcpy(user1, user2); printf("\n%s won! Congratulations!!", user1); break; } } ++count; } if (count == SIZE*SIZE) { printf("\nIt's a draw. Well played, both of you!"); } printf("\nDo you want to start a new game? (y/n): "); scanf(" %c", &playAgain); if (playAgain == 'Y' || playAgain == 'y') { system("cls"); continue; } else { break; } } } //Function Definition void Initialize(cell grid[SIZE][SIZE], int rowSize, int columnSize) { int i, j; for (i = 0; i < rowSize; i++) { for (j = 0; j < columnSize; j++) { (grid[i][j]).isOccupied = false; (grid[i][j]).position = i*rowSize + j + 1; } } } bool IsValid(cell grid[SIZE][SIZE], int position) { int row, column; if (position <= 0 || position > SIZE*SIZE)return false; row = (position - 1) / SIZE; column = (position - 1) % SIZE; if ((grid[row][column]).isOccupied == true)return false; return true; } void ReadUserName(char name[], int num) { printf("\nEnter player name %d: ", num); scanf("%s", name); } void Input(cell grid[SIZE][SIZE], int number) { char symbol; character enumSymbol; bool isValid = false; char position[30]; int pos = 0; if (number % 2 == 0) { symbol = 'X'; enumSymbol = X; } else { symbol = 'O'; enumSymbol = O; } printf("\nEnter position to draw %c: ", symbol); while (1) { scanf(" %s", position); pos = atoi(position); isValid = IsValid(grid, pos - 48) || IsValid(grid, pos); if (isValid == false) { printf("\nPlease enter a valid input. Try again: "); continue; } break; } pos = IsValid(grid, pos) ? pos : pos - 48; grid[(pos - 1) / SIZE][(pos - 1) % SIZE].isOccupied = true; grid[(pos - 1) / SIZE][(pos - 1) % SIZE].character = enumSymbol; } void WriteLine(int rowSize) { int i; printf("\n"); for (i = 0; i < 2 * rowSize; i++) { if (i % 2 == 0) printf("_"); else printf(" "); } } void Display(cell grid[SIZE][SIZE], char mode) { int i, j; switch (mode) { case 'M': { WriteLine(SIZE); for (i = 0; i < SIZE; i++) { printf("\n"); for (j = 0; j < SIZE; j++) { if (grid[i][j].isOccupied == false) { printf(" "); } else { printf("%c ", (int)grid[i][j].character); } } } WriteLine(SIZE); } break; case 'P': { WriteLine(SIZE); for (i = 0; i < SIZE; i++) { printf("\n"); for (j = 0; j < SIZE; j++) { if (grid[i][j].isOccupied == false) { printf("%d ", grid[i][j].position); } else { printf(" "); } } } WriteLine(SIZE); } } } int Toss() { srand((int)time(NULL)); return (rand() % 2); } void InitializeTheArray(int a[], int size, int num) { int i; for (i = 0; i < size; i++) { a[i] = num; } } int IsGameOver(cell grid[SIZE][SIZE]) { int i, j; bool flag = false; int rows[SIZE]; int columns[SIZE]; int diag[2]; InitializeTheArray(rows, SIZE, 0); InitializeTheArray(columns, SIZE, 0); InitializeTheArray(diag, 2, 0); for (i = 0; i < SIZE; ++i) { for (j = 0; j < SIZE; ++j) { if (grid[i][j].isOccupied == true && grid[i][j].character == X) { rows[i]++; columns[j]++; } if (grid[i][j].isOccupied == true && grid[i][j].character == O) { rows[i]--; columns[j]--; } } } for (i = 0; i < SIZE; i++) { if (grid[i][i].isOccupied == true && grid[i][i].character == X) { diag[0]++; } if (grid[i][i].isOccupied == true && grid[i][i].character == O) { diag[0]--; } } for (i = 0; i < SIZE; i++) { if (grid[i][SIZE - i - 1].isOccupied == true && grid[i][SIZE - i - 1].character == X) { diag[1]++; } if (grid[i][SIZE - i - 1].isOccupied == true && grid[i][SIZE - i - 1].character == O) { diag[1]--; } } for (i = 0; i < SIZE; i++) { if (rows[i] == SIZE || columns[i] == SIZE)return 88; if (rows[i] == -SIZE || columns[i] == -SIZE)return 79; } for (i = 0; i < 2; i++) { if (diag[i] == SIZE)return 88; if (diag[i] == -SIZE)return 79; } return -1; } int next(cell grid[SIZE][SIZE]) { int n; do { n = (rand() % 9) + 1; }while(IsValid(grid, n)==false); return n; }
4eeeaf8e1b5a5cf083d7f6a7e65f02acd58390f9
[ "Markdown", "C" ]
2
Markdown
mrsauravsahu/TicTacToe
62b18cce149622466b2006442120270c366718ae
946af64897d6f86b93817720bc4e3dadb8562e10
refs/heads/master
<file_sep>package com.le.api; import com.le.enums.RespStatus; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class CommResp<T> { private String code; private String message; private T data; public static CommResp ok(RespStatus status, Object data) { return new CommResp(status.code(), status.message(), data); } public static CommResp error(RespStatus status) { return new CommResp(status.code(), status.message(), null); } public static CommResp ok(String code, String message, Object data) { return new CommResp(code, message, data); } public static CommResp error(String code, String message) { return new CommResp(code, message, null); } } <file_sep>package com.le.utils; public class JsonUtil { }
4c397df188d8de077304441e281678801b7f0db9
[ "Java" ]
2
Java
Ale-CN/le-cloud
e44a9f5c29cbd86d1c3ed15653c57a0d21512dc7
3fa07495a6cdc739c49d17f088113660d2a96d13
refs/heads/master
<repo_name>evvil/my-boring-python<file_sep>/holiday-gui/holiday-gui.py import datetime,easygui,math,os,re,sys,time #导入模块 while True: #循环 summer_holiday = datetime.datetime(2017, 8, 29) #暑假结束时间 summer_holiday_start = datetime.datetime(2017, 7, 8) #暑假开始时间 now_time = datetime.datetime.now() #现在的时间 today = datetime.date.today() summer_holiday_last = (summer_holiday - now_time).days #暑假还剩下多少天(错误) summer_holiday_last_ture = summer_holiday_last+1 #暑假还剩下多少天(正确) summer_holiday_last_baifenbi = (((now_time - summer_holiday_start).days)/53)*100 #计算百分比 summer_holiday_last_baifenbi_ture = math.floor(summer_holiday_last_baifenbi) #换成整数 bfb = open("/home/redapple/.holiday/bfb.txt", "w") #打开百分比的写入文件(请按自己实际情况更改) bfb.write(str(summer_holiday_last_baifenbi_ture)) #写入百分比 bfb.close() #关闭文件 os.system("rm /home/redapple/.holiday/jdt.txt") #删除jdt文件 os.system("python3 /home/redapple/.holiday/jdt.py >> /home/redapple/.holiday/jdt.txt") #把另外一个py程序输出的百分比进度条写入到文件里(路径自己修改)比 file = open("/home/redapple/.holiday/homework.txt", "r") #打开作业列表(自己修改路径) jdt = open("/home/redapple/.holiday/jdt.txt", "r").read() #打开进度条文件(自己修改路径) summer_holiday_homework_monitor = open("/home/redapple/.holiday/homework.txt", "r").read() mark = re.compile('`') #设定要查找的内容(注意在作业前要加`) find = re.findall(mark, summer_holiday_homework_monitor) #查找 find_mount = len(find) #显示有多少个 finish_homework = 14-find_mount #用作业总数减去得到的结果(自己改作业总数) calc = math.floor((finish_homework/15)*100) #计算 homework_baifenbi = open("/home/redapple/.holiday/homework_bfb.txt", "w") #打开一个百分比文件 homework_baifenbi.write(str(calc)) #写入计算的百分比 homework_baifenbi.close() os.system("rm /home/redapple/.holiday/homework_jdt.txt") #删掉已有的文件(自己改路径) os.system('python3 /home/redapple/.holiday/homework_jdt.py > /home/redapple/.holiday/homework_jdt.txt') #把进度条写入文件 homework_jindutiao = open("/home/redapple/.holiday/homework_jdt.txt", "r").read() #读取文件 tips = "今天是" + str(today) + "\n" + "距离暑假结束还有" + str(summer_holiday_last_ture) + "天" + "\n" + "暑假已经过去了" + str(jdt) + "\n" + "暑假作业已经完成了" + str(homework_jindutiao) #配置窗口要显示的内容 tips_finally = easygui.codebox(tips,"倒计时小程序",file) #显示窗口 file.close() #关闭文件 if tips_finally == None: #如果用户按了关闭或取消 break #退出程序 else: #反之 file = open("/home/redapple/.holiday/homework.txt", "w") #打开homework文档(自己修改路径) file.write(tips_finally) #写入用户输入新的内容 file.close() #关闭文件
571434fe8e8ee1451473fe3b16a57d2227716c2b
[ "Python" ]
1
Python
evvil/my-boring-python
0677db8ce43edd8eaefbbbb114535121c1eb1648
9f2a4f95638f12ae3709e26227ee21b3359354b3
refs/heads/master
<repo_name>lazyp/js_checker<file_sep>/js_checker.js /** *@author <EMAIL> */ (function() { /************************************内部变量、对象**************************************/ var _emailRegExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/, _urlRegExp = /^(http|https):\/\/.*$/; /*****************************************end*******************************************/ var __checker = { /** * 检验是否为数字 */ isValidNumeric : function(num) { if (isFinite(num)) { return !isNaN(parseInt(num)); } return false; } , /** *是否为手机号码 */ isMobile : function(tel){ if(__checker.isValidNumeric(tel) && tel.length == 11){ return true; }else{ return false; } }, /** * url是否合法性 */ isValidUrl : function(url) { return _urlRegExp.test(url); } , // 检验IP isValidIP : function(ip) { try { var nums = ip.split("."); if (nums.length != 4) { return false; } for ( var index = 0; index < nums.length; index++) { var num = nums[index]; if (this.isValidNumeric(num)) { num = parseInt(num); if (num > 255 || num < 0) { return false; } } else { return false; } } } catch (e) { return false; } return true; }, isValidEmail : function(email){ return _emailRegExp.test(email); } }; // 注册 window.checker = __checker; })(); <file_sep>/README.md 各种验证工具集. <pre> 如:url、ip、数字等 </pre> ```javascript checker.isValidUrl(url);//检测url合法性 checker.isValidIP(ip);//检测ip合法性 checker.isValidNumeric(num);//检测数字合法性 checker.isValidEmail(email);//检测email合法性 checker.isMobile(tel);//检测是否为手机号码 ```
49d28aabb5c28eb10fa9e7937bf2cbc7ea9624aa
[ "JavaScript", "Markdown" ]
2
JavaScript
lazyp/js_checker
1083f0e10a72322ee38c191a3faf9df683572367
9564cc1a02fa181cebd584a12075a7291a682269
refs/heads/master
<file_sep>import datetime import os import shutil from pathlib import Path print('This Script will back up a valid source file path: ') print('The program works by copying the input directory to a specified destination path: ') source_path = Path(input(' Please enter the source c:file path: ')) if not source_path.exists(): print('Oops, source path provided does not exist!') else: print('The source path is valid. Proceeding in copying files process... ') target_path = Path(input(' Please enter the target file path: ')) if not target_path.exists(): print('Oops, the destination path provided does not exist!') makenew = input('Would you like to create the missing directory: True or False?') if makenew == (True): shutil.rmtree(target_path) os.makedirs(target_path) shutil.copytree(source_path, target_path) if makenew == (False): print('Back up Process Canceled') else: print('The destination path is valid. Copying files... ') shutil.rmtree(target_path) shutil.copytree(source_path, target_path) print('Back up Process Complete')
a4ac3a9d8543a21057bcbcb2b219fdcc5e58ef04
[ "Python" ]
1
Python
mxg0633/Python-Scripts
273d6d23990bf8ff4bcc4716af5ea8ad87293470
94664d34e0939248fbd5528390b280da1812bb30
refs/heads/master
<repo_name>stoleS/startit-ar<file_sep>/startit-ar/Assets/vb_anim.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using Vuforia; public class vb_anim : MonoBehaviour, IVirtualButtonEventHandler { public GameObject vbBtnObj; public GameObject canvas; public Animator sphereAni; private bool spawned = false; // Use this for initialization void Start () { vbBtnObj = GameObject.Find("spawnButton"); vbBtnObj.GetComponent<VirtualButtonBehaviour>().RegisterEventHandler(this); sphereAni.GetComponent<Animator>(); sphereAni.speed = 0f; } public void OnButtonPressed(VirtualButtonBehaviour vb) { if(!spawned) { sphereAni.Play("sphere_anim", -1, 0f); sphereAni.speed = 1f; spawned = true; } else { sphereAni.Play("sphere_anim_exit", -1, 0f); spawned = false; } } public void OnButtonReleased(VirtualButtonBehaviour vb) { } // Update is called once per frame void Update () { } }
2ce6019bf07f49e388fff632e23a7876d7e6d83c
[ "C#" ]
1
C#
stoleS/startit-ar
31c67a0b9fcc4323640fc6c16c8c844040732481
1a1c5b278249fc829f46b6dde2d7f9128c97c048
refs/heads/master
<file_sep># Following tutorial found # https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd from keras.models import Sequential from keras.layers import Convolution2D,MaxPooling2D,Flatten,Dense # Initialize the CNN classifier = Sequential() classifier.add(Convolution2D(32,(3,3), input_shape = (64,64,3),activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2,2))) classifier.add(Flatten()) # Full Conection classifier.add(Dense(activation = 'relu',units = 128)) classifier.add(Dense(activation = 'sigmoid',units = 1)) classifier.compile(optimizer = 'adam',loss = 'binary_crossentropy',metrics = ['accuracy']) # load data in from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory(directory = 'data/dataset/',target_size = (64,64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory(directory = 'data/dataset-test/',target_size = (64,64), batch_size = 32, class_mode = 'binary') # Train network from IPython.display import display from PIL import Image #train classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 1, validation_data = test_set, validation_steps = 800) <file_sep>import glob from keras.preprocessing.image import load_img folder_path = 'data/dataset\\' import os all_plants = [x[0].replace(folder_path,'') for x in os.walk(folder_path)] format_error = 0 mode_error = 0 oserrors = 0 for plant in all_plants[1:]: for img_path in glob.glob('data/dataset/{}/*.jpg'.format(plant)): try: img = load_img(img_path) except OSError: oserrors += 1 os.remove(img_path) oserrors # if img.format != 'JPEG': # # print("Format ERROR") # # print(img_path) # # print() # format_error += 1 # # if img.mode != 'RGB': # # print("Mode ERROR") # # print(img_path) # # print() # print(img.mode) # mode_error += 1 mode_error format_error <file_sep># Plant-Classifier We are going to make real good classify plant Multi class/ not binary #$weg Currenty working with 40% Classification rate <file_sep>from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) from keras import backend as K K.tensorflow_backend._get_available_gpus() <file_sep>#https://towardsdatascience.com/a-simple-cnn-multi-image-classifier-31c463324fa import pandas as pd import numpy as np import itertools import keras from sklearn import metrics from sklearn.metrics import confusion_matrix from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img from keras.models import Sequential from keras import optimizers from keras.preprocessing import image from keras.layers import Dropout, Flatten, Dense from keras import applications from keras.utils.np_utils import to_categorical import matplotlib.pyplot as plt import matplotlib.image as mpimg import math import datetime import time #Default dimensions we found online img_width, img_height = 224, 224 #Create a bottleneck file top_model_weights_path = 'bottleneck_fc_model.h5' # loading up our datasets train_data_dir = 'data/dataset' validation_data_dir = 'data/dataset-validation' test_data_dir = 'data/dataset-test' # number of epochs to train top model EPOCHS = 100 #this has been changed after multiple model run # batch size used by flow_from_directory and predict_generator batch_size = 50 #Loading vgc16 model vgg16 = applications.VGG16(include_top=False, weights='imagenet') datagen = ImageDataGenerator(rescale=1. / 255) #needed to create the bottleneck .npy files # Training start = datetime.datetime.now() generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) nb_train_samples = len(generator.filenames) num_classes = len(generator.class_indices) predict_size_train = int(math.ceil(nb_train_samples / batch_size)) bottleneck_features_train = vgg16.predict_generator(generator, predict_size_train) np.save('bottleneck_features_train.npy', bottleneck_features_train) end= datetime.datetime.now() elapsed= end-start print ('Time: ', elapsed) #training data generator_top = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', shuffle=False) nb_train_samples = len(generator_top.filenames) num_classes = len(generator_top.class_indices) # load the bottleneck features saved earlier train_data = np.load('bottleneck_features_train.npy') # get the class labels for the training data, in the original order train_labels = generator_top.classes # convert the training labels to categorical vectors train_labels = to_categorical(train_labels, num_classes=num_classes) # validation start = datetime.datetime.now() generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) nb_train_samples = len(generator.filenames) num_classes = len(generator.class_indices) predict_size_train = int(math.ceil(nb_train_samples / batch_size)) bottleneck_features_train = vgg16.predict_generator(generator, predict_size_train) np.save('bottleneck_features_validation.npy', bottleneck_features_train) end= datetime.datetime.now() elapsed= end-start print ('Time: ', elapsed) #validation data generator_top = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', shuffle=False) nb_train_samples = len(generator_top.filenames) num_classes = len(generator_top.class_indices) # load the bottleneck features saved earlier validation_data = np.load('bottleneck_features_validation.npy') # get the class labels for the training data, in the original order validation_labels = generator_top.classes # convert the training labels to categorical vectors validation_labels = to_categorical(validation_labels, num_classes=num_classes) # test start = datetime.datetime.now() generator = datagen.flow_from_directory( test_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) nb_train_samples = len(generator.filenames) num_classes = len(generator.class_indices) predict_size_train = int(math.ceil(nb_train_samples / batch_size)) bottleneck_features_train = vgg16.predict_generator(generator, predict_size_train) np.save('bottleneck_features_test.npy', bottleneck_features_train) end= datetime.datetime.now() elapsed= end-start print ('Time: ', elapsed) #validation data generator_top = datagen.flow_from_directory( test_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', shuffle=False) nb_train_samples = len(generator_top.filenames) num_classes = len(generator_top.class_indices) # load the bottleneck features saved earlier test_data = np.load('bottleneck_features_test.npy') # get the class labels for the training data, in the original order test_labels = generator_top.classes # convert the training labels to categorical vectors test_labels = to_categorical(test_labels, num_classes=num_classes) test_labels.shape validation_labels.shape train_labels.shape start = datetime.datetime.now() model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(100, activation=keras.layers.LeakyReLU(alpha=0.3))) model.add(Dropout(0.5)) model.add(Dense(50, activation=keras.layers.LeakyReLU(alpha=0.3))) model.add(Dropout(0.3)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc']) history = model.fit(train_data, train_labels, epochs=EPOCHS, batch_size=batch_size, validation_data=(validation_data, validation_labels)) model.save_weights(top_model_weights_path) (eval_loss, eval_accuracy) = model.evaluate( validation_data, validation_labels, batch_size=batch_size, verbose=1) print('[INFO] accuracy: {:.2f}%'.format(eval_accuracy * 100)) print('[INFO] Loss: {}'.format(eval_loss)) end= datetime.datetime.now() elapsed= end-start print ('Time: ', elapsed) #Graphing our training and validation acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) figure = plt.figure(figsize = (10,7),dpi = 216) plt.plot(epochs, acc, 'r', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend() plt.savefig("Plots/Train_validation_accuracy.png") plt.show() figure = plt.figure(figsize = (10,7),dpi = 216) plt.plot(epochs, loss, 'r', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend() plt.savefig("Plots/Train_validation_loss.png") plt.show() model.evaluate(test_data,test_labels) preds = np.round(model.predict(test_data),0) import glob import os folder_path = 'data/dataset\\' all_plants = [x[0].replace(folder_path,'') for x in os.walk(folder_path)] import pandas as pd metrics.accuracy_score(test_labels,preds) classification_metrics = metrics.classification_report(test_labels,preds,target_names = all_plants[1:]) type(classification_metrics) print(classification_metrics)
b9b9aa6660af9ef532ede47f4a5e4151165da118
[ "Markdown", "Python" ]
5
Python
wfath/Plant-Classifier
28057352910eee0776cc38e672e57844136470a2
70d7ee4b325864cf49f34875ab635f621e6c0058
refs/heads/master
<repo_name>a1exweb/default-start<file_sep>/gulpfile.js const gulp = require('gulp'); const cleanCSS = require('gulp-clean-css'); const jsmin = require('gulp-jsmin'); const htmlmin = require('gulp-htmlmin'); const tinify = require('gulp-tinify'); const rename = require('gulp-rename'); // Сжатие css файлов gulp.task('minify-css', () => { return gulp.src('src/css/*.css') .pipe(cleanCSS()) .pipe(gulp.dest('build/css/')) }); // Перенос и сжатых js файлов gulp.task('move-js', () => { return gulp.src('src/js/*.min.js') .pipe(gulp.dest('build/js')) }); // Перенос и сжатие js-файлов gulp.task('minify-js', () => { return gulp.src(['src/js/*.js', '!src/js/*.min.js']) .pipe(jsmin()) // .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('build/js')) }); // Сжатие и перенос html файлов gulp.task('htmlmin', () => { return gulp.src('src/*.html') .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('build/')) }); // Перенос шрифтов gulp.task('move-fonts', () => { return gulp.src('src/fonts/**/*.*') .pipe(gulp.dest('build/fonts')) }); // Сжатие и перенос картинок gulp.task('imagemin', () => { return gulp.src('src/img/**/*.*') .pipe(tinify('mfmpwGzQZWQ0TB6XwDv9tb31b8blLhRq')) .pipe(gulp.dest('build/img')) }); // Перенос phpmailer gulp.task('move-phpmailer', () => { return gulp.src('src/phpmailer/*.*') .pipe(gulp.dest('build/phpmailer')) }); // gulp.task('move-php', () => { return gulp.src('src/*.php') .pipe(gulp.dest('build/')) }); gulp.task('build', gulp.series('minify-css', 'move-js', 'htmlmin', 'minify-js', 'move-fonts', 'move-phpmailer', 'move-php'));
9e83ae9fb4356d5452bc2f1554bd370b171c58da
[ "JavaScript" ]
1
JavaScript
a1exweb/default-start
274c49a7dbe407db5b882d10f1cadfc3d26416d3
9bfd7efb92730b94080834d9c5f4cbe0d984acd5
refs/heads/master
<repo_name>OdioALouise/interactive<file_sep>/public/javascripts/app/libs/app.js define(['text!views/templates/index.html'], function (Index){ console.log('Todas las librerías cargadas y listas.'); $('div#main-container').html(_.template(Index, {app_name: 'Interactive'})); });
fbfeba86799d4b7a3f8297ce3e62b4378a545a29
[ "JavaScript" ]
1
JavaScript
OdioALouise/interactive
7cdb9857048dd26ed21493ebd0a3ef156352ad61
7e0f10c6151de5b41d9b44be0aab0ea432bb4bba
refs/heads/master
<repo_name>dreamindustries/telegraph-automation<file_sep>/routes/light/index.js 'use strict' var driver = require('./lightsdriver') var _ = require('lodash') var Lights = new driver.Lights var areas = require('./areas') var makeInputMatrix = function(){ var matrix = [] for (var x=0;x<16;x++){ var d2 = [] for (var y=0;y<7;y++){ d2.push(undefined) } matrix.push(d2) } return matrix } // GET /light/area/:name exports.areaGet = function (req, res) { res.send(200, areas.getAreaStatus(Lights.matrix, req.params.name)) } // PATCH /light/area/:name exports.areaPatch = function (req, res) { Lights.manipulateArea(req.params.name, req.body.action) res.send(200, areas.getAreaStatus(Lights.matrix, req.params.name)) } // GET /light/area exports.areaGetAll = function (req, res) { res.send(200, _.keys(areas.shapes).map(function (areaname) { return areas.getAreaStatus(Lights.matrix, areaname) }) )} // PATCH /light/area exports.areaPatchMultiple = function (req, res) { var response = [] req.body.forEach(function (area) { Lights.manipulateArea(area.name, area.action) response.push(areas.getAreaStatus(Lights.matrix, area.name)) }) res.send(200, response) } // GET /light/matrix exports.matrixGet = function (req, res) { res.send(200, Lights.matrix) } // PATCH /light/matrix exports.matrixPatch = function (req, res) { Lights.writeMatrix(req.body) res.send(200, Lights.matrix) } // GET /light/xy/:row/:x/ exports.rowGet = function (req, res) { var row = _.at(Lights.matrix,[req.params.row]) if (!req.params.x){ // row res.jsonp(row) }else{ // single cell res.jsonp(_.at(row, [req.params.x])) } } // PATCH /light/xy/:row/:x/ exports.rowPatch = function (req, res) { if (!req.params.x){ // row var row = (req.params.row % 2 === 0) ? _.range(8,16) : _.range(0,8) row.forEach(function(cell){ Lights.writeSingle(req.params.row-1, cell, req.body.action) }) }else{ Lights.writeSingle(req.params.row-1, req.params.x-1, req.body.action) } res.jsonp({res:'ok'}) } <file_sep>/routes/light/lightsdriver.js var SerialPort = require("serialport").SerialPort var fs = require('fs') var _ = require('lodash') var areas = require('./areas') function makeMatrix (){ // returns an empty matrix, 2dimensional array of 8 * 14 var matrix = [] var count = 1 for (var x=0;x<16;x++){ var d2 = [] for (var y=0;y<7;y++){ d2.push(0) count++ } matrix.push(d2) } return matrix } var coordTrans = function (x,y){ // transform coordinatates from 16x7 to 8x14 matrix var nx = Math.round((x-1)/2) if (x % 2 === 0){ // even return [nx, y] }else{ // odd return [nx, y+7] } } function Lights(deviceName) { var self = this this.matrix = makeMatrix() this.device = deviceName || '/dev/tty.usbmodem1431' this.serial setInterval(this.sendMatrix, 2050) fs.stat(this.device, function(err, stats){ if (err){ console.log("Couldn't stat "+ self.device) process.exit() } self.serial = new SerialPort(self.device, {baudrate: 115200}) self.serial.on("open", function () { console.log("Started serial connection.") self.writeMatrix(this.matrix) // TODO write matrix every x microseconds //setInterval(this.sendMatrix, 250) }); }) } // TODO write matrix over serial //Lights.prototype.sendMatrix = function () { //var buf = new Buffer(112); //for(var i=0;i<112;i++){ //buf.writeUInt8(254, i); //} //serial.write(buf); //} Lights.prototype.writeMatrix = function(input) { var self = this this.matrix = _.merge(this.matrix, input) } Lights.prototype.writeSingle = function (x, y, action) { // TODO need to fetch turnon/off events if(parseInt(action) !== NaN){ var brightness = parseInt(action) if(brightness <= 255 && brightness >= 0){ this.matrix[x][y] = brightness }else{ console.log('action is something else: '+action) } } } Lights.prototype.manipulateArea = function (areaname, action) { var self = this areas.setArea(areaname, function(x,y){ self.writeSingle(x, y, action) }) } module.exports.Lights = Lights module.exports.coordTrans = coordTrans <file_sep>/README.markdown ## Telegraph Lights ### Dependencies * SPI interface * Node.js ### Run API 1. ```npm install``` 2. add serial port on line 36 in ```routes/light/lightsdriver.js``` 3. ```node app``` ### Install interface ```npm install -g bower && cd public && bower install```
ebf90a3efb6e8c1405e75f27ca088b7c772d3d9f
[ "JavaScript", "Markdown" ]
3
JavaScript
dreamindustries/telegraph-automation
cd04d6b430f9edcbc8c23ac5d9e93bfac8cac190
013b521b0f9c431f431616c3103e39d87c5beeda
refs/heads/master
<file_sep>from multiprocessing.dummy import Pool from service import ClttService, PhoneService, UserService from verificationUntils import Chaojiying, CrackTouClick from model import BaseInfo # 超级鹰用户名、密码、软件ID(需要注册) CHAOJIYING_USERNAME = 'XXXXXX' CHAOJIYING_PASSWORD = '<PASSWORD>' CHAOJIYING_SOFT_ID = 'XXXXXX' CHAOJIYING_KIND = 9004 # 验证码类型 # 报名链接 CLTTURL = 'http://scbm.cltt.org/pscweb/signUp.html' # 报名城市 CITY = '成都市' def run(base_info, user_list, chaojiying, phone_dict): """ 将参数装进数据列表启动进程 """ # ClttService.sign_up函数的参数列表 data_list = [] # 参数列表[(base_info, user, chaojiying, phone_touple), (base_info, user, chaojiying, phone_touple)....] phone_dict_items = phone_dict.items() for user, phone_touple in zip(user_list, phone_dict_items): data = (base_info, user, chaojiying, phone_touple) data_list.append(data) # 创建用户数量个进程 pool = Pool(len(user_list)) # 每个进程启动功能函数 pool.map(sign_up, data_list) pool.close() pool.join() def sign_up(data): # 调用报名 ClttService.sign_up(data[0], data[1], data[2], data[3]) if __name__ == '__main__': # 普通话报名网址 cltt_url = CLTTURL # 报名城市 city = CITY # 手机号获取网址 phone_url = 'https://www.yinsiduanxin.com/china-phone-number/page/{}.html' # 客户信息文件 user_path = 'config.txt' # 需要照片 格式: 张三#女#汉族#5115XXXXXXXXXXX#C:\\Users\\ahao\\Desktop\\WPS图片-修改尺寸.jpg # 不需要照片格式: 张三#女#汉族#5115XXXXXXXXXXX#无 # 读取客户信息 user_list = UserService().get_user(user_path) user_num = len(user_list) # 创建基本信息对象 base_info = BaseInfo(cltt_url, city).get_base_info() # 创建手机验证码服务对象 phoneService = PhoneService(phone_url, user_num) phone_dict = phoneService.get_phone_dict() # 创建超级鹰验证对象 chaojiying = Chaojiying(CHAOJIYING_USERNAME, CHAOJIYING_PASSWORD, CHAOJIYING_SOFT_ID, CHAOJIYING_KIND) # 启用多进程报名服务 run(base_info, user_list, chaojiying, phone_dict) <file_sep>requests~=2.23.0 lxml~=4.5.1 selenium~=3.141.0 pillow~=7.2.0<file_sep>import re import requests import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from lxml import etree from model import Phone, Browser, User from verificationUntils import CrackTouClick class PhoneService: def __init__(self, url, phone_num): self.phone_dict = {} # 需要获取的页数 page_num = phone_num // 8 + 1 for i in range(1, page_num + 1): phone_d = Phone(url.format(i)).get_phone() self.phone_dict.update(phone_d) def get_phone_dict(self): return self.phone_dict @staticmethod def get_phone_code(detail_href): headers = { 'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', } url = 'https://www.yinsiduanxin.com' + detail_href res = requests.get(url, headers=headers) resp = res.content html = etree.HTML(resp) td = html.xpath('//tbody//tr//td//a[@href="/receive-sms-from/畅言普通话"]/../..//' 'td[@style="word-break:break-word;"]//text()') try: phone_code = re.search('\\d{6}', td[0]).group() except IndexError: phone_code = 0 print('手机验证码为: ', phone_code) return phone_code class ClttService: """ 普通话报名服务类 """ @staticmethod def sign_up(base_info, user, chaojiying, phone_touple): """ 普通话报名 :base_info: 基本信息类实例 :user: user实例 :chaojiying: 超级鹰实例 :phone_touple: 手机号 """ print(phone_touple[0]) print(user.name + ' https://www.yinsiduanxin.com' + phone_touple[1]) browser = Browser().getBrowser() # 创建浏览器对象 # browser.maximize_window() # 窗口最大化 browser.get(base_info['url']) # 访问报名链接 wait = WebDriverWait(browser, 600) # 设置显示等待 # 选择城市 getCheckCity = wait.until( lambda browser: browser.find_elements_by_xpath('//li[@class="fl item"]')) for i in getCheckCity: # print(i.text) if i.text == base_info['city']: i.click() break # 选择测试时间 wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'choose-time'))) choose_time_js = ''' function choose_time(){ time_li = document.getElementsByClassName('choose-time')[0].getElementsByTagName('li'); mycars = new Array(); for(i=0; i < time_li.length; i++){ mycars.push(i); } index = mycars.splice(Math.floor(Math.random()*mycars.length), 1) document.getElementsByClassName('choose-time')[0].getElementsByTagName('li')[index].getElementsByTagName('a')[0].click(); while(document.getElementsByClassName('data-none')[0] != undefined && mycars.length != 0){//当剩余名额为零,重新选择测试时间 index = mycars.splice(Math.floor(Math.random()*mycars.length), 1) document.getElementsByClassName('choose-time')[0].getElementsByTagName('li')[index].getElementsByTagName('a')[0].click(); } }choose_time(); ''' browser.execute_script(choose_time_js) # 点击下一步 阅读报名须知 wait.until(EC.element_to_be_clickable((By.ID, 'toReadNote'))).click() browser.execute_script('document.getElementById("toReadNote").click()') # 识别极验 CrackTouClick(browser, wait, chaojiying).crack_touh_click(0, 4, user) # 点击下一步 填写报名信息 wait.until(EC.element_to_be_clickable((By.ID, 'lastRead'))).click() # 上传图片 if user.photo != '无': wait.until(EC.presence_of_element_located((By.NAME, 'file'))).send_keys(user.photo) # 填写考生姓名 wait.until(EC.presence_of_element_located((By.NAME, 'name'))).send_keys(user.name) # 选择性别 if user.sex == '男': choose_sex_js = 'document.getElementsByName("gender")[0].parentElement.getElementsByTagName("i")[0].click()' else: # 女 choose_sex_js = 'document.getElementsByName("gender")[0].parentElement.getElementsByTagName("i")[1].click()' browser.execute_script(choose_sex_js) # 选择民族 ClttService.choose_nation(browser, user.nation) # 身份证号 wait.until(EC.presence_of_element_located((By.NAME, 'idcard'))).send_keys(user.idCard) # 从事职业 js = 'document.getElementsByName("employment")[0].parentElement.getElementsByTagName("dd")[8].click()' browser.execute_script(js) # 所在单位 wait.until(EC.presence_of_element_located((By.NAME, 'wunit'))).send_keys(user.address) # 联系电话 wait.until(EC.presence_of_element_located((By.NAME, 'telcontact'))).send_keys(phone_touple[0]) # 点击下一步 到发送验证码界面 time.sleep(3) click_to_phone_code_page_js = 'document.getElementsByTagName("button")[2].click()' browser.execute_script(click_to_phone_code_page_js) # 点击发送验证码 wait.until(EC.element_to_be_clickable((By.ID, 'portMessage'))).click() # 识别极验 CrackTouClick(browser, wait, chaojiying).crack_touh_click(1, 4, user) # 对接接码平台填入验证码 # TODO time.sleep(30) phone_code = PhoneService.get_phone_code(phone_touple[1]) wait.until(EC.presence_of_element_located((By.NAME, 'title'))).send_keys(phone_code) # 提交报名 wait.until(EC.element_to_be_clickable((By.ID, 'save'))).click() @staticmethod def choose_nation(browser, nation): """ 选择民族 """ choose_nation_js = ''' function choose(nation){ ddlist = document.getElementsByName('nation')[0].parentElement.getElementsByTagName('dd'); for (i=0; i < 58; i++){ if(ddlist[i].textContent == nation){ ddlist = document.getElementsByName('nation')[0].parentElement.getElementsByTagName('dd')[i].click();break; } } } choose("''' + nation + '''")''' browser.execute_script(choose_nation_js) class UserService: """ 客户服务类 """ def __init__(self): self.user_list = [] def get_user(self, path): """ 获取客户信息 """ with open(path, 'r', encoding='utf-8') as f: for line in f.readlines(): user_info1 = line.strip('\n') user_info2 = user_info1.split('#') # 装载用户信息 user = User(user_info2[0], user_info2[1], user_info2[2], user_info2[3], photo=user_info2[4]) self.user_list.append(user) return self.user_list # if __name__ == '__main__': # PhoneService.get_phone_code('/china-phone-number/verification-code-16224457442.html') <file_sep># clttsign ## 普通话报名网站自动化 ## 特别声明: - 本仓库发布的`clttsign`项目中涉及的任何脚本,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。 - 本项目内所有资源文件,禁止任何公众号、自媒体进行任何形式的转载、发布。 - `ahaox` 对任何脚本问题概不负责,包括但不限于由任何脚本错误导致的任何损失或损害. - 间接使用脚本的任何用户,包括但不限于建立VPS或在某些行为违反国家/地区法律或相关法规的情况下进行传播, `ahaox` 对于由此引起的任何隐私泄漏或其他后果概不负责。 - 请勿将`clttsign`项目的任何内容用于商业或非法目的,否则后果自负。 - 如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关脚本。 - 以任何方式查看此项目的人或直接或间接使用`clttsign`项目的任何脚本的使用者都应仔细阅读此声明。`ahaox` 保留随时更改或补充此免责声明的权利。一旦使用并复制了任何相关脚本或`clttsign`项目,则视为您已接受此免责声明。 - 您必须在下载后的24小时内从计算机或手机中完全删除以上内容。 > ***您使用或者复制了本仓库且本人制作的任何代码或项目,则视为`已接受`此声明,请仔细阅读*** > ***您在本声明未发出之时点使用或者复制了本仓库且本人制作的任何代码或项目且此时还在使用,则视为`已接受`此声明,请仔细阅读*** ## 项目简介 项目使用了Chrome + Python3 + selenium 实现普通话PSC自动化报名。支持自动识别验证码并点击(验证码点击非100%正确!!!),自动获取手机号和手机验证码,自动提交。支持批量报名!! ## 使用教程 ### 环境安装 ##### python环境:推荐python3.6 ##### 浏览器:推荐Chrome浏览器 ##### 准备对应的浏览器驱动:Chrome浏览器参考:http://chromedriver.storage.googleapis.com/index.html ##### 安装环境依赖: pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/ ### 参数配置 ##### 配置超级鹰打码 `main.py`中 ```python # 超级鹰用户名、密码、软件ID(需要注册) CHAOJIYING_USERNAME = 'XXXXXX' CHAOJIYING_PASSWORD = '<PASSWORD>' CHAOJIYING_SOFT_ID = 'XXXXXX' CHAOJIYING_KIND = 9004 # 验证码类型 ``` > 需要自行注册超级鹰并充值!!!网站:https://www.chaojiying.com/ 验证码类型无须更改 ##### 配置用户信息`config.txt` 批量报名请保证报名资料每条一行 * 需要上传照片的格式 姓名#性别#民族#身份证号#照片全路径 ``` 张三#女#汉族#511XXXXXXXXXXX#C:\\Users\\ahao\\Desktop\\张三.jpg ``` * 不需要照片的格式: 姓名#性别#民族#身份证号#无 ```txt 王五#男#苗族#511XXXXXXXXXXX#无 ``` ##### 修改报名链接和报名城市 `main.py` 中 ```python CLTTURL = 'http://scbm.cltt.org/pscweb/signUp.html' # 例如四川的报名链接 CITY = '成都市' # 城市必须要与网站上显示一致 ``` > 手机号无需配置,本项目自动利用公开的接码平台,自动获取手机验证码,如有需要自行更改。 ##### 最后说明 <font style="color:red;">本项目以学习交流为目的,切勿非法使用!!!!</font> <file_sep>import requests from lxml import etree from selenium import webdriver class User: """ 客户类 """ def __init__(self, name, sex, nation, idCard, phone=None, address='无', photo=None): """ @param name: 姓名 @param idCard: 身份证号 @param sex: 性别 @param nation: 民族 @param address: 地址 @param photo: 照片 @param phone: 手机号 """ self.name = name self.idCard = idCard self.sex = sex self.nation = nation self.address = address self.photo = photo self.phone = phone class BaseInfo: """ 基本信息类 """ def __init__(self, url, city, station=None, time=None): """ @param url: 报名地址 @param city: 报名城市 @param station: 测试站 @param time: 测试时间 """ self.base_info = {'url': url, 'city': city, 'station': station, 'time': time} def get_base_info(self): return self.base_info class Browser: """ 浏览器类 """ def __init__(self): # 创建浏览器对象 option = webdriver.ChromeOptions() option.add_experimental_option('useAutomationExtension', False) option.add_experimental_option('excludeSwitches', ['enable-automation']) # 不自动关闭浏览器 option.add_experimental_option("detach", True) self.browser = webdriver.Chrome(chrome_options=option) def getBrowser(self): """ 返回浏览器对象列表 """ return self.browser class Phone: """ 手机号类 """ def __init__(self, url): self.phone = None self.code = None self.url = url self.headers = { 'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', } def get_phone(self): res = requests.get(url=self.url, headers=self.headers) resp = res.content # print(resp) html = etree.HTML(resp) # 获取手机号 phone_l1 = html.xpath('//p[@title="点击接收短信验证码"]//a//text()') # ['+86', ' 16532701568', '+86', ' 16532701568'....] phone_l2 = [x for x in phone_l1 if x != '+86'] # [' 16532701568', ' 16532701568', ' 16532701568', .....] phone_list = [x[1:] for x in phone_l2] # ['16532701568', '16532701569', '17107703029'] # 获取验证码详情页链接 code_detial_page_href = html.xpath('//p[@title="点击接收短信验证码"]//a//@href') # {'phone': 'detail_href'....} phone_dict = dict(zip(phone_list, code_detial_page_href)) return phone_dict <file_sep>import requests from hashlib import md5 from io import BytesIO from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from PIL import Image import time class Chaojiying(object): def __init__(self, username, password, soft_id, kind): self.kind = kind self.username = username password = <PASSWORD>("<PASSWORD>") self.password = md5(password).hexdigest() self.soft_id = soft_id self.base_params = { 'user': self.username, 'pass2': self.password, 'softid': self.soft_id, } self.headers = { 'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', } def post_pic(self, im, codetype): """ im: 图片字节 codetype: 题目类型 参考 http://www.chaojiying.com/price.html """ params = { 'codetype': codetype, } params.update(self.base_params) files = {'userfile': ('ccc.jpg', im)} r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers) return r.json() def report_error(self, im_id): """ im_id:报错题目的图片ID """ params = { 'id': im_id, } params.update(self.base_params) r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers) return r.json() class CrackTouClick: """ 过验证码类 """ def __init__(self, browser, browser_wait, chaojiying): self.browser = browser self.wait = browser_wait self.chaojiying = chaojiying def judge_success(self, step): """ 判断是否验证成功 """ if step == 0: tip = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_result_tip'))).get_attribute('textContent') else: tip = self.browser.execute_script('document.getElementsByClassName("geetest_result_tip")[1].textContent') if tip == '验证失败 请按提示重新操作': return False else: return True def get_touclick_element_one(self): """ 第一次极验,获取验证码图片对象 :return: 图片元素 """ element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.geetest_holder'))) return element def get_touclick_element_two(self): """ 第二次极验,获取验证码图片对象 :return: 图片元素 """ element = self.browser.find_elements_by_class_name('geetest_panel_next')[2] return element def get_position(self, step): """ 获取验证码位置 :step: 极验的次序 :return: 验证码位置元组 """ if step == 0: element = self.get_touclick_element_one() else: element = self.get_touclick_element_two() location = element.location size = element.size top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size[ 'width'] return (top, bottom, left, right) def get_screenshot(self): """ 获取网页截图 :return: 截图对象 """ screenshot = self.browser.get_screenshot_as_png() screenshot = Image.open(BytesIO(screenshot)) return screenshot def get_touclick_image(self, step, user, name='captcha.png'): """ 获取点触验证码图片 :param name: :return: 图片对象 """ if step == 0: im = self.get_touclick_element_one() else: im = self.get_touclick_element_two() time.sleep(3) im.screenshot(user.name + 'captcha_.png') captcha = Image.open(user.name + 'captcha_.png') # 改变截图的大小 和原图一致 captcha = captcha.resize((im.size['width'], im.size['height'])) captcha.save(user.name + 'captcha_resize.png') return captcha def send_image_to_chaojiying(self, step, user): """ 超级鹰识别坐标 : return:超级鹰返回的坐标 """ image = self.get_touclick_image(step, user) bytes_array = BytesIO() image.save(bytes_array, format='PNG') # 读取到图片 result = self.chaojiying.post_pic(bytes_array.getvalue(), self.chaojiying.kind) return result def get_points(self, captcha_result): """ 解析识别结果 :param captcha_result: 识别结果 :return:转换后的结果 """ # 获取点击的坐标 groups = captcha_result.get('pic_str').split('|') locations = [[int(number) for number in group.split(',')] for group in groups] return locations def touch_click_words(self, locations, step): """ 点击验证图片 :param locations: 点击位置 :return: """ for location in locations: if step == 0: ActionChains(self.browser).move_to_element_with_offset(self.get_touclick_element_one(), location[0], location[1]).click().perform() time.sleep(1) else: ActionChains(self.browser).move_to_element_with_offset(self.get_touclick_element_two(), location[0], location[1]).click().perform() time.sleep(1) def crack_touh_click(self, step, test_num, user): test_num -= 1 if test_num == 0: print('客户:' + user.name + ' 二次极验未通过, 请人工点击验证码') exit() # 获取点击的位置 result = self.send_image_to_chaojiying(step, user) # TODO self.chaojiying.report_error(result['pic_id']) locations = self.get_points(result) self.touch_click_words(locations, step) if step == 0: # 点击确定 self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_commit'))).click() # 延时等待验证结果 self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_up'))) else: # 点击确定 sure_click_js = 'document.getElementsByClassName("geetest_commit")[1].click()' self.browser.execute_script(sure_click_js) # 延时等待验证结果 time.sleep(1) # 判断是否成功 if self.judge_success(step): print('验证成功') self.chaojiying.report_error(result['pic_id']) else: # 可能不成功 重来 print('重新验证') self.chaojiying.report_error(result['pic_id']) # time.sleep(2) self.crack_touh_click(step, test_num, user)
ecefcd8a0d47f9fd5bcc1d2092ef5ac0fd4c972c
[ "Markdown", "Python", "Text" ]
6
Python
ahaox/clttsign
ef3b5e5805e03cfe093da83b0773209191f98627
58070441cfdedd6f220a2dac9e0854af9c3386f9
refs/heads/main
<repo_name>leigangjian/C-language<file_sep>/pa chong .c #include<stdio.h> #include<math.h> #include<windows.h> #include<time.h> #define U 0.1 #define V 0.053 void SetColor(unsigned short ForeColor, unsigned short BackGroundColor) { HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hCon, (ForeColor % 16) | (BackGroundColor % 16 * 16)); } int main() { int i, s = 0, t, a = 10, b = 11, c = 12, d = 13, e = 14; int z[] = { 32 ,- 61 ,- 56 ,- 61 ,- 56 ,- 55, - 6, - 56, - 43, - 65 ,- 20 ,- 64, - 42 }; float x, y; srand(time(NULL)); for (y = 1.3; y >= -1.1; y -= U) { for (x = -2; x < 1.4; x += V) { if ((((x * x + y * y - 1) * (x * x + y * y - 1) * (x * x + y * y - 1) - x * x * y * y * y) <= 0)) { if (y >= 1.3 - 10 * U || y <= 1.3 - 11 * U) { s++; if (s % 4 == 1) { SetColor(a, 0); printf("l"); } if (s % 4 == 2) { SetColor(e, 0); printf("o"); } if (s % 4 == 3) { SetColor(c, 0); printf("v"); } if (s % 4 == 0) { SetColor(d, 0); printf("e"); } } else { for (i = 0; i < 42; i++) { if (i <= 14 || i >= 28) { s++; if (s % 4 == 1) { SetColor(a, 0); printf("l"); } if (s % 4 == 2) { SetColor(e, 0); printf("o"); } if (s % 4 == 3) { SetColor(c, 0); printf("v"); } if (s % 4 == 0) { SetColor(d, 0); printf("e"); } } else { SetColor(b, 0); printf("%c", z[i - 15]); Sleep(50); } } break; } } else printf(" "); Sleep(1); } printf("\n"); } printf("°´ÈÎÒâ¼ü¼ÌÐø£¡"); getchar(); while (1) { system("cls"); t = a; a = b; b = c; c = d; d = e; e = t; for (y = 1.3; y >= -1.1; y -= U) { for (x = -2; x < 1.4; x += V) { if ((((x * x + y * y - 1) * (x * x + y * y - 1) * (x * x + y * y - 1) - x * x * y * y * y) <= 0)) { if (y >= 1.3 - 10 * U || y <= 1.3 - 11 * U) { s++; if (s % 4 == 1) { SetColor(a, 0); printf("l"); } if (s % 4 == 2) { SetColor(b, 0); printf("o"); } if (s % 4 == 3) { SetColor(c, 0); printf("v"); } if (s % 4 == 0) { SetColor(d, 0); printf("e"); } } else { for (i = 0; i < 42; i++) { if (i <= 14 || i >= 28) { s++; if (s % 4 == 1) { SetColor(a, 0); printf("l"); } if (s % 4 == 2) { SetColor(b, 0); printf("o"); } if (s % 4 == 3) { SetColor(c, 0); printf("v"); } if (s % 4 == 0) { SetColor(d, 0); printf("e"); } } else { SetColor(e, 0); printf("%c", z[i - 15]); } } break; } } else printf(" "); } printf("\n"); } Sleep(1000); system("cls"); } }
ec6247b83a70264ea6ccb791adecf6e4e229de58
[ "C" ]
1
C
leigangjian/C-language
cf08d0fa6ceae2e1b5bf394dd07e4a41ca12bbda
1191964941333710b95fc9957a8576db344c1e35
refs/heads/master
<repo_name>megilangr1/CafeAllegra<file_sep>/application/views/Admin/main.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Top Navigation</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/bootstrap/dist/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/Ionicons/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="<?= base_url('assets/') ?>dist/css/AdminLTE.min.css"> <!-- Skin --> <link rel="stylesheet" href="<?= base_url('assets/') ?>dist/css/skins/_all-skins.min.css"> <!-- DataTables --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css"> <!-- Select2 --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/select2/dist/css/select2.min.css"> <style type="text/css"> .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 28px; } .select2-container--default .select2-selection--single { border-radius: 0px; } .select2-container .select2-selection--single { height: 34px; } .select2-container .select2-selection--single .select2-selection__rendered { padding-left: 0px; } .select2-container--default .select2-selection--single .select2-selection__arrow { height: 34px; } </style> <style> .example-modal .modal { position: relative; top: auto; bottom: auto; right: auto; left: auto; display: block; z-index: 1; } .example-modal .modal { background: transparent !important; } </style> </head> <!-- ADD THE CLASS layout-top-nav TO REMOVE THE SIDEBAR. --> <body class="hold-transition skin-blue layout-top-nav"> <div class="wrapper"> <header class="main-header"> <nav class="navbar navbar-static-top"> <div class="container"> <div class="navbar-header"> <a href="<?= base_url('Admin') ?>" class="navbar-brand"><b>Allegra</b></a> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <i class="fa fa-bars"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="<?= base_url('Admin') ?>">Halaman Utama</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Master Data <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <!-- <li><a href="<?= site_url('Admin/Barang') ?>">Barang</a></li> <li class="divider"></li> --> <li><a href="<?= site_url('Admin/Group-Produk') ?>">Group Produk 1</a></li> <li><a href="<?= site_url('Admin/Group-Produk-Detail') ?>">Group Produk 2</a></li> <li><a href="<?= site_url('Admin/Produk') ?>">Produk</a></li> <li class="divider"></li> <li><a href="<?= site_url('Admin/Group-Material') ?>">Group Material 1</a></li> <li><a href="<?= site_url('Admin/Group-Material-Detail') ?>">Group Material 2</a></li> <li><a href="<?= site_url('Admin/Material') ?>">Material</a></li> <li class="divider"></li> <li><a href="<?= site_url('Admin/Supplier') ?>">Supplier</a></li> <li class="divider"></li> <li><a href="<?= site_url('Admin/Relasi-Material-Supplier') ?>">Relasi Material - Supplier</a></li> <li class="divider"></li> <li><a href="<?= site_url('Admin/Perkiraan') ?>">Perkiraan</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Transaksi <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="<?= site_url('Admin/Pembelian') ?>">Pembelian</a></li> <li><a href="<?= site_url('Admin/Hutang-Dagang') ?>">Hutang Dagang</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Data Transaksi <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="<?= site_url('Admin/Transaksi-Pembelian') ?>">Pembelian</a></li> </ul> </li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- User Account Menu --> <li class="dropdown user user-menu"> <!-- Menu Toggle Button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <!-- The user image in the navbar--> <img src="<?= base_url('assets/') ?>dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <!-- hidden-xs hides the username on small devices so only the image appears. --> <span class="hidden-xs"><?= $user->nama_pegawai ?></span> </a> <ul class="dropdown-menu"> <!-- The user image in the menu --> <li class="user-header"> <img src="<?= base_url('assets/') ?>dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> <?= $user->nama_pegawai ?> </p> </li> <!-- Menu Footer--> <li class="user-footer"> <a href="<?= site_url('Admin/Logout') ?>" class="btn btn-default btn-block btn-flat">Logout</a> </li> </ul> </li> </ul> </div> <!-- /.navbar-custom-menu --> </div> <!-- /.container-fluid --> </nav> </header> <!-- Full Width Column --> <div class="content-wrapper"> <div class="container"> <?php if (!isset($pg)) : ?> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Halaman Admin <small>Program Cafe Allegra V-1.0</small> </h1> <ol class="breadcrumb"> <li><a href="<?= base_url('Admin') ?>"><i class="fa fa-home"></i> Halaman Utama</a></li> </ol> </section> <?php endif; ?> <!-- Main content --> <section class="content"> <div class="row"> <?php if (isset($pg)) { $this->load->view($pg); } else { } ?> </div> </section> <!-- /.content --> </div> <!-- /.container --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="container"> <div class="pull-right hidden-xs"> <b>Version</b> 2.4.0 </div> <strong>Copyright &copy; 2014-2016 <a href="https://adminlte.io">Almsaeed Studio</a>.</strong> All rights reserved. </div> <!-- /.container --> </footer> </div> <!-- ./wrapper --> <!-- jQuery 3 --> <script src="<?= base_url('assets/') ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/') ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- SlimScroll --> <script src="<?= base_url('assets/') ?>bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="<?= base_url('assets/') ?>bower_components/fastclick/lib/fastclick.js"></script> <!-- AdminLTE App --> <script src="<?= base_url('assets/') ?>dist/js/adminlte.min.js"></script> <!-- DataTables --> <script src="<?= base_url('assets/') ?>bower_components/datatables.net/js/jquery.dataTables.min.js"></script> <script src="<?= base_url('assets/') ?>bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <!-- Select2 --> <script src="<?= base_url('assets/') ?>bower_components/select2/dist/js/select2.full.min.js"></script> <!-- page script --> <script> $(function() { //Initialize Select2 Elements $('.select2').select2() $('#example1').DataTable() $('#example2').DataTable({ 'paging': true, 'lengthChange': false, 'searching': false, 'ordering': true, 'info': true, 'autoWidth': false }) }) </script> </body> </html><file_sep>/application/controllers/GroupMaterial.php <?php class GroupMaterial extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('GroupMaterialM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGM' => $this->GroupMaterialM->dataGM(), 'pg' => 'Admin/Master/groupmaterial1' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $a = trim($this->input->post('nama')); $cekNama = $this->GroupMaterialM->cekNama($a); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Material $a Sudah Ada !');window.history.back();</script>"; }else{ $k = $this->GroupMaterialM->kodeOtomatis(); $k1 = $k->row_array(); $k2 = $k1['kode']; $k3 = (int) substr($k2, 0,3); $k3++; $kode = sprintf('%03s', $k3); $this->GroupMaterialM->save($kode, $a); echo "<script>alert('Data Group Material Berhasil di-Tambahkan !');window.location='".base_url('Admin/Group-Material')."';</script>"; } }else{ redirect('Admin/Group-Material'); } } public function hapus() { $kode = $this->uri->segment(4); $cek = $this->GroupMaterialM->cekKode($kode); if ($cek->num_rows() > 0) { $this->GroupMaterialM->delete($kode); echo "<script>alert('Data Group Material Berhasil di-Hapus !');window.location='".base_url('Admin/Group-Material')."';</script>"; }else{ redirect(base_url('Admin/Group-Material')); } } public function edit() { $kode = $this->uri->segment(4); $cek = $this->GroupMaterialM->cekKode($kode); if ($cek->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGM' => $this->GroupMaterialM->dataGM(), 'pg' => 'Admin/Master/groupmaterial1', 'edit' => $cek->row() ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Group-Material')); } } public function update() { if (isset($_POST['ed'])) { $kode = $this->input->post('kode'); $namaLama = $this->input->post('namaLama'); $a = trim($this->input->post('nama')); if ($a == $namaLama) { $this->GroupMaterialM->update($kode, $namaLama); echo "<script>alert('Data Group Material Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Material')."';</script>"; }else{ $cekNama = $this->GroupMaterialM->cekNama($a); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Material $a Sudah Ada !');window.history.back();</script>"; }else{ $this->GroupMaterialM->update($kode, $a); echo "<script>alert('Data Group Material Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Material')."';</script>"; } } }else{ redirect('Admin/Group-Material'); } } } ?><file_sep>/databaseMentahan/cafeallegra_mentahan.sql -- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 30 Jul 2019 pada 04.04 -- Versi Server: 10.1.21-MariaDB -- PHP Version: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `cafeallegra` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `h_beli` -- CREATE TABLE `h_beli` ( `FNO_BELI` char(7) NOT NULL, `FTGL_BELI` date DEFAULT NULL, `FK_SUP` char(3) NOT NULL, `FHC` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `h_beli` -- INSERT INTO `h_beli` (`FNO_BELI`, `FTGL_BELI`, `FK_SUP`, `FHC`) VALUES ('1900001', '2019-06-19', '002', '0'); -- -------------------------------------------------------- -- -- Struktur dari tabel `h_kas` -- CREATE TABLE `h_kas` ( `FNO_KAS` char(7) NOT NULL, `FTGL_KAS` date DEFAULT NULL, `FMUTASI` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `h_kas` -- INSERT INTO `h_kas` (`FNO_KAS`, `FTGL_KAS`, `FMUTASI`) VALUES ('1900001', '2019-06-05', 'D'); -- -------------------------------------------------------- -- -- Struktur dari tabel `m_brg` -- CREATE TABLE `m_brg` ( `FK_BRG` char(6) NOT NULL, `FN_BRG` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FSTOK_MIN` decimal(18,0) DEFAULT NULL, `FSTOK_MAX` decimal(18,0) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Struktur dari tabel `m_mat` -- CREATE TABLE `m_mat` ( `FK_MAT` char(6) NOT NULL, `FN_MAT` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FSTOK_MIN` decimal(18,0) DEFAULT NULL, `FSTOK_MAX` decimal(18,0) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `m_mat` -- INSERT INTO `m_mat` (`FK_MAT`, `FN_MAT`, `FSAT`, `FSTOK_MIN`, `FSTOK_MAX`) VALUES ('001201', 'Test material', 'PCS', '2', '2'), ('001202', 'TEST MATERIAL 01', 'PCS', '10', '40'), ('001203', 'material 3', 'PCS', '10', '10'), ('003404', 'TEST MATERIAL 04', 'PCS', '200', '400'); -- -------------------------------------------------------- -- -- Struktur dari tabel `m_perk` -- CREATE TABLE `m_perk` ( `FK_PERK` char(8) NOT NULL, `FN_PERK` varchar(50) DEFAULT NULL, `FSALDO_NORMAL` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `m_perk` -- INSERT INTO `m_perk` (`FK_PERK`, `FN_PERK`, `FSALDO_NORMAL`) VALUES ('55555555', 'TEST PERIKIRAAN', 'K'), ('66666666', 'TEST PERKIRAAN DUA', 'D'); -- -------------------------------------------------------- -- -- Struktur dari tabel `m_pr` -- CREATE TABLE `m_pr` ( `FK_BPR` char(6) NOT NULL, `FN_BPR` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FHARGA` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `m_pr` -- INSERT INTO `m_pr` (`FK_BPR`, `FN_BPR`, `FSAT`, `FHARGA`) VALUES ('F01101', 'COBA EDIT', 'PORSI', 7000), ('F01202', 'TESTT', 'PORSI', 5000), ('F02101', 'KOPI TORAJA NO 1', 'PCS', 50000), ('F02102', 'KOPI TORAJA 2', 'KG', 55000), ('F02103', 'TEST KOPI TORAJA', 'PCS', 200000), ('F023', 'TEST', 'PCS', 2000), ('F02301', 'TEST KOPI LUWAK 01', 'PCS', 2000); -- -------------------------------------------------------- -- -- Struktur dari tabel `m_sup` -- CREATE TABLE `m_sup` ( `FK_SUP` char(3) NOT NULL, `FNA_SUP` varchar(20) DEFAULT NULL, `FALAMAT` varchar(100) DEFAULT NULL, `FKOTA` varchar(30) DEFAULT NULL, `FTEL` varchar(12) DEFAULT NULL, `FCP` varchar(20) DEFAULT NULL, `FLAMA_BAYAR` int(11) DEFAULT NULL, `FPENERIMA` varchar(40) DEFAULT NULL, `FBANK` varchar(20) DEFAULT NULL, `FNO_ACC` varchar(15) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `m_sup` -- INSERT INTO `m_sup` (`FK_SUP`, `FNA_SUP`, `FALAMAT`, `FKOTA`, `FTEL`, `FCP`, `FLAMA_BAYAR`, `FPENERIMA`, `FBANK`, `FNO_ACC`) VALUES ('001', 'CV PRIMA A', '<NAME>', 'SUKABUMI', '0987654321', 'BUDI ARIYADI', 30, 'BUDI', 'BCA', '001002'), ('002', 'CV INDAH', '<NAME>', 'BANDUNG', '022 2345678', 'FATHIAN', 30, 'FATHIAN', 'MANDIRI', '001003'), ('003', 'CV TEST', '<NAME>', 'SUKABUMI', '0987654322', 'ARI', 30, 'ARI', 'MANDIRI', '002003'); -- -------------------------------------------------------- -- -- Struktur dari tabel `ref_gmat1` -- CREATE TABLE `ref_gmat1` ( `FK_GMAT1` char(3) NOT NULL, `FN_GMAT1` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `ref_gmat1` -- INSERT INTO `ref_gmat1` (`FK_GMAT1`, `FN_GMAT1`) VALUES ('001', 'TEST'), ('002', 'TEST02'), ('003', 'TEST03'); -- -------------------------------------------------------- -- -- Struktur dari tabel `ref_gmat2` -- CREATE TABLE `ref_gmat2` ( `FK_GMAT1` char(3) NOT NULL, `FK_GMAT2` char(1) NOT NULL, `FN_GMAT2` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `ref_gmat2` -- INSERT INTO `ref_gmat2` (`FK_GMAT1`, `FK_GMAT2`, `FN_GMAT2`) VALUES ('001', '1', 'TEST NO 1'), ('001', '2', 'TEST NO 2'), ('003', '3', 'TEST MAT TIGA'), ('003', '4', 'TEST MAT DUA'); -- -------------------------------------------------------- -- -- Struktur dari tabel `ref_gpr1` -- CREATE TABLE `ref_gpr1` ( `FK_GPR1` char(3) NOT NULL, `FN_GPR1` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `ref_gpr1` -- INSERT INTO `ref_gpr1` (`FK_GPR1`, `FN_GPR1`) VALUES ('F01', 'NASI'), ('F02', 'KOPI'), ('F03', 'TEH'), ('F04', 'SOP'); -- -------------------------------------------------------- -- -- Struktur dari tabel `ref_gpr2` -- CREATE TABLE `ref_gpr2` ( `FK_GPR1` char(3) NOT NULL, `FK_GPR2` char(1) NOT NULL, `FN_GPR2` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `ref_gpr2` -- INSERT INTO `ref_gpr2` (`FK_GPR1`, `FK_GPR2`, `FN_GPR2`) VALUES ('F01', '1', 'NASI GORENG SPESIAL'), ('F01', '2', 'NASI PUTIH NO 1'), ('F01', '3', 'TEST'), ('F01', '4', 'TEST NASI 01'), ('F02', '1', 'KOPI TORAJA'), ('F02', '2', 'KOPI JAWA'), ('F02', '3', 'KOPI LUWAK'), ('F03', '1', 'TEH SARIWANGI'), ('F03', '2', 'TEH MELATI'); -- -------------------------------------------------------- -- -- Struktur dari tabel `rls_mat_sup` -- CREATE TABLE `rls_mat_sup` ( `FK_SUP` char(3) NOT NULL, `FK_MAT` char(6) NOT NULL, `FHARGA` decimal(7,2) DEFAULT NULL, `FN_MAT_SUP` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `rls_mat_sup` -- INSERT INTO `rls_mat_sup` (`FK_SUP`, `FK_MAT`, `FHARGA`, `FN_MAT_SUP`) VALUES ('001', '001201', '3000.00', 'test'), ('001', '001203', '4000.00', 'material 3 A'), ('001', '003404', '25000.00', 'MATERIAL TEST 04'), ('002', '001201', '20000.00', 'test'), ('003', '001201', '90000.00', 'testtttt'); -- -------------------------------------------------------- -- -- Struktur dari tabel `t_beli` -- CREATE TABLE `t_beli` ( `FNO_BELI` char(7) NOT NULL, `FK_MAT` char(6) NOT NULL, `FQTY` decimal(18,0) DEFAULT NULL, `FHARGA` decimal(7,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `t_beli` -- INSERT INTO `t_beli` (`FNO_BELI`, `FK_MAT`, `FQTY`, `FHARGA`) VALUES ('1900001', '001201', '10', '20000.00'), ('1900001', '003404', '10', '25000.00'); -- -------------------------------------------------------- -- -- Struktur dari tabel `t_hd` -- CREATE TABLE `t_hd` ( `FNO_BELI` char(7) NOT NULL, `FK_SUP` char(3) NOT NULL, `FJML` decimal(15,2) DEFAULT NULL, `FBAYAR` decimal(15,2) DEFAULT NULL, `FTGL_BAYAR` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `t_hd` -- INSERT INTO `t_hd` (`FNO_BELI`, `FK_SUP`, `FJML`, `FBAYAR`, `FTGL_BAYAR`) VALUES ('1900001', '002', '450000.00', NULL, NULL); -- -------------------------------------------------------- -- -- Struktur dari tabel `t_kas` -- CREATE TABLE `t_kas` ( `FNO_KAS` char(7) NOT NULL, `FKET` varchar(50) DEFAULT NULL, `FK_PERK` char(8) NOT NULL, `FJML` decimal(9,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `t_kas` -- INSERT INTO `t_kas` (`FNO_KAS`, `FKET`, `FK_PERK`, `FJML`) VALUES ('1900001', 'test', '66666666', '300000.00'); -- -- Indexes for dumped tables -- -- -- Indexes for table `h_beli` -- ALTER TABLE `h_beli` ADD PRIMARY KEY (`FNO_BELI`,`FK_SUP`); -- -- Indexes for table `h_kas` -- ALTER TABLE `h_kas` ADD PRIMARY KEY (`FNO_KAS`); -- -- Indexes for table `m_brg` -- ALTER TABLE `m_brg` ADD PRIMARY KEY (`FK_BRG`); -- -- Indexes for table `m_mat` -- ALTER TABLE `m_mat` ADD PRIMARY KEY (`FK_MAT`); -- -- Indexes for table `m_perk` -- ALTER TABLE `m_perk` ADD PRIMARY KEY (`FK_PERK`); -- -- Indexes for table `m_pr` -- ALTER TABLE `m_pr` ADD PRIMARY KEY (`FK_BPR`); -- -- Indexes for table `m_sup` -- ALTER TABLE `m_sup` ADD PRIMARY KEY (`FK_SUP`); -- -- Indexes for table `ref_gmat1` -- ALTER TABLE `ref_gmat1` ADD PRIMARY KEY (`FK_GMAT1`); -- -- Indexes for table `ref_gmat2` -- ALTER TABLE `ref_gmat2` ADD PRIMARY KEY (`FK_GMAT1`,`FK_GMAT2`); -- -- Indexes for table `ref_gpr1` -- ALTER TABLE `ref_gpr1` ADD PRIMARY KEY (`FK_GPR1`); -- -- Indexes for table `ref_gpr2` -- ALTER TABLE `ref_gpr2` ADD PRIMARY KEY (`FK_GPR1`,`FK_GPR2`); -- -- Indexes for table `rls_mat_sup` -- ALTER TABLE `rls_mat_sup` ADD PRIMARY KEY (`FK_SUP`,`FK_MAT`); -- -- Indexes for table `t_beli` -- ALTER TABLE `t_beli` ADD PRIMARY KEY (`FNO_BELI`,`FK_MAT`); -- -- Indexes for table `t_hd` -- ALTER TABLE `t_hd` ADD PRIMARY KEY (`FNO_BELI`,`FK_SUP`); -- -- Indexes for table `t_kas` -- ALTER TABLE `t_kas` ADD PRIMARY KEY (`FNO_KAS`,`FK_PERK`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/application/views/Admin/Transaksi/hutangdagang.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Hutang Dagang </h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>No. Pembelian</th> <th>Supplier</th> <th>Jumlah</th> <th>Hutang</th> <th>Status Bayar</th> </tr> </thead> <tbody> <?php foreach ($tb->result() as $rb) { ?> <?php } ?> </tbody> </table> </div> </div> </div> </div><file_sep>/application/models/PrintM.php <?php class PrintM extends CI_Model { public function tpembelian($id, $sup) { $query = $this->db->get_where('v_beli', ['FNO_BELI' => $id, 'FK_SUP' => $sup]); return $query; } } <file_sep>/application/models/GroupMaterialDetailM.php <?php class GroupMaterialDetailM extends CI_Model { private $_table = 'ref_gmat2'; private $_tablev = 'v_gmat2'; public function dataGM() { $query = $this->db->get('ref_gmat1'); return $query; } public function dataGMD() { $query = $this->db->get($this->_table); return $query; } public function cekNama($gmat1, $nama) { $query = $this->db->get_where($this->_table, ['FN_GMAT2' => $nama, 'FK_GMAT1' => $gmat1]); return $query; } public function kodeOtomatis($gmat1) { $query = $this->db->query("SELECT max(FK_GMAT2) as kode FROM $this->_table WHERE FK_GMAT1='$gmat1' "); return $query; } public function save($gmat1, $kode, $nama) { $data = [ 'FK_GMAT1' => $gmat1, 'FK_GMAT2' => $kode, 'FN_GMAT2' => $nama ]; $this->db->insert($this->_table, $data); } public function cekKode($gmat1, $kode) { $query = $this->db->get_where($this->_tablev, ['FK_GMAT2' => $kode, 'FK_GMAT1' => $gmat1]); return $query; } public function update($gmat1, $kode, $nama) { $data = [ 'FN_GMAT2' => $nama ]; $this->db->where('FK_GMAT2', $kode); $this->db->where('FK_GMAT1', $gmat1); $this->db->update($this->_table, $data); } public function delete($gmat1, $kode) { $this->db->where('FK_GMAT2', $kode); $this->db->where('FK_GMAT1', $gmat1); $this->db->delete($this->_table); } } ?><file_sep>/application/models/RelasiM.php <?php class RelasiM extends CI_Model { private $_table = 'rls_mat_sup'; private $_vtable = 'v_rls_mat_sup'; public function dataSP() { $query = $this->db->get('m_sup'); return $query; } public function dataRelasi($sup) { $query = $this->db->get_where($this->_vtable, ['FK_SUP' => $sup]); return $query; } public function dataMaterial() { $query = $this->db->get('m_mat'); return $query; } public function dMaterial($mat) { $query = $this->db->get_where('m_mat', ['FK_MAT' => $mat]); return $query; } public function cekSP($sup) { $query = $this->db->get_where('m_sup', ['FK_SUP' => $sup]); return $query; } public function cekRelasi($sup, $mat) { $query = $this->db->get_where($this->_table, ['FK_SUP' => $sup, 'FK_MAT' => $mat]); return $query; } public function save($a, $b, $c, $d) { $data = [ 'FK_SUP' => $a, 'FK_MAT' => $b, 'FHARGA' => $c, 'FN_MAT_SUP' => $d ]; $this->db->insert($this->_table, $data); } public function delete($sup, $mat) { $this->db->where('FK_SUP', $sup); $this->db->where('FK_MAT', $mat); $this->db->delete($this->_table); } } ?><file_sep>/application/controllers/PrintData.php <?php class PrintData extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); } else { if ($cek->level != '1') { redirect(base_url()); } else { $this->dataUser = $cek; $this->load->model('PrintM'); } } } else { $this->session->sess_destroy(); redirect(base_url()); } } public function pembelian($id, $sup) { $data = [ 'tb' => $this->PrintM->tpembelian($id, $sup), 'sd' => $this->PrintM->tpembelian($id, $sup)->row() ]; $this->load->view('Admin/Print/printdata', $data); } } <file_sep>/application/views/Admin/Master/supplier.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-users"></span> &ensp; Supplier</h4> </div> <div class="box-body"> <?php if (isset($edit)) : ?> <form action="<?= site_url('Admin/Supplier/Simpan-Perubahan') ?>" method="post" class="form"> <input type="hidden" name="kode" value="<?= $edit->FK_SUP ?>"> <input type="hidden" name="namaLama" value="<?= $edit->FNA_SUP ?>"> <?php else : ?> <form action="<?= site_url('Admin/Supplier/Tambah') ?>" method="post" class="form"> <?php endif; ?> <div class="col-md-6"> <div class="form-group"> <label for="">Nama Supplier : </label> <?php if (isset($edit)) : ?> <input type="text" name="nama" id="nama" required="" placeholder="Nama Supplier" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FNA_SUP ?>"> <?php else : ?> <input type="text" name="nama" id="nama" required="" placeholder="Nama Supplier" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-8"> <div class="form-group"> <label for="">Alamat Supplier : </label> <?php if (isset($edit)) : ?> <textarea name="alamat" id="" class="form-control" maxlength="100" required="" placeholder="Alamat Supplier" rows="4"><?= $edit->FALAMAT ?></textarea> <?php else : ?> <textarea name="alamat" id="" class="form-control" maxlength="100" required="" placeholder="Alamat Supplier" rows="4"></textarea> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Kota : </label> <?php if (isset($edit)) : ?> <input type="text" name="kota" id="kota" required="" placeholder="Kota Supplier" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FKOTA ?>"> <?php else : ?> <input type="text" name="kota" id="kota" required="" placeholder="Kota Supplier" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">No. Telfon : </label> <?php if (isset($edit)) : ?> <input type="text" name="telp" id="telp" required="" placeholder="Nomor Telfon Supplier" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FTEL ?>"> <?php else : ?> <input type="text" name="telp" id="telp" required="" placeholder="Nomor Telfon Supplier" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Contact Person : </label> <?php if (isset($edit)) : ?> <input type="text" name="cp" id="cp" required="" placeholder="Contact Person Supplier" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FCP ?>"> <?php else : ?> <input type="text" name="cp" id="cp" required="" placeholder="Contact Person Supplier" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Lama Bayar : </label> <?php if (isset($edit)) : ?> <input type="number" name="lamaBayar" id="lamaBayar" min="0" required="" placeholder="Lama Bayar" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FLAMA_BAYAR ?>"> <?php else : ?> <input type="number" name="lamaBayar" id="lamaBayar" min="0" required="" placeholder="Lama Bayar" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Penerima : </label> <?php if (isset($edit)) : ?> <input type="text" name="penerima" id="penerima" required="" placeholder="Penerima" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FPENERIMA ?>"> <?php else : ?> <input type="text" name="penerima" id="penerima" required="" placeholder="Penerima" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Bank : </label> <?php if (isset($edit)) : ?> <input type="text" name="bank" id="bank" required="" placeholder="Bank Supplier" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FBANK ?>"> <?php else : ?> <input type="text" name="bank" id="bank" required="" placeholder="Bank Supplier" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">No Account : </label> <?php if (isset($edit)) : ?> <input type="text" name="noacc" id="noacc" required="" placeholder="Nomor Account" autofocus="" class="form-control" maxlength="20" value="<?= $edit->FNO_ACC ?>"> <?php else : ?> <input type="text" name="noacc" id="noacc" required="" placeholder="Nomor Account" autofocus="" class="form-control" maxlength="20"> <?php endif; ?> </div> </div> <div class="col-md-12"> <div class="form-group"> <?php if (isset($edit)) : ?> <button type="submit" class="btn btn-success btn-flat" name="ed"> <span class="fa fa-check"></span> Simpan Perubahan </button> <a href="<?= site_url('Admin/Supplier') ?>" class="btn btn-danger btn-flat"> <span class="fa fa-undo"></span> Batalkan Perubahan Data </a> <?php else : ?> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Tambah Data Supplier </button> <button type="reset" class="btn btn-danger btn-flat"> <span class="fa fa-times"></span> Reset Input </button> <?php endif; ?> </div> </div> </form> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Supplier</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-striped table-hover" id="example1"> <thead> <tr> <th>Kode Supplier</th> <th>Nama Supplier</th> <th>Alamat Supplier</th> <th>Kota</th> <th>Telfon</th> <th>CP</th> <th>Lama Bayar</th> <th>Penerima</th> <th>Bank</th> <th>No. Acc</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($dataS->result() as $row) { ?> <tr> <td width="5%"> <h5><?= $row->FK_SUP ?></h5> </td> <td> <h5><?= $row->FNA_SUP ?></h5> </td> <td> <h5><?= $row->FALAMAT ?></h5> </td> <td> <h5><?= $row->FKOTA ?></h5> </td> <td> <h5><?= $row->FTEL ?></h5> </td> <td> <h5><?= $row->FCP ?></h5> </td> <td> <h5><?= $row->FLAMA_BAYAR ?></h5> </td> <td> <h5><?= $row->FPENERIMA ?></h5> </td> <td> <h5><?= $row->FBANK ?></h5> </td> <td> <h5><?= $row->FNO_ACC ?></h5> </td> <td width="10%" align="center"> <a href="<?= site_url('Admin/Supplier/Edit/') . $row->FK_SUP ?>"> <button class="btn btn-warning btn-flat" title="Edit Data"> <span class="fa fa-edit"></span> </button> </a> <a href="<?= site_url('Admin/Supplier/Hapus/') . $row->FK_SUP ?>"> <button class="btn btn-danger btn-flat" title="Hapus Data"> <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div><file_sep>/application/controllers/CekCart.php <?php class CekCart extends CI_Controller { public function __construct() { parent::__construct(); $cart = $this->cart->contents(); print_r($cart); } public function index() { $cart = $this->cart->contents(); print_r($cart); } } <file_sep>/application/controllers/DataPembelian.php <?php class DataPembelian extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); } else { if ($cek->level != 1) { redirect(base_url()); } else { $this->dataUser = $cek; $this->load->model('DataPembelianM', 'DModel'); } } } else { $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'pg' => 'Admin/Data/pembelian', 'tb' => $this->DModel->dataPembelian() ]; $this->load->view('Admin/main', $data); } } <file_sep>/application/controllers/Barang.php <?php class Barang extends CI_Controller { private $dataUser = ''; // Variable Private Untuk Menampung Data User pada Controller Barang public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); // Mengambil Data UID pada Session $this->load->model('Sesi'); // Menggunakan Model Sesi $cek = $this->Sesi->cekLogin($uid); // Pengecekan Data Pegawai Sesuai UID yang di-Ambil dari Sesi if ($cek == '0') { // Return Data dari Model $this->session->sess_destroy(); // Penghancuran sesi / Menghapus segala sesi redirect(base_url()); // Mengalihkan Pengguna Ke-Halaman base_url() / http://localhost/CafeAllegra }else{ if ($cek->level != '1') { // Pengecekan Apakah level User adalah bukan Admin / 1 jika Ya, maka Pegawai di alihkan ke halaman Login / base_url() redirect(base_url()); }else{ $this->dataUser = $cek; // Menampung data user hasil return model ke dalam variable dataUser $this->load->model('BarangM'); // Menggunakan Model BarangM } } }else{ $this->session->sess_destroy(); // Jika Sesi Pegawai tidak di-temukan pengguna di Alihkan ke halaman login redirect(base_url()); } } public function index() { $data = [ // Kumpulan data untuk di-kirim ke bagian view 'user' => $this->dataUser, // $user akan berisi $dataUser 'databarang' => $this->BarangM->dataBarang(), // $databarang akan berisi 'pg' => 'Admin/Master/barang' // $pg = akan berisi Admin/Master/barang yang di tujukan untuk me-load file view pada main.php ]; $this->load->view('Admin/main', $data); // me-load main.php view pada folder view/Admin } public function tambah() { if (isset($_POST['sav'])) { // Melakukan Pengecekan Tombol / Data yang bernama 'sav' terkirim ke-controller jika YA maka $nama_barang = trim($this->input->post('nama_barang')); // Mengambil data nama_barang yang di kirim melalui method post $cek_nama = $this->BarangM->cekNama($nama_barang); // Pengecekan Nama Barang menggunakan function cekNama pada model BarangM if ($cek_nama->num_rows() > 0) { // Jika pengecekan nama di temukan nama yang sama echo "<script>alert('Nama Barang $nama_barang Sudah Ada !');window.history.back();</script>"; // Memunculkan alert bahwa nama sudah ada }else{ // Jika belum ada $satuan = $this->input->post('satuan'); // Mengambil data satuan yang di kirim melalui method post $stok_min = $this->input->post('stok_min'); // Mengambil data stok_min yang di kirim melalui method post $stok_max = $this->input->post('stok_max'); // Mengambil data stok_max yang di kirim melalui method post $n1 = preg_replace('/[^a-zA-Z-0-9-]/', '', $nama_barang); // Menghapus dan hanya menyisakan huruf dari a-z A-Z 0-9 pada nama_barang $n2 = str_replace(' ', '', $n1); // menghilangkan spasi pada $n1 / nama_barang $n3 = substr($n2, 0,1); // mengambil huruf satu huruf pertama $n4 = strtoupper($n3); // Mengubah $n3 / nama_barang menjadi huruf kapital $kode_otomatis = $this->BarangM->kodeOtomatis($n4); // Membuat kode otomatis dengan menggunakan function kodeOtomatis pada model BarangM $r = $kode_otomatis->row_array(); // Pengambilan data dari kode_otomatis berupa array $r1 = $r['kode']; // Mengambil data kode metoder array $r2 = (int) substr($r1, 3,3); // Mengambil 3 huruf dari huruf ke-3 $r2++; // Pengambilan data terakhir / max hasil pengambilan $kode_barang = "BR".$n4.sprintf('%03s', $r2); // Membuat format Kode Otomatis $save = $this->BarangM->save($kode_barang, $nama_barang, $satuan, $stok_min, $stok_max); // Menggunakan function save pada Model barangM echo "<script>alert('Data Barang Berhasil Di-Tambahkan !');window.location='".base_url('Admin/Barang')."';</script>"; // Memunculkan alert saat selesai melakukan penyimpanan data } }else{ // Jika Button / Data 'sav' tidak di temukan telah di kirim ke controller redirect('Admin/Barang'); } } public function hapus() { $kode = $this->uri->segment(4); // Mengambil segment ke-4 pada url $cekKode = $this->BarangM->cekKode($kode); // Pengecekan Kode pada database if ($cekKode->num_rows() > 0) { // Jika di-temukan data dengan kode yang di kirim ke Model $this->BarangM->delete($kode); // Melakukan penghapusan dengan function delete pada model BarangM echo "<script>alert('Data Berhasil Di-Hapus !');window.location='".base_url('Admin/Barang')."';</script>"; // Alert Data Berhasil di-Hapus dan redirect pada js }else{ // Jika tidak di-temukan data dengan kode yang di kirim redirect(site_url('Admin/Barang')); // redirect halaman Admin/Barang } } public function edit() { $kode = $this->uri->segment(4); // Mengambil segment ke-4 pada url $cekKode = $this->BarangM->cekKode($kode); // Pengecekan Kode pada database if ($cekKode->num_rows() > 0) { // Jika di-temukan data dengan kode yang di kirim ke Model $data = [ 'user' => $this->dataUser, // $user akan berisi $dataUser 'databarang' => $this->BarangM->dataBarang(), // $databarang akan berisi 'pg' => 'Admin/Master/barang', // $pg = akan berisi Admin/Master/barang yang di tujukan untuk me-load file view pada main.php 'edit' => $cekKode->row() // $edit akan berisi data dari barang sesuai kode yang di cek ]; $this->load->view('Admin/Main', $data); // me-load file main.php pada folder view/Admin }else{ // Jika data dengan kode yang di kirim tidak di-Temukan redirect(site_url('Admin/Barang')); // Redirect ke halaman Admin/Barang } } public function update() { if (isset($_POST['ed'])) { $kode = $this->input->post('kode'); // mengabil data dari view dengan method post dan name='kode' $namaLama = $this->input->post('namaLama'); // mengabil data dari view dengan method post dan name='namaLama' $nama_baru = $this->input->post('nama_barang'); // mengabil data dari view dengan method post dan name='nama_barang' $satuan = $this->input->post('satuan'); // mengabil data dari view dengan method post dan name='satuan' $stok_min = $this->input->post('stok_min'); // mengabil data dari view dengan method post dan name='stok_min' $stok_max = $this->input->post('stok_max'); // mengabil data dari view dengan method post dan name='stok_max' if ($namaLama == $nama_baru) { // Pengecekan apakah namaLama sama dengan nama yang baru di kirim ke controller Jika ya maka $this->BarangM->update($kode, $namaLama, $satuan, $stok_min, $stok_max); // Melakukan Peng-update an dengan function update pada model BarangM echo "<script>alert('Data Barang Berhasil Di-Edit !');window.location='".base_url('Admin/Barang')."';</script>"; // Alert data berhasil di-Edit }else{ // Bila namaLama Tidak sama $cekNama = $this->BarangM->cekNama($nama_baru); // Melakukan pengecekan nama if($cekNama->num_rows() > 0){ // Jika di-temukan nama sudah ada echo "<script>alert('Nama Barang $nama_baru Sudah Ada !');window.history.back();</script>"; // Alert atas di-temukan nya nama yang sama }else{ // Jika tidak di-temukan nama yang sama $this->BarangM->update($kode, $namaLama, $satuan, $stok_min, $stok_max); // Melakukan Peng-update an dengan function update pada model BarangM echo "<script>alert('Data Barang Berhasil Di-Edit !');window.location='".base_url('Admin/Barang')."';</script>"; // Alert data berhasil di-Edit } } }else{ redirect(base_url('Admin/Barang')); } } } ?><file_sep>/application/models/GroupProdukDetailM.php <?php class GroupProdukDetailM extends CI_Model { private $_table = 'ref_gpr2'; private $_view = 'v_gpr2'; public function dataGPD() { $query = $this->db->get($this->_table); return $query; } public function cekNama($kodeGPR1, $nama) { $query = $this->db->get_where($this->_table, ['FK_GPR1' => $kodeGPR1, 'FN_GPR2' => $nama]); return $query; } public function kodeOtomatis($kodeGPR1) { $query = $this->db->query("SELECT max(FK_GPR2) as kode FROM $this->_table WHERE FK_GPR1='$kodeGPR1' "); return $query; } public function save($kodeGPR1, $kode, $nama) { $data = [ 'FK_GPR1' => $kodeGPR1, 'FK_GPR2' => $kode, 'FN_GPR2' => $nama ]; $this->db->insert($this->_table, $data); } public function cekKode($kodeGPR1, $kode) { $query = $this->db->get_where($this->_view, ['FK_GPR1' => $kodeGPR1, 'FK_GPR2' => $kode]); return $query; } public function delete($kodeGPR1, $kode) { $this->db->where('FK_GPR1', $kodeGPR1); $this->db->where('FK_GPR2', $kode); $this->db->delete($this->_table); } public function update($kodeGPR1, $kode, $nama) { $data = [ 'FN_GPR2' => $nama ]; $this->db->where('FK_GPR1', $kodeGPR1); $this->db->where('FK_GPR2', $kode); $this->db->update($this->_table, $data); } } ?><file_sep>/application/views/Admin/Master/groupproduk2.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-cogs"></span> &ensp; Group Produk Detail</h4> </div> <div class="box-body"> <div class="col-md-8"> <?php if(isset($edit)): ?> <form action="<?=site_url('Admin/Group-Produk-Detail/Simpan-Perubahan')?>" class="form" method="post"> <input type="hidden" name="gpr1" value="<?=$edit->FK_GPR1?>"> <input type="hidden" name="gpr2" value="<?=$edit->FK_GPR2?>"> <input type="hidden" name="namaLama" value="<?=$edit->FN_GPR2?>"> <?php else: ?> <form action="<?=site_url('Admin/Group-Produk-Detail/Tambah')?>" class="form" method="post"> <?php endif;?> <?php if(!isset($edit)): ?> <div class="form-group"> <label for="">Group Produk : </label> <select name="groupProduk" id="" class="select2" style="width: 100%;" data-placeholder="Silahkan Pilih Group Produk"> <option></option> <?php foreach ($dataGP->result() as $rgp) { echo "<option value='$rgp->FK_GPR1'>$rgp->FN_GPR1</option>"; }?> </select> </div> <?php else: ?> <div class="form-group"> <label for="">Group Produk : <?=$edit->FK_GPR1?> - (<?=$edit->FN_GPR1?>)</label> </div> <?php endif; ?> <div class="form-group"> <label for="">Nama Group Produk Detail : </label> <?php if(isset($edit)): ?> <input type="text" name="namaGroupDetail" id="" class="form-control" value="<?=$edit->FN_GPR2?>" class="form-control" required="" maxlength="20"> <?php else: ?> <input type="text" name="namaGroupDetail" id="" class="form-control" class="form-control" required="" maxlength="20"> <?php endif;?> </div> <div class="form-group"> <?php if(isset($edit)): ?> <button type="submit" class="btn btn-success btn-flat" name="ed"> <span class="fa fa-check"></span> Simpan Perubahan Group Produk </button> <a href="<?=site_url('Admin/Group-Produk-Detail')?>" class="btn btn-danger btn-flat"> <span class="fa fa-times"></span> Batal Merubah Data </a> <?php else: ?> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Tambah Data Group Produk </button> <button type="reset" class="btn btn-danger btn-flat"> <span class="fa fa-undo"></span> Reset Input </button> <?php endif;?> </div> </form> </div> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Group Produk</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>Kode Group Produk</th> <th>Kode Group Produk Detail</th> <th>Nama Group</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($dataGPD->result() as $row) { ?> <tr> <td width="20%"><h5><?=$row->FK_GPR1?></h5></td> <td width="15%"><h5><?=$row->FK_GPR2?></h5></td> <td><h5><?=$row->FN_GPR2?></h5></td> <td width="15%" align="center"> <a href="<?=site_url('Admin/Group-Produk-Detail/Edit/').$row->FK_GPR1."/".$row->FK_GPR2?>"> <button class="btn btn-warning btn-flat" title="Edit Data Group Produk"> <span class="fa fa-edit"></span> </button> </a> <a href="<?=site_url('Admin/Group-Produk-Detail/Hapus/').$row->FK_GPR1."/".$row->FK_GPR2?>" onclick="return confirm('Hapus Data Produk ?')"> <button class="btn btn-danger btn-flat" title="Hapus Data Group Produk" > <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div><file_sep>/application/controllers/GroupProdukDetail.php <?php class GroupProdukDetail extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cekSesi = $this->Sesi->cekLogin($uid); if ($cekSesi == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cekSesi->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cekSesi; $this->load->model('GroupProdukDetailM'); $this->load->model('GroupProdukM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->GroupProdukM->dataGroupProduk(), 'dataGPD' => $this->GroupProdukDetailM->dataGPD(), 'pg' => 'Admin/Master/groupproduk2' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $groupProduk = trim($this->input->post('groupProduk')); $namaGroupDetail = trim($this->input->post('namaGroupDetail')); $cekNama = $this->GroupProdukDetailM->cekNama($groupProduk, $namaGroupDetail); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Group Produk Detail $namaGroupDetail pada Group Produk Sudah Ada !');window.history.back();</script>"; }else{ $kode_otomatis = $this->GroupProdukDetailM->kodeOtomatis($groupProduk); $r = $kode_otomatis->row_array(); $r1 = $r['kode']; $r2 = (int) substr($r1, 0,1); $r2++; $kode = sprintf('%01s', $r2); $this->GroupProdukDetailM->save($groupProduk, $kode, $namaGroupDetail); echo "<script>alert('Data Group Produk Berhasil di-Tambahkan !');window.location='".base_url('Admin/Group-Produk-Detail')."';</script>"; } }else{ redirect(base_url('Admin/Group-Produk-Detail')); } } public function hapus() { $gpr1 = $this->uri->segment(4); $gpr2 = $this->uri->segment(5); $cek = $this->GroupProdukDetailM->cekKode($gpr1, $gpr2); if ($cek->num_rows() > 0) { $this->GroupProdukDetailM->delete($gpr1, $gpr2); echo "<script>alert('Data Group Detail Berhasil di-Hapus !');window.location='".base_url('Admin/Group-Produk-Detail')."';</script>"; }else{ redirect(base_url('Admin/Group-Produk-Detail')); } } public function edit() { $gpr1 = $this->uri->segment(4); $gpr2 = $this->uri->segment(5); $cek = $this->GroupProdukDetailM->cekKode($gpr1, $gpr2); if ($cek->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->GroupProdukM->dataGroupProduk(), 'dataGPD' => $this->GroupProdukDetailM->dataGPD(), 'pg' => 'Admin/Master/groupproduk2', 'edit' => $cek->row() ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Group-Produk-Detail')); } } public function update() { if (isset($_POST['ed'])) { $gpr1 = trim($this->input->post('gpr1')); $gpr2 = trim($this->input->post('gpr2')); $namaLama = trim($this->input->post('namaLama')); $namaBaru = trim($this->input->post('namaGroupDetail')); if ($namaLama == $namaBaru) { $this->GroupProdukDetailM->update($gpr1, $gpr2, $namaLama); echo "<script>alert('Data Group Model Berhasil Di-Ubah !');window.location='".base_url('Admin/Group-Produk-Detail')."';</script>"; }else{ $cekNama = $this->GroupProdukDetailM->cekNama($gpr1, $namaBaru); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Group Produk Detail $namaBaru Sudah Ada Untuk Group Produk $gpr1');window.history.back();</script>"; }else{ $this->GroupProdukDetailM->update($gpr1, $gpr2, $namaBaru); echo "<script>alert('Data Group Model Berhasil Di-Ubah !');window.location='".base_url('Admin/Group-Produk-Detail')."';</script>"; } } }else{ redirect(base_url('Admin/Group-Produk-Detail')); } } } ?><file_sep>/application/controllers/HutangDagang.php <?php class HutangDagang extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); } else { if ($cek->level != '1') { redirect(base_url()); } else { $this->dataUser = $cek; $this->load->model('HutangDagangM'); } } } else { $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'tb' => $this->HutangDagangM->dataHutang(), 'user' => $this->dataUser, 'pg' => 'Admin/Transaksi/hutangdagang' ]; $this->load->view('Admin/main', $data); } } <file_sep>/application/models/DataPembelianM.php <?php class DataPembelianM extends CI_Model { public function dataPembelian() { $this->db->select('*, SUM(FHARGA * FQTY) as total, COUNT(FK_MAT) as jml_mat'); $this->db->group_by('FK_SUP'); $this->db->group_by('FNO_BELI'); $query = $this->db->get('v_beli'); return $query; } } <file_sep>/application/views/Admin/Master/groupmaterial2.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-cogs"></span> &ensp; Group Material Detail</h4> </div> <div class="box-body"> <div class="col-md-8"> <?php if(isset($edit)): ?> <form action="<?=site_url('Admin/Group-Material-Detail/Simpan-Perubahan')?>" class="form" method="post"> <input type="hidden" name="gmat1" value="<?=$edit->FK_GMAT1?>"> <input type="hidden" name="gmat2" value="<?=$edit->FK_GMAT2?>"> <input type="hidden" name="namaLama" value="<?=$edit->FN_GMAT2?>"> <?php else: ?> <form action="<?=site_url('Admin/Group-Material-Detail/Tambah')?>" class="form" method="post"> <?php endif;?> <?php if(!isset($edit)): ?> <div class="form-group"> <label for="">Group Material : </label> <select name="gmat1" id="" class="select2" style="width: 100%;" data-placeholder="Silahkan Pilih Group Material"> <option></option> <?php foreach ($dataGM->result() as $rgp) { echo "<option value='$rgp->FK_GMAT1'>$rgp->FN_GMAT1</option>"; }?> </select> </div> <?php else: ?> <div class="form-group"> <label for="">Group Material : <?=$edit->FK_GMAT1?> - (<?=$edit->FN_GMAT1?>)</label> </div> <?php endif; ?> <div class="form-group"> <label for="">Nama Group Material Detail : </label> <?php if(isset($edit)): ?> <input type="text" name="nama" id="" class="form-control" value="<?=$edit->FN_GMAT2?>" class="form-control" required="" maxlength="20"> <?php else: ?> <input type="text" name="nama" id="" class="form-control" class="form-control" required="" maxlength="20"> <?php endif;?> </div> <div class="form-group"> <?php if(isset($edit)): ?> <button type="submit" class="btn btn-success btn-flat" name="ed"> <span class="fa fa-check"></span> Simpan Perubahan Group Material </button> <a href="<?=site_url('Admin/Group-Material-Detail')?>" class="btn btn-danger btn-flat"> <span class="fa fa-times"></span> Batal Merubah Data </a> <?php else: ?> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Tambah Data Group Material </button> <button type="reset" class="btn btn-danger btn-flat"> <span class="fa fa-undo"></span> Reset Input </button> <?php endif;?> </div> </form> </div> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Group Material</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>Kode Group Material</th> <th>Kode Group Material Detail</th> <th>Nama Group</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($dataGMD->result() as $row) { ?> <tr> <td width="20%"><h5><?=$row->FK_GMAT1?></h5></td> <td width="15%"><h5><?=$row->FK_GMAT2?></h5></td> <td><h5><?=$row->FN_GMAT2?></h5></td> <td width="15%" align="center"> <a href="<?=site_url('Admin/Group-Material-Detail/Edit/').$row->FK_GMAT1."/".$row->FK_GMAT2?>"> <button class="btn btn-warning btn-flat" title="Edit Data Group Material"> <span class="fa fa-edit"></span> </button> </a> <a href="<?=site_url('Admin/Group-Material-Detail/Hapus/').$row->FK_GMAT1."/".$row->FK_GMAT2?>" onclick="return confirm('Hapus Data Material ?')"> <button class="btn btn-danger btn-flat" title="Hapus Data Group Material" > <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div><file_sep>/application/models/Sesi.php <?php class Sesi extends CI_Model { private $_table = 'pegawai'; public function cekLogin($a) { $s1 = $this->db->get_where($this->_table, ['uid' => $a]); if ($s1->num_rows() > 0) { $r1 = $s1->row(); if ($r1->aktif != '1') { $data = '0'; }else{ $data = $r1; } }else{ $data = '0'; } return $data; } } ?><file_sep>/application/views/Admin/Master/material.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-cubes"></span> &ensp; Master Material </h4> </div> <div class="box-body"> <div class="col-md-12"> <?php if(isset($edit)): ?> <form action="<?=site_url('Admin/Material/Simpan-Perubahan')?>" method="post" class="form"> <input type="hidden" name="kode" value="<?=$edit['material']->FK_MAT?>"> <input type="hidden" name="namaLama" value="<?=$edit['material']->FN_MAT?>" > <?php else: ?> <form action="<?=site_url('Admin/Material/Tambah')?>" method="post" class="form"> <?php endif; ?> <div class="col-md-6"> <?php if(isset($edit)): ?> <div class="form-group"> <label for="">Group Material : <?=$edit['gmat1']->FK_GMAT1?> - <?=$edit['gmat1']->FN_GMAT1?> </label> <br> <label for="">Group Material Detail : <?=$edit['gmat2']->FN_GMAT2?></label> </div> <?php else: ?> <div class="form-group"> <label for="">Group Material</label> <select name="gmat1" id="gmat1" class="select2" style="width: 100%;" data-placeholder="Silahkan Pilih Group Material" required="" autofocus=""> <option value=""></option> <?php foreach ($dataGM->result() as $gp) { ?> <?php echo "<option value='$gp->FK_GMAT1'> $gp->FN_GMAT1 - $gp->FK_GMAT1 </option>"; } ?> </select> </div> <div class="form-group"> <label for="">Group Material Detail</label> <select name="gmat2" id="gmat2" class="select2" style="width: 100%;" data-placeholder="Silahkan Pilih Group Material Detail" required=""> <option value=""></option> </select> </div> <?php endif; ?> </div> <div class="col-md-8"> <div class="form-group"> <label for="">Nama Material</label> <?php if(isset($edit)): ?> <input type="text" name="nama" id="" class="form-control" placeholder="Nama Material" required="" value="<?=$edit['material']->FN_MAT?>"> <?php else: ?> <input type="text" name="nama" id="" class="form-control" placeholder="Nama Material" required="" maxlength="50"> <?php endif; ?> </div> </div> <div class="col-md-5"> <div class="form-group"> <label for="">Satuan Material</label> <?php if(isset($edit)): ?> <input type="text" name="satuan" id="" class="form-control" placeholder="Satuan Material" required="" value="<?=$edit['material']->FSAT?>" maxlength="6"> <?php else: ?> <input type="text" name="satuan" id="" class="form-control" placeholder="Satuan Material" required="" maxlength="6"> <?php endif; ?> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Min</label> <?php if(isset($edit)): ?> <input type="number" name="min" id="" class="form-control" required="" min="0" placeholder="0" value="<?=$edit['material']->FSTOK_MIN?>"> <?php else: ?> <input type="number" name="min" id="" class="form-control" required="" min="0" placeholder="0"> <?php endif; ?> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Max</label> <?php if(isset($edit)): ?> <input type="number" name="max" id="" class="form-control" required="" min="0" placeholder="0" value="<?=$edit['material']->FSTOK_MAX?>"> <?php else: ?> <input type="number" name="max" id="" class="form-control" required="" min="0" placeholder="0"> <?php endif; ?> </div> </div> <div class="col-md-12"> <?php if(isset($edit)): ?> <button type="submit" class="btn btn-success btn-flat" name="ed"> <span class="fa fa-check"></span> Simpan Perubahan </button> <a href="<?=site_url('Admin/Material')?>" class="btn btn-danger btn-flat"> <span class="fa fa-times"></span> Batal Melakukan Perubahan </a> <?php else:?> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Tambah Data Material </button> <button type="reset" class="btn btn-danger btn-flat"> <span class="fa fa-undo"></span> Reset Input </button> <?php endif;?> </div> </form> </div> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Material </h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-striped table-hover" id="example1"> <thead> <tr> <th>Kode Material</th> <th>Nama Material</th> <th>Satuan</th> <th>Stok Min</th> <th>Stok Max</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($dataMaterial->result() as $dp) { ?> <tr> <td><h5><?=$dp->FK_MAT?></h5></td> <td><h5><?=$dp->FN_MAT?></h5></td> <td><h5><?=$dp->FSAT?></h5></td> <td><h5><?=$dp->FSTOK_MIN?></h5></td> <td><h5><?=$dp->FSTOK_MAX?></h5></td> <td width="10%" align="center"> <a href="<?=site_url('Admin/Material/Edit/').$dp->FK_MAT?>"> <button class="btn btn-warning btn-flat" title="Edit Data"> <span class="fa fa-edit"></span> </button> </a> <a href="<?=site_url('Admin/Material/Hapus/').$dp->FK_MAT?>" onclick="return confirm('Apakah Anda Yakin Ingin Menghapus Data Tersebut ?');"> <button class="btn btn-danger btn-flat" title="Hapus Data"> <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <script src="<?=base_url('jquery/jquery-3.3.1.js')?>"></script> <script> $(document).ready(function(){ $('#gmat1').change(function(){ var id = $(this).val(); $.ajax({ url: "<?=site_url('Material/detailGM')?>", method: "POST", data: {id: id}, async: true, dataType: 'json', success: function(data){ var option = ''; var i; for (let i = 0; i < data.length; i++) { option += '<option value='+data[i].FK_GMAT2+'>'+data[i].FN_GMAT2+'</option>'; } $('#gmat2').html(option); } }); }); $("#harga").on('keyup', function(){ var n = parseInt($(this).val().replace(/\D/g,''),10); $(this).val(n.toLocaleString()); //do something else as per updated question }); }); </script><file_sep>/application/controllers/Material.php <?php class Material extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('MaterialM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGM' => $this->MaterialM->dataGM(), 'dataMaterial' => $this->MaterialM->dataMaterial(), 'pg' => 'Admin/Master/Material' ]; $this->load->view('Admin/main', $data); } public function detailGM() { $gmat1 = $this->input->post('id', TRUE); $data = $this->MaterialM->dataGMD($gmat1)->result(); echo json_encode($data); } public function tambah() { if (isset($_POST['sav'])) { $a = $this->input->post('gmat1'); $b = $this->input->post('gmat2'); $c = trim($this->input->post('nama')); $cekNama = $this->MaterialM->cekNama($a.$b, $c); if ($cekNama->num_rows() > 0) { echo "<script>alert('Data Material $c Sudah Ada Untuk Group Produk Tersebut !');window.history.back();</script>"; }else{ $d = trim($this->input->post('satuan')); $e = trim($this->input->post('min')); $f = trim($this->input->post('max')); $kodeOtomatis = $this->MaterialM->kodeOtomatis($a.$b); $k = $kodeOtomatis->row_array(); $k1 = $k['kode']; $k2 = (int) substr($k1, 4,2); $k2++; $kode = $a.$b.sprintf('%02s', $k2); $this->MaterialM->save($kode, $c, $d, $e, $f); echo "<script>alert('Data Material Berhasil Di-Tambahkan !');window.location='".base_url('Admin/Material')."';</script>"; } }else{ redirect(base_url('Admin/Material')); } } public function hapus() { $kode = $this->uri->segment(4); $cek = $this->MaterialM->cekKode($kode); if ($cek->num_rows() > 0) { $this->MaterialM->delete($kode); echo "<script>alert('Data Material di-Hapus !');window.location='".base_url('Admin/Material')."';</script>"; }else{ redirect(base_url('Admin/Material')); } } public function edit() { $kode = $this->uri->segment(4); $cek = $this->MaterialM->cekKode($kode); if ($cek->num_rows() > 0) { $r = $cek->row(); $gmat1 = substr($r->FK_MAT, 0,3); $gmat2 = substr($r->FK_MAT, 3,1); $q1 = $this->MaterialM->gmat1($gmat1); $q2 = $this->MaterialM->gmat2($gmat1, $gmat2); if ($q1->num_rows() > 0 && $q2->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGM' => $this->MaterialM->dataGM(), 'dataMaterial' => $this->MaterialM->dataMaterial(), 'pg' => 'Admin/Master/Material', 'edit' => [ 'material' => $r, 'gmat1' => $q1->row(), 'gmat2' => $q2->row() ] ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Material')); } }else{ redirect(base_url('Admin/Material')); } } public function update() { if (isset($_POST['ed'])) { $kode = trim($this->input->post('kode')); $namaLama = trim($this->input->post('namaLama')); $a = trim($this->input->post('nama')); $b = trim($this->input->post('satuan')); $c = trim($this->input->post('min')); $d = trim($this->input->post('max')); if ($a == $namaLama) { $this->MaterialM->update($kode, $namaLama, $b, $c, $d); echo "<script>alert('Data Material Berhasil di-Ubah !');window.location='".base_url('Admin/Material')."';</script>"; }else{ $gmat1 = substr($kode, 0,3); $gmat2 = substr($kode, 3,1); $cekNama = $this->MaterialM->cekNama($gmat1.$gmat2, $a); if ($cekNama->num_rows() > 0) { echo "<script>alert('Data Material $a Sudah Ada Untuk Group Produk Tersebut !');window.history.back();</script>"; }else{ $this->MaterialM->update($kode, $a, $b, $c, $d); echo "<script>alert('Data Material Berhasil di-Ubah !');window.location='".base_url('Admin/Material')."';</script>"; } } }else{ redirect('Admin/Material'); } } } ?><file_sep>/application/controllers/Login.php <?php class Login extends CI_Controller { public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $this->load->model('Sesi'); $uid = $this->session->userdata('uid'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level == '1') { redirect('Admin'); }else if ($cek->level == '2') { redirect('Pegawai'); }else{ $this->session->sess_destroy(); redirect(base_url()); } } } $this->load->model('LoginM'); } public function index() { $this->form_validation->set_rules('username', 'Username', 'required|trim', [ 'required' => "Username Tidak Boleh Kosong !" ]); $this->form_validation->set_rules('password', '<PASSWORD>', 'required', [ 'required' => "Password <PASSWORD> !" ]); if ($this->form_validation->run() == FALSE) { $this->load->view('login'); }else{ $a = htmlspecialchars($this->input->post('username')); $b = htmlspecialchars(sha1($this->input->post('password'))); $cek = $this->LoginM->login($a, $b); if ($cek->num_rows() > 0) { $r1 = $cek->row(); if ($r1->aktif != '1') { $this->session->set_flashdata('message', '<div class="alert alert-warning alert-dismissible"> <button class="close" data-dismiss="alert" aria-hidden="true">&times;</button> User Anda Tidak Dapat Mengakses Program </div>'); redirect(base_url()); }else{ $this->session->set_userdata('uid', $r1->uid); if ($r1->level == '1') { redirect('Admin'); }else if ($r1->level == '2') { redirect('Pegawai'); }else{ $this->session->sess_destroy(); redirect(base_url()); } } }else{ $this->session->set_flashdata('message', '<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> Username / Password Salah ! </div>'); redirect(base_url()); } } } } ?><file_sep>/application/controllers/GroupMaterialDetail.php <?php class GroupMaterialDetail extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('GroupMaterialDetailM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGM' => $this->GroupMaterialDetailM->dataGM(), 'dataGMD' => $this->GroupMaterialDetailM->dataGMD(), 'pg' => 'Admin/Master/groupmaterial2' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $gmat1 = trim($this->input->post('gmat1')); $a = trim($this->input->post('nama')); $cek = $this->GroupMaterialDetailM->cekNama($gmat1, $a); if ($cek->num_rows() > 0) { echo "<script>alert('Nama Group Material Detail $a Sudah Ada ! ');window.history.back();</script>"; }else{ $k = $this->GroupMaterialDetailM->kodeOtomatis($gmat1); $k1 = $k->row_array(); $k2 = $k1['kode']; $k3 = (int) substr($k2, 0,1); $k3++; $kode = sprintf('%01s', $k3); $this->GroupMaterialDetailM->save($gmat1, $kode, $a); echo "<script>alert('Data Group Material Berhasil di-Tambahkan !');window.location='".base_url('Admin/Group-Material-Detail')."';</script>"; } }else{ redirect('Admin/Group-Material-Detail'); } } public function hapus() { $gmat1 = $this->uri->segment(4); $gmat2 = $this->uri->segment(5); $cek = $this->GroupMaterialDetailM->cekKode($gmat1, $gmat2); if ($cek->num_rows() > 0) { $this->GroupMaterialDetailM->delete($gmat1, $gmat2); echo "<script>alert('Data Group Produk Detail Berhasil di-Hapus !');window.location='".base_url('Admin/Group-Material-Detail')."';</script>"; }else{ redirect('Admin/Group-Material-Detail'); } } public function edit() { $gmat1 = $this->uri->segment(4); $gmat2 = $this->uri->segment(5); $cek = $this->GroupMaterialDetailM->cekKode($gmat1, $gmat2); if ($cek->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGMD' => $this->GroupMaterialDetailM->dataGMD(), 'pg' => 'Admin/Master/groupmaterial2', 'edit' => $cek->row() ]; $this->load->view('Admin/main', $data); }else{ redirect('Admin/Group-Material->Detail'); } } public function update() { if (isset($_POST['ed'])) { $gmat1 = trim($this->input->post('gmat1')); $gmat2 = trim($this->input->post('gmat2')); $namaLama = trim($this->input->post('namaLama')); $a = trim($this->input->post('nama')); if ($a == $namaLama) { $this->GroupMaterialDetailM->update($gmat1, $gmat2, $a); echo "<script>alert('Data Group Produk Detail Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Material-Detail')."';</script>"; }else{ $cek = $this->GroupMaterialDetailM->cekNama($gmat1, $a); if ($cek->num_rows() > 0) { echo "<script>alert('Nama Group Material Detail $a Sudah Ada ! ');window.history.back();</script>"; }else{ $this->GroupMaterialDetailM->update($gmat1, $gmat2, $a); echo "<script>alert('Data Group Produk Detail Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Material-Detail')."';</script>"; } } }else{ redirect('Admin/Group-Material-Detail'); } } } ?><file_sep>/application/controllers/GroupProduk.php <?php class GroupProduk extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('GroupProdukM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->GroupProdukM->dataGroupProduk(), 'pg' => 'Admin/Master/groupproduk1' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $namaGroup = trim($this->input->post('namaGroup')); $cekNama = $this->GroupProdukM->cekNama($namaGroup); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Group Produk $namaGroup Sudah Ada !');window.history.back();</script>"; }else{ $kode_otomatis = $this->GroupProdukM->kodeOtomatis(); $r = $kode_otomatis->row_array(); $r1 = $r['kode']; $r2 = (int) substr($r1, 1,2); $r2++; $kode = "F".sprintf('%02s', $r2); $this->GroupProdukM->save($kode, $namaGroup); echo "<script>alert('Data Group Produk Berhasil di-Tambahkan !');window.location='".base_url('Admin/Group-Produk')."';</script>"; } }else{ redirect(base_url('Admin/Group-Produk')); } } public function hapus() { $kode = $this->uri->segment(4); $cekKode = $this->GroupProdukM->cekKode($kode); if ($cekKode->num_rows() > 0) { $this->GroupProdukM->delete($kode); echo "<script>alert('Data Group Produk Berhasil di-Hapus !');window.location='".base_url('Admin/Group-Produk')."';</script>"; }else{ redirect(base_url('Admin/Group-Produk')); } } public function edit() { $kode = $this->uri->segment(4); $cekKode = $this->GroupProdukM->cekKode($kode); if ($cekKode->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->GroupProdukM->dataGroupProduk(), 'pg' => 'Admin/Master/groupproduk1', 'edit' => $cekKode->row() ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Group-Produk')); } } public function update() { if (isset($_POST['ed'])) { $kode = trim($this->input->post('kode')); $namaLama = trim($this->input->post('namaLama')); $namaBaru = trim($this->input->post('namaGroup')); if ($namaLama == $namaBaru) { $this->GroupProdukM->update($kode, $namaBaru); echo "<script>alert('Data Group Produk Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Produk')."';</script>"; }else{ $cekNama = $this->GroupProdukM->cekNama($namaBaru); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Group Produk $namaBaru Sudah Ada !');window.history.back();</script>"; }else{ $this->GroupProdukM->update($kode, $namaBaru); echo "<script>alert('Data Group Produk Berhasil di-Ubah !');window.location='".base_url('Admin/Group-Produk')."';</script>"; } } }else{ redirect(base_url('Admin/Group-Produk')); } } } ?><file_sep>/application/models/MaterialM.php <?php class MaterialM extends CI_Model { private $_table = 'm_mat'; public function dataMaterial() { $query = $this->db->get($this->_table); return $query; } public function dataGM() { $query = $this->db->get('ref_gmat1'); return $query; } public function dataGMD($gmat1) { $query = $this->db->get_where('ref_gmat2', ['FK_GMAT1' => $gmat1]); return $query; } public function cekNama($kode, $nama) { $query = $this->db->query("SELECT * FROM $this->_table WHERE FN_MAT='$nama' AND FK_MAT LIKE '$kode%' "); return $query; } public function kodeOtomatis($FK) { $query = $this->db->query("SELECT max(FK_MAT) as kode FROM $this->_table WHERE FK_MAT LIKE '$FK%' "); return $query; } public function save($a, $b, $c, $d, $e) { $data = [ 'FK_MAT' => $a, 'FN_MAT' => $b, 'FSAT' => $c, 'FSTOK_MIN' => $d, 'FSTOK_MAX' => $e ]; $this->db->insert($this->_table, $data); } public function cekKode($kode) { $query = $this->db->get_where($this->_table, ['FK_MAT' => $kode]); return $query; } public function gmat1($gmat1) { $query = $this->db->get_where('ref_gmat1', ['FK_GMAT1' => $gmat1]); return $query; } public function gmat2($gmat1, $gmat2) { $query = $this->db->get_where('ref_gmat2', ['FK_GMAT1' => $gmat1, 'FK_GMAT2' => $gmat2]); return $query; } public function delete($kode) { $this->db->where('FK_MAT', $kode); $this->db->delete($this->_table); } public function update($kode, $a, $b, $c, $d) { $data = [ 'FN_MAT' => $a, 'FSAT' => $b, 'FSTOK_MIN' => $c, 'FSTOK_MAX' => $d ]; $this->db->where('FK_MAT', $kode); $this->db->update($this->_table, $data); } } ?><file_sep>/application/controllers/Pembelian.php <?php class Pembelian extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); } else { if ($cek->level != '1') { redirect(base_url()); } else { $this->dataUser = $cek; $this->load->model('PembelianM'); } } } else { $this->session->sess_destroy(); redirect(base_url()); } } public function index() { if ($this->session->has_userdata('Supplier-Pembelian')) { $kodeSp = $this->session->userdata('Supplier-Pembelian'); $cekSp = $this->PembelianM->cekSupplier($kodeSp); if ($cekSp->num_rows() > 0) { $sp = $cekSp->row(); $mat = $this->PembelianM->dataMaterial($kodeSp); $tbc = $this->cart->contents(); } else { $this->session->unset_userdata('Supplier-Pembelian'); redirect('Admin/Pembelian'); } } else { $sp = ''; $mat = ''; $tbc = ''; } $data = [ 'user' => $this->dataUser, 'dataSupplier' => $this->PembelianM->dataSupplier(), 'sp' => $sp, 'mat' => $mat, 'pg' => 'Admin/Transaksi/pembelian', 'tbc' => $tbc ]; $this->load->view('Admin/main', $data); } public function supplier() { $sp = $this->uri->segment(4); $cekSp = $this->PembelianM->cekSupplier($sp); if ($cekSp->num_rows() > 0) { $this->session->set_userdata('Supplier-Pembelian', $sp); redirect(base_url('Admin/Pembelian')); } else { redirect(base_url('Admin/Pembelian')); } } public function material() { $mat = $this->input->post('mat', true); $cek = $this->PembelianM->cekMaterial($mat)->row(); echo json_encode($cek); } public function batal() { $cart = $this->cart->contents(); $uid = $this->session->userdata('uid'); $tgl = $this->session->userdata('Tanggal-Pembelian'); $pem = $this->session->userdata('Pembayaran-Pembelian'); $sup = $this->session->userdata('Supplier-Pembelian'); foreach ($cart as $ca) { if ($ca['transaksi'] == 'Pembelian' && $ca['tanggal'] == $tgl && $ca['jenis'] == $pem && $ca['supplier'] == $sup && $ca['uid'] == $uid) { $rowid = $ca['rowid']; $this->cart->remove($rowid); } } $this->session->unset_userdata('Supplier-Pembelian'); $this->session->unset_userdata('Tanggal-Pembelian'); $this->session->unset_userdata('Pembayaran-Pembelian'); redirect('Admin/Pembelian'); } public function tambah() { if (isset($_POST['sav'])) { $sup = $this->session->userdata('Supplier-Pembelian'); if ($this->session->has_userdata('Tanggal-Pembelian')) { $tgl = $this->session->userdata('Tanggal-Pembelian'); } else { $tgl = trim($this->input->post('tgl')); $this->session->set_userdata('Tanggal-Pembelian', $tgl); } if ($this->session->has_userdata('Pembayaran-Pembelian')) { $jenis = $this->session->userdata('Pembayaran-Pembelian'); } else { $jenis = trim($this->input->post('jenis')); $this->session->set_userdata('Pembayaran-Pembelian', $jenis); } $mat = trim($this->input->post('mat')); $nmat = trim($this->input->post('nmat1')); $qty = trim($this->input->post('qty')); $harga = trim($this->input->post('harga')); $harga = str_replace(',', '', $harga); $cart = $this->cart->contents(); $data = [ 'id' => $mat, 'qty' => $qty, 'price' => $harga, 'name' => $nmat, 'supplier' => $sup, 'tanggal' => $tgl, 'jenis' => $jenis, 'uid' => $this->session->userdata('uid'), 'transaksi' => "Pembelian" ]; $this->cart->insert($data); echo "<script>alert('Data di-Masukan Keranjang Pembelian !');window.location='" . base_url('Admin/Pembelian') . "';</script>"; } else { redirect(base_url('Admin/Pembelian')); } } public function hapus() { $rid = $this->uri->segment(4); $this->cart->remove($rid); echo "<script>alert('Material di-Hapus dari Cart !');window.location='" . base_url('Admin/Pembelian') . "';</script>"; } public function selesai() { $uid = $this->session->userdata('uid'); $sup = $this->session->userdata('Supplier-Pembelian'); $tgl = $this->session->userdata('Tanggal-Pembelian'); $pem = $this->session->userdata('Pembayaran-Pembelian'); $d = date('d'); $k = $this->PembelianM->kodeOtomatis($d, $sup); $kk = $k->row_array(); $k1 = $kk['kode']; $k2 = (int) substr($k1, 2, 5); $k2++; $kode = $d . sprintf('%05s', $k2); $s1 = $this->PembelianM->saveh($kode, $tgl, $sup, $pem); $cart = $this->cart->contents(); $jmlMat = 0; $bayar = 0; foreach ($cart as $dc) { if ($dc['transaksi'] == 'Pembelian' && $dc['tanggal'] == $tgl && $dc['jenis'] == $pem && $dc['supplier'] == $sup && $dc['uid'] == $uid) { $jmlMat += 1; $bayar += $dc['qty'] * $dc['price']; $rowid = $dc['rowid']; $mat = $dc['id']; $jml = $dc['qty']; $harga = $dc['price']; $s2 = $this->PembelianM->saved($kode, $mat, $jml, $harga); $data = [ 'rowid' => $rowid, 'qty' => 0 ]; $this->cart->update($data); } } if ($pem == '0') { $s3 = $this->PembelianM->savehd($kode, $sup, $jmlMat, $bayar); } $this->session->unset_userdata('Supplier-Pembelian'); $this->session->unset_userdata('Tanggal-Pembelian'); $this->session->unset_userdata('Pembayaran-Pembelian'); echo "<script> alert('Transaksi Selesai !'); window.location='" . base_url('Admin/Pembelian') . "'; window.open('" . base_url() . "Admin/Print/Pembelian/" . $kode . "/" . $sup . "'); </script>"; echo "<script></script>"; } } <file_sep>/application/views/Admin/Data/pembelian.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-file"></span> &ensp; Data Pembelian</h4> </div> <div class="box-body"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-bordered" id="example1"> <thead> <tr> <th>No Pembelian</th> <th>Tanggal Pembelian</th> <th>Supplier</th> <th>Jenis Pembelian</th> <th>Jumlah Material</th> <th>Total Pembelian</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($tb->result() as $rd) { $fhc = $rd->FHC; if ($fhc == '0') { $hc = 'Kredit'; } else if ($fhc == '1') { $hc = 'Cash'; } ?> <tr> <td> <h5><?= $rd->FNO_BELI ?></h5> </td> <td> <h5><?= $rd->FTGL_BELI ?></h5> </td> <td> <h5><?= $rd->FNA_SUP ?></h5> </td> <td> <h5><?= $hc ?></h5> </td> <td> <h5><?= $rd->jml_mat ?></h5> </td> <td> <h5><?= "Rp. " . number_format($rd->total, 0, ',', '.') ?></h5> </td> <td class="text-center"> <a href="<?= base_url('Admin/Print/Pembelian/') . $rd->FNO_BELI . "/" . $rd->FK_SUP ?>" target="_blank"> <button class="btn btn-info"> <span class="glyphicon glyphicon-print"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep>/application/views/Admin/Relasi/mat_sup.php <?php if(isset($detailSP)): ?> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-exchange"></span> &ensp; Relasi Material - Supplier </h4> </div> <div class="box-body"> <form action="<?=site_url('Admin/Relasi-Material-Supplier/').$detailSP->FK_SUP."/Tambah"?>" method="post" class="form"> <input type="hidden" name="kodeSupplier" value="<?=$detailSP->FK_SUP?>"> <div class="col-md-12"> <div class="col-md-12"> <div class="form-group"> <label for="">Pilih Material : </label> <select name="material" id="material" class="select2" style="width: 100%;" data-placeholder="Silahkan Pilih Material" required="" autofocus=""> <option value=""></option> <?php foreach ($dataMaterial->result() as $gp) { ?> <?php echo "<option value='$gp->FK_MAT'> $gp->FN_MAT - $gp->FK_MAT </option>"; } ?> </select> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Kode Material :</label> <input type="text" name="kodeMaterial" id="kodeMaterial" disabled="" class="form-control"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Nama Material :</label> <input type="text" name="namaMaterial" id="namaMaterial" disabled="" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Satuan Material :</label> <input type="text" name="satuanMaterial" id="satuanMaterial" disabled="" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Minimal :</label> <input type="text" name="stokMin" id="stokMin" disabled="" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Max :</label> <input type="text" name="stokMax" id="stokMax" disabled="" class="form-control"> </div> </div> </div> <div class="col-md-12" id="formTambah" hidden=""> <div class="col-md-6"> <div class="form-group"> <label for="">Nama Material Pada Supplier : </label> <input type="text" name="nama" id="nama" class="form-control" required=""> </div> </div> <div class="col-md-6"> <div class="input-group"> <label for="">Harga Produk</label> </div> <div class="input-group"> <span class="input-group-addon">Rp. </span> <input type="text" name="harga" id="harga" class="form-control" placeholder="Harga Produk" required=""> </div> </div> <div class="col-md-12"> <div class="form-group"> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Buat Relasi Material Supplier </button> </div> </div> </div> </form> </div> <div class="box-footer"> <a href="<?=site_url('Admin/Relasi-Material-Supplier')?>" class="btn btn-info btn-flat btn-block"> <span class="fa fa-hand-o-left"></span> Pilih Ulang Supplier </a> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Relasi Supplier - <?=$detailSP->FNA_SUP?> </h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-striped table-hover" id="example1"> <thead> <tr> <th>Kode Material</th> <th>Kode Material</th> <th>Nama Material</th> <th>Nama Material Pada Supplier</th> <th>Harga Pada Supplier</th> <th>Pilih</th> </tr> </thead> <tbody> <?php foreach ($dataRelasi->result() as $row) { ?> <tr> <td width="5%"><h5><?=$row->FK_SUP?></h5></td> <td><h5><?=$row->FK_MAT?></h5></td> <td><h5><?=$row->FN_MAT?></h5></td> <td><h5><?=$row->FN_MAT_SUP?></h5></td> <td><h5><?="Rp. ".number_format($row->FHARGA, 2, ',', '.')?></h5></td> <td width="10%" align="center"> <a href="<?=site_url('Admin/Relasi-Material-Supplier/').$row->FK_SUP."/Hapus/".$row->FK_MAT?>"> <button class="btn btn-danger btn-flat" title="Hapus Data"> <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <script src="<?=base_url('jquery/jquery-3.3.1.js')?>"></script> <script> $(document).ready(function(){ $('#material').change(function(){ var id = $(this).val(); $.ajax({ url: "<?=site_url('Relasi/detailM')?>", method: "POST", data: {id: id}, async: true, dataType: 'json', success: function(data){ $('#kodeMaterial').val(data.FK_MAT); $('#namaMaterial').val(data.FN_MAT); $('#satuanMaterial').val(data.FSAT); $('#stokMin').val(data.FSTOK_MIN); $('#stokMax').val(data.FSTOK_MAX); $('#formTambah').show(); $('#nama').focus(); } }); }); $("#harga").on('keyup', function(){ var n = parseInt($(this).val().replace(/\D/g,''),10); $(this).val(n.toLocaleString()); //do something else as per updated question }); }); </script> <?php else: ?> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Pilih Data Supplier</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-striped table-hover" id="example1"> <thead> <tr> <th>Kode Supplier</th> <th>Nama Supplier</th> <th>Alamat Supplier</th> <th>Kota</th> <th>Telfon</th> <th>CP</th> <th>Lama Bayar</th> <th>Penerima</th> <th>Bank</th> <th>No. Acc</th> <th>Pilih</th> </tr> </thead> <tbody> <?php foreach ($dataSP->result() as $row) { ?> <tr> <td width="5%"><h5><?=$row->FK_SUP?></h5></td> <td><h5><?=$row->FNA_SUP?></h5></td> <td><h5><?=$row->FALAMAT?></h5></td> <td><h5><?=$row->FKOTA?></h5></td> <td><h5><?=$row->FTEL?></h5></td> <td><h5><?=$row->FCP?></h5></td> <td><h5><?=$row->FLAMA_BAYAR?></h5></td> <td><h5><?=$row->FPENERIMA?></h5></td> <td><h5><?=$row->FBANK?></h5></td> <td><h5><?=$row->FNO_ACC?></h5></td> <td width="10%" align="center"> <a href="<?=site_url('Admin/Relasi-Material-Supplier/').$row->FK_SUP?>"> <button class="btn btn-info btn-flat" title="Pilih Data Supplier"> <span class="fa fa-hand-o-right"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <?php endif; ?><file_sep>/application/controllers/Supplier.php <?php class Supplier extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('SupplierM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataS' => $this->SupplierM->dataSupplier(), 'pg' => 'Admin/Master/supplier' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $a = trim($this->input->post('nama')); $cekNama = $this->SupplierM->cekNama($a); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Supplier $a Sudah Ada !');window.history.back();</script>"; }else{ $b = trim($this->input->post('alamat')); $c = trim($this->input->post('kota')); $d = trim($this->input->post('telp')); $e = trim($this->input->post('cp')); $f = trim($this->input->post('lamaBayar')); $g = trim($this->input->post('penerima')); $h = trim($this->input->post('bank')); $i = trim($this->input->post('noacc')); $kode_otomatis = $this->SupplierM->kodeOtomatis(); $r = $kode_otomatis->row_array(); $r1 = $r['kode']; $r2 = (int) substr($r1, 0,3); $r2++; $kode = sprintf('%03s', $r2); $this->SupplierM->save($kode, $a, $b, $c, $d, $e, $f, $g, $h, $i); echo "<script>alert('Data Supplier Berhasil di-Tambahkan !');window.location='".base_url('Admin/Supplier')."';</script>"; } }else{ redirect(base_url('Admin/Supplier')); } } public function hapus() { $kode = $this->uri->segment(4); $cekKode = $this->SupplierM->cekKode($kode); if ($cekKode->num_rows() > 0) { $this->SupplierM->delete($kode); echo "<script>alert('Data Supplier Berhasil di-Hapus !');window.location='".base_url('Admin/Supplier')."';</script>"; }else{ redirect(base_url('Admin/Supplier')); } } public function edit() { $kode = $this->uri->segment(4); $cekKode = $this->SupplierM->cekKode($kode); if ($cekKode->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataS' => $this->SupplierM->dataSupplier(), 'pg' => 'Admin/Master/supplier', 'edit' => $cekKode->row() ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Supplier')); } } public function update() { if (isset($_POST['ed'])) { $kode = trim($this->input->post('kode')); $namaLama = trim($this->input->post('namaLama')); $namaBaru = trim($this->input->post('nama')); $b = trim($this->input->post('alamat')); $c = trim($this->input->post('kota')); $d = trim($this->input->post('telp')); $e = trim($this->input->post('cp')); $f = trim($this->input->post('lamaBayar')); $g = trim($this->input->post('penerima')); $h = trim($this->input->post('bank')); $i = trim($this->input->post('noacc')); if ($namaLama == $namaBaru) { $this->SupplierM->update($kode, $namaBaru, $b, $c, $d, $e, $f, $g, $h, $i); echo "<script>alert('Data Supplier Berhasil di-Ubah !');window.location='".base_url('Admin/Supplier')."';</script>"; }else{ $cekNama = $this->SupplierM->cekNama($namaBaru); if ($cekNama->num_rows() > 0) { echo "<script>alert('Nama Supplier $namaBaru Sudah Ada !');window.history.back();</script>"; }else{ $this->SupplierM->update($kode, $namaBaru, $b, $c, $d, $e, $f, $g, $h, $i); echo "<script>alert('Data Supplier Berhasil di-Ubah !');window.location='".base_url('Admin/Supplier')."';</script>"; } } }else{ redirect(base_url('Admin/Supplier')); } } } ?><file_sep>/application/views/Admin/Master/perkiraan.php <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title">&ensp; <span class="fa fa-bullseye"></span> &ensp; Master Perkiraan</h4> </div> <div class="box-body"> <div class="col-md-12"> <form action="<?= site_url('Admin/Perkiraan/Tambah') ?>" method="POST"> <div class="col-md-3"> <div class="form-group"> <label for="">Kode Perkiraan : </label> <input type="text" name="kode" id="kode" class="form-control" maxlength="8" required="" autofocus=""> </div> </div> <div class="col-md-5"> <div class="form-group"> <label for="">Nama Perkiraan : </label> <input type="text" name="nama" id="nama" class="form-control"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Saldo Normal : </label> <div class="radio"> <label> <input type="radio" name="saldo" id="saldo" value="K"> Kredit </label> &ensp; &ensp; <label> <input type="radio" name="saldo" id="saldo" value="D"> Debit </label> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <button type="submit" class="btn btn-success btn-flat" name="sav"> <span class="fa fa-plus"></span> Tambah Data Perkiraan </button> <button type="reset" class="btn btn-danger btn-flat"> <span class="fa fa-undo"></span> Reset Input </button> </div> </div> </form> </div> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Perkiraan </h4> </div> <div class="box-body"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>Kode Perkiraan</th> <th>Nama Perkiraan</th> <th>Saldo Normal</th> <th>Aksi</th> </tr> </thead> <tbody> <?php foreach ($tb->result() as $row) { if ($row->FSALDO_NORMAL == 'K') { $saldo = 'Kredit'; } else if ($row->FSALDO_NORMAL == 'D') { $saldo = 'Debit'; } ?> <tr> <td> <h5><?= $row->FK_PERK ?></h5> </td> <td> <h5><?= $row->FN_PERK ?></h5> </td> <td width="20%"> <h5><?= $saldo ?></h5> </td> <td width="10%" class="text-center"> <a href="<?= site_url('Admin/Perkiraan/Edit/') . $row->FK_PERK ?>"> <button class="btn btn-warning btn-flat"> <span class="fa fa-edit"></span> </button> </a> <a href="<?= site_url('Admin/Perkiraan/Hapus/') . $row->FK_PERK ?>" onclick="return confirm('Yakin Untuk Menghapus Data ?')"> <button class="btn btn-danger btn-flat"> <span class="fa fa-trash"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div><file_sep>/cafeallegra.sql -- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 04, 2019 at 10:55 AM -- Server version: 10.1.38-MariaDB -- PHP Version: 7.2.17 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `cafeallegra` -- -- -------------------------------------------------------- -- -- Table structure for table `h_beli` -- CREATE TABLE `h_beli` ( `FNO_BELI` char(7) NOT NULL, `FTGL_BELI` date DEFAULT NULL, `FK_SUP` char(3) NOT NULL, `FHC` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `h_beli` -- INSERT INTO `h_beli` (`FNO_BELI`, `FTGL_BELI`, `FK_SUP`, `FHC`) VALUES ('3100001', '2019-08-31', '001', '1'), ('3100001', '2019-08-31', '002', '0'); -- -------------------------------------------------------- -- -- Table structure for table `h_kas` -- CREATE TABLE `h_kas` ( `FNO_KAS` char(7) NOT NULL, `FTGL_KAS` date DEFAULT NULL, `FMUTASI` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `m_brg` -- CREATE TABLE `m_brg` ( `FK_BRG` char(6) NOT NULL, `FN_BRG` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FSTOK_MIN` decimal(18,0) DEFAULT NULL, `FSTOK_MAX` decimal(18,0) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `m_mat` -- CREATE TABLE `m_mat` ( `FK_MAT` char(6) NOT NULL, `FN_MAT` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FSTOK_MIN` decimal(18,0) DEFAULT NULL, `FSTOK_MAX` decimal(18,0) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `m_mat` -- INSERT INTO `m_mat` (`FK_MAT`, `FN_MAT`, `FSAT`, `FSTOK_MIN`, `FSTOK_MAX`) VALUES ('001101', 'Test 1.1.1', 'PCS', '10', '50'), ('001102', 'Test 1.1.2', 'PCS', '10', '20'), ('001201', 'Test 1.2.1', 'PCS', '10', '15'), ('001202', 'Test 1.2.2', 'PCS', '5', '10'), ('001301', 'Test 1.3.1', 'PCS', '20', '25'), ('001302', 'Test 1.3.2', 'PCS', '3', '15'), ('001401', 'Test 1.4.1', 'PCS', '20', '25'), ('001402', 'Test 1.4.2', 'PCS', '5', '25'), ('002101', 'Test 2.1.1', 'PCS', '8', '20'), ('002102', 'Test 2.1.2', 'PCS', '5', '30'), ('002201', 'Test 2.2.1', 'PCS', '20', '30'), ('002202', 'Test 2.2.2', 'PCS', '1', '10'), ('002301', 'Test 2.3.1', 'PCS', '10', '20'), ('002302', 'Test 2.3.2', 'PCS', '10', '20'), ('002401', 'Test 2.4.1', 'PCS', '5', '15'), ('002402', 'Test 2.4.2', 'PCS', '5', '20'); -- -------------------------------------------------------- -- -- Table structure for table `m_perk` -- CREATE TABLE `m_perk` ( `FK_PERK` char(8) NOT NULL, `FN_PERK` varchar(50) DEFAULT NULL, `FSALDO_NORMAL` char(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `m_pr` -- CREATE TABLE `m_pr` ( `FK_BPR` char(6) NOT NULL, `FN_BPR` varchar(50) DEFAULT NULL, `FSAT` varchar(6) DEFAULT NULL, `FHARGA` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `m_pr` -- INSERT INTO `m_pr` (`FK_BPR`, `FN_BPR`, `FSAT`, `FHARGA`) VALUES ('F01101', 'Test Produk 1.1.1', 'PCS', 5000), ('F01102', 'Test Produk 1.1.2', 'PCS', 8000), ('F01201', 'Test Produk 1.2.1', 'PCS', 8000), ('F01202', 'Test Produk 1.2.2', 'PCS', 12000), ('F02101', 'Test Produk 2.1.1', 'PCS', 15000), ('F02102', 'Test Produk 2.1.2', 'PCS', 5500); -- -------------------------------------------------------- -- -- Table structure for table `m_sup` -- CREATE TABLE `m_sup` ( `FK_SUP` char(3) NOT NULL, `FNA_SUP` varchar(20) DEFAULT NULL, `FALAMAT` varchar(100) DEFAULT NULL, `FKOTA` varchar(30) DEFAULT NULL, `FTEL` varchar(12) DEFAULT NULL, `FCP` varchar(20) DEFAULT NULL, `FLAMA_BAYAR` int(11) DEFAULT NULL, `FPENERIMA` varchar(40) DEFAULT NULL, `FBANK` varchar(20) DEFAULT NULL, `FNO_ACC` varchar(15) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `m_sup` -- INSERT INTO `m_sup` (`FK_SUP`, `FNA_SUP`, `FALAMAT`, `FKOTA`, `FTEL`, `FCP`, `FLAMA_BAYAR`, `FPENERIMA`, `FBANK`, `FNO_ACC`) VALUES ('001', 'Supplier Test 1', 'Test 1', 'Test 1', '085551222', 'Test 1', 10, 'Test 1', 'Test 1', '100'), ('002', 'Supplier Test 2', 'Test 2', 'Test 2', '082221222', 'Test 2', 30, 'Test 2', 'Test 2', '200'); -- -------------------------------------------------------- -- -- Table structure for table `pegawai` -- CREATE TABLE `pegawai` ( `uid` char(6) NOT NULL, `nama_pegawai` varchar(40) NOT NULL, `username` varchar(40) NOT NULL, `password` varchar(50) NOT NULL, `level` int(1) NOT NULL, `aktif` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `pegawai` -- INSERT INTO `pegawai` (`uid`, `nama_pegawai`, `username`, `password`, `level`, `aktif`) VALUES ('ADM001', '<PASSWORD>', '<PASSWORD>', '<PASSWORD>', 1, 1), ('ADM002', 'Test', 'test', '<PASSWORD>', 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `ref_gmat1` -- CREATE TABLE `ref_gmat1` ( `FK_GMAT1` char(3) NOT NULL, `FN_GMAT1` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ref_gmat1` -- INSERT INTO `ref_gmat1` (`FK_GMAT1`, `FN_GMAT1`) VALUES ('001', 'Test 1'), ('002', 'Test 2'), ('003', 'Test 3'), ('004', 'Test 4'); -- -------------------------------------------------------- -- -- Table structure for table `ref_gmat2` -- CREATE TABLE `ref_gmat2` ( `FK_GMAT1` char(3) NOT NULL, `FK_GMAT2` char(1) NOT NULL, `FN_GMAT2` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ref_gmat2` -- INSERT INTO `ref_gmat2` (`FK_GMAT1`, `FK_GMAT2`, `FN_GMAT2`) VALUES ('001', '1', 'Test 1.1'), ('001', '2', 'Test 1.2'), ('001', '3', 'Test 1.3'), ('001', '4', 'Test 1.4'), ('002', '1', 'Test 2.1'), ('002', '2', 'Test 2.2'), ('002', '3', 'Test 2.3'), ('002', '4', 'Test 2.4'), ('003', '1', 'Test 3.1'), ('003', '2', 'Test 3.2'), ('003', '3', 'Test 3.3'), ('003', '4', 'Test 3.4'), ('004', '1', 'Test 4.1'), ('004', '2', 'Test 4.2'), ('004', '3', 'Test 4.3'), ('004', '4', 'Test 4.4'); -- -------------------------------------------------------- -- -- Table structure for table `ref_gpr1` -- CREATE TABLE `ref_gpr1` ( `FK_GPR1` char(3) NOT NULL, `FN_GPR1` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ref_gpr1` -- INSERT INTO `ref_gpr1` (`FK_GPR1`, `FN_GPR1`) VALUES ('F01', 'Test Produk 1'), ('F02', 'Test Produk 2'), ('F03', 'Test Produk 3'), ('F04', 'Test Produk 4'); -- -------------------------------------------------------- -- -- Table structure for table `ref_gpr2` -- CREATE TABLE `ref_gpr2` ( `FK_GPR1` char(3) NOT NULL, `FK_GPR2` char(1) NOT NULL, `FN_GPR2` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ref_gpr2` -- INSERT INTO `ref_gpr2` (`FK_GPR1`, `FK_GPR2`, `FN_GPR2`) VALUES ('F01', '1', 'Test Produk 1.1'), ('F01', '2', 'Test Produk 1.2'), ('F01', '3', 'Test Produk 1.3'), ('F01', '4', 'Test Produk 1.4'), ('F02', '1', 'Test Produk 2.1'), ('F02', '2', 'Test Produk 2.2'), ('F02', '3', 'Test Produk 2.3'), ('F02', '4', 'Test Produk 2.4'), ('F03', '1', 'Test Produk 3.1'), ('F03', '2', 'Test Produk 3.2'), ('F03', '3', 'Test Produk 3.3'), ('F03', '4', 'Test Produk 3.4'), ('F04', '1', 'Test Produk 4.1'), ('F04', '2', 'Test Produk 4.2'), ('F04', '3', 'Test Produk 4.3'), ('F04', '4', 'Test Produk 4.4'); -- -------------------------------------------------------- -- -- Table structure for table `rls_mat_sup` -- CREATE TABLE `rls_mat_sup` ( `FK_SUP` char(3) NOT NULL, `FK_MAT` char(6) NOT NULL, `FHARGA` decimal(7,2) DEFAULT NULL, `FN_MAT_SUP` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `rls_mat_sup` -- INSERT INTO `rls_mat_sup` (`FK_SUP`, `FK_MAT`, `FHARGA`, `FN_MAT_SUP`) VALUES ('001', '001101', '20000.00', 'Test 1.1'), ('001', '001102', '15600.00', 'Test 1.2'), ('001', '001201', '50000.00', 'Test 2.1'), ('001', '001202', '13000.00', 'Test 2.2'), ('001', '001301', '10000.00', 'Test 3.1'), ('001', '001302', '18500.00', 'Test 3.2'), ('002', '002101', '15000.00', 'Test 1.1'), ('002', '002102', '5600.00', 'Test 2.2'), ('002', '002201', '15000.00', 'Test 2.1'), ('002', '002202', '18500.00', 'Test 2.2'); -- -------------------------------------------------------- -- -- Table structure for table `t_beli` -- CREATE TABLE `t_beli` ( `FNO_BELI` char(7) NOT NULL, `FK_MAT` char(6) NOT NULL, `FQTY` decimal(18,0) DEFAULT NULL, `FHARGA` decimal(7,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `t_beli` -- INSERT INTO `t_beli` (`FNO_BELI`, `FK_MAT`, `FQTY`, `FHARGA`) VALUES ('3100001', '001101', '5', '20000.00'), ('3100001', '001102', '10', '15600.00'), ('3100001', '002101', '10', '15000.00'), ('3100001', '002102', '30', '5600.00'); -- -------------------------------------------------------- -- -- Table structure for table `t_hd` -- CREATE TABLE `t_hd` ( `FNO_BELI` char(7) NOT NULL, `FK_SUP` char(3) NOT NULL, `FJML` decimal(15,2) DEFAULT NULL, `FBAYAR` decimal(15,2) DEFAULT NULL, `FTGL_BAYAR` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `t_hd` -- INSERT INTO `t_hd` (`FNO_BELI`, `FK_SUP`, `FJML`, `FBAYAR`, `FTGL_BAYAR`) VALUES ('3100001', '002', '2.00', '318000.00', NULL); -- -------------------------------------------------------- -- -- Table structure for table `t_kas` -- CREATE TABLE `t_kas` ( `FNO_KAS` char(7) NOT NULL, `FKET` varchar(50) DEFAULT NULL, `FK_PERK` char(8) NOT NULL, `FJML` decimal(9,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Stand-in structure for view `v_beli` -- (See below for the actual view) -- CREATE TABLE `v_beli` ( `FNO_BELI` char(7) ,`FTGL_BELI` date ,`FK_SUP` char(3) ,`FNA_SUP` varchar(20) ,`FALAMAT` varchar(100) ,`FKOTA` varchar(30) ,`FTEL` varchar(12) ,`FCP` varchar(20) ,`FLAMA_BAYAR` int(11) ,`FPENERIMA` varchar(40) ,`FBANK` varchar(20) ,`FNO_ACC` varchar(15) ,`FHC` char(1) ,`FK_MAT` char(6) ,`FN_MAT` varchar(50) ,`FSAT` varchar(6) ,`FSTOK_MIN` decimal(18,0) ,`FSTOK_MAX` decimal(18,0) ,`FQTY` decimal(18,0) ,`FHARGA` decimal(7,2) ); -- -------------------------------------------------------- -- -- Stand-in structure for view `v_gmat2` -- (See below for the actual view) -- CREATE TABLE `v_gmat2` ( `FK_GMAT1` char(3) ,`FN_GMAT1` varchar(20) ,`FK_GMAT2` char(1) ,`FN_GMAT2` varchar(20) ); -- -------------------------------------------------------- -- -- Stand-in structure for view `v_gpr2` -- (See below for the actual view) -- CREATE TABLE `v_gpr2` ( `FK_GPR1` char(3) ,`FN_GPR1` varchar(20) ,`FK_GPR2` char(1) ,`FN_GPR2` varchar(20) ); -- -------------------------------------------------------- -- -- Stand-in structure for view `v_rls_mat_sup` -- (See below for the actual view) -- CREATE TABLE `v_rls_mat_sup` ( `FK_SUP` char(3) ,`FK_MAT` char(6) ,`FN_MAT` varchar(50) ,`FSAT` varchar(6) ,`FSTOK_MIN` decimal(18,0) ,`FSTOK_MAX` decimal(18,0) ,`FHARGA` decimal(7,2) ,`FN_MAT_SUP` varchar(50) ); -- -------------------------------------------------------- -- -- Structure for view `v_beli` -- DROP TABLE IF EXISTS `v_beli`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_beli` AS select `h_beli`.`FNO_BELI` AS `FNO_BELI`,`h_beli`.`FTGL_BELI` AS `FTGL_BELI`,`h_beli`.`FK_SUP` AS `FK_SUP`,`m_sup`.`FNA_SUP` AS `FNA_SUP`,`m_sup`.`FALAMAT` AS `FALAMAT`,`m_sup`.`FKOTA` AS `FKOTA`,`m_sup`.`FTEL` AS `FTEL`,`m_sup`.`FCP` AS `FCP`,`m_sup`.`FLAMA_BAYAR` AS `FLAMA_BAYAR`,`m_sup`.`FPENERIMA` AS `FPENERIMA`,`m_sup`.`FBANK` AS `FBANK`,`m_sup`.`FNO_ACC` AS `FNO_ACC`,`h_beli`.`FHC` AS `FHC`,`t_beli`.`FK_MAT` AS `FK_MAT`,`m_mat`.`FN_MAT` AS `FN_MAT`,`m_mat`.`FSAT` AS `FSAT`,`m_mat`.`FSTOK_MIN` AS `FSTOK_MIN`,`m_mat`.`FSTOK_MAX` AS `FSTOK_MAX`,`t_beli`.`FQTY` AS `FQTY`,`t_beli`.`FHARGA` AS `FHARGA` from (((`h_beli` join `m_sup` on((`m_sup`.`FK_SUP` = `h_beli`.`FK_SUP`))) join `t_beli` on((`t_beli`.`FNO_BELI` = `h_beli`.`FNO_BELI`))) join `m_mat` on((`m_mat`.`FK_MAT` = `t_beli`.`FK_MAT`))) ; -- -------------------------------------------------------- -- -- Structure for view `v_gmat2` -- DROP TABLE IF EXISTS `v_gmat2`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_gmat2` AS select `ref_gmat2`.`FK_GMAT1` AS `FK_GMAT1`,`ref_gmat1`.`FN_GMAT1` AS `FN_GMAT1`,`ref_gmat2`.`FK_GMAT2` AS `FK_GMAT2`,`ref_gmat2`.`FN_GMAT2` AS `FN_GMAT2` from (`ref_gmat2` join `ref_gmat1` on((`ref_gmat1`.`FK_GMAT1` = `ref_gmat2`.`FK_GMAT1`))) ; -- -------------------------------------------------------- -- -- Structure for view `v_gpr2` -- DROP TABLE IF EXISTS `v_gpr2`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_gpr2` AS select `ref_gpr2`.`FK_GPR1` AS `FK_GPR1`,`ref_gpr1`.`FN_GPR1` AS `FN_GPR1`,`ref_gpr2`.`FK_GPR2` AS `FK_GPR2`,`ref_gpr2`.`FN_GPR2` AS `FN_GPR2` from (`ref_gpr2` join `ref_gpr1` on((`ref_gpr1`.`FK_GPR1` = `ref_gpr2`.`FK_GPR1`))) ; -- -------------------------------------------------------- -- -- Structure for view `v_rls_mat_sup` -- DROP TABLE IF EXISTS `v_rls_mat_sup`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_rls_mat_sup` AS select `rls_mat_sup`.`FK_SUP` AS `FK_SUP`,`rls_mat_sup`.`FK_MAT` AS `FK_MAT`,`m_mat`.`FN_MAT` AS `FN_MAT`,`m_mat`.`FSAT` AS `FSAT`,`m_mat`.`FSTOK_MIN` AS `FSTOK_MIN`,`m_mat`.`FSTOK_MAX` AS `FSTOK_MAX`,`rls_mat_sup`.`FHARGA` AS `FHARGA`,`rls_mat_sup`.`FN_MAT_SUP` AS `FN_MAT_SUP` from (`rls_mat_sup` join `m_mat` on((`m_mat`.`FK_MAT` = `rls_mat_sup`.`FK_MAT`))) ; -- -- Indexes for dumped tables -- -- -- Indexes for table `h_beli` -- ALTER TABLE `h_beli` ADD PRIMARY KEY (`FNO_BELI`,`FK_SUP`); -- -- Indexes for table `h_kas` -- ALTER TABLE `h_kas` ADD PRIMARY KEY (`FNO_KAS`); -- -- Indexes for table `m_brg` -- ALTER TABLE `m_brg` ADD PRIMARY KEY (`FK_BRG`); -- -- Indexes for table `m_mat` -- ALTER TABLE `m_mat` ADD PRIMARY KEY (`FK_MAT`); -- -- Indexes for table `m_perk` -- ALTER TABLE `m_perk` ADD PRIMARY KEY (`FK_PERK`); -- -- Indexes for table `m_pr` -- ALTER TABLE `m_pr` ADD PRIMARY KEY (`FK_BPR`); -- -- Indexes for table `m_sup` -- ALTER TABLE `m_sup` ADD PRIMARY KEY (`FK_SUP`); -- -- Indexes for table `pegawai` -- ALTER TABLE `pegawai` ADD PRIMARY KEY (`uid`), ADD UNIQUE KEY `username` (`username`); -- -- Indexes for table `ref_gmat1` -- ALTER TABLE `ref_gmat1` ADD PRIMARY KEY (`FK_GMAT1`); -- -- Indexes for table `ref_gmat2` -- ALTER TABLE `ref_gmat2` ADD PRIMARY KEY (`FK_GMAT1`,`FK_GMAT2`); -- -- Indexes for table `ref_gpr1` -- ALTER TABLE `ref_gpr1` ADD PRIMARY KEY (`FK_GPR1`); -- -- Indexes for table `ref_gpr2` -- ALTER TABLE `ref_gpr2` ADD PRIMARY KEY (`FK_GPR1`,`FK_GPR2`); -- -- Indexes for table `rls_mat_sup` -- ALTER TABLE `rls_mat_sup` ADD PRIMARY KEY (`FK_SUP`,`FK_MAT`); -- -- Indexes for table `t_beli` -- ALTER TABLE `t_beli` ADD PRIMARY KEY (`FNO_BELI`,`FK_MAT`); -- -- Indexes for table `t_hd` -- ALTER TABLE `t_hd` ADD PRIMARY KEY (`FNO_BELI`,`FK_SUP`); -- -- Indexes for table `t_kas` -- ALTER TABLE `t_kas` ADD PRIMARY KEY (`FNO_KAS`,`FK_PERK`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/application/models/GroupMaterialM.php <?php class GroupMaterialM extends CI_Model { private $_table = 'ref_gmat1'; public function dataGM() { $query = $this->db->get($this->_table); return $query; } public function cekNama($nama) { $query = $this->db->get_where($this->_table, ['FN_GMAT1' => $nama]); return $query; } public function kodeOtomatis() { $query = $this->db->query("SELECT max(FK_GMAT1) as kode FROM $this->_table"); return $query; } public function save($kode, $nama) { $data = [ 'FK_GMAT1' => $kode, 'FN_GMAT1' => $nama ]; $this->db->insert($this->_table, $data); } public function cekKode($kode) { $query = $this->db->get_where($this->_table, ['FK_GMAT1' => $kode]); return $query; } public function delete($kode) { $this->db->where('FK_GMAT1', $kode); $this->db->delete($this->_table); } public function update($kode, $nama) { $data = [ 'FN_GMAT1' => $nama ]; $this->db->where('FK_GMAT1', $kode); $this->db->update($this->_table, $data); } } <file_sep>/application/controllers/Produk.php <?php class Produk extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('ProdukM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->ProdukM->dataGroupProduk(), 'dataProduk' => $this->ProdukM->dataProduk(), 'pg' => 'Admin/Master/produk' ]; $this->load->view('Admin/main', $data); } public function detailGP() { $gpr1 = $this->input->post('id', TRUE); $data = $this->ProdukM->dataGPD($gpr1)->result(); echo json_encode($data); } public function tambah() { if (isset($_POST['sav'])) { $a = $this->input->post('gpr1'); $b = $this->input->post('gpr2'); $c = trim($this->input->post('nama')); $cekNama = $this->ProdukM->cekNama($a.$b, $c); if ($cekNama->num_rows() > 0) { echo "<script>alert('Data Produk $c Sudah Ada Untuk Group Produk Tersebut !');window.history.back();</script>"; }else{ $d = trim($this->input->post('satuan')); $e = trim($this->input->post('harga')); $ee = str_replace(',', '', $e); $kodeOtomatis = $this->ProdukM->kodeOtomatis($a.$b); $k = $kodeOtomatis->row_array(); $k1 = $k['kode']; $k2 = (int) substr($k1, 4,2); $k2++; $kode = $a.$b.sprintf('%02s', $k2); $this->ProdukM->save($kode, $c, $d, $ee); echo "<script>alert('Data Produk Berhasil Di-Tambahkan !');window.location='".base_url('Admin/Produk')."';</script>"; } }else{ redirect(base_url('Admin/Produk')); } } public function hapus() { $kode = $this->uri->segment(4); $cek = $this->ProdukM->cekKode($kode); if ($cek->num_rows() > 0) { $this->ProdukM->delete($kode); echo "<script>alert('Data Produk di-Hapus !');window.location='".base_url('Admin/Produk')."';</script>"; }else{ redirect(base_url('Admin/Produk')); } } public function edit() { $kode = $this->uri->segment(4); $cek = $this->ProdukM->cekKode($kode); if ($cek->num_rows() > 0) { $r = $cek->row(); $gpr1 = substr($r->FK_BPR, 0,3); $gpr2 = substr($r->FK_BPR, 3,1); $q1 = $this->ProdukM->gpr1($gpr1); $q2 = $this->ProdukM->gpr2($gpr1, $gpr2); if ($q1->num_rows() > 0 && $q2->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataGP' => $this->ProdukM->dataGroupProduk(), 'dataProduk' => $this->ProdukM->dataProduk(), 'pg' => 'Admin/Master/produk', 'edit' => [ 'produk' => $r, 'gpr1' => $q1->row(), 'gpr2' => $q2->row() ] ]; $this->load->view('Admin/main', $data); }else{ redirect(base_url('Admin/Produk')); } }else{ redirect(base_url('Admin/Produk')); } } public function update() { if (isset($_POST['ed'])) { $kode = trim($this->input->post('kode')); $namaLama = trim($this->input->post('namaLama')); $a = trim($this->input->post('nama')); $b = trim($this->input->post('satuan')); $c = trim($this->input->post('harga')); $cc = str_replace(',', '', $c); if ($a == $namaLama) { $this->ProdukM->update($kode, $namaLama, $b, $cc); echo "<script>alert('Data Produk Berhasil di-Ubah !');window.location='".base_url('Admin/Produk')."';</script>"; }else{ $gpr1 = substr($kode, 0,3); $gpr2 = substr($kode, 3,1); $cekNama = $this->ProdukM->cekNama($gpr1.$gpr2, $a); if ($cekNama->num_rows() > 0) { echo "<script>alert('Data Produk $a Sudah Ada Untuk Group Produk Tersebut !');window.history.back();</script>"; }else{ $this->ProdukM->update($kode, $a, $b, $cc); echo "<script>alert('Data Produk Berhasil di-Ubah !');window.location='".base_url('Admin/Produk')."';</script>"; } } }else{ redirect('Admin/Produk'); } } } ?><file_sep>/query_cafeallegra.sql CRE ATE VIEW v_gpr2 AS SELECT ref_gmat2.FK_GPR1, ref_gpr1.FN_GPR1, ref_gpr2.FK_GPR2, ref_gpr2.FN_GPR2 FROM ref_gpr2 INNER JOIN ref_gpr1 ON ref_gpr1.FK_GPR1=ref_gpr2.FK_GPR1; -- CREATE VIEW v_gmat2 -- AS -- SELECT -- ref_gmat2.FK_GMAT1, ref_gmat1.FN_GMAT1, ref_gmat2.FK_GMAT2, ref_gmat2.FN_GMAT2 -- FROM ref_gmat2 -- INNER JOIN ref_gmat1 ON ref_gmat1.FK_GMAT1=ref_gmat2.FK_GMAT1 CREATE VIEW v_rls_mat_sup AS SELECT rls_mat_sup.FK_SUP, rls_mat_sup.FK_MAT, m_mat.FN_MAT, m_mat.FSAT, m_mat.FSTOK_MIN, m_mat.FSTOK_MAX, rls_mat_sup.FHARGA, rls_mat_sup.FN_MAT_SUP FROM rls_mat_sup INNER JOIN m_mat ON m_mat.FK_MAT=rls_mat_sup.FK_MAT SELECT h_beli.FNO_BELI, h_beli.FTGL_BELI, h_beli.FK_SUP, m_sup.FNA_SUP, m_sup.FALAMAT, m_sup.FKOTA, m_sup.FTEL, m_sup.FCP, m_sup.FLAMA_BAYAR, m_sup.FPENERIMA, m_sup.FBANK, m_sup.FNO_ACC, h_beli.FHC, t_beli.FK_MAT, m_mat.FN_MAT, m_mat.FSAT, m_mat.FSTOK_MIN, m_mat.FSTOK_MAX, t_beli.FQTY, t_beli.FHARGA, SUM(t_beli.FQTY*t_beli.FHARGA) as SUBTOTAL FROM h_beli INNER JOIN m_sup ON m_sup.FK_SUP = h_beli.FK_SUP INNER JOIN t_beli ON t_beli.FNO_BELI = h_beli.FNO_BELI INNER JOIN m_mat ON m_mat.FK_MAT = t_beli.FK_MAT CREATE VIEW v_beli AS SELECT h_beli.FNO_BELI, h_beli.FTGL_BELI, h_beli.FK_SUP, m_sup.FNA_SUP, m_sup.FALAMAT, m_sup.FKOTA, m_sup.FTEL, m_sup.FCP, m_sup.FLAMA_BAYAR, m_sup.FPENERIMA, m_sup.FBANK, m_sup.FNO_ACC, h_beli.FHC, t_beli.FK_MAT, m_mat.FN_MAT, m_mat.FSAT, m_mat.FSTOK_MIN, m_mat.FSTOK_MAX, t_beli.FQTY, t_beli.FHARGA FROM h_beli INNER JOIN m_sup ON m_sup.FK_SUP = h_beli.FK_SUP INNER JOIN t_beli ON t_beli.FNO_BELI = h_beli.FNO_BELI INNER JOIN m_mat ON m_mat.FK_MAT = t_beli.FK_MAT <file_sep>/application/models/SupplierM.php <?php class SupplierM extends CI_Model { private $_table = 'm_sup'; public function dataSupplier() { $query = $this->db->get($this->_table); return $query; } public function cekNama($nama) { $query = $this->db->get_where($this->_table, ['FNA_SUP' => $nama]); return $query; } public function kodeOtomatis() { $query = $this->db->query("SELECT max(FK_SUP) as kode FROM $this->_table "); return $query; } public function save($kode, $a, $b, $c, $d, $e, $f, $g, $h, $i) { $data = [ 'FK_SUP' => $kode, 'FNA_SUP' => $a, 'FALAMAT' => $b, 'FKOTA' => $c, 'FTEL' => $d, 'FCP' => $e, 'FLAMA_BAYAR' => $f, 'FPENERIMA' => $g, 'FBANK' => $h, 'FNO_ACC' => $i, ]; $this->db->insert($this->_table, $data); } public function cekKode($kode) { $query = $this->db->get_where($this->_table, ['FK_SUP' => $kode]); return $query; } public function delete($kode) { $this->db->where('FK_SUP', $kode); $this->db->delete($this->_table); } public function update($kode, $nama, $b, $c, $d, $e, $f, $g, $h, $i) { $data = [ 'FNA_SUP' => $nama, 'FALAMAT' => $b, 'FKOTA' => $c, 'FTEL' => $d, 'FCP' => $e, 'FLAMA_BAYAR' => $f, 'FPENERIMA' => $g, 'FBANK' => $h, 'FNO_ACC' => $i, ]; $this->db->where('FK_SUP', $kode); $this->db->update($this->_table, $data); } } ?><file_sep>/application/models/PerkiraanM.php <?php class PerkiraanM extends CI_Model { private $_table = 'm_perk'; public function dataPerkiraan() { $query = $this->db->get($this->_table); return $query; } public function save($a, $b, $c) { $data = [ 'FK_PERK' => $a, 'FN_PERK' => $b, 'FSALDO_NORMAL' => $c ]; $this->db->insert($this->_table, $data); } public function cekKode($id) { $query = $this->db->get_where($this->_table, ['FK_PERK' => $id]); return $query; } } <file_sep>/application/models/BarangM.php <?php class BarangM extends CI_Model { private $_table = 'm_brg'; // Pendeklarasian Table public function dataBarang() { $query = $this->db->get($this->_table); // $query = "SELECT * FROM m_brg"; return $query; // Pengiriman Data Hasil Eksekusi Query Menuju Controller } public function cekNama($nama) // $nama -> adalah data yang di kirim dari controller { $query = $this->db->get_where($this->_table, ['FN_BRG' => $nama]); // $query = "SELECT * FROM m_brg WHERE FN_BRG = '$nama' "; return $query; // Pengiriman Data Hasil Eksekusi Query Menuju Controller } public function kodeOtomatis($huruf_pertama) // $huruf_pertama -> adalah data yang di kirim dari controller { $query = $this->db->query("SELECT max(FK_BRG) as kode FROM $this->_table WHERE FK_BRG LIKE 'BR$huruf_pertama%' "); return $query; // Pengiriman Data Hasil Eksekusi Query Menuju Controller } public function save($kode_barang, $nama_barang, $satuan, $stok_min, $stok_max) // $kode_barang, $nama_barang, $satuan, $stok_min, $stok_max -> adalah data yang di kirim dari controller { $data = [ 'FK_BRG' => $kode_barang, // Field FK_BRG di isi dengan $kode_barang 'FN_BRG' => $nama_barang, // Field FN_BRG di isi dengan $nama_barang 'FSAT' => $satuan, // Field FSAT di isi dengan $satuan 'FSTOK_MIN' => $stok_min, // Field FSTOK_MIN di isi dengan $stok_min 'FSTOK_MAX' => $stok_max // Field FSTOK_MIN di isi dengan $stok_min ]; $this->db->insert($this->_table, $data); // "INSERT INTO m_brg VALUES $data"; } public function cekKode($kode) // $kode -> adalah data yang di kirim dari controller { $query = $this->db->get_where($this->_table, ['FK_BRG' => $kode]); // $query = "SELECT * FROM m_brg WHERE FK_BRG = '$kode' "; return $query; // Pengiriman Data Hasil Eksekusi Query Menuju Controller } public function update($kode_barang, $nama_barang, $satuan, $stok_min, $stok_max) // $kode_barang, $nama_barang, $satuan, $stok_min, $stok_max -> adalah data yang di kirim dari controller { $data = [ 'FN_BRG' => $nama_barang, // Field FN_BRG di isi dengan $nama_barang 'FSAT' => $satuan, // Field FSAT di isi dengan $satuan 'FSTOK_MIN' => $stok_min, // Field FSTOK_MIN di isi dengan $stok_min 'FSTOK_MAX' => $stok_max // Field FSTOK_MIN di isi dengan $stok_min ]; // Pencocokan Field Untuk Update Data $this->db->where('FK_BRG', $kode_barang); // Kondisi Where Untuk Update | query = "WHERE FK_BRG = '$kode_barang'; $this->db->update($this->_table, $data); // Query Update | query = "UPDATE m_brg SET $data"; /* ---- Penting !! ---- Alur Update Pada Model CI 1. $data / Pencocokan Data Yang Akan di-Update 2. Pendeklarasian WHERE (Apabila Menggunakan Kondisi WHERE) | $this->db->where(field_table, $kode); 3. Eksekusi Query Update | $this->db->update(table, $data); -------------------- */ } public function delete($kode_barang) // $kode_barang -> adalah data yang di kirim dari controller { $this->db->where('FK_BRG', $kode_barang); // Kondisi Where Untuk Delete | query = "WHERE FK_BRG = '$kode_barang'; $this->db->delete($this->_table); // "DELETE FROM m_brg"; /* ---- Penting !! ---- Alur Delete Pada Model CI 1. Pendeklarasian WHERE (Apabila Menggunakan Kondisi WHERE) | $this->db->where(field_table, $kode); 2. Eksekusi Query Delete | $this->db->delete(table); -------------------- */ } } ?><file_sep>/application/models/ProdukM.php <?php class ProdukM extends CI_Model { private $_table = 'm_pr'; public function dataProduk() { $query = $this->db->get($this->_table); return $query; } public function dataGroupProduk() { $query = $this->db->get('ref_gpr1'); return $query; } public function dataGPD($gpr1) { $query = $this->db->get_where('ref_gpr2', ['FK_GPR1' => $gpr1]); return $query; } public function cekNama($kode, $nama) { $query = $this->db->query("SELECT * FROM $this->_table WHERE FN_BPR='$nama' AND FK_BPR LIKE '$kode%' "); return $query; } public function kodeOtomatis($FK) { $query = $this->db->query("SELECT max(FK_BPR) as kode FROM $this->_table WHERE FK_BPR LIKE '$FK%' "); return $query; } public function save($a, $b, $c, $d) { $data = [ 'FK_BPR' => $a, 'FN_BPR' => $b, 'FSAT' => $c, 'FHARGA' => $d ]; $this->db->insert($this->_table, $data); } public function cekKode($kode) { $query = $this->db->get_where($this->_table, ['FK_BPR' => $kode]); return $query; } public function gpr1($gpr1) { $query = $this->db->get_where('ref_gpr1', ['FK_GPR1' => $gpr1]); return $query; } public function gpr2($gpr1, $gpr2) { $query = $this->db->get_where('ref_gpr2', ['FK_GPR1' => $gpr1, 'FK_GPR2' => $gpr2]); return $query; } public function delete($kode) { $this->db->where('FK_BPR', $kode); $this->db->delete($this->_table); } public function update($kode, $a, $b, $c) { $data = [ 'FN_BPR' => $a, 'FSAT' => $b, 'FHARGA' => $c ]; $this->db->where('FK_BPR', $kode); $this->db->update($this->_table, $data); } } ?><file_sep>/application/models/PembelianM.php <?php class PembelianM extends CI_Model { private $_h = 'h_beli'; private $_t = 't_beli'; private $_th = 't_hd'; public function dataSupplier() { $query = $this->db->get('m_sup'); return $query; } public function cekSupplier($sp) { $query = $this->db->get_where('m_sup', ['FK_SUP' => $sp]); return $query; } public function dataMaterial($sup) { $query = $this->db->get_where('v_rls_mat_sup', ['FK_SUP' => $sup]); return $query; } public function cekMaterial($mat) { $query = $this->db->get_where('v_rls_mat_sup', ['FK_MAT' => $mat]); return $query; } public function kodeOtomatis($tg, $sup) { $query = $this->db->query("SELECT max(FNO_BELI) as kode FROM h_beli WHERE FNO_BELI LIKE '$tg%' AND FK_SUP='$sup' "); return $query; } public function saveh($a, $b, $c, $d) { $data = [ 'FNO_BELI' => $a, 'FTGL_BELI' => $b, 'FK_SUP' => $c, 'FHC' => $d ]; $this->db->insert($this->_h, $data); } public function saved($a, $b, $c, $d) { $data = [ 'FNO_BELI' => $a, 'FK_MAT' => $b, 'FQTY' => $c, 'FHARGA' => $d ]; $this->db->insert($this->_t, $data); } public function savehd($a, $b, $c, $d) { $data = [ 'FNO_BELI' => $a, 'FK_SUP' => $b, 'FJML' => $c, 'FBAYAR' => $d, 'FTGL_BAYAR' => null ]; $this->db->insert($this->_th, $data); } } <file_sep>/application/models/LoginM.php <?php class LoginM extends CI_Model { private $_table = 'pegawai'; public function login($a, $b) { $s1 = $this->db->get_where($this->_table, ['username' => $a, 'password' => $b]); return $s1; } } ?><file_sep>/application/controllers/Perkiraan.php <?php class Perkiraan extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); } else { if ($cek->level != '1') { redirect(base_url()); } else { $this->dataUser = $cek; $this->load->model('PerkiraanM'); } } } else { $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $data = [ 'tb' => $this->PerkiraanM->dataPerkiraan(), 'user' => $this->dataUser, 'pg' => 'Admin/Master/perkiraan' ]; $this->load->view('Admin/main', $data); } public function tambah() { if (isset($_POST['sav'])) { $a = trim($this->input->post('kode')); $b = trim($this->input->post('nama')); $c = trim($this->input->post('saldo')); $this->PerkiraanM->save($a, $b, $c); echo "<script>alert('Data Perkiraan Berhasil di-Tambahkan !');window.location='" . base_url('Admin/Perkiraan') . "';</script>"; } else { redirect('Admin/Perkiraan'); } } public function hapus($id) { $cek = $this->PerkiraanM->cekKode($id); if ($cek->num_rows() > 0) { $this->PerkiraanM->delete($id); echo "<script>alert('Data Perkiraan Berhasil di-Hapus !');window.location='" . base_url('Admin/Perkiraan') . "';</script>"; } else { redirect('Admin/Perkiraan'); } } } <file_sep>/application/views/Admin/Print/printdata.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Printing Data</title> <!-- Bootstrap 3.3.7 --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/bootstrap/dist/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/Ionicons/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="<?= base_url('assets/') ?>dist/css/AdminLTE.min.css"> <!-- Skin --> <link rel="stylesheet" href="<?= base_url('assets/') ?>dist/css/skins/_all-skins.min.css"> <!-- DataTables --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css"> <!-- Select2 --> <link rel="stylesheet" href="<?= base_url('assets/') ?>bower_components/select2/dist/css/select2.min.css"> </head> <body> <div class="table-responsive"> <table class="table"> <tr> <td colspan="2" class="text-center"> <h3>Detail Pembelian</h3> </td> </tr> <tr> <td width="50%"> <h5 class="text-center">Transaksi <?= $this->uri->segment(3) ?></h5> </td> <td width="50%"> <h5 class="text-center">Tanggal Transaksi : <?= $sd->FTGL_BELI ?></h5> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </div> <div class="table-responsive"> <table class="table"> <tr> <td></td> <td width="20%" class="text-left">Nomor Pembelian </td> <td width="5%">:</td> <td><?= $sd->FNO_BELI ?></td> </tr> <tr> <td></td> <td width="20%" class="text-left">Supplier : </td> <td width="5%">:</td> <td><?= $sd->FNA_SUP ?></td> </tr> </table> </div> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <td colspan="4" class="text-center"> <h4><b>Data Pembelian</b></h4> </td> </tr> <tr> <th class="text-center">Material</th> <th class="text-center">Qty</th> <th class="text-center">Harga</th> <th class="text-center">Sub Total</th> </tr> </thead> <tbody> <?php $total = 0; foreach ($tb->result() as $r1) { $sub = $r1->FQTY * $r1->FHARGA; $total += $sub; ?> <tr> <td class="text-center"><?= $r1->FN_MAT ?></td> <td class="text-center"><?= $r1->FQTY ?></td> <td class="text-center"><?= "Rp. " . number_format($r1->FHARGA, 0, ',', '.') ?></td> <td class="text-center"><?= "Rp. " . number_format($sub, 0, ',', '.') ?></td> </tr> <?php } ?> <tr> <td colspan="3" class="text-right"><b>Total : </b></td> <td class="text-center"> <?= "Rp. " . number_format($total, 0, ',', '.') ?> </td> </tr> </tbody> </table> </div> <!-- jQuery 3 --> <script src="<?= base_url('assets/') ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/') ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- SlimScroll --> <script src="<?= base_url('assets/') ?>bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="<?= base_url('assets/') ?>bower_components/fastclick/lib/fastclick.js"></script> <!-- AdminLTE App --> <script src="<?= base_url('assets/') ?>dist/js/adminlte.min.js"></script> <!-- DataTables --> <script src="<?= base_url('assets/') ?>bower_components/datatables.net/js/jquery.dataTables.min.js"></script> <script src="<?= base_url('assets/') ?>bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <!-- Select2 --> <script src="<?= base_url('assets/') ?>bower_components/select2/dist/js/select2.full.min.js"></script> <!-- page script --> <script> $(function() { //Initialize Select2 Elements $('.select2').select2() $('#example1').DataTable() $('#example2').DataTable({ 'paging': true, 'lengthChange': false, 'searching': false, 'ordering': true, 'info': true, 'autoWidth': false }) }) window.print(); </script> </body> </html><file_sep>/application/config/routes.php <?php defined('BASEPATH') or exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | https://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'Login'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; $route['Admin/Barang'] = 'Barang'; $route['Admin/Barang/Tambah'] = 'Barang/tambah'; $route['Admin/Barang/Hapus/(:any)'] = 'Barang/hapus/$1'; $route['Admin/Barang/Edit/(:any)'] = 'Barang/edit/$1'; $route['Admin/Barang/Simpan-Perubahan'] = 'Barang/update'; $route['Admin/Group-Produk'] = 'GroupProduk'; $route['Admin/Group-Produk/Tambah'] = 'GroupProduk/tambah'; $route['Admin/Group-Produk/Hapus/(:any)'] = 'GroupProduk/hapus/$1'; $route['Admin/Group-Produk/Edit/(:any)'] = 'GroupProduk/edit/$1'; $route['Admin/Group-Produk/Simpan-Perubahan'] = 'GroupProduk/update'; $route['Admin/Group-Produk-Detail'] = 'GroupProdukDetail'; $route['Admin/Group-Produk-Detail/Tambah'] = 'GroupProdukDetail/tambah'; $route['Admin/Group-Produk-Detail/Hapus/(:any)/(:any)'] = 'GroupProdukDetail/hapus/$1/$2'; $route['Admin/Group-Produk-Detail/Edit/(:any)/(:any)'] = 'GroupProdukDetail/edit/$1/$2'; $route['Admin/Group-Produk-Detail/Simpan-Perubahan'] = 'GroupProdukDetail/update'; $route['Admin/Produk'] = 'Produk'; $route['Admin/Produk/Tambah'] = 'Produk/tambah'; $route['Admin/Produk/Hapus/(:any)'] = 'Produk/hapus/$1'; $route['Admin/Produk/Edit/(:any)'] = 'Produk/edit/$1'; $route['Admin/Produk/Simpan-Perubahan'] = 'Produk/update'; $route['Admin/Group-Material'] = 'GroupMaterial'; $route['Admin/Group-Material/Tambah'] = 'GroupMaterial/tambah'; $route['Admin/Group-Material/Hapus/(:any)'] = 'GroupMaterial/hapus/$1'; $route['Admin/Group-Material/Edit/(:any)'] = 'GroupMaterial/edit/$1'; $route['Admin/Group-Material/Simpan-Perubahan'] = 'GroupMaterial/update'; $route['Admin/Group-Material-Detail'] = 'GroupMaterialDetail'; $route['Admin/Group-Material-Detail/Tambah'] = 'GroupMaterialDetail/tambah'; $route['Admin/Group-Material-Detail/Hapus/(:any)/(:any)'] = 'GroupMaterialDetail/hapus/$1/$2'; $route['Admin/Group-Material-Detail/Edit/(:any)/(:any)'] = 'GroupMaterialDetail/edit/$1/$2'; $route['Admin/Group-Material-Detail/Simpan-Perubahan'] = 'GroupMaterialDetail/update'; $route['Admin/Material'] = 'Material'; $route['Admin/Material/Tambah'] = 'Material/tambah'; $route['Admin/Material/Hapus/(:any)'] = 'Material/hapus/$1'; $route['Admin/Material/Edit/(:any)'] = 'Material/edit/$1'; $route['Admin/Material/Simpan-Perubahan'] = 'Material/update'; $route['Admin/Supplier'] = 'Supplier'; $route['Admin/Supplier/Tambah'] = 'Supplier/tambah'; $route['Admin/Supplier/Hapus/(:any)'] = 'Supplier/hapus/$1'; $route['Admin/Supplier/Edit/(:any)'] = 'Supplier/edit/$1'; $route['Admin/Supplier/Simpan-Perubahan'] = 'Supplier/update'; $route['Admin/Relasi-Material-Supplier'] = 'Relasi'; $route['Admin/Relasi-Material-Supplier/(:any)'] = 'Relasi'; $route['Admin/Relasi-Material-Supplier/(:any)/Tambah'] = 'Relasi/tambah'; $route['Admin/Relasi-Material-Supplier/(:any)/Hapus/(:any)'] = 'Relasi/hapus'; $route['Admin/Perkiraan'] = 'Perkiraan'; $route['Admin/Perkiraan/Tambah'] = 'Perkiraan/tambah'; $route['Admin/Pembelian'] = 'Pembelian'; $route['Admin/Pembelian/Supplier/(:any)'] = 'Pembelian/supplier/$1'; $route['Admin/Pembelian/Material'] = 'Pembelian/material'; $route['Admin/Pembelian/Batal-Pembelian'] = 'Pembelian/batal'; $route['Admin/Pembelian/Tambah'] = 'Pembelian/tambah'; $route['Admin/Pembelian/Hapus/(:any)'] = 'Pembelian/hapus/$1'; $route['Admin/Pembelian/Selesai'] = 'Pembelian/selesai'; $route['Admin/Transaksi-Pembelian'] = 'DataPembelian'; $route['Admin/Print/Pembelian/(:any)/(:any)'] = 'PrintData/pembelian/$1/$2'; $route['Admin/Hutang-Dagang'] = 'HutangDagang'; <file_sep>/application/views/Admin/Transaksi/pembelian.php <?php if ($this->session->has_userdata('Supplier-Pembelian')) : ?> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-shopping-cart"></span> &ensp; Pembelian </h4> </div> <div class="box-body"> <form action="<?= site_url('Admin/Pembelian/Tambah') ?>" method="post" class="form"> <div class="col-md-12"> <div class="col-md-4"> <div class="form-group"> <label for="">Supplier : </label> <input type="text" name="supplier" id="supplier" class="form-control" value="<?= $sp->FNA_SUP ?>" disabled=""> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Tanggal Pembelian : </label> <?php if ($this->session->has_userdata('Tanggal-Pembelian')) : ?> <input type="date" name="tgl" id="tgl" class="form-control" disabled="" value="<?= $this->session->userdata('Tanggal-Pembelian') ?>"> <?php else : ?> <input type="date" name="tgl" id="tgl" class="form-control" required="" autofocus=""> <?php endif; ?> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Jenis Pembayaran : </label> <div class="radio"> <?php if ($this->session->has_userdata('Pembayaran-Pembelian')) : ?> <?php if ($this->session->userdata('Pembayaran-Pembelian') == '1') { ?> <label> <input type="radio" name="jenis" id="jenis" value="1" checked="" disabled=""> Cash </label> &ensp; &ensp; <label> <input type="radio" name="jenis" id="jenis" value="0" disabled=""> Kredit </label> <?php } else if ($this->session->userdata('Pembayaran-Pembelian') == '0') { ?> <label> <input type="radio" name="jenis" id="jenis" value="1" disabled=""> Cash </label> &ensp; &ensp; <label> <input type="radio" name="jenis" id="jenis" value="0" checked="" disabled=""> Kredit </label> <?php } else { ?> <label> <input type="radio" name="jenis" id="jenis" value="1" required=""> Cash </label> &ensp; &ensp; <label> <input type="radio" name="jenis" id="jenis" value="0" required=""> Kredit </label> <?php } ?> <?php else : ?> <label> <input type="radio" name="jenis" id="jenis" value="1" required=""> Cash </label> &ensp; &ensp; <label> <input type="radio" name="jenis" id="jenis" value="0" required=""> Kredit </label> <?php endif; ?> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <label for="">Material</label> <select name="mat" id="mat" class="select2" style="width: 100%" required="" data-placeholder="Silahkan Pilih Material"> <option value=""></option> <?php foreach ($mat->result() as $rm) { echo "<option value='$rm->FK_MAT'>$rm->FK_MAT - $rm->FN_MAT / $rm->FN_MAT_SUP</option>"; } ?> </select> </div> </div> <div id="detMat" hidden=""> <div class="col-md-2"> <div class="form-group"> <label for="">Kode Material</label> <input type="text" name="kmat" id="kmat" disabled="" class="form-control"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="">Nama Material</label> <input type="text" name="nmat" id="nmat" disabled="" class="form-control"> <input type="hidden" name="nmat1" id="nmat1" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Satuan</label> <input type="text" name="smat" id="smat" disabled="" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Min</label> <input type="number" name="mimat" id="mimat" disabled="" class="form-control"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="">Stok Max</label> <input type="number" name="mamat" id="mamat" disabled="" class="form-control"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="">Nama Material Pada Supplier</label> <input type="text" name="nmats" id="nmats" disabled="" class="form-control"> </div> </div> <div class="col-md-6"> <div class="form-group"> <div class="input-group"> <label for="">Harga Material Pada Supplier</label> </div> <div class="input-group"> <span class="input-group-addon">Rp. </span> <input type="text" name="hargas" id="hargas" class="form-control" placeholder="Harga Material" disabled=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="">Banyak Pembelian </label> <input type="number" name="qty" id="qty" min="0" required="" class="form-control" placeholder="0"> </div> </div> <div class="col-md-6"> <div class="form-group"> <div class="input-group"> <label for="">Harga Material</label> </div> <div class="input-group"> <span class="input-group-addon">Rp. </span> <input type="text" name="harga" id="harga" class="form-control" placeholder="Harga Material" required=""> </div> </div> </div> <hr> <div class="col-md-12" align="center"> <hr> <div class="form-group"> <button type="submit" class="btn btn-success btn-flat btn-block" name="sav"> <span class="fa fa-plus"></span> &ensp; Tambahkan Data Ke-Keranjang Pembelian </button> </div> </div> </div> </div> </form> </div> </div> </div> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-table"></span> &ensp; Data Keranjang Pembelian</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>Kode Material</th> <th>Nama Material</th> <th>Jumlah</th> <th>Harga</th> <th>Sub Total</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $uid = $this->session->userdata('uid'); $sup = $this->session->userdata('Supplier-Pembelian'); $tgl = $this->session->userdata('Tanggal-Pembelian'); $pem = $this->session->userdata('Pembayaran-Pembelian'); $total = 0; foreach ($tbc as $rc) { if ($rc['transaksi'] == 'Pembelian' && $rc['supplier'] == $sup && $rc['tanggal'] == $tgl && $rc['jenis'] == $pem && $rc['uid'] == $uid) { $total += $rc['subtotal']; ?> <tr> <td> <h5><?= $rc['id'] ?></h5> </td> <td> <h5><?= $rc['name'] ?></h5> </td> <td> <h5><?= $rc['qty'] ?></h5> </td> <td> <h5><?= "Rp. " . number_format($rc['price'], 2, ',', '.') ?></h5> </td> <td> <h5><?= "Rp. " . number_format($rc['subtotal'], 2, ',', '.') ?></h5> </td> <td align="center"> <a href="<?= site_url('Admin/Pembelian/Hapus/') . $rc['rowid'] ?>"> <div class="btn btn-danger btn-flat" title="Hapus Material"> <span class="fa fa-trash"></span> </div> </a> </td> </tr> <?php } } ?> <tr> <td colspan="4" align="right"> <h5><b>Total : </b></h5> </td> <td> <h5><?= "Rp. " . number_format($total, 2, ',', '.') ?></h5> </td> <td></td> </tr> </tbody> </table> </div> </div> <div class="box-footer" align="center"> <a href="<?= site_url('Admin/Pembelian/Selesai') ?>" class="btn btn-success btn-flat"> <span class="fa fa-check"></span> Selesaikan Pembelian </a> <a href="<?= site_url('Admin/Pembelian/Batal-Pembelian') ?>" class="btn btn-danger btn-flat"> <span class="fa fa-times"></span> Batalkan Pembelian </a> </div> </div> </div> <script src="<?= base_url('jquery/jquery-3.3.1.js') ?>"></script> <script> $('#res').on('click', function() { $('#detMat').hide(); }); </script> <script> $(document).ready(function() { $('#mat').change(function() { var mat = $(this).val(); $.ajax({ url: "<?= site_url('Admin/Pembelian/Material') ?>", method: 'POST', data: { mat, mat }, async: true, dataType: 'json', success: function(data) { $('#detMat').show(); $('#kmat').val(data.FK_MAT); $('#nmat').val(data.FN_MAT); $('#nmat1').val(data.FN_MAT); $('#nmats').val(data.FN_MAT_SUP); $('#smat').val(data.FSAT); $('#mimat').val(data.FSTOK_MIN); $('#mamat').val(data.FSTOK_MAX); var h = data.FHARGA; var harga = h.replace(".00", ""); $('#harga').val(harga); $('#hargas').val(harga); var n = parseInt($('#harga').val().replace(/\D/g, ''), 10); $('#harga').val(n.toLocaleString()); var n = parseInt($('#hargas').val().replace(/\D/g, ''), 10); $('#hargas').val(n.toLocaleString()); $('#qty').focus(); } }); return false; }); $("#harga").on('keyup', function() { var n = parseInt($(this).val().replace(/\D/g, ''), 10); $(this).val(n.toLocaleString()); }); }); </script> <?php else : ?> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header"> <h4 class="box-title"> &ensp; <span class="fa fa-users"></span> &ensp; Silahkan Pilih Data Supplier Untuk Transaksi</h4> </div> <div class="box-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="example1"> <thead> <tr> <th>Kode Supplier</th> <th>Nama Supplier</th> <th>Alamat Supplier</th> <th>Kota</th> <th>No. Telp</th> <th>Contact Person</th> <th>Pilih</th> </tr> </thead> <tbody> <?php foreach ($dataSupplier->result() as $row) { ?> <tr> <td> <h5><?= $row->FK_SUP ?></h5> </td> <td> <h5><?= $row->FNA_SUP ?></h5> </td> <td> <h5><?= $row->FALAMAT ?></h5> </td> <td> <h5><?= $row->FKOTA ?></h5> </td> <td> <h5><?= $row->FTEL ?></h5> </td> <td> <h5><?= $row->FCP ?></h5> </td> <td align="center"> <a href="<?= site_url('Admin/Pembelian/Supplier/') . $row->FK_SUP ?>"> <button class="btn btn-info btn-flat" title="Pilih Supplier"> <span class="fa fa-hand-o-right"></span> </button> </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <?php endif; ?><file_sep>/application/models/HutangDagangM.php <?php class HutangDagangM extends CI_Model { private $_table = 't_hd'; public function dataHutang() { $query = $this->db->get($this->_table); return $query; } } <file_sep>/application/controllers/Relasi.php <?php class Relasi extends CI_Controller { private $dataUser = ''; public function __construct() { parent::__construct(); if ($this->session->has_userdata('uid')) { $uid = $this->session->userdata('uid'); $this->load->model('Sesi'); $cek = $this->Sesi->cekLogin($uid); if ($cek == '0') { $this->session->sess_destroy(); redirect(base_url()); }else{ if ($cek->level != '1') { redirect(base_url()); }else{ $this->dataUser = $cek; $this->load->model('RelasiM'); } } }else{ $this->session->sess_destroy(); redirect(base_url()); } } public function index() { $sp = $this->uri->segment(3); if (!empty($sp)) { $cek = $this->RelasiM->cekSP($sp); if ($cek->num_rows() > 0) { $data = [ 'user' => $this->dataUser, 'dataSP' => $this->RelasiM->dataSP(), 'dataMaterial' => $this->RelasiM->dataMaterial(), 'detailSP' => $cek->row(), 'dataRelasi' => $this->RelasiM->dataRelasi($sp), 'pg' => 'Admin/Relasi/mat_sup' ]; }else{ redirect('Admin/Relasi-Material-Supplier'); } }else{ $data = [ 'user' => $this->dataUser, 'dataSP' => $this->RelasiM->dataSP(), 'pg' => 'Admin/Relasi/mat_sup' ]; } $this->load->view('Admin/main', $data); } public function detailM() { $mat = $this->input->post('id', TRUE); $data = $this->RelasiM->dMaterial($mat)->row(); echo json_encode($data); } public function tambah() { if (isset($_POST['sav'])) { $sup = trim($this->input->post('kodeSupplier')); $mat = trim($this->input->post('material')); $nama = trim($this->input->post('nama')); $harga = trim($this->input->post('harga')); $harga = str_replace(',', '', $harga); $cek = $this->RelasiM->cekRelasi($sup, $mat); if ($cek->num_rows() > 0) { echo "<script>alert('Relasi Material Sudah Ada !');window.location='".base_url('Admin/Relasi-Material-Supplier/').$sup."';</script>"; }else{ $this->RelasiM->save($sup, $mat, $harga, $nama); echo "<script>alert('Relasi Berhasil di-Tambahkan !');window.location='".base_url('Admin/Relasi-Material-Supplier/').$sup."';</script>"; } }else{ redirect('Admin/Relasi-Material-Supplier'); } } public function hapus() { $sup = $this->uri->segment(3); $mat = $this->uri->segment(5); $cek = $this->RelasiM->cekRelasi($sup, $mat); if ($cek->num_rows() > 0) { $this->RelasiM->delete($sup, $mat); echo "<script>alert('Data Relasi Berhasil di-Hapus !');window.location='".base_url('Admin/Relasi-Material-Supplier/').$sup."';</script>"; }else{ redirect('Admin/Relasi-Material-Supplier'); } } } ?><file_sep>/application/models/GroupProdukM.php <?php class GroupProdukM extends CI_Model { private $_table = 'ref_gpr1'; public function dataGroupProduk() { $query = $this->db->get($this->_table); return $query; } public function cekNama($nama) { $query = $this->db->get_where($this->_table, ['FN_GPR1' => $nama]); return $query; } public function kodeOtomatis() { $query = $this->db->query("SELECT max(FK_GPR1) as kode FROM $this->_table WHERE FK_GPR1 LIKE 'F%' "); return $query; } public function save($kode, $nama) { $data = [ 'FK_GPR1' => $kode, 'FN_GPR1' => $nama ]; $this->db->insert($this->_table, $data); } public function cekKode($kode) { $query = $this->db->get_where($this->_table, ['FK_GPR1' => $kode]); return $query; } public function delete($kode) { $this->db->where('FK_GPR1', $kode); $this->db->delete($this->_table); } public function update($kode, $nama) { $data = [ 'FN_GPR1' => $nama ]; $this->db->where('FK_GPR1', $kode); $this->db->update($this->_table, $data); } } ?>
afb6e4ab0dde8f7755e39d76bbe969a5d7306b5a
[ "SQL", "PHP" ]
47
PHP
megilangr1/CafeAllegra
ef3ed151a9df571b501c5889f9f79a888574393b
9ee6db0ab594d3bef27290b4d2fe4b02c6ba644a
refs/heads/master
<repo_name>mmehta18/my-first-blog<file_sep>/blog/models.py from django.db import models #these add other files to this existing one # Create your models here. from django.utils import timezone class Post(models.Model): #class means that we are defining an object author = models.ForeignKey('auth.User') #the models.Model mean that it's a Django file title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title #defining each model type # models.CharField – this is how you define text with a limited number of characters. #models.TextField – this is for long text without a limit. Sounds ideal for blog post content, right? #models.DateTimeField – this is a date and time. #models.ForeignKey – this is a link to another model.
73faa76a15b6536d24b79cb51dcf48d95247a537
[ "Python" ]
1
Python
mmehta18/my-first-blog
62c22d7ace3b61f020befd52e245f1d6aaee2eb8
b0595792d5307281be8669eb86b5842309b74a00
refs/heads/master
<repo_name>mobile32/RSS-Reader<file_sep>/RSS Reader/DAL/IRSSrepo.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using RSS_Reader.Model; namespace RSS_Reader.DAL { /// <summary> /// Interface reposytorium do obsługi zapisywania oraz odczytu z bazy danych /// </summary> interface IRSSrepo { /// <summary> /// Funkcja zapisująca wybraną wiadomość do bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="news">Wiadomość do zapisania</param> void AddSelectedArticle(ObservableCollection<Category> ArchiveListCategories, News news); /// <summary> /// Funkcja kasująca wybraną wiadomość z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="id">Id wybranej wiadomości</param> void DeleteSelectedArticle(ObservableCollection<Category> ArchiveListCategories, string Id); /// <summary> /// Funkcja pobierająca zapisane wiadomości (o danej kategorii) z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="category">kategoria</param> void GetSavedNews(ObservableCollection<News> lineNews, ObservableCollection<Category> ArchiveListCategories, string category); /// <summary> /// Funkcja aktualizująca (dodaje lub usuwa) listę kategorii w bazie danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="selectedCategory">kategoria</param> /// <param name="toAdd">zmienna warunkująca dodawanie bądż usuwanie kategorii</param> void UpdateArchiveCategory(ObservableCollection<Category> ArchiveListCategories, string selectedCategory, bool toAdd); /// <summary> /// Funkcja pobierająca listę kategorii z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> void GetListArchiveCategories(ObservableCollection<Category> ArchiveListCategories); } } <file_sep>/RSS Reader/DAL/RSSrepo.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using RSS_Reader.Model; namespace RSS_Reader.DAL { /// <summary> /// Klasa implementująca metody interface'u IRSSrepo /// </summary> class RSSrepo : IRSSrepo { private RSSContext _rssContext = new RSSContext(); /// <summary> /// Funkcja zapisująca wybraną wiadomość do bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="news">Wiadomość do zapisania</param> public void AddSelectedArticle(ObservableCollection<Category> archiveListCategories, News news) { bool newsExist = _rssContext.News.Any(n => n.Id == news.Id); if (!newsExist) { _rssContext.News.Add(new News { Category = news.Category, Date = news.Date, Description = news.Description, Photo = news.Photo, Title = news.Title, UrlNews = news.UrlNews, UrlImage = news.UrlImage, Id = news.Id }); _rssContext.SaveChanges(); if (!archiveListCategories.Any(n => n.Name == news.Category)) UpdateArchiveCategory(archiveListCategories, news.Category, true); } } /// <summary> /// Funkcja kasująca wybraną wiadomość z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="id">Id wybranej wiadomości</param> public void DeleteSelectedArticle(ObservableCollection<Category> archiveListCategories, string id) { if (!string.IsNullOrEmpty(id)) { string selectedCategory = _rssContext.News.Where(n => n.Id == id).Select(n => n.Category).Single(); _rssContext.News.Remove(_rssContext.News.FirstOrDefault(n => n.Id == id)); _rssContext.SaveChanges(); if (!_rssContext.News.Any(n => n.Category == selectedCategory)) UpdateArchiveCategory(archiveListCategories, selectedCategory, false); } } /// <summary> /// Funkcja pobierająca listę kategorii z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> public void GetListArchiveCategories(ObservableCollection<Category> archiveListCategories) { var articles = _rssContext.News.GroupBy(n => n.Category).Select(n => n.FirstOrDefault()).ToList(); foreach (var a in articles) { archiveListCategories.Add(new Category { Name = a.Category, Url = string.Empty }); } } /// <summary> /// Funkcja pobierająca zapisane wiadomości (o danej kategorii) z bazy danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="category">kategoria</param> public void GetSavedNews(ObservableCollection<News> lineNews, ObservableCollection<Category> archiveListCategories, string category) { if (archiveListCategories.Any()) { var savedNews = _rssContext.News.Where(n => n.Category == category); foreach (var news in savedNews) { lineNews.Add(new News { Category = news.Category, Date = news.Date, Description = news.Description, Id = news.Id, Photo = news.Photo, Title = news.Title, UrlImage = news.UrlImage, UrlNews = news.UrlNews }); } } } /// <summary> /// Funkcja aktualizująca (dodaje lub usuwa) listę kategorii w bazie danych /// </summary> /// <param name="archiveListCategories">Lista kategorii dostępnych w bazie danych</param> /// <param name="selectedCategory">kategoria</param> /// <param name="toAdd">zmienna warunkująca dodawanie bądż usuwanie kategorii</param> public void UpdateArchiveCategory(ObservableCollection<Category> archiveListCategories, string selectedCategory, bool toAdd) { if (toAdd) { archiveListCategories.Add(new Category { Name = selectedCategory, Url = string.Empty }); } else if (!toAdd) { foreach (var category in archiveListCategories.ToList()) { if (category.Name == selectedCategory) { archiveListCategories.Remove(category); break; } } } } } } <file_sep>/RSS Reader/Model/Reader.cs using System; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net; using System.ServiceModel.Syndication; using System.Web; using System.Windows; using System.Xml; using RSS_Reader.DAL; namespace RSS_Reader.Model { /// <summary> /// Klasa służąca odczytu danych wiadomości z plików xml i html /// </summary> public class Reader { /// <summary> /// Wybiera stronę na podstawie adresu url i zapisuje wszystkie wiadomości w kolekcji /// </summary> /// <param name="lineNews">Lista wiadomości</param> /// <param name="category">Kategoria źródłowa do odczytu</param> public void ParseXml(ObservableCollection<News> lineNews, Category category) { try { using (XmlReader reader = XmlReader.Create(category.Url)) { var formatter = new Rss20FeedFormatter(); formatter.ReadFrom(reader); foreach (var item in formatter.Feed.Items) { lineNews.Add(new News { Title = item.Title.Text, Date = item.PublishDate.DateTime.ToString(), UrlNews = item.Links.First().Uri.ToString(), Description = item.Summary.Text, Category = category.Name, Id = item.Id }); if (item.Links.Count > 1 && item.Links.Any(n => n.Uri.ToString().Contains(".jpg"))) lineNews.Last().UrlImage = item.Links[1].Uri.ToString(); ParseId(lineNews.Last()); ParseDescription(lineNews.Last()); } } } catch (WebException ex) { MessageBox.Show(ex.Message, "Syndication Reader"); } } /// <summary> /// Dekoduje z opisu ze znacznikami HTML do normalnego opisu /// </summary> /// <param name="news">Wiadomość do dekodowania</param> private void ParseDescription(News news) { StringWriter myWriter = new StringWriter(); string description = string.Empty; string start = string.Empty; string end = ResourceRss.EndDescription; int index = 0; HttpUtility.HtmlDecode(news.Description, myWriter); string decode = myWriter.ToString(); if (decode[0] == Convert.ToChar(ResourceRss.OneSymbol) && decode[1] == Convert.ToChar(ResourceRss.TwoSymbol)) { start = ResourceRss.StartDescription; if (news.UrlImage == null && decode.Contains(ResourceRss.CheckedTwice) == false) start = ResourceRss.StartDescriptionWithoutImage; index = decode.IndexOf(start); } if (!decode.Contains(end)) end = ResourceRss.EndDescriptionBr; if (index > -1) { for (int i = index + start.Length; i < decode.Length; i++) { if (i + end.Length < decode.Length) { string tmp = decode.Substring(i, end.Length); if (tmp != end) description += decode[i]; else { if (description != string.Empty) news.Description = description[0] == '-' ? description.Substring(1) : description; return; } } } } } /// <summary> /// Dekoduje z id ze znacznikami HTML do normalnego id /// </summary> /// <param name="news">Wiadomość do dekodowania</param> public void ParseId(News news) { string ipLong = news.Id; int index = ipLong.IndexOf(ResourceRss.SearchId); news.Id = ipLong.Substring(index + ResourceRss.SearchId.Length, Convert.ToInt32(ResourceRss.LengthId)); } /// <summary> /// Odczytuje dane z bazy na podstawie kategorii i kopiuje do podanej kolekcji /// </summary> /// <param name="lineNews">Kolekcja do wczytania wiadomości</param> /// <param name="ArchiveListCategories">Kolkcja do wczytania wszystkich kategorii w archiwum</param> /// <param name="category">Docelowa kategoria</param> public void ReadBase(ObservableCollection<News> lineNews, ObservableCollection<Category> ArchiveListCategories, Category category) { IRSSrepo rssRepo = new RSSrepo(); rssRepo.GetSavedNews(lineNews, ArchiveListCategories, category.Name); } } } <file_sep>/RSS Reader/Model/Category.cs namespace RSS_Reader.Model { /// <summary> /// Klasa definiująca kategorię /// </summary> public class Category { /// <summary> /// Nazwa /// </summary> public string Name { get; set; } /// <summary> /// Link do RSS'a /// </summary> public string Url { get; set; } } } <file_sep>/RSS Reader/DAL/RSSContext.cs using System.Data.Entity; using RSS_Reader.Model; namespace RSS_Reader.DAL { /// <summary> /// Klasa definująca model bazy danych /// </summary> public class RSSContext : DbContext { public DbSet<News> News { get; set; } /// <summary> /// Konstruktor obsługujący tworzenie bazy danych /// </summary> public RSSContext() { Database.SetInitializer<RSSContext>(new CreateDatabaseIfNotExists<RSSContext>()); } } } <file_sep>/RSS Reader/MainWindow.xaml.cs using MahApps.Metro.Controls; using RSS_Reader.ViewModel; using System; namespace RSS_Reader { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : MetroWindow { public MainWindow() { AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory); InitializeComponent(); DataContext = new MainWindowViewModel(); } } } <file_sep>/RSS Reader/Model/News.cs using PropertyChanged; namespace RSS_Reader.Model { /// <summary> /// Klasa definiująca wiadomość /// </summary> [ImplementPropertyChanged] public class News { /// <summary> /// Tytuł /// </summary> public string Title { get; set; } /// <summary> /// Data /// </summary> public string Date { get; set; } /// <summary> /// Streszczenie /// </summary> public string Description { get; set; } /// <summary> /// Numer Id /// </summary> public string Id { get; set; } /// <summary> /// Link do zdjęcia /// </summary> public string UrlImage { get; set; } /// <summary> /// Link do strony z wiadomością /// </summary> public string UrlNews { get; set; } /// <summary> /// Kategoria /// </summary> public string Category { get; set; } /// <summary> /// Zdjęcie zapisanie jako tablica bajtów /// </summary> public byte[] Photo { get; set; } } } <file_sep>/RSS Reader/ViewModel/MainWindowViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Text; using System.Windows.Input; using HtmlAgilityPack; using PropertyChanged; using RSS_Reader.DAL; using RSS_Reader.Model; namespace RSS_Reader.ViewModel { /// <summary> /// Klasa do obsługi głównego okna /// </summary> [ImplementPropertyChanged] public class MainWindowViewModel { private int _selectedIndexListBoxNews; private int _selectedIndexCategories; private int _selectedIndexTab; public ObservableCollection<News> LineNews { get; set; } public ObservableCollection<Category> ListCategories { get; set; } public ObservableCollection<Category> ArchiveListCategories { get; set; } public News News { get; set; } public Reader Reader { get; set; } public int SelectedIndexTab { get { return _selectedIndexTab; } set { _selectedIndexTab = value; SelectedIndexCategories = 0; ReadNews(); } } public ICommand OpenWebsiteCommand { get; set; } public ICommand SaveAllCommand { get; set; } public ICommand SaveCommand { get; set; } public ICommand DeleteCommand { get; set; } public int SelectedIndexCategories { get { return _selectedIndexCategories; } set { _selectedIndexCategories = value; ReadNews(); } } /// <summary> /// Wyświetla informacje wiadomości na zakładce nowe, lub wczytuje wiadomości z bazy na zakładce archiwalne /// </summary> private void ReadNews() { LineNews = new ObservableCollection<News>(); News = new News(); SelectedIndexListBoxNews = 0; if (SelectedIndexTab == 0) Reader.ParseXml(LineNews, ListCategories[SelectedIndexCategories]); else if (ArchiveListCategories.Any()) { if (SelectedIndexCategories < 0) Reader.ReadBase(LineNews, ArchiveListCategories, ArchiveListCategories[0]); else Reader.ReadBase(LineNews, ArchiveListCategories, ArchiveListCategories[SelectedIndexCategories]); } ShowDescription(); } public int SelectedIndexListBoxNews { get { return _selectedIndexListBoxNews; } set { _selectedIndexListBoxNews = value; ShowDescription(); } } /// <summary> /// Konstruktor klasy obsugującej główne okno /// </summary> public MainWindowViewModel() { ListCategories = new ObservableCollection<Category>(); ArchiveListCategories = new ObservableCollection<Category>(); RSSrepo rssRepo = new RSSrepo(); rssRepo.GetListArchiveCategories(ArchiveListCategories); Reader = new Reader(); OpenWebsiteCommand = new RelayCommand(OpenWebsite, (m) => true); SaveAllCommand = new RelayCommand(SaveAll, (m) => true); SaveCommand = new RelayCommand(Save, (m) => true); DeleteCommand = new RelayCommand(Delete, (m) => true); GetCategories(); SelectedIndexTab = 0; SelectedIndexCategories = 0; ReadNews(); } /// <summary> /// Wywołuje funkcje usuwania wiadomości z bazy danych i usuwa ją z wyświetlanej listy /// </summary> /// <param name="obj"> id wiadomości do usunięcia</param> private void Delete(object obj) { RSSrepo rssRepo = new RSSrepo(); string id = (string)obj; rssRepo.DeleteSelectedArticle(ArchiveListCategories, id); if (LineNews.Count != 0) { LineNews.Remove(LineNews.First(n => n.Id == id)); if (SelectedIndexListBoxNews < 0) SelectedIndexListBoxNews = 0; } } /// <summary> /// Wywołuje funkcje do zapisywania wiadomości do bazy danych /// </summary> /// <param name="obj"></param> private void Save(object obj) { News newsSave = new News(); int index = SelectedIndexListBoxNews; if (obj is Int32) index = (int)obj; newsSave.Title = LineNews[index].Title; newsSave.Description = LineNews[index].Description; newsSave.Id = LineNews[index].Id; newsSave.UrlImage = LineNews[index].UrlImage; newsSave.Category = LineNews[index].Category; newsSave.UrlNews = LineNews[index].UrlNews; newsSave.Date = LineNews[index].Date; newsSave.Photo = GetImageAsByte(newsSave.UrlImage); RSSrepo rssRepo = new RSSrepo(); rssRepo.AddSelectedArticle(ArchiveListCategories, newsSave); } /// <summary> /// Zapisuje wszystkie wiadomości /// </summary> /// <param name="obj"></param> private void SaveAll(object obj) { for (int i = 0; i < LineNews.Count; i++) { Save(i); } } /// <summary> /// Przenosi do strony wybranej wiadomości /// </summary> /// <param name="obj">Wybrana wiadomość</param> private void OpenWebsite(object obj) { if (LineNews.Any()) if (string.IsNullOrEmpty(LineNews[SelectedIndexListBoxNews].UrlNews) == false) { System.Diagnostics.Process.Start(LineNews[SelectedIndexListBoxNews].UrlNews); } } /// <summary> /// Wyświetla opis wiadomości /// </summary> private void ShowDescription() { if (LineNews.Count > 0 && SelectedIndexListBoxNews > -1) { News.Title = LineNews[SelectedIndexListBoxNews].Title; News.Date = LineNews[SelectedIndexListBoxNews].Date; News.Description = LineNews[SelectedIndexListBoxNews].Description; News.UrlNews = LineNews[SelectedIndexListBoxNews].UrlNews; } } /// <summary> /// Funkcja do wczytywania kategorii i ich linków. Zmienia kodowanie. /// </summary> private void GetCategories() { var listTitles = new List<string>(); var listUrls = new List<string>(); WebClient webClient = new WebClient(); Encoding enc = Encoding.GetEncoding("ISO-8859-2"); webClient.Encoding = enc; string page = webClient.DownloadString(ResourceRss.UrlWebsite); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(page); var titles = from node in doc.DocumentNode.SelectNodes("//td[@class = 'tdPolecane01']") select node.InnerText.ToString(); listTitles = titles.AsQueryable().ToList(); var urls = from node in doc.DocumentNode.SelectNodes("//td[@class = 'tdPolecane02']") select node.InnerText.ToString(); listUrls = urls.AsQueryable().ToList(); for (int i = 0; i < listTitles.Count(); i++) { ListCategories.Add(new Category { Name = listTitles[i], Url = listUrls[i] }); } } /// <summary> /// Funkcja która zapisuje obrazek jako tablicę bajtów /// </summary> /// <param name="LinkImage">link, z którego pobierany jest obrazek</param> /// <returns></returns> private byte[] GetImageAsByte(string LinkImage) { if (!string.IsNullOrWhiteSpace(LinkImage)) { WebClient webClient = new WebClient(); return News.Photo = webClient.DownloadData(LinkImage); } else { byte[] c = new byte[] { 0 }; return c; } } } }
d3b55c043282c05a650dda02282d61714c5c034d
[ "C#" ]
8
C#
mobile32/RSS-Reader
aff374b4b1c46a332be21b4b8aa8f6bcf2084fca
3ec4d9e1287c0137216ce897201e6ace60505bd9
refs/heads/main
<repo_name>simpledimplejohn/career-quiz-styling<file_sep>/README.md JUST A PLACE TO TEST BOOTSTRAP STYLING<file_sep>/js/scripts.js $(document).ready(function() { console.log("works"); $('#radio-form').submit(function(event) { event.preventDefault(); const q1 = $("input:radio[name=q1]:checked").val(); const q2 = $("input:radio[name=q2]:checked").val(); let answerArray = [q1,q2]; let a = 0 let b = 0 let c = 0 let d = 0 let e = 0 let f = 0 for(let char of answerArray) { if(char === "a") { a ++; } if(char === "b") { b ++; } if(char === "c") { c ++; } if(char === "d") { d ++; } if(char === "e") { e ++; } if(char === "f") { f ++; } } a = Math.round((a/2)*100) b = Math.round((b/2)*100) c = Math.round((c/2)*100) d = Math.round((d/2)*100) e = Math.round((e/2)*100) f = Math.round((f/2)*100) console.log(a,b,c,d,e,f) $("#a").html(`<p><em>${a}%<em><p>`) $("#b").html(`<p><em>${b}%<em><p>`) $("#c").html(`<p><em>${c}%<em><p>`) $("#d").html(`<p><em>${d}%<em><p>`) $("#e").html(`<p><em>${e}%<em><p>`) $("#f").html(`<p><em>${f}%<em><p>`) }) })<file_sep>/js/quizConsole.js // This file is a test console app for the questions to get them working console.log("test") <file_sep>/NOTES.md The Mary Quiz Career Goals Personality Profile. A web app created for career coach <NAME> for her clients to better explore what career goals they should have based on a series of personality questions. This data will be collected and a personality profile can be created for each client. -Eight Primary Questions Questions -Each question gives 1 point score to the possible outcome -Score is added up and percentage given Six Possible Outcomes: A Social % B Organized % C Investigative Problem Solving % D Creative Problem Solving % E Driven % F Leadership % 1 How would you like to approach relationships at work? -I love relationships and collaboration. They are my favorite part about going to work. -I'd like to be the one directing things, either as an expert (alone) or as a manager (with a team). -I might not admit this to other people, but I like to be recognized for my achievements among a group of people. I strive to be the best I can be. -I like to be recognized for my achievements and always strive for excellence. -I prefer to work on creative projects - sometimes that's alone and sometimes with other people. -I like to be the one organizing things, creating schedules, and planning. -I like to be able to ask a lot of questions, do research, and understand more about the process or systems. 2 How would you like to work with leaders? -I'd like to think of creative ideas for the future. -I'd like to ask lots of questions, research, and analyze data to understand processes. -I'd like to be a part of the big picture decisions of leadership. -I'd like to plan the timeline for projects and plan the step-by-step process. -I'd like to help move things forward quickly and be a part of some big achievements. -I'd like to work collaboratively with people on my level rather than leadership. 3 How would you like to organize at home and at work? -I'd like to work with spreadsheets, research, or numbers to organize information. -I'd like to organize creatively based on color coding or making things look aesthetically pleasing. -I'd like to be in charge of how things are organized and direct the project planning. -I'd like to get things done quickly and love the feeling of achievement when I can see tangible results -I'd like to create to-do lists and plan a timeline so that projects are organized. -I'd like to work with people and collaborate as a group. 4 How would you like to work with data, research, and reports? -I'd love it! I could research and analyze information all day and be happy. -I'd like it as long as it's creative. I enjoy design with information for colorful charts and graphs or creatively researching idea -Collaborating with other people to gather information would be most enjoyable. I don't want to be stuck working on a computer alone. -I'd like to make decisions and move forward with a project – not get caught up in too much analyzing. -I'd like to be in charge so I can make sure the research fits with the big picture. -Planning and organizing would be my favorite part of research projects or reporting. 5 What role would you like to take on a creative project? -I'd enjoy working collaboratively with other people to brainstorm ideas. -Creativity is my jam! I'd love to be a part of all aspects of creative projects. -I'd like to plan and make sure that projects get finished on time and understand the process of how things are created. -I'd like the more analytical role on the project: looking at the budget or research data. -I'd like to lead - even if I'm not the one creating, I like to see the big picture and be in charge. -I'd work hard to make sure the project was finished and celebrate the results. 6 How detail-oriented are you? -I'm more interested in moving forward and making things happen than getting caught up in the details. -I like to pay attention to creative details, but other types of details can be boring. -Details are important. I'm good at catching mistakes, errors, typos, and incorrect information. -I like planning out the important details for things to run smoothly. Small, insignificant details don't matter as much. -I'm better with the big picture and would like to delegate the details. -I'd want to make sure I'm working with other people to sort out details through conversation. 7 What is your secret career desire? -I'd like to feel like I'm making a difference in people's lives and collaborate more with other people. -I'd like to be more creative and imaginative. -I'd like to be in charge and direct decisions. -I'd like to get more recognition for my work and celebrate more achievements. -I'd like to have more time to read, analyze, and research information. -I'd like to create a plan for the future and keep things organized. 8 If you were going on vacation with friends, what would you want your role to be for the trip? -Leader. I like to make decisions and be in charge. -Idea person. I like discovering unique detours and planning new adventures. -Researcher. I like reading reviews of businesses and travel blogs to find the best information to make decisions. -Motivator. I'd get people going, wouldn't waste time, and would make sure we're having the best possible experience on our trip. -I'd plan and organize everything: itinerary, travel plans, and accommodations. I always make sure everything runs smoothly. -Camp Counselor. I'd check in with each person to make sure they're happy and gather the group to make sure everyone is enjoying themselves. OUTCOMES: A SOCIAL You might have described yourself as simply a "people person" in the past, but there are many layers to your personality beyond just being friendly. You are wise, dynamic, and have a deep understanding of psychology and the human experience. You have emotional intelligence and can interpret subtle nuances in people’s communication that other people might not even notice. You understand that being good with people is all about communication. You’re incredibly empathetic. You have great communication skills and can problem solve through listening, speaking, or writing. When you speak, you deliver information in crystal clear language. You're observant of people's behaviors and naturally understand how to support their ability to resolve problems or develop to their full potential. You have high emotional IQ – the ability to understand and manage your emotions so you can empathize with other people and notice complex social cues that signal the need to problem solve effectively. You're good at understanding issues from other people's point of view and can adjust to situations in order to resolve situations that are stressful or challenging. Not every social person enjoys working directly face-to-face with people every day, but even if you’re an introvert, you understand the psychology of how people make choices, build relationships, and engage with each other. Even if you prefer to work alone, you like observing people and working on projects that relate to communication or the human experience. You have the ability to understand perspectives that are different from your own and this allows you to understand how to work toward a resolution on larger social problems, customer issues, or know how people might interact with technology. You understand that people are complex, fascinating beings and your people and communication skills are highly developed and multifaceted. Don't let anyone downplay these as "soft skills" or "people skills." You have the ability to navigate the most complex system in the universe and can simultaneously comprehend and problem solve the elaborate algorithms of human interaction. Don't believe the stereotypes about social people only being suited to client-facing roles – it’s actually the opposite. You’re suited for any career path because almost every profession has a social element to it. For example, software engineering is a job that requires creating software for humans to use, so it's important to know how to write code that will translate to a better experience for the people using it on the other end. Although the stereotypical professions for people who score high in the social personality type are jobs like psychologist, social worker, or teacher, you are not limited to those career paths. As a social person, you can do anything, but it has to be through the perspective of human experience. For example, the tech industry might not seem like a place for social people to flourish, but it’s actual the opposite. Because technology is mostly created for people to use, it is a very human-focused profession. It’s a misconception that career paths like software engineering are anti-social when they’re very collaborative by nature (people often share code with each other on teams and help each other problem solve). Also, the problems in technology are often understanding psychology of human behavior and how people interact with computers. This is just an example of one industry, but it’s important to think outside of the stereotypes and look at how your personality can fit with different career paths. Another aspect of the social personality that is often overlooked is the potential for growth into leadership. Many social people have natural leadership skills that can evolve as they gain more experience in their careers. It’s a misconception that a focus on collaboration is not a leadership skill. Good leaders are empathetic and tuned in to group decision making. If you’re a social person it might be good to consider growing into a leadership role over time (but only if you want to – you’re in charge of your career!) Learn more about your career personality and how to match that with different career paths here. B ORGANIZED You have a talent for organization and planning, and you like the world around you to be streamlined, efficient, and easy to navigate. You care about quality and like to plan things out in advance to avoid unnecessary problems, delays, confusion, and miscommunication. You like systems and processes because they create structure and provide a step-by-step approach to getting things accomplished and improved. You know that the world is a chaotic and complex place, so you prefer to make it simple and easy to understand by identifying the destination of a project and outlining a roadmap to provide a clear direction on how to get there. You enjoy using these roadmaps to organize task in front of you as well as communication with other people to show them how to navigate complex challenges. You like to plan for the future. You enjoy the process of thinking and envisioning how things could be better and planning out all the steps that need to happen day-to-day to move forward toward accomplishing little tasks and eventually completing bigger projects. It’s fun for you to think about the bigger picture and then break it down into smaller steps to create milestones that can help motivate you toward a larger goal. You have a keen eye for details and can detect when something is wrong to anticipate small problems that impact the overall final outcome. There are different types of organized people and not everyone is considered tidy or clean. Some people like the chaos of being in the mix of a messy problem and sorting it out. Other people don’t like disorder and prefer to work only in systems that are already organized and spend their energy working to improve them and make them even better. Some organized people have a talent for detecting details and enjoy finding errors, discovering mistakes, and correcting them by making small adjustments — but not every organized person likes this type of work — some prefer to resolve bigger, messier problems. In fact, some organized people have a messy workspace but have everything organized in their head. Some organized people like to create structures from scratch and build systems where none existed before. Other organized people prefer to have these processes already in place so they can work focus on improving it rather than building something new. As an organized person, you see the world through the perspective of structure and can provide tools, schedules, and information tracking to help people work better, communicate more effectively, and have less stress when working toward a goal. To an organized person, the future can seem less overwhelming because you can focus on a calendar to understand and communicate how to accomplish bigger tasks by arranging activities on specific dates to make sure everything is finished on time. A plan and a to-do list can help you make sense of complex projects. You understand how to use the right tools to organize information, timelines, or break complex problems down into systems that create easier solutions and less stress. As an organized person, you are a blessing to any workplace because you have solutions that help everyone work better, communicate more effectively, and relax more. You can work in a variety of different professions but need to be in a position that allows you to make changes and improvements in the systems and processes around you. Depending on the specifics of your personality, you might either want to work in a career path that allows you to create a structure from scratch or one where that structure already exists. The most obvious career paths for organizers are project manager, operations manager, or professional organizer, but everyone is different, and you can approach organizing careers from a variety of perspectives. You might be highly detail-oriented and be great at catching errors so a career path as a proofreader would be an ideal match for your strengths. On the other hand, you might be great at organized chaos and love the excitement of being an event planner. As an organized person, you could work in any industry. Combining these talents with other areas of interest can help you understand the right match for your career. Learn more about your career personality and how to match that with different career paths here. C INVESTIGATIVE PROBLEM SOLVING You are inherently curious and like to understand the complexities of the world around you. Problem solving is your favorite work-related activity, and you enjoy understanding how things operate, digging into the details, and putting together the puzzle to understand how to resolve issues. You like investigating through research, asking questions, reading, looking at data, or gathering information from a variety of sources to discover answers — and possibly more questions. Your goal might be to improve things or finish a project, but you’re not always interested in the final outcome and may be satisfied coming up with more problems than when you started. You enjoy investigating to get to the heart of an issue and fixing the root cause of a problem rather than finding a shallow quick-fix solution. You’re very curious and determined — you will keep asking questions, researching, and investigating until you find solutions that improve processes and ensure quality. You might be someone who reads every review of a product before you buy it. You might prefer to read more about an issue before forming an opinion on it. Or you might need to think or research a problem before providing a solution to people. For some people that means that you’re quiet because you think first before responding, but for other people, it means you like to talk and think through solutions verbally. You love to learn new information and are attracted to complex situations that require you to think deeper, pay attention to layers of information, and investigate more details to discover different perspectives on a situation. You’re drawn to entertainment that makes you think deeply like complex movie plots with mysterious endings or podcasts that provide unique perspectives and give you insight into complicated issues. You like to think, learn, and process information in a pragmatic and logical way based on data and research. You enjoy using technical tools to gather information and would enjoy creating reports to communicate this information to other people. You’re good at seeing patterns and synthesizing information. You focus on quality and good design or engineering that makes things work effectively. You’d rather spend more time on something to make it quality than finish something quicky. You understand the importance of solving problems at the root of the issue and spending time to understand all the information available to create a process or system that has a long-term and permanent solution. A small percentage of my clients with this personality type consider themselves more curious than other people to the point where they can be disruptive. They describe being the person who always has a lot of questions during meetings and can’t proceed with a project before understanding all of the details. They have to read through all of the legal documents, policies, and procedures before moving forward to the next step and can pick out details to identify problems that need to be examined first before agreeing that something is complete. This can cause conflict in the workplace if leadership or people on a team want to move forward quickly, but this type of personality can also be praised for identifying risks or saving time and money by preventing bigger long-term issues. There are different types of investigative problem-solving people. Some love researching by reading long, complex documents and others prefer to gather information from a variety of scattered sources and then bring the data all together. Some people with this personality type love data and numbers but others prefer to have conversations and understand more qualitative information. You might consider yourself scientific, mathematical, technical — or even nerdy, but you might not. With this personality type, you could be a dreamer, a social butterfly, or not identify with logic at all — you might simply enjoy research, thinking, and understanding the world. The stereotype of an Investigative Problem-Solving personality type is an engineer or scientist, but you may or may not identify with these career paths. You can work in any career path as long as it gives you the opportunity to understand problems from a more complex perspective and spend time researching, asking questions, and diving into the details to understand bigger solutions before moving forward with decisions. You get bored easily, so you need a career path that allows you continuous learning and professional growth opportunities. You need time in your workday to understand longer-term projects, examine the bigger picture, and look through the details. You prefer not to be pushed to make decisions quickly based on shallow knowledge of a project. D CREATIVE PROBLEM-SOLVING You are a creative thinker who likes to come up with new ideas, learn about innovative ways of doing things, and look at the world from unique perspectives to keep things interesting. You are bored easily with conventional ways of doing things and are constantly craving new challenges. You don’t like routine unless the purpose is to create something new or work on the details of a bigger creative picture. You might not consider yourself talented artistically, but you enjoy being around creativity, colors, or new adventures. Not every Creative Problem-Solving personality type has to be hands-on creative, but you definitely enjoy thinking about designing or building something new or being a part of this process. You like coming up with new concepts, brainstorming, ideating, and creating. You can see a vision for something different and imagine outcomes that other people might not see or believe are possible. You can simultaneously see the small details and the big picture—and synthesize this information into a clear vision. Creativity is all about expression—whether that means writing, art, or communicating with people about ideas. You like to be in an environment that allows you to feel authentic and that gives you the freedom to voice your thoughts and opinions openly. You get energized by having the creative space to develop new ideas—whether it’s through collaboration or independent thought and imagination. You’re good at using your intuition to come up with ideas and new ways of thinking about things. Ideas often come to you randomly out of the blue and you sometimes have spontaneous bursts of inspiration that don’t fit into a logical structure of a work environment. People can be intimidated by the concept of creativity because it’s often associated with artistic talent. Just because you think from a creative perspective, doesn’t mean you must have an artistic craft. Having the Creative Problem-Solving personality type just means that you enjoy freedom, big picture thinking, and self-expression in your career. You tend to get bored easily, so you need a career path that is creatively stimulating and full of continuous learning, professional growth opportunities, and the ability to think from different perspectives. You like understanding complex issues and having the time to work through solutions that address all of the problems through complex and interesting solutions. E DRIVEN You are a hard worker and like to see results from the effort that you put forth on projects. You have very high standards for your achievements and push yourself to do the best that you possibly can at everything you do. These high standards often make it so that you don’t always see how incredibly accomplished, intelligent, and creative you actually are because you’re too busy focusing on improving upon what you’ve already done. You like a challenge and don’t mind pushing yourself to achieve even greater accomplishments. You like to take things to the next level and see how much success you can achieve. Each project or situation is a new chance for you to boost your confidence and prove to yourself that you can push yourself to a new level. You can be a risk taker, but sometimes you don’t like starting over with new things because it takes longer for you to be good at them. However, you don’t mind trying something new if it presents a new opportunity for you to learn, grow, and reach the next level of success. You like to be successful at everything you do and enjoy projects that provide you with clear opportunities to measure achievements so you can see real results. Ambiguous and confusing expectations make you less motivated, and you prefer to keep score on your success and celebrate when you’ve gone above and beyond. You’re self-motivated and have an entrepreneurial spirt that keeps you focused on the success of a project because you’re not satisfied with the status quo and will push for improvements and innovation. You have a natural curiosity for the world and passion for launching new projects that keep you motivated, driven, and energized for work projects. However, you can also get bored easily, so it’s important to continue to have new challenges and learning opportunities in front of you to keep motivated and interested. It can be confusing for the Driven personality type on whether they should be leaders or entrepreneurs because their ambition and drive to succeed is sometimes (but not always) combined with a desire to manage, lead projects, or start a business. You might feel excited to be successful at projects but may or may not want to take on a leadership role. Sometimes leadership is a natural next step in this personality type but other times you’d rather move forward and accomplish goals as an individual contributor. Similarly, you might have fantasies of starting your own business (and would probably be great at it) but sometimes it seems nice to not have the responsibility of the entire company. Either way, you have a strong work ethic and the potential to achieve great success in your work. F LEADERSHIP You are a big-picture thinker who has the ability to visualize the future to direct people forward. You understand strategically how things should be done well and can anticipate what steps need to be taken in order to be successful. You like to voice your opinions for making big, important decisions and like to be in charge of strategy to make sure your ideas are fully realized. Even if you haven’t had leadership experience, you may find yourself craving this role, so you come up with big ideas, as well as direct and influence decision making to turn your ideas into successful projects. The idea of leadership can feel intimidating to some, but there are many different types of leaders and a variety of different leadership styles. You can discover your personal leadership style by thinking about how much responsibility you want to take on and what types of projects are exciting to you. Think of leaders that you admire and pay attention to what inspires you about their personalities in order to express your own way of leading in the world. There are two types of leaders: experts and managers. Experts are leaders who prefer to focus on knowledge, skills, and passions but don’t want the responsibility of managing a team. Thought leadership is the focus for experts, who prefer to have subjects that they’re knowledgeable about and can guide the decision-making process for projects from beginning to end without directly managing. In fact, some experts have very little interaction with people and can lead through presentations, writing, or reports without managing a team. Managers, on the other hand, are people leaders. They enjoy working with teams to motivate, mentor, and provide feedback on areas of improvement and growth. Managers like guiding projects through direct communication with employees and find fulfillment leading teams of people through a process to ensure success. You may identify somewhere on the spectrum between these types of leaders. Whether you’re currently a leader in your career or just recognize leadership qualities in your personality, it’s going to be important for you to explore opportunities to grow in leadership within your career in the future. Fortunately, there is no end to growth, education, and advancement when it comes to leadership, so you have a lifetime of opportunities for learning and self-development in the future. Every career path has the opportunity for growth as a leader, including entrepreneurship, so you will have unlimited potential for career advancement.
9ef6b163b060094d63f32a71958fcd19ea23ae80
[ "Markdown", "JavaScript" ]
4
Markdown
simpledimplejohn/career-quiz-styling
5c687dd4b6714539dc812c2cd26dbe5c8b2c0fa5
9e738ea1939d9d6b7473441e6135699cb2aee0f7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Net.Sockets; using System.Net; using System.Runtime.InteropServices; using System.IO; using System.Management; using System.Diagnostics; using System.Net.NetworkInformation; using System.Configuration; using System.Drawing.Imaging; namespace Wifi_PC_Remote { public partial class Form1 : Form { int count = 0; static TcpClient client = null; static int fl = 0, fr = 0, fm = 0; static int fshift = 0, fctrl = 0, fwin = 0, falt = 0; Thread th, th1; static bool flag = true; public const int SM_CXSCREEN = 0; public const int SM_CYSCREEN = 1; public const int SRCCOPY = 13369376; static UdpClient server; static TcpListener tcp; static string str = ""; static string ipaddr = ""; public Bitmap bmp; public static Point CursorPosition; delegate void SetTextCallback(String text); [DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("USER32.DLL")] static extern IntPtr GetShellWindow(); delegate bool EnumWindowsProc(IntPtr hwnd, int lParam); [DllImport("USER32.DLL")] static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam); [DllImport("USER32.DLL")] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("USER32.DLL")] static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("USER32.DLL")] static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("USER32.DLL")] private static extern bool EndTask(IntPtr h, bool a, bool b); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message message) { base.WndProc(ref message); if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT) message.Result = (IntPtr)HTCAPTION; } public Form1() { InitializeComponent(); } private void status_Click(object sender, EventArgs e) { } private void groupBox1_Enter(object sender, EventArgs e) { } private void TrayMinimizerForm_Resize() { if (FormWindowState.Minimized == this.WindowState) { this.Hide(); } if (FormWindowState.Normal == this.WindowState) { notifyIcon2.Visible = false; } } private void Form1_Load(object sender, EventArgs e) { status.Text = "Status : Running"; uptime.Text = "Uptime : 00:00:00"; startbutton.Enabled = false; stopbutton.Enabled = true; timer1.Enabled = true; count = 0; timer1.Interval = 1000; flag = true; Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (config.AppSettings.Settings["tcp"] == null) { tcpport.Value = 9999; config.AppSettings.Settings.Add("tcp", tcpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { tcpport.Value = Convert.ToInt64(config.AppSettings.Settings["tcp"].Value); } if (config.AppSettings.Settings["udp"] == null) { udpport.Value = 8888; config.AppSettings.Settings.Add("udp", udpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { udpport.Value = Convert.ToInt64(config.AppSettings.Settings["udp"].Value); } if (config.AppSettings.Settings["password"] == null) { textbox_password.Text = ""; config.AppSettings.Settings.Add("password", textbox_password.Text); config.Save(ConfigurationSaveMode.Modified); } else { textbox_password.Text = config.AppSettings.Settings["password"].Value; } server = new UdpClient((int)udpport.Value); tcp = new TcpListener(IPAddress.Any, (int)tcpport.Value); tcp.Start(); notifyIcon2.BalloonTipTitle = "Wifi PC Remote Running on Notification Tray"; notifyIcon2.BalloonTipText = "Click to Open Wifi PC Remote"; notifyIcon2.Text = "Wifi PC Remote"; this.notifyIcon2.ContextMenuStrip = contextMenuStrip1; notifyIcon2.Visible = true; notifyIcon2.ShowBalloonTip(500); this.th = new Thread(new ThreadStart(ThreadProc)); this.th.Start(); } private void timer1_Tick(object sender, EventArgs e) { count++; TimeSpan span = TimeSpan.FromSeconds(count); uptime.Text = "Uptime : " + span.ToString(); } private void stopbutton_Click(object sender, EventArgs e) { timer1.Enabled = false; status.Text = "Status : Stopped"; uptime.Text = "Uptime : 00:00:00"; stopbutton.Enabled = false; startbutton.Enabled = true; server.Close(); tcp.Server.Close(); tcp.Stop(); flag = false; this.th.Abort(); } private void startbutton_Click(object sender, EventArgs e) { timer1.Enabled = true; status.Text = "Status : Running"; uptime.Text = "Uptime : 00:00:00"; stopbutton.Enabled = true; startbutton.Enabled = false; count = 0; flag = true; Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (config.AppSettings.Settings["tcp"] == null) { tcpport.Value = 9999; config.AppSettings.Settings.Add("tcp", tcpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { tcpport.Value = Convert.ToInt64(config.AppSettings.Settings["tcp"].Value); } if (config.AppSettings.Settings["udp"] == null) { udpport.Value = 8888; config.AppSettings.Settings.Add("udp", udpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { udpport.Value = Convert.ToInt64(config.AppSettings.Settings["udp"].Value); } if (config.AppSettings.Settings["password"] == null) { textbox_password.Text = ""; config.AppSettings.Settings.Add("password", textbox_password.Text); config.Save(ConfigurationSaveMode.Modified); } else { textbox_password.Text = config.AppSettings.Settings["password"].Value; } server = new UdpClient((int)udpport.Value); tcp = new TcpListener(IPAddress.Any, (int)tcpport.Value); tcp.Start(); this.th = new Thread(new ThreadStart(ThreadProc)); this.th.Start(); } private int Match_password(string sp) { Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (passwordcheck.Checked == true) { int x = sp.IndexOf('$'); sp = sp.Substring(0, x); if (sp.Equals(config.AppSettings.Settings["password"].Value)) { return 1; } else { return 0; } } else { return 1; } } private void ThreadProc() { while (flag) { try { var remoteEP = new IPEndPoint(IPAddress.Any, (int)udpport.Value); byte[] data = server.Receive(ref remoteEP); String sp = Encoding.ASCII.GetString(data); ipaddr = remoteEP.Address.ToString(); if (Match_password(sp) == 1) { sp = sp.Substring(sp.IndexOf('$') + 1); if (sp[0] == 's')/*scroll*/ { str = sp.Substring(7); mouse_event(0x800, 0, 0, (int)(double.Parse(str) * -1), 0); } else if (sp[0] == 'f')/*file explorer*/ { str = sp.Substring(3); fileexplorer(str, remoteEP); } else if (sp[0] == 'c')/*connectlist*/ { byte[] b = Encoding.ASCII.GetBytes("1"); server.Send(b, b.Length, remoteEP); } else if (sp[0] == 'k')/*keyboard*/ { keyboard(sp); } else if (sp[0] == 'a')/*file longclick check*/ { longclick(sp, remoteEP); } else if (sp[0] == 'b')/*file operation*/ { fileoperations(sp, remoteEP); } else if (sp[0] == 'v') { vlc(sp, remoteEP); } else if (sp[0] == 'd') { viewdesktop(sp); } else { mouse(sp); } } else { byte[] b = Encoding.ASCII.GetBytes("0"); server.Send(b, b.Length, remoteEP); } } catch (Exception e) { } } } private static void vlc(string str, IPEndPoint remoteEP) { int vlcval = Int16.Parse(str.Substring(2, 1)); int val; if (vlcval == 2) { val = Int16.Parse(str.Substring(4, 1)); if (val == 2) { showvlc(); } else if (val == 1) { showvlc(); keybd_event(0x41, 0x45, 0x0001 | 0, 0); keybd_event(0x41, 0x45, 0x0001 | 0x0002, 0); } else if (val == 3) { showvlc(); keybd_event(0xBD, 0x45, 0x0001 | 0, 0); keybd_event(0xBD, 0x45, 0x0001 | 0x0002, 0); } else if (val == 4) { showvlc(); keybd_event(0x6B, 0x45, 0x0001 | 0, 0); keybd_event(0x6B, 0x45, 0x0001 | 0x0002, 0); } else if (val == 9) { showvlc(); keybd_event(0x4D, 0x45, 0x0001 | 0, 0); keybd_event(0x4D, 0x45, 0x0001 | 0x0002, 0); } } else if (vlcval == 3) { val = Int16.Parse(str.Substring(4, 1)); if (val == 1) { try { System.Diagnostics.Process.Start("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"); } catch (Exception e2) { } try { System.Diagnostics.Process.Start("C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"); } catch (Exception e2) { } } else if (val == 2) { foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle.EndsWith("VLC media player")) { p.Kill(); } } } else if (val == 3) showvlc(); } else if (vlcval == 4) { IntPtr lshell = GetShellWindow(); String ss = ""; EnumWindows(delegate(IntPtr hWnd, int lParam) { if (hWnd == lshell) return true; if (!IsWindowVisible(hWnd)) return true; int lLength = GetWindowTextLength(hWnd); if (lLength == 0) return true; StringBuilder lBuilder = new StringBuilder(lLength); GetWindowText(hWnd, lBuilder, lLength + 1); ss += lBuilder.ToString() + "\n"; return true; }, 0); byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } else if (vlcval == 5) { string ss = ""; foreach (Process p in Process.GetProcesses()) { ss += p.ProcessName + "\n"; } byte[] aa = Encoding.ASCII.GetBytes(ss.ToString()); server.Send(aa, aa.Length, remoteEP); } else if (vlcval == 6) { string ss = str.Substring(4); IntPtr lshell = GetShellWindow(); EnumWindows(delegate(IntPtr hWnd, int lParam) { if (hWnd == lshell) return true; if (!IsWindowVisible(hWnd)) return true; int lLength = GetWindowTextLength(hWnd); if (lLength == 0) return true; StringBuilder lBuilder = new StringBuilder(lLength); GetWindowText(hWnd, lBuilder, lLength + 1); if (lBuilder.ToString().EndsWith(ss)) { ShowWindow(hWnd, 9); SetForegroundWindow(hWnd); } return true; }, 0); } else if (vlcval == 7) { val = Int16.Parse(str.Substring(4, 1)); string ss = str.Substring(6); if (val == 0) { IntPtr lshell = GetShellWindow(); EnumWindows(delegate(IntPtr hWnd, int lParam) { if (hWnd == lshell) return true; if (!IsWindowVisible(hWnd)) return true; int lLength = GetWindowTextLength(hWnd); if (lLength == 0) return true; StringBuilder lBuilder = new StringBuilder(lLength); GetWindowText(hWnd, lBuilder, lLength + 1); if (lBuilder.ToString().EndsWith(ss)) { EndTask(hWnd, false, true); } return true; }, 0); } else if (val == 1) { foreach (Process p in Process.GetProcesses()) { if (p.ProcessName.Equals(ss.Substring(0, ss.Length - 4))) { p.Kill(); } } } } } private static void showvlc() { foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle.EndsWith("VLC media player")) { IntPtr hand = p.MainWindowHandle; ShowWindow(hand, 3); SetForegroundWindow(hand); break; } } } private static void fileoperations(String str, IPEndPoint remoteEP) { int val = Int16.Parse(str.Substring(2, 1)); try { if (val == 1) { str = str.Substring(4); try { File.Delete(str); } catch (Exception e) { } try { Directory.Delete(str, true); } catch (Exception e) { } } else if (val == 2) { int p = str.IndexOf('\n', 4); string old = str.Substring(4, p - 4); string ne = str.Substring(p + 1); try { File.Move(old, ne); } catch (FileNotFoundException e) { } try { Directory.Move(old, ne); } catch (DirectoryNotFoundException e) { } } else if (val == 3) { str = str.Substring(4); String ss = Directory.GetCreationTime(str) + "$"; ss += Directory.GetLastWriteTime(str) + "$"; byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } else if (val == 4) { str = str.Substring(4); String ss = File.GetCreationTime(str) + "$"; ss += File.GetLastWriteTime(str) + "$"; ss += new System.IO.FileInfo(str).Length.ToString() + "$"; byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } else if (val == 5) { long i; str = str.Substring(4); NetworkStream ns = null; FileStream fs = null; try { if (tcp.Pending() == true) { client = tcp.AcceptTcpClient(); if (client != null) { ns = client.GetStream(); fs = new FileStream(str, FileMode.Open, FileAccess.Read); long len = fs.Length; byte[] aa = Encoding.ASCII.GetBytes(len.ToString()); ns.Write(aa, 0, aa.Length); long Buffersize = 10000024, size; long noofpacket = Convert.ToInt64(Math.Ceiling(Convert.ToDouble(fs.Length) / Convert.ToDouble(Buffersize))); for (i = 0; i < noofpacket; i++) { if (len > Buffersize) { size = Buffersize; len = len - size; } else size = len; byte[] ar = new byte[size]; fs.Read(ar, 0, (int)size); ns.Write(ar, 0, (int)ar.Length); } fs.Close(); ns.Close(); } client.Close(); } } catch (Exception e) { fs.Close(); ns.Close(); client.Close(); } } else if (val == 6) { int x = Int16.Parse(str.Substring(4, 1)); string filename = "", arguments = ""; if (x == 1) { filename = "shutdown.exe"; arguments = "-s"; } else if (x == 2) { Application.SetSuspendState(PowerState.Suspend, true, true); } else if (x == 3) { filename = "shutdown.exe"; arguments = "-l"; } else if (x == 4) { Application.SetSuspendState(PowerState.Hibernate, true, true); } else if (x == 5) { filename = "shutdown.exe"; arguments = "-r"; } else if (x == 6) { filename = "shutdown.exe"; arguments = "-a"; } ProcessStartInfo startinfo = new ProcessStartInfo(filename, arguments); Process.Start(startinfo); } else if (val == 7) { int x = Int16.Parse(str.Substring(4, 1)); if (x == 1) { keybd_event(0xB1, 0x45, 0x0001 | 0, 0); keybd_event(0xB1, 0x45, 0x0001 | 0x0002, 0); } else if (x == 2) { keybd_event(0xB3, 0x45, 0x0001 | 0, 0); keybd_event(0xB3, 0x45, 0x0001 | 0x0002, 0); } else if (x == 3) { keybd_event(0xB0, 0x45, 0x0001 | 0, 0); keybd_event(0xB0, 0x45, 0x0001 | 0x0002, 0); } else if (x == 4) { keybd_event(0xAF, 0x45, 0x0001 | 0, 0); keybd_event(0xAF, 0x45, 0x0001 | 0x0002, 0); } else if (x == 5) { keybd_event(0xAE, 0x45, 0x0001 | 0, 0); keybd_event(0xAE, 0x45, 0x0001 | 0x0002, 0); } else if (x == 6) { keybd_event(0xB2, 0x45, 0x0001 | 0, 0); keybd_event(0xB2, 0x45, 0x0001 | 0x0002, 0); } else if (x == 7) { keybd_event(0xAD, 0x45, 0x0001 | 0, 0); keybd_event(0xAD, 0x45, 0x0001 | 0x0002, 0); } } else if (val == 8) { str = str.Substring(4); SendKeys.SendWait(str); } } catch (Exception e) { } } private void longclick(String str, IPEndPoint remoteEP) { String ss = ""; str = str.Substring(2); try { if (str[str.Length - 1] == '\\') { ss = "1"; } else { if (Directory.Exists(str)) ss = "2"; else if (File.Exists(str)) ss = "3"; } byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } catch (Exception e) { } } private static ImageCodecInfo GetEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } private void viewdesktop(string sp) { int width; int height; try { sp = sp.Substring(sp.IndexOf('$') + 1); width = Int16.Parse(sp.Substring(0, sp.IndexOf('$'))); height = Int16.Parse(sp.Substring(sp.IndexOf('$') + 1)); if (width < height) { int temp = width; width = height; height = temp; } } catch (Exception e4) { Rectangle bounds = Screen.PrimaryScreen.Bounds; width = bounds.Width; height = bounds.Height; } NetworkStream ns = null; try { if (tcp.Pending() == true) { client = tcp.AcceptTcpClient(); while (true) { //Thread.Sleep(1000); Rectangle bounds = Screen.PrimaryScreen.Bounds; using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size); } ns = client.GetStream(); byte[] imageData; using (var stream = new MemoryStream()) { Bitmap b = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(b)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(bitmap, 0, 0, width, height); } EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)50); ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; b.Save(stream, jpegCodec, encoderParams); // b.Save(stream, ImageFormat.Jpeg); imageData = stream.ToArray(); int buff = 10000024; int siz = imageData.Length; int noofpacket = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(siz) / Convert.ToDouble(buff))); int j = 0; byte[] aa = Encoding.ASCII.GetBytes(siz.ToString()); ns.Write(aa, 0, aa.Length); ns.Write(imageData, 0, siz); /* for (int i = 0; i < noofpacket; i++) { if (siz > buff) { ns.Write(imageData, j, buff); siz = siz - buff; j = j + buff; } else { ns.Write(imageData, j, siz); } }*/ // ns.Write(imageData, 0, 10024);; } } } } } catch (Exception e2) { } } public struct SIZE { public int cx; public int cy; } private static void fileexplorer(String str, IPEndPoint remoteEP) { int i; try { if (str.Equals("\\")) { ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("Select * from Win32_LogicalDisk"); String ss = mosDisks.Get().Count.ToString() + "$"; foreach (ManagementObject moDisk in mosDisks.Get()) { if (moDisk["Size"] != null) { ss += moDisk["Size"].ToString() + "\n"; ss += moDisk["FreeSpace"].ToString() + "\n"; ss += moDisk["Name"].ToString() + "\\\n"; } else { ss += "0\n"; ss += "0\n"; ss += moDisk["Name"].ToString() + "\\\n"; } } byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } else { String ss = ""; if (Directory.Exists(str)) { String[] l = Directory.GetDirectories(str); int tc = 0; for (i = 0; i < l.Length; i++) { DirectoryInfo dir = new DirectoryInfo(l[i]); if ((dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) { ss += "1\n"; ss += Directory.GetCreationTime(l[i]) + "\n"; ss += l[i] + "\n"; tc += 1; } } String[] f = Directory.GetFiles(str); for (i = 0; i < f.Length; i++) { FileInfo fir = new FileInfo(f[i]); if ((fir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) { ss += "0\n"; ss += new System.IO.FileInfo(f[i]).Length.ToString() + "\n"; ss += f[i] + "\n"; tc += 1; } } ss = tc.ToString() + "$" + ss; byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } else if (File.Exists(str)) { ss += "-2$null\n"; byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); System.Diagnostics.Process.Start(str); } else { ss += "-1$null\n"; byte[] ar = Encoding.ASCII.GetBytes(ss); server.Send(ar, ar.Length, remoteEP); } } } catch (Exception e) { } } private static void keyboard(String sp) { String extraval = sp.Substring(4, 4); String str = sp.Substring(9); if (extraval[0] == '1' && fshift == 0) { keybd_event(0x10, 0x45, 0x0001 | 0, 0); fshift = 1; } if (extraval[0] == '0' && fshift == 1) { keybd_event(0x10, 0x45, 0x0001 | 0x0002, 0); fshift = 0; } if (extraval[1] == '1' && fctrl == 0) { keybd_event(0x11, 0x45, 0x0001 | 0, 0); fctrl = 1; } if (extraval[1] == '0' && fctrl == 1) { keybd_event(0x11, 0x45, 0x0001 | 0x0002, 0); fctrl = 0; } if (extraval[2] == '1' && fwin == 0) { keybd_event(0x5B, 0x45, 0x0001 | 0, 0); fwin = 1; } if (extraval[2] == '0' && fwin == 1) { keybd_event(0x5B, 0x45, 0x0001 | 0x0002, 0); fwin = 0; } if (extraval[3] == '1' && falt == 0) { keybd_event(0x12, 0x45, 0x0001 | 0, 0); falt = 1; } if (extraval[3] == '0' && falt == 1) { keybd_event(0x12, 0x45, 0x0001 | 0x0002, 0); falt = 0; } if (str.Equals("bescape")) { keybd_event(0x1B, 0x45, 0x0001 | 0, 0); keybd_event(0x1B, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("btidle")) { keybd_event(0xC0, 0x45, 0x0001 | 0, 0); keybd_event(0xC0, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bdash")) { keybd_event(0xBD, 0x45, 0x0001 | 0, 0); keybd_event(0xBD, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bequal")) { keybd_event(0xBB, 0x45, 0x0001 | 0, 0); keybd_event(0xBB, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bsquare")) { keybd_event(0xDB, 0x45, 0x0001 | 0, 0); keybd_event(0xDB, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bsqclose")) { keybd_event(0xDD, 0x45, 0x0001 | 0, 0); keybd_event(0xDD, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bdel")) { keybd_event(0x2E, 0x45, 0x0001 | 0, 0); keybd_event(0x2E, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bback")) { keybd_event(0x08, 0x45, 0x0001 | 0, 0); keybd_event(0x08, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bone")) { keybd_event(0x31, 0x45, 0x0001 | 0, 0); keybd_event(0x31, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("btwo")) { keybd_event(0x32, 0x45, 0x0001 | 0, 0); keybd_event(0x32, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bthree")) { keybd_event(0x33, 0x45, 0x0001 | 0, 0); keybd_event(0x33, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bfour")) { keybd_event(0x34, 0x45, 0x0001 | 0, 0); keybd_event(0x34, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bfive")) { keybd_event(0x35, 0x45, 0x0001 | 0, 0); keybd_event(0x35, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bsix")) { keybd_event(0x36, 0x45, 0x0001 | 0, 0); keybd_event(0x36, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bseven")) { keybd_event(0x37, 0x45, 0x0001 | 0, 0); keybd_event(0x37, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("beight")) { keybd_event(0x38, 0x45, 0x0001 | 0, 0); keybd_event(0x38, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bnine")) { keybd_event(0x39, 0x45, 0x0001 | 0, 0); keybd_event(0x39, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bzero")) { keybd_event(0x30, 0x45, 0x0001 | 0, 0); keybd_event(0x30, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bq")) { keybd_event(0x51, 0x45, 0x0001 | 0, 0); keybd_event(0x51, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bw")) { keybd_event(0x57, 0x45, 0x0001 | 0, 0); keybd_event(0x57, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("be")) { keybd_event(0x45, 0x45, 0x0001 | 0, 0); keybd_event(0x45, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("br")) { keybd_event(0x52, 0x45, 0x0001 | 0, 0); keybd_event(0x52, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bt")) { keybd_event(0x54, 0x45, 0x0001 | 0, 0); keybd_event(0x54, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("by")) { keybd_event(0x59, 0x45, 0x0001 | 0, 0); keybd_event(0x59, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bu")) { keybd_event(0x55, 0x45, 0x0001 | 0, 0); keybd_event(0x55, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bi")) { keybd_event(0x49, 0x45, 0x0001 | 0, 0); keybd_event(0x49, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bo")) { keybd_event(0x4F, 0x45, 0x0001 | 0, 0); keybd_event(0x4F, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bp")) { keybd_event(0x50, 0x45, 0x0001 | 0, 0); keybd_event(0x50, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("btab")) { keybd_event(0x09, 0x45, 0x0001 | 0, 0); keybd_event(0x09, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("ba")) { keybd_event(0x41, 0x45, 0x0001 | 0, 0); keybd_event(0x41, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bs")) { keybd_event(0x53, 0x45, 0x0001 | 0, 0); keybd_event(0x53, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bd")) { keybd_event(0x44, 0x45, 0x0001 | 0, 0); keybd_event(0x44, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf")) { keybd_event(0x46, 0x45, 0x0001 | 0, 0); keybd_event(0x46, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bg")) { keybd_event(0x47, 0x45, 0x0001 | 0, 0); keybd_event(0x47, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bh")) { keybd_event(0x48, 0x45, 0x0001 | 0, 0); keybd_event(0x48, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bj")) { keybd_event(0x4A, 0x45, 0x0001 | 0, 0); keybd_event(0x4A, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bk")) { keybd_event(0x4B, 0x45, 0x0001 | 0, 0); keybd_event(0x4B, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bl")) { keybd_event(0x4C, 0x45, 0x0001 | 0, 0); keybd_event(0x4C, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bcapsoff")) { keybd_event(0x14, 0x45, 0x0001 | 0, 0); keybd_event(0x14, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bz")) { keybd_event(0x5A, 0x45, 0x0001 | 0, 0); keybd_event(0x5A, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bx")) { keybd_event(0x58, 0x45, 0x0001 | 0, 0); keybd_event(0x58, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bc")) { keybd_event(0x43, 0x45, 0x0001 | 0, 0); keybd_event(0x43, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bv")) { keybd_event(0x56, 0x45, 0x0001 | 0, 0); keybd_event(0x56, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bb")) { keybd_event(0x42, 0x45, 0x0001 | 0, 0); keybd_event(0x42, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bn")) { keybd_event(0x4E, 0x45, 0x0001 | 0, 0); keybd_event(0x4E, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bm")) { keybd_event(0x4D, 0x45, 0x0001 | 0, 0); keybd_event(0x4D, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("benter")) { keybd_event(0x0D, 0x45, 0x0001 | 0, 0); keybd_event(0x0D, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bcolon")) { keybd_event(0xBA, 0x45, 0x0001 | 0, 0); keybd_event(0xBA, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bquotes")) { keybd_event(0xDE, 0x45, 0x0001 | 0, 0); keybd_event(0xDE, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bor")) { keybd_event(0xDC, 0x45, 0x0001 | 0, 0); keybd_event(0xDC, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bcomma")) { keybd_event(0xBC, 0x45, 0x0001 | 0, 0); keybd_event(0xBC, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bdot")) { keybd_event(0xBE, 0x45, 0x0001 | 0, 0); keybd_event(0xBE, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("btop")) { keybd_event(0x26, 0x45, 0x0001 | 0, 0); keybd_event(0x26, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bslash")) { keybd_event(0xBF, 0x45, 0x0001 | 0, 0); keybd_event(0xBF, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bspace")) { keybd_event(0x20, 0x45, 0x0001 | 0, 0); keybd_event(0x20, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bleft")) { keybd_event(0x25, 0x45, 0x0001 | 0, 0); keybd_event(0x25, 0x45, 0x0001 | 0x0002, 0); ; } else if (str.Equals("bdown")) { keybd_event(0x28, 0x45, 0x0001 | 0, 0); keybd_event(0x28, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bright")) { keybd_event(0x27, 0x45, 0x0001 | 0, 0); keybd_event(0x27, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf1")) { keybd_event(0x70, 0x45, 0x0001 | 0, 0); keybd_event(0x70, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf2")) { keybd_event(0x71, 0x45, 0x0001 | 0, 0); keybd_event(0x71, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf3")) { keybd_event(0x72, 0x45, 0x0001 | 0, 0); keybd_event(0x72, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf4")) { keybd_event(0x73, 0x45, 0x0001 | 0, 0); keybd_event(0x73, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf5")) { keybd_event(0x74, 0x45, 0x0001 | 0, 0); keybd_event(0x74, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf6")) { keybd_event(0x75, 0x45, 0x0001 | 0, 0); keybd_event(0x75, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf7")) { keybd_event(0x76, 0x45, 0x0001 | 0, 0); keybd_event(0x76, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf8")) { keybd_event(0x77, 0x45, 0x0001 | 0, 0); keybd_event(0x77, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf9")) { keybd_event(0x78, 0x45, 0x0001 | 0, 0); keybd_event(0x78, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf10")) { keybd_event(0x79, 0x45, 0x0001 | 0, 0); keybd_event(0x79, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf11")) { keybd_event(0x7A, 0x45, 0x0001 | 0, 0); keybd_event(0x7A, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bf12")) { keybd_event(0x7B, 0x45, 0x0001 | 0, 0); keybd_event(0x7B, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bprint")) { keybd_event(0x2C, 0x45, 0x0001 | 0, 0); keybd_event(0x2C, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bscroll")) { keybd_event(0x91, 0x45, 0x0001 | 0, 0); keybd_event(0x91, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bpause")) { keybd_event(0x13, 0x45, 0x0001 | 0, 0); keybd_event(0x13, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("binsert")) { keybd_event(0x2D, 0x45, 0x0001 | 0, 0); keybd_event(0x2D, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bhome")) { keybd_event(0x24, 0x45, 0x0001 | 0, 0); keybd_event(0x24, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bpageup")) { keybd_event(0x21, 0x45, 0x0001 | 0, 0); keybd_event(0x21, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bdelete")) { keybd_event(0x2E, 0x45, 0x0001 | 0, 0); keybd_event(0x2E, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bend")) { keybd_event(0x23, 0x45, 0x0001 | 0, 0); keybd_event(0x23, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bpagedown")) { keybd_event(0x22, 0x45, 0x0001 | 0, 0); keybd_event(0x22, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bcut")) { keybd_event(0x11, 0x45, 0x0001 | 0, 0); keybd_event(0x58, 0x45, 0x0001 | 0, 0); keybd_event(0x58, 0x45, 0x0001 | 0x0002, 0); keybd_event(0x11, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bcopy")) { keybd_event(0x11, 0x45, 0x0001 | 0, 0); keybd_event(0x43, 0x45, 0x0001 | 0, 0); keybd_event(0x43, 0x45, 0x0001 | 0x0002, 0); keybd_event(0x11, 0x45, 0x0001 | 0x0002, 0); } else if (str.Equals("bpaste")) { keybd_event(0x11, 0x45, 0x0001 | 0, 0); keybd_event(0x56, 0x45, 0x0001 | 0, 0); keybd_event(0x56, 0x45, 0x0001 | 0x0002, 0); keybd_event(0x11, 0x45, 0x0001 | 0x0002, 0); } } private static void mouse(String sp) { double x = Cursor.Position.X; double y = Cursor.Position.Y; int prev = 0, i; double tempx = 0.0, tempy = 0.0; for (i = 0; i < sp.Length; i++) { if (sp[i] == '$') { tempx = double.Parse(sp.Substring(prev, i - prev)); prev = i; } else if (sp[i] == '*') { tempy = double.Parse(sp.Substring(prev + 1, i - prev - 1)); prev = i; } } str = sp.Substring(prev + 1, i - prev - 1); tempx /= 6; tempy /= 6; for (i = 1; i <= 80; i++) { Cursor.Position = new Point((int)(x + tempx), (int)(y + tempy)); } if (str.Equals("lc")) { mouse_event(0x02, 0, 0, 0, 0); mouse_event(0x04, 0, 0, 0, 0); fl = 0; } else if (str.Equals("rc")) { mouse_event(0x08, 0, 0, 0, 0); mouse_event(0x10, 0, 0, 0, 0); fr = 0; } else if (str.Equals("mc")) { mouse_event(0x20, 0, 0, 0, 0); mouse_event(0x40, 0, 0, 0, 0); fm = 0; } else if (str.Equals("ll") && fl == 0) { mouse_event(0x02, 0, 0, 0, 0); fl = 1; } else if (str.Equals("null")) { if (fl == 1) mouse_event(0x04, 0, 0, 0, 0); if (fr == 1) mouse_event(0x10, 0, 0, 0, 0); if (fm == 1) mouse_event(0x40, 0, 0, 0, 0); } } private void SetText(String text) { if (this.status.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.status.Text = text; } } private void notifyIcon2_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { } private void notifyIcon2_BalloonTipClicked(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } private void openToolStripMenuItem_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { flag = false; this.th.Abort(); Environment.Exit(0); } private void ipbutton_Click(object sender, EventArgs e) { string ss = ""; /* foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ss += ip.Address.ToString() + "\n"; } } } }*/ IPHostEntry ll = Dns.GetHostByName(Dns.GetHostName()); ss = ll.HostName + "\n"; foreach (IPAddress address in ll.AddressList) ss += address.ToString() + "\n"; MessageBox.Show(ss); } private void vlcbutton_Click(object sender, EventArgs e) { foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle.EndsWith("VLC media player")) { p.Kill(); } } int check = 0; int vlccheck = 0; try { System.Diagnostics.Process.Start("C:\\Program Files\\VideoLAN\\VLC\\vlc.exe", "--reset-config --reset-plugins-cache vlc://quit"); } catch (Exception vv) { vlccheck = 1; } if (vlccheck == 1) { try { System.Diagnostics.Process.Start("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe", "--reset-config --reset-plugins-cache vlc://quit"); } catch (Exception vv) { check = 1; } } //MessageBox.Show(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu)); string roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); vlccheck = 0; try { File.WriteAllText("C:\\Program Files (x86)\\VideoLAN\\VLC\\http\\.hosts", "127.0.0.1\n" + ipaddr); } catch (Exception e1) { vlccheck = 1; } if (vlccheck == 1) { vlccheck = 0; try { File.WriteAllText("C:\\Program Files\\VideoLAN\\VLC\\http\\.hosts", "127.0.0.1\n" + ipaddr); } catch (Exception e1) { vlccheck = 1; } } if (vlccheck == 1) { try { File.WriteAllText("C:\\Program Files\\VideoLAN\\VLC\\lua\\http\\.hosts", "127.0.0.1\n" + ipaddr); } catch (Exception e1) { vlccheck = 1; } } if (check == 0) MessageBox.Show("Configuration Successfull"); else { try { Directory.Delete(roaming + "\\vlc"); } catch (Exception e1) { } try { System.Diagnostics.Process.Start("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"); } catch (Exception e1) { } try { System.Diagnostics.Process.Start("C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"); } catch (Exception e1) { } foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle.EndsWith("VLC media player")) { p.Kill(); } } } StringBuilder newFile = new StringBuilder(); string temp = ""; try { string[] file = File.ReadAllLines(roaming + "\\vlc\\vlcrc"); foreach (string line in file) { if (line.Contains("#http-password=")) { temp = line.Replace("#http-password=", "http-password=<PASSWORD>"); newFile.Append(temp + "\r\n"); } if (line.Contains("#extraintf=")) { temp = line.Replace("#extraintf=", "extraintf=http"); newFile.Append(temp + "\r\n"); } newFile.Append(line + "\r\n"); } File.WriteAllText(roaming + "\\vlc\\vlcrc", newFile.ToString()); } catch (Exception e1) { } } private void okbutton_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; TrayMinimizerForm_Resize(); } private void notifyIcon2_MouseClick(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Normal) this.WindowState = FormWindowState.Minimized; } private void tabControl1_TabIndexChanged(object sender, EventArgs e) { } private void applybutton_Click(object sender, EventArgs e) { Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (config.AppSettings.Settings["tcp"] != null) config.AppSettings.Settings.Remove("tcp"); config.AppSettings.Settings.Add("tcp", tcpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); if (config.AppSettings.Settings["udp"] != null) config.AppSettings.Settings.Remove("udp"); config.AppSettings.Settings.Add("udp", udpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); if (stopbutton.Enabled == true) { server.Close(); tcp.Server.Close(); tcp.Stop(); flag = false; this.th.Abort(); flag = true; server = new UdpClient((int)udpport.Value); tcp = new TcpListener(IPAddress.Any, (int)tcpport.Value); tcp.Start(); this.th = new Thread(new ThreadStart(ThreadProc)); this.th.Start(); } MessageBox.Show("Ports saved successfully"); } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (tabControl1.SelectedTab == tabPage2) { if (config.AppSettings.Settings["tcp"] == null) { tcpport.Value = 9999; config.AppSettings.Settings.Add("tcp", tcpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { tcpport.Value = Convert.ToInt64(config.AppSettings.Settings["tcp"].Value); } if (config.AppSettings.Settings["udp"] == null) { udpport.Value = 8888; config.AppSettings.Settings.Add("udp", udpport.Value.ToString()); config.Save(ConfigurationSaveMode.Modified); } else { udpport.Value = Convert.ToInt64(config.AppSettings.Settings["udp"].Value); } } if (tabControl1.SelectedTab == tabPage3) { if (config.AppSettings.Settings["checkbox"] == null) { passwordcheck.Checked = false; config.AppSettings.Settings.Add("checkbox", "0"); config.Save(ConfigurationSaveMode.Modified); } else { if (config.AppSettings.Settings["checkbox"].Value.Equals("1")) { passwordcheck.Checked = true; } else passwordcheck.Checked = false; } if (passwordcheck.Checked == true) { textbox_password.Enabled = true; } else textbox_password.Enabled = false; if (config.AppSettings.Settings["password"] == null) { textbox_password.Text = ""; config.AppSettings.Settings.Add("password", textbox_password.Text); config.Save(ConfigurationSaveMode.Modified); } else { textbox_password.Text = config.AppSettings.Settings["password"].Value; } } } private void button1_Click(object sender, EventArgs e) { Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (config.AppSettings.Settings["password"] != null) config.AppSettings.Settings.Remove("password"); config.AppSettings.Settings.Add("password", textbox_password.Text); config.Save(ConfigurationSaveMode.Modified); if (config.AppSettings.Settings["checkbox"] != null) config.AppSettings.Settings.Remove("checkbox"); if (passwordcheck.Checked == true) config.AppSettings.Settings.Add("checkbox", "1"); else config.AppSettings.Settings.Add("checkbox", "0"); config.Save(ConfigurationSaveMode.Modified); MessageBox.Show("Settings saved successfully"); } private void passwordcheck_CheckedChanged(object sender, EventArgs e) { if (passwordcheck.Checked == true) textbox_password.Enabled = true; else textbox_password.Enabled = false; } } }
9ffb4247578d4df861d83e97d389f1e8bc8a4b83
[ "C#" ]
1
C#
Shahrukh931/WifiPCRemote_Server
65aa3d9519fcb33ea7ce44476546e83a20041540
5628ce3be3ed9ac0d31aac57f312541ad6895f44
refs/heads/master
<repo_name>rotorlab/chappy-android-sample<file_sep>/app/src/main/java/com/rotor/chappy/activities/chat/ChatActivity.java package com.rotor.chappy.activities.chat; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.makeramen.roundedimageview.RoundedImageView; import com.nostra13.universalimageloader.core.ImageLoader; import com.rotor.chappy.R; import com.rotor.chappy.activities.chat_detail.ChatDetailActivity; import com.rotor.chappy.model.Chat; import com.rotor.chappy.model.Member; import com.rotor.chappy.model.Message; import com.rotor.chappy.model.User; import com.rotor.chappy.model.mpv.ProfilesView; import com.rotor.core.Rotor; import com.rotor.notifications.Notifications; import org.apache.commons.lang3.StringEscapeUtils; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class ChatActivity extends AppCompatActivity implements ChatInterface.View<Chat>, ProfilesView { private RecyclerView messageList; private Chat chat; private Button sendButton; private EditText messageText; private String path; private static final Map<String, User> users = new HashMap<>(); private ChatPresenter<Chat> presenter; private FirebaseAuth mAuth = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.rotor.chappy.R.layout.activity_chat); Toolbar toolbar = findViewById(com.rotor.chappy.R.id.toolbar); setSupportActionBar(toolbar); presenter = new ChatPresenter<>(this, this); mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() == null) { finish(); } Intent intent = getIntent(); path = "/chats/" + intent.getStringExtra("path").replaceAll(" ", "_"); messageList = findViewById(com.rotor.chappy.R.id.messages_list); final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); linearLayoutManager.setReverseLayout(true); messageList.setLayoutManager(linearLayoutManager); messageList.setAdapter(new MessageAdapter()); messageText = findViewById(com.rotor.chappy.R.id.message_text); messageText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { handled = true; if (messageText.length() > 0) { sendButton.performClick(); } } return handled; } }); sendButton = findViewById(com.rotor.chappy.R.id.send_button); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mAuth.getCurrentUser() != null && mAuth.getCurrentUser().getUid() != null) { Message message = new Message(mAuth.getCurrentUser().getUid(), StringEscapeUtils.escapeJava(messageText.getText().toString())); chat.getMessages().put(String.valueOf(new Date().getTime()), message); presenter.sync(path); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { messageText.setText(""); sendButton.setEnabled(messageText.length() > 0); } }, 100); } } }); messageText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { sendButton.setEnabled(s.toString().length() > 0 && chat != null); } @Override public void afterTextChanged(Editable s) { } }); sendButton.setEnabled(messageText.getText().toString().length() > 0 && chat != null); FloatingActionButton fab = findViewById(com.rotor.chappy.R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); Notifications.remove(intent.getStringExtra("path")); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_chat, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_remove) { presenter.remove(path); return true; } else if (id == R.id.action_detail) { Intent intent = new Intent(this, ChatDetailActivity.class); intent.putExtra("path", chat.getId()); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); Rotor.onResume(); presenter.onResumeView(); presenter.prepareFor(path, Chat.class); sendButton.setEnabled(messageText.getText().toString().length() > 0 && chat != null); } @Override protected void onPause() { presenter.onPauseView(); Rotor.onPause(); super.onPause(); } @Override public void onCreateReference() { finish(); } @Override public void onReferenceChanged(Chat chat) { ChatActivity.this.chat = chat; for (Map.Entry<String, Member> entry : chat.getMembers().entrySet()) { if (!users.containsKey("/users/" + entry.getValue().getId())) { presenter.prepareProfileFor("/users/" + entry.getValue().getId()); } } ChatActivity.this.setTitle(chat.getName()); Map<String, Message> messageMap = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { Long a = Long.valueOf(o1); Long b = Long.valueOf(o2); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } }); messageMap.putAll(chat.getMessages()); chat.setMessages(messageMap); messageList.getAdapter().notifyDataSetChanged(); messageList.smoothScrollToPosition(0); sendButton.setEnabled(messageText.toString().length() > 0); } @Override public Chat onUpdateReference() { return ChatActivity.this.chat; } @Override public void onDestroyReference() { chat = null; finish(); } @Override public void progress(int value) { } @Override public void onCreateUser(String key) { // should be called } @Override public void onUserChanged(String key, User user) { users.put(key, user); messageList.getAdapter().notifyDataSetChanged(); messageList.smoothScrollToPosition(0); } @Override public User onUpdateUser(String key) { return users.get(key); } @Override public void onDestroyUser(String key) { users.remove(key); } @Override public void userProgress(String key, int value) { // nothing to do here } public class MessageAdapter extends RecyclerView.Adapter<VHMessages> { private MessageAdapter() { // nothing to do here } @Override @NonNull public VHMessages onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false); return new VHMessages(itemView); } @Override public void onBindViewHolder(@NonNull VHMessages holder, int position) { List<String> messages = new ArrayList<>(); for (Map.Entry<String, Message> entry : chat.getMessages().entrySet()) { messages.add(entry.getKey()); } Message message = chat.getMessages().get(messages.get((messages.size() - 1) - position)); if (users.containsKey("/users/" + message.getAuthor())) { User user = users.get("/users/" + message.getAuthor()); holder.author.setText(user.getName() + ":"); holder.message.setText(StringEscapeUtils.unescapeJava(message.getText())); if (presenter.getLoggedUid() != null) { } ImageLoader.getInstance().displayImage(user.getPhoto(), holder.image); } } @Override public int getItemCount() { if (chat == null || chat.getMessages() == null) { return 0; } else { return chat.getMessages().size(); } } } static class VHMessages extends RecyclerView.ViewHolder { RelativeLayout content; RoundedImageView image; TextView author; TextView message; VHMessages(View itemView) { super(itemView); content = itemView.findViewById(R.id.message_content); image = itemView.findViewById(R.id.image); author = itemView.findViewById(R.id.author); message = itemView.findViewById(R.id.message); } } } <file_sep>/app/src/main/java/com/rotor/chappy/model/mpv/ReferenceView.java package com.rotor.chappy.model.mpv; public interface ReferenceView<T> { void onCreateReference(); void onReferenceChanged(T chat); T onUpdateReference(); void onDestroyReference(); void progress(int value); } <file_sep>/database/src/main/java/com/rotor/database/request/UpdateFromServer.kt package com.rotor.database.request /** * Created by efraespada on 11/03/2018. */ data class UpdateFromServer( val method: String, val database: String, val path: String, val token: String, val os: String, val content: String)<file_sep>/database/src/main/java/com/rotor/database/utils/ReferenceUtils.kt package com.rotor.database.utils import android.content.ContentValues import android.database.sqlite.SQLiteException import com.rotor.core.Rotor import com.rotor.database.Docker import com.rotor.database.Docker.Companion.COLUMN_DATA import com.rotor.database.Docker.Companion.COLUMN_ID import com.rotor.database.interfaces.Server import com.stringcare.library.SC import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.math.BigInteger /** * Created by efraespada on 14/03/2018. */ class ReferenceUtils { companion object { var docker: Docker? = null private val VERSION = 1 private val TABLE_NAME = "ref" fun addElement(path: String, info: String) { if (docker == null) { val name = "RealtimeDatabase.db" docker = Docker(Rotor.context!!, name, TABLE_NAME, VERSION) } try { val enId = SC.encryptString(path) val db = docker!!.getWritableDatabase() val values = ContentValues() values.put(COLUMN_ID, enId) values.put(COLUMN_DATA, SC.encryptString(info)) if (exist(path)) { val selection = COLUMN_ID + " = ?" val selectionArgs = arrayOf<String>(enId) db.update(docker!!.table, values, selection, selectionArgs).toLong() } else { db.insert(docker!!.table, null, values) } } catch (e: SQLiteException) { e.printStackTrace() } } fun exist(path: String): Boolean { if (docker == null) { val name = "RealtimeDatabase.db" docker = Docker(Rotor.context!!, name, TABLE_NAME, VERSION) } val enPath = SC.encryptString(path) try { val db = docker!!.getReadableDatabase() // Define a projection that specifies which columns from the database // you will actually use after this query. val projection = arrayOf(COLUMN_ID, COLUMN_DATA) // Filter results WHERE "title" = hash val selection = "$COLUMN_ID = ?" val selectionArgs = arrayOf(enPath) val cursor = db.query( docker!!.table, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, null, null, null )// The values for the WHERE clause // don't group the rows val exists = cursor.getCount() > 0 cursor.close() //database.close(); return exists } catch (e: SQLiteException) { e.printStackTrace() return false } } fun removeElement(path: String) { if (docker == null) { val name = "RealtimeDatabase.db" docker = Docker(Rotor.context!!, name, TABLE_NAME, VERSION) } val enPath = SC.encryptString(path) try { val db = docker!!.getReadableDatabase() val selection = "$COLUMN_ID = ?" val selectionArgs = arrayOf(enPath) db.delete( docker!!.table, // The table to query selection, // The columns for the WHERE clause selectionArgs // The values for the WHERE clause ) } catch (e: SQLiteException) { e.printStackTrace() } } /** * returns stored object * @param path * @return String */ fun getElement(path: String): String? { if (docker == null) { val name = "RealtimeDatabase.db" docker = Docker(Rotor.context!!, name, TABLE_NAME, VERSION) } val enPath = SC.encryptString(path) try { val db = docker!!.getReadableDatabase() val projection = arrayOf(COLUMN_ID, COLUMN_DATA) val selection = "$COLUMN_ID = ?" val selectionArgs = arrayOf(enPath) val cursor = db.query( docker!!.table, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, null, null, null// The sort order )// The values for the WHERE clause // don't group the rows // don't filter by row groups var info: String? = null while (cursor.moveToNext()) { info = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_DATA)) } cursor.close() return if (info != null) { SC.decryptString(info) } else { null } } catch (e: SQLiteException) { return null } } private fun string2Hex(data: ByteArray): String { return BigInteger(1, data).toString(16) } fun hex2String(value: String): String { return String(BigInteger(value, 16).toByteArray()) } fun service(url: String): Server { val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(url) .build() return retrofit.create(Server::class.java) } } }<file_sep>/notifications/src/main/java/com/rotor/notifications/interfaces/Listener.kt package com.rotor.notifications.interfaces import com.rotor.notifications.model.Notification /** * Created by efraespada on 25/03/2018. */ interface Listener { fun opened(deviceId: String, notification: Notification) fun removed(notification: Notification) }<file_sep>/database/src/main/java/com/rotor/database/models/PrimaryReferece.kt package com.rotor.database.models import android.content.Context import com.efraespada.jsondiff.JSONDiff import com.google.gson.Gson import com.google.gson.GsonBuilder import com.rotor.core.Rotor import com.rotor.database.Database import com.rotor.database.Docker import com.rotor.database.utils.ReferenceUtils import com.stringcare.library.SC import org.json.JSONException import org.json.JSONObject import java.text.Normalizer import java.util.* /** * Created by efraespada on 14/03/2018. */ abstract class PrimaryReferece<T>(context: Context, db: String, path: String) { companion object { internal var EMPTY_OBJECT = "{}" internal var OS = "android" internal var ACTION_SIMPLE_UPDATE = "simple_update" internal var ACTION_SLICE_UPDATE = "slice_update" internal var ACTION_NO_UPDATE = "no_update" internal var ACTION_SIMPLE_CONTENT = "simple_content" internal var ACTION_SLICE_CONTENT = "slice_content" internal var ACTION_NO_CONTENT = "no_content" internal var ACTION_NEW_OBJECT = "new_object" internal var ACTION_REFERENCE_REMOVED = "reference_removed" internal var STAG = "tag" internal var PATH = "id" internal var SHA1 = "sha1" internal var REFERENCE = "reference" internal var SIZE = "size" internal var INDEX = "index" internal var ACTION = "action" internal var NULL = "null" } private val mapParts: HashMap<String, Array<String?>> var database: Docker? = null private val context: Context protected var gson: Gson var serverLen: Int = 0 var moment: Long ? = null var databaseName: String protected var path: String protected var stringReference: String? = null private val TAG = KReference::class.java.simpleName protected val blowerMap = HashMap<Long, T>() init { this.context = context this.databaseName = db this.path = path this.gson = getGsonBuilder() this.serverLen = 0 SC.init(this.context) this.mapParts = HashMap() this.stringReference = ReferenceUtils.getElement(path) } /** * notify update percent */ abstract fun getLastest(): T abstract fun progress(value: Int) // abstract fun addBlower(creation: Long, blower: *) /** * tag or identifier used to identify incoming object updates * from server cluster * * @return String */ fun getTag(): String { return path + "_sync" } /** * returns actual reference in string format * @return String */ abstract fun getReferenceAsString(): String /** * removes cached reference */ abstract fun remove() /** * loads stored JSON object on db. if not exists, * gets current reference and stores * */ abstract fun loadCachedReference() /** * returns the result of applying differences to current JSON object * after being stored on local DB * @param value */ abstract fun blowerResult(value: String) private fun getGsonBuilder(): Gson { return GsonBuilder() .excludeFieldsWithoutExposeAnnotation().create() } fun getDifferences(clean: Boolean): Array<Any?> { val len: Int val objects = arrayOfNulls<Any>(2) if (clean || stringReference == null) { this.stringReference = "{}" } try { val actual = getReferenceAsString() JSONDiff.setDebug(Rotor.debug!!) val diff = JSONDiff.diff(JSONObject(stringReference), JSONObject(actual)) val jsonObject = JSONObject() // max 3 for ((key, value) in diff) { jsonObject.put(key, value) } len = actual.length objects[0] = len objects[1] = jsonObject.toString() return objects } catch (e: JSONException) { e.printStackTrace() } return objects } fun onMessageReceived(json: JSONObject) { try { val tag = json.getString(STAG) val action = json.getString(ACTION) val data = if (json.has(REFERENCE)) json.getString(REFERENCE) else null val path = json.getString(PATH) val rData = if (data == null) "{}" else ReferenceUtils.hex2String(data) if (!tag.equals(getTag(), ignoreCase = true)) { return } when (action) { ACTION_SIMPLE_UPDATE -> { val sha1 = json.getString(SHA1) parseUpdateResult(path, rData, sha1) } ACTION_SLICE_UPDATE -> { val size = json.getInt(SIZE) val index = json.getInt(INDEX) val sha1 = json.getString(SHA1) if (mapParts.containsKey(path)) { mapParts[path]!![index] = rData } else { val parts = arrayOfNulls<String>(size) parts[index] = rData mapParts[path] = parts } var ready = true var alocated = 0 for (p in mapParts[path]!!.size - 1 downTo 0) { if (mapParts[path]!![p] == null) { ready = false } else { alocated++ } } val percent = 100f / size.toFloat() * alocated progress(percent.toInt()) if (ready && mapParts[path]!!.size - 1 == index) { val complete = StringBuilder() for (i in 0 until mapParts[path]!!.size) { complete.append(mapParts[path]!![i]) } mapParts.remove(path) val result = complete.toString() parseUpdateResult(path, result, sha1) } } ACTION_NO_UPDATE -> blowerResult(stringReference!!) ACTION_SIMPLE_CONTENT -> parseContentResult(path, rData) ACTION_SLICE_CONTENT -> { val sizeContent = json.getInt(SIZE) val indexContent = json.getInt(INDEX) if (mapParts.containsKey(path)) { mapParts[path]!![indexContent] = rData } else { val partsContent = arrayOfNulls<String>(sizeContent) partsContent[indexContent] = rData mapParts[path] = partsContent } var readyContent = true var alocatedContent = 0 for (p in mapParts[path]!!.size - 1 downTo 0) { if (mapParts[path]!![p] == null) { readyContent = false } else { alocatedContent++ } } val percentContent = 100f / sizeContent.toFloat() * alocatedContent progress(percentContent.toInt()) if (readyContent && mapParts[path]!!.size - 1 == indexContent) { val completeContent = StringBuilder() for (i in 0 until mapParts[path]!!.size) { completeContent.append(mapParts[path]!![i]) } mapParts.remove(path) val resultContent = completeContent.toString() parseContentResult(path, resultContent) } } ACTION_NO_CONTENT -> blowerResult("{}") else -> { } }// nothing to do here .. //Log.e(TAG, data); } catch (e: Exception) { e.printStackTrace() } } private fun parseUpdateResult(path: String, data: String, sha1: String) { try { val jsonObject: JSONObject var prev: String? = getReferenceAsString() if (prev != null) { prev = Normalizer.normalize(prev, Normalizer.Form.NFC) jsonObject = JSONObject(prev) } else { jsonObject = JSONObject() } val differences = JSONObject(data) if (differences.has("\$unset")) { val set = differences.getJSONObject("\$unset") val keys = set.keys() while (keys.hasNext()) { val key = keys.next() val p = key.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var aux = jsonObject for (w in p.indices) { val currentIndex = p[w] if (aux.has(currentIndex) && w != p.size - 1) { aux = aux.getJSONObject(currentIndex) } else if (w != p.size - 1) { aux.put(currentIndex, JSONObject()) aux = aux.getJSONObject(currentIndex) } if (w == p.size - 1 && aux.has(currentIndex)) { aux.remove(currentIndex) } } } } if (differences.has("\$set")) { val set = differences.getJSONObject("\$set") val keys = set.keys() while (keys.hasNext()) { val key = keys.next() val p = key.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var aux = jsonObject for (w in p.indices) { val currentIndex = p[w] if (aux.has(currentIndex) && w != p.size - 1) { aux = aux.getJSONObject(currentIndex) } else if (w != p.size - 1) { aux.put(currentIndex, JSONObject()) aux = aux.getJSONObject(currentIndex) } if (w == p.size - 1) { if (aux.has(currentIndex)) { if (aux.get(currentIndex) is JSONObject) { try { aux = aux.getJSONObject(currentIndex) val toExport = set.getJSONObject(key) val y = toExport.keys() while (y.hasNext()) { val k = y.next() aux.put(k, toExport.get(k)) } } catch (e: Exception) { aux.put(currentIndex, set.get(key)) } } else { aux.put(currentIndex, set.get(key)) } } else { try { // test if element to save is JSON object var cached = set.getJSONObject(key).toString() cached = Normalizer.normalize(cached, Normalizer.Form.NFC) val `object` = JSONObject(cached) aux.put(currentIndex, `object`) } catch (e: Exception) { aux.put(currentIndex, set.get(key)) } } } } } } stringReference = jsonObject.toString() ReferenceUtils.addElement(path, stringReference!!) if (sha1.equals(Database.sha1(stringReference!!))) { blowerResult(stringReference!!) } else { Database.refreshFromServer(path, stringReference!!) } } catch (e: JSONException) { e.printStackTrace() } } /** * updates current string object with incoming data * @param path * @param data */ private fun parseContentResult(path: String, data: String) { ReferenceUtils.addElement(path, data) stringReference = data blowerResult(stringReference!!) } }<file_sep>/README.md <p align="center"><img width="10%" vspace="20" src="https://github.com/rotorlab/chappy-android-sample/raw/develop/app/src/main/res/mipmap-xxxhdpi/ic_launcher_rounded.png"></p> Chappy: sample of real-time changes ------------------------------------------- Sample app of the use of Rotor libraries (Core and Database). Clone the repo and open the project in Android Studio: ```bash git clone https://github.com/rotorlab/chappy-android-sample.git ``` ### Datamodel sample ```java public class Chat { @SerializedName("name") @Expose String name; @SerializedName("members") @Expose Map<String, Member> members; @SerializedName("messages") @Expose Map<String, Message> messages; public Chat(String name, Map<String, Member> members, Map<String, Message> messages) { this.name = name; this.members = members; this.messages = messages; } /* getter and setter methods */ } ``` ### Interaction sample Define a chat listener and add messages: ```java private Chat chat; class ChatActivity .. @Override protected void onCreate(Bundle savedInstanceState) { final String path = "/chats/welcome_chat"; /* object instances, list adapter, etc.. */ Database.listen(path, new Reference<Chat>(Chat.class) { @Override public void onCreate() { chat = new Chat(); chat.setTitle("Foo Chat"); Database.sync(path); } @Override public Chat onUpdate() { return chat; } @Override public void onChanged(Chat chat) { ChatActivity.this.chat = chat; // update screent title ChatActivity.this.setTitle(chat.getName()); // order messages Map<String, Message> messageMap = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { Long a = Long.valueOf(o1); Long b = Long.valueOf(o2); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } }); messageMap.putAll(ChatActivity.this.chat.getMessages()); ChatActivity.this.chat.setMessages(messageMap); // update list messageList.getAdapter().notifyDataSetChanged(); messageList.smoothScrollToPosition(0); } @Override public void progress(int value) { // print progress } }); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE); String username = prefs.getString("username", null); if (name != null) { Message message = new Message(username, messageText.getText().toString()); chat.getMessages().put(String.valueOf(new Date().getTime()), message); Database.sync(path); messageText.setText(""); } } }); } ``` You can do changes or wait for them. All devices listening the same object will receive this changes to stay up to date: <p align="center"><img width="30%" vspace="20" src="https://github.com/rotorlab/chappy-android-sample/raw/develop/sample1.png"></p> License ------- Copyright 2018 RotorLab Organization Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>/app/src/main/java/com/rotor/chappy/model/Message.java package com.rotor.chappy.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by efraespada on 04/06/2017. */ public class Message { @SerializedName("author") @Expose String author; @SerializedName("text") @Expose String text; public Message(String author, String text) { this.author = author; this.text = text; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getText() { return text; } public void setText(String text) { this.text = text; } } <file_sep>/notifications/src/main/java/com/rotor/notifications/NotificationRouterActivity.kt package com.rotor.notifications import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.rotor.core.Rotor /** * Created by efraespada on 23/03/2018. */ abstract class NotificationRouterActivity : AppCompatActivity() { var enter: Boolean ? = false interface NotificationsStatus { fun ready() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enter = true var requestCode : Int ? = null var id : String ? = null var room : String ? = null if (intent.hasExtra(Notifications.ID)) { id = intent.getStringExtra(Notifications.ID) if (id == null){ id = "" } } if (intent.hasExtra(Notifications.RC)) { requestCode = intent.getIntExtra(Notifications.RC, 0) } if (intent.hasExtra(Notifications.ROOM)) { room = intent.getStringExtra(Notifications.ROOM) if (room == null){ room = "" } } Notifications.listener(object : NotificationsStatus { override fun ready() { if (enter != null && enter as Boolean) { notificationTouched(requestCode!!, id!!, room!!) } enter = false } }) onCreate() } abstract fun notificationTouched(action: Int, id: String, room: String) abstract fun onCreate() override fun onResume() { super.onResume() Rotor.onResume() } override fun onPause() { Rotor.onPause() super.onPause() } }<file_sep>/core/src/main/java/com/rotor/core/interfaces/BuilderFace.kt package com.rotor.core.interfaces import org.json.JSONObject /** * Created by efraespada on 12/03/2018. */ public interface BuilderFace { fun onMessageReceived(jsonObject: JSONObject) }<file_sep>/notifications/src/main/java/com/rotor/notifications/model/Receiver.java package com.rotor.notifications.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by efraespada on 19/03/2018. */ public class Receiver { @SerializedName("id") @Expose String id; @SerializedName("viewed") @Expose Long viewed; public Receiver() { // nothing to do here } public Receiver(String id, Long viewed) { this.id = id; this.viewed = viewed; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getViewed() { return viewed; } public void setViewed(Long viewed) { this.viewed = viewed; } } <file_sep>/database/src/main/java/com/rotor/database/response/SyncResponse.kt package com.rotor.database.request import org.json.JSONObject /** * Created by efraespada on 11/03/2018. */ data class SyncResponse(val status: String, val data: JSONObject, val error: String)<file_sep>/database/src/main/java/com/rotor/database/Docker.kt package com.rotor.database import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper /** * Created by efraespada on 14/03/2018. */ class Docker(context: Context, name: String, table: String, version: Int) : SQLiteOpenHelper(context, name, null, version) { companion object { val COLUMN_ID = "id_hash" val COLUMN_DATA = "data" } var dbName: String var table: String init { this.dbName = name this.table = table } override fun onCreate(db: SQLiteDatabase?) { val SQL_CREATE_ENTRIES = "CREATE TABLE " + table + " (" + COLUMN_ID + " TEXT PRIMARY KEY, " + COLUMN_DATA + " TEXT);" db?.execSQL(SQL_CREATE_ENTRIES) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { try { val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS $table" db?.execSQL(SQL_DELETE_ENTRIES) } catch (e: SQLiteException) { e.printStackTrace() } finally { onCreate(db) } } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { onUpgrade(db, oldVersion, newVersion) } }<file_sep>/database/src/main/java/com/rotor/database/abstr/Reference.kt package com.rotor.database.abstr import android.support.annotation.NonNull import android.support.annotation.Nullable /** * Created by efraespada on 14/03/2018. */ abstract class Reference<T>(clazz: Class<T>) { val clazz: Class<T> init { this.clazz = clazz } abstract fun onCreate() @Nullable abstract fun onUpdate() : T ? abstract fun onChanged(@NonNull ref: T) abstract fun onDestroy() abstract fun progress(value: Int) fun clazz() : Class<T> { return clazz } }<file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'io.fabric' android { compileSdkVersion 27 buildToolsVersion '27.0.3' defaultConfig { applicationId "com.rotor.chappy" minSdkVersion 21 targetSdkVersion 27 versionCode 2 versionName "1.1" multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } flavorDimensions "origin" buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { emulator { applicationId "com.rotor.chappy" versionNameSuffix "-emulator" buildConfigField "String", "database_url", "\"http://10.0.2.2:1508/\"" buildConfigField "String", "redis_url", "\"redis://10.0.2.2\"" dimension "origin" } device { applicationId "com.rotor.chappy" versionNameSuffix "-device" buildConfigField "String", "database_url", "\"http://192.168.1.130:1508/\"" buildConfigField "String", "redis_url", "\"redis://192.168.1.130\"" dimension "origin" } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.0' implementation 'com.android.support:design:27.1.1' testImplementation 'junit:junit:4.12' implementation 'com.afollestad.material-dialogs:core:0.9.6.0' implementation 'com.google.firebase:firebase-core:16.0.0' implementation 'com.google.firebase:firebase-auth:16.0.1' implementation 'com.firebaseui:firebase-ui-auth:3.3.1' implementation 'com.google.android.gms:play-services-auth:15.0.1' implementation 'com.crashlytics.sdk.android:crashlytics:2.9.3' implementation 'com.makeramen:roundedimageview:2.3.0' implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' implementation 'org.apache.commons:commons-lang3:3.6' implementation 'com.efraespada:motiondetector:0.0.3' implementation 'me.dm7.barcodescanner:zxing:1.9.2' implementation 'com.github.kenglxn.QRGen:android:2.2.0' implementation('com.github.KingsMentor:MobileVisionBarcodeScanner:v1.2') { transitive = true } implementation 'com.google.android.gms:play-services-vision:15.0.2' implementation "com.stringcare:library:$stringcare_version" implementation 'com.google.code.gson:gson:2.8.2' implementation("com.mikepenz:materialdrawer:6.0.7@aar") { transitive = true } implementation "com.android.support:appcompat-v7:27.1.1" implementation "com.android.support:recyclerview-v7:27.1.1" implementation "com.android.support:support-annotations:27.1.1" implementation "com.android.support:design:27.1.1" implementation "com.mikepenz:iconics-core:3.0.4@aar" implementation "com.mikepenz:iconics-views:3.0.4@aar" implementation 'com.mikepenz:google-material-typeface:3.0.1.2.original@aar' implementation 'com.mikepenz:material-design-iconic-typeface:2.2.0.4@aar' implementation 'com.mikepenz:community-material-typeface:2.0.46.1@aar' implementation ('com.rotor:core:0.3@aar') { transitive = true } implementation ('com.rotor:database:0.3@aar') { transitive = true } implementation ('com.rotor:notifications:0.3@aar') { transitive = true } // implementation project(":core") // implementation project(":database") // implementation project(":notifications") } apply plugin: 'com.google.gms.google-services' <file_sep>/app/src/main/java/com/rotor/chappy/model/mpv/ProfileView.java package com.rotor.chappy.model.mpv; import com.rotor.chappy.model.User; public interface ProfileView { void onCreateUser(); void onUserChanged(User user); User onUpdateUser(); void onDestroyUser(); void userProgress(int value); } <file_sep>/database/src/main/java/com/rotor/database/interfaces/QueryCallback.kt package com.rotor.database.interfaces import com.google.gson.internal.LinkedTreeMap interface QueryCallback { fun response(list: List<LinkedTreeMap<String, String>>) }<file_sep>/notifications/src/main/java/com/rotor/notifications/data/NotificationDocker.kt package com.rotor.notifications.data import com.rotor.notifications.model.Notification /** * Created by efraespada on 18/03/2018. */ class NotificationDocker() { var notifications: HashMap<String, Notification> ? = null init { notifications = HashMap() } }<file_sep>/app/src/main/java/com/rotor/chappy/ContactsListener.java package com.rotor.chappy; /** * Created by efraespada on 20/03/2018. */ public interface ContactsListener { void contactsReady(); } <file_sep>/notifications/src/main/java/com/rotor/notifications/model/Data.java package com.rotor.notifications.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by efraespada on 19/03/2018. */ public class Data { @SerializedName("room") @Expose Object data; public Data() { // nothing to do here } public Data(Object data) { this.data = data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } <file_sep>/notifications/src/main/java/com/rotor/notifications/Notifications.kt package com.rotor.notifications import android.content.Context import android.support.v4.app.NotificationCompat import com.nostra13.universalimageloader.core.ImageLoader import com.nostra13.universalimageloader.core.ImageLoaderConfiguration import com.rotor.core.Builder import com.rotor.core.Rotor import com.rotor.core.interfaces.BuilderFace import com.rotor.database.Database import com.rotor.database.abstr.Reference import com.rotor.notifications.enums.Method import com.rotor.notifications.model.* import org.json.JSONObject import java.util.* import kotlin.collections.HashMap import android.graphics.Bitmap import android.view.View import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener import android.support.v4.app.NotificationManagerCompat import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_NO_HISTORY import android.os.Build import android.util.Log import com.google.gson.Gson import com.rotor.database.utils.ReferenceUtils import com.rotor.notifications.data.NotificationDocker import com.rotor.notifications.interfaces.ClazzLoader import com.rotor.notifications.interfaces.Listener import com.rotor.notifications.interfaces.Server import com.rotor.notifications.request.NotificationGetter import com.rotor.notifications.request.NotificationSender import com.stringcare.library.SC import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import kotlin.collections.ArrayList /** * Created by efraespada on 18/03/2018. */ class Notifications { companion object { val ID = "id" val ROOM = "room" val RC = "request_code" val NOTIFICATION = "/notifications/" private var docker: NotificationDocker? = null private var listener: Listener? = null private val TAG: String = Notifications::class.java.simpleName!! private var loader: ClazzLoader<*> ? = null private var notificationStatusListener: NotificationRouterActivity.NotificationsStatus ? = null val api by lazy { service(Rotor.urlServer!!) } @JvmStatic fun <T> initialize(clazz: Class<T>, listener: Listener) { SC.init(Rotor.context) Database.initialize() loader = ClazzLoader<T>(clazz) this.listener = listener loadCachedNotifications() val config = ImageLoaderConfiguration.Builder(Rotor.context).build() ImageLoader.getInstance().init(config) Rotor.prepare(Builder.NOTIFICATION, object: BuilderFace { override fun onMessageReceived(jsonObject: JSONObject) { try { if (jsonObject.has("notifications")) { val notification = jsonObject.getJSONObject("notifications") if (notification.has("method") && notification.has("id")) { val method = notification.getString("method") if (Method.ADD.getMethod().equals(method)) { if (!docker!!.notifications!!.containsKey(notification.getString("id"))) { notify(notification.getString("id")) } } else if (Method.REMOVE.getMethod().equals(method)) { if (docker!!.notifications!!.containsKey(notification.getString("id"))) { remove(NOTIFICATION + notification.getString("id")) } } } } } catch (e: Throwable) { e.printStackTrace() } } }) if (notificationStatusListener != null) { notificationStatusListener!!.ready() } } @JvmStatic fun listener(notificationStatusListener: NotificationRouterActivity.NotificationsStatus) { this.notificationStatusListener = notificationStatusListener } private fun service(url: String): Server { val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(url) .build() return retrofit.create(Server::class.java) } @JvmStatic fun builder(content: Content ?, receivers: List<String>) : Notification { val id = Date().time val map = HashMap<String, Receiver>() for (receiver in receivers) { if (receiver.equals(Rotor.id)) { continue } map[receiver] = Receiver(receiver, null) } content?.id = id.toString() return Notification(id.toString(), id, content, Sender(Rotor.id!!, id), map) } @JvmStatic fun notify(id: String) { notify(id, null) } @JvmStatic fun notify(notification: Notification) { notify(notification.id, notification) } @JvmStatic private fun notify(id: String, notification: Notification ?) { val identifier = if (!id.contains("notifications")) NOTIFICATION + id else id Database.listen("notifications", identifier, object: Reference<Notification>(Notification::class.java) { var created = false override fun onCreate() { notification?.let { docker!!.notifications!![identifier] = notification Database.sync(identifier) Log.e(TAG, "notification added") created = true } } override fun onChanged(ref: Notification) { Log.e(TAG, "notification returned") var readCount = 0 val newOpens = ArrayList<String>() if (ref.sender.id.equals(Rotor.id)) { for (receiver in ref.receivers.values) { if (receiver.viewed != docker!!.notifications!![identifier]!!.receivers[receiver.id]!!.viewed || (receiver.viewed != null && Rotor.id.equals(receiver.id))) { newOpens.add(receiver.id) } if (receiver.viewed != null) { readCount++ } } } docker!!.notifications!![identifier] = ref val gson = Gson() ReferenceUtils.addElement(NOTIFICATION, gson.toJson(docker!!)) if (!ref.sender.id.equals(Rotor.id)) { show(identifier) } if (created) { created = false var rece: ArrayList<Receiver> = arrayListOf() rece.addAll(ref.receivers.values) sendNotification(identifier, rece) } else if (ref.receivers.containsKey(Rotor.id) && ref.receivers[Rotor.id]!!.viewed != null && !ref.sender!!.id!!.equals(Rotor.id)) { val notificationManager = NotificationManagerCompat.from(Rotor.context!!) val idNumber = ref.id.toLong() notificationManager.cancel(idNumber.toInt()) docker!!.notifications!!.remove(identifier) Database.unlisten(identifier) ReferenceUtils.addElement(NOTIFICATION, gson.toJson(docker!!)) } else if (ref.sender.id.equals(Rotor.id) && listener != null) { for (r in newOpens) { listener!!.opened(r, docker!!.notifications!![identifier]!!) } if (readCount == docker!!.notifications!![identifier]!!.receivers.size) { val notificationManager = NotificationManagerCompat.from(Rotor.context!!) val idNumber = docker!!.notifications!![identifier]!!.id.toLong() notificationManager.cancel(idNumber.toInt()) Database.remove(identifier) } } } override fun onUpdate(): Notification ? { if (docker!!.notifications!!.containsKey(identifier)) { return docker!!.notifications!!.get(identifier) } else { return null } } override fun progress(value: Int) { // nothing to do here } override fun onDestroy() { if (docker != null && docker!!.notifications != null && docker!!.notifications!!.containsKey(identifier) && docker!!.notifications!![identifier]!!.sender.id.equals(Rotor.id)) { listener?.let { it.removed(docker!!.notifications!![identifier]!!) } docker!!.notifications!!.remove(identifier) Database.unlisten(identifier) val gson = Gson() ReferenceUtils.addElement(NOTIFICATION, gson.toJson(docker!!)) } } }) } @JvmStatic fun remove(value: String) : Boolean { var deleted = false for (notification in docker!!.notifications!!.values) { if (value.equals(notification.content.room)) { if (notification.receivers.containsKey(Rotor.id)) { notification.receivers.get(Rotor.id)!!.viewed = Date().time Database.sync(NOTIFICATION + notification.id) deleted = true } } } if (!deleted) { val identifier = if (!value.contains("notifications")) NOTIFICATION + value else value if (docker!!.notifications!!.containsKey(identifier)) { docker!!.notifications!![identifier]!!.receivers.get(Rotor.id)!!.viewed = Date().time Database.sync(identifier) deleted = true } } return deleted } @JvmStatic fun show(id: String) { var identifier = if (!id.contains("notifications")) NOTIFICATION + id else id if (docker!!.notifications!!.containsKey(identifier)) { val notification = docker!!.notifications!![identifier] val content = notification!!.content content?.let { if (content.photo != null) { val imageLoader = ImageLoader.getInstance() imageLoader.loadImage(content.photo, object : SimpleImageLoadingListener() { override fun onLoadingComplete(imageUri: String, view: View, loadedImage: Bitmap) { interShow(identifier, content, loadedImage) } }) } else { interShow(identifier, content, null) } } } } private fun interShow(id: String, content: Content, bitmap: Bitmap ?) { var mBuilder: NotificationCompat.Builder ? = null if (bitmap != null) { mBuilder = NotificationCompat.Builder(Rotor.context!!, id) .setSmallIcon(R.mipmap.ic_launcher_round) .setLargeIcon(bitmap) .setContentTitle(content.title) .setContentText(content.body) .setContentIntent(intentBuilder(content)) .setStyle(NotificationCompat.BigTextStyle().bigText(content.body)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) } else { mBuilder = NotificationCompat.Builder(Rotor.context!!, id) .setSmallIcon(R.mipmap.ic_launcher_round) .setContentTitle(content.title) .setContentText(content.body) .setStyle(NotificationCompat.BigTextStyle().bigText(content.body)) .setContentIntent(intentBuilder(content)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (content.channel != null && content.channelDescription != null) { val name = content.channel val description = content.channelDescription val importance = NotificationManager.IMPORTANCE_DEFAULT var channel: NotificationChannel ? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { channel = NotificationChannel(id, name, importance) } channel!!.description = description val notificationManager = Rotor.context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager; if (notificationManager.areNotificationsEnabled()) { var found = false for (channels in notificationManager.notificationChannels) { if (channels.id.equals(id)) { found = true break } } if (!found) { notificationManager.createNotificationChannel(channel) } } } else { return } } val notificationManager = NotificationManagerCompat.from(Rotor.context!!) val idNumber = id.split("/")[2].toLong() notificationManager.notify(idNumber.toInt(), mBuilder.build()) } private fun intentBuilder(content: Content) : PendingIntent { val resultIntent = Intent(Rotor.context, loader!!.getClazz()) resultIntent.addFlags(FLAG_ACTIVITY_NO_HISTORY) resultIntent.putExtra(ID, content.id) resultIntent.putExtra(ROOM, content.room) resultIntent.putExtra(RC, content.requestCode) val resultPendingIntent = PendingIntent.getActivity(Rotor.context, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT); return resultPendingIntent } @JvmStatic private fun loadCachedNotifications() { val notificationsAsString: String ? = ReferenceUtils.getElement(NOTIFICATION) if (notificationsAsString == null) { docker = NotificationDocker() } else { val gson = Gson() docker = gson.fromJson(notificationsAsString, NotificationDocker::class.java) as NotificationDocker for (notification in docker!!.notifications!!.values) { for (receiver in notification.receivers.values) { if (receiver.id.equals(Rotor.id) && receiver.viewed == null) { notify(notification.id) } } if (notification.sender.id.equals(Rotor.id, true)) { notify(notification.id) } } } getPendingNotification() } @JvmStatic private fun sendNotification(id: String, receivers: ArrayList<Receiver>) { api.sendNotification(NotificationSender("send_notifications", Rotor.id, id, receivers)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } @JvmStatic private fun getPendingNotification() { val receivers: ArrayList<String> = ArrayList() receivers.add(Rotor.id!!) api.getNotifications(NotificationGetter("pending_notifications", Rotor.id, receivers)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } } } <file_sep>/database/src/main/java/com/rotor/database/interfaces/Server.kt package com.rotor.database.interfaces import com.google.gson.internal.LinkedTreeMap import com.rotor.database.request.* import io.reactivex.Observable import org.json.JSONArray import retrofit2.http.* /** * Created by efraespada on 14/03/2018. */ interface Server { @Headers("Content-Type: application/json") @POST("/") fun createReference(@Body createListener: CreateListener) : Observable<SyncResponse> @Headers("Content-Type: application/json") @POST("/") fun removeListener(@Body removeListener: RemoveListener) : Observable<SyncResponse> @Headers("Content-Type: application/json") @POST("/") fun refreshFromServer(@Body updateFromServer: UpdateFromServer) : Observable<SyncResponse> @Headers("Content-Type: application/json") @POST("/") fun refreshToServer(@Body updateToServer: UpdateToServer) : Observable<SyncResponse> @Headers("Content-Type: application/json") @POST("/") fun removeReference(@Body removeReference: RemoveReference) : Observable<SyncResponse> @Headers("Content-Type: application/json") @GET("/") fun query(@Query("token") token: String, @Query("database") database: String, @Query("path") path: String, @Query("query") query: String, @Query("mask") mask: String) : Observable<List<LinkedTreeMap<String, String>>> }<file_sep>/core/src/main/java/com/rotor/core/Rotor.kt package com.rotor.core import android.content.ComponentName import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import android.provider.Settings import android.util.Log import com.rotor.core.interfaces.InternalServiceListener import com.rotor.core.interfaces.StatusListener import com.google.gson.Gson import com.rotor.core.RotorService.Companion.PREF_CONFIG import com.rotor.core.RotorService.Companion.PREF_ID import com.rotor.core.interfaces.BuilderFace import org.json.JSONObject /** * Created by efraespada on 11/03/2018. */ class Rotor { companion object { private val TAG = Rotor::class.java.simpleName var context: Context? = null @JvmStatic var id: String ? = null @JvmStatic var urlServer: String ? = null @JvmStatic var urlRedis: String ? = null lateinit var statusListener: StatusListener var rotorService: RotorService? = null private var isServiceBound: Boolean? = null var gson: Gson? = null var debug: Boolean? = null var initializing: Boolean? = null var builders: HashMap<Builder, BuilderFace> ? = null @JvmStatic val serviceConnection: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { if (service is RotorService.FBinder) { rotorService = service.service rotorService?.sc = this rotorService?.listener = object : InternalServiceListener { override fun connected() { if (initializing!!) { initializing = false statusListener.connected() } } override fun reconnecting() { statusListener.reconnecting() } } if (initializing!!) { rotorService?.startService() } if (debug!!) Log.e(TAG, "instanced service") } } override fun onServiceDisconnected(className: ComponentName) { if (className.className == RotorService::class.java.name) { rotorService?.listener = null rotorService = null } if (debug!!) Log.e(TAG, "disconnected") } } @JvmStatic fun initialize(context: Context, urlServer: String, redisServer: String, statusListener: StatusListener) { Companion.context = context Companion.urlServer = urlServer Companion.urlRedis = redisServer Companion.statusListener = statusListener if (Companion.builders == null) { Companion.builders = HashMap<Builder, BuilderFace>() } Companion.debug = false Companion.gson = Gson() val shared = context.getSharedPreferences(PREF_CONFIG, MODE_PRIVATE) Companion.id = shared.getString(PREF_ID, null) if (Companion.id == null) { Companion.id = generateNewId() } Companion.initializing = true start() } private fun generateNewId(): String { val id = Settings.Secure.getString(context!!.getContentResolver(), Settings.Secure.ANDROID_ID) val shared = context!!.getSharedPreferences(PREF_CONFIG, MODE_PRIVATE).edit() shared.putString(PREF_ID, id) shared.apply() return id } @JvmStatic fun stop() { if (isServiceBound != null && isServiceBound!! && rotorService != null && rotorService!!.getServiceConnection() != null) { rotorService!!.stopService() try { context!!.unbindService(rotorService!!.getServiceConnection()) } catch (e: IllegalArgumentException) { // nothing to do here } if (debug!!) Log.e(TAG, "unbound") context!!.stopService(Intent(context, RotorService::class.java)) isServiceBound = false } } private fun start() { if (isServiceBound == null || !isServiceBound!!) { val i = Intent(context, RotorService::class.java) context!!.startService(i) context!!.bindService(i, getServiceConnection(RotorService())!!, Context.BIND_AUTO_CREATE) isServiceBound = true } } @JvmStatic fun onResume() { start() } @JvmStatic fun onPause() { if (rotorService != null && isServiceBound != null && isServiceBound!!) { context!!.unbindService(rotorService!!.getServiceConnection()) isServiceBound = false } } @JvmStatic private fun getServiceConnection(obj: Any): ServiceConnection? { return if (obj is RotorService) { serviceConnection } else { null } } @JvmStatic fun onMessageReceived(jsonObject: JSONObject) { if (Companion.builders != null) { for (face in Companion.builders!!.values) { face.onMessageReceived(jsonObject) } } } @JvmStatic fun prepare(type: Builder, face: BuilderFace) { if (Companion.builders != null) { Companion.builders!![type] = face } } @JvmStatic fun debug(debug: Boolean) { Companion.debug = debug } } }<file_sep>/app/src/main/java/com/rotor/chappy/activities/contact_scanner/ContactScannerActivity.java package com.rotor.chappy.activities.contact_scanner; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.SparseArray; import com.google.android.gms.samples.vision.barcodereader.BarcodeCapture; import com.google.android.gms.samples.vision.barcodereader.BarcodeGraphic; import com.google.android.gms.vision.barcode.Barcode; import com.rotor.chappy.R; import com.stringcare.library.SC; import java.util.List; import xyz.belvi.mobilevisionbarcodescanner.BarcodeRetriever; public class ContactScannerActivity extends AppCompatActivity implements BarcodeRetriever { private final String TAG = ContactScannerActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_scanner); BarcodeCapture barcodeCapture = (BarcodeCapture) getSupportFragmentManager().findFragmentById(R.id.barcode); barcodeCapture.setRetrieval(this); } @Override public void onRetrieved(final Barcode barcode) { Log.e(TAG, "Barcode read: " + barcode.displayValue); runOnUiThread(new Runnable() { @Override public void run() { Bundle conData = new Bundle(); conData.putString("uid", SC.decryptString(barcode.displayValue)); Intent intent = new Intent(); intent.putExtras(conData); setResult(RESULT_OK, intent); finish(); } }); } @Override public void onRetrievedMultiple(Barcode barcode, List<BarcodeGraphic> list) { // nothing to do here } @Override public void onBitmapScanned(SparseArray<Barcode> sparseArray) { // when image is scanned and processed } @Override public void onRetrievedFailed(String reason) { // in case of failure } }<file_sep>/notifications/src/main/java/com/rotor/notifications/interfaces/ClazzLoader.kt package com.rotor.notifications.interfaces /** * Created by efraespada on 23/03/2018. */ class ClazzLoader<T>(c: Class<T>) { val c: Class<T> init{ this.c = c } fun getClazz() : Class<T> { return c } }<file_sep>/core/src/main/java/com/rotor/core/RotorService.kt package com.rotor.core import android.app.Service import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Binder import android.os.Handler import android.os.IBinder import android.os.StrictMode import android.util.Log import com.rotor.core.interfaces.InternalServiceListener import com.lambdaworks.redis.RedisClient import com.lambdaworks.redis.pubsub.RedisPubSubConnection import com.lambdaworks.redis.pubsub.RedisPubSubListener import org.json.JSONException import org.json.JSONObject import java.util.* /** * Created by efraespada on 11/03/2018. */ class RotorService: Service() { companion object { internal val PREF_ID = "rotor_id" internal val PREF_URL = "rotor_url" internal val PREF_CONFIG = "rotor_config" } private val TAG = RotorService::class.java.simpleName private val EXCEPTION_NO_SERVER_URL = "No URL was defined for Rotor Server" internal var binder: FBinder = FBinder() internal var initialized: Boolean = false internal var client: RedisClient ? = null internal var moment: Long = 0 internal var url: String ? = null internal var connection: RedisPubSubConnection<String, String> ? = null internal var sc: ServiceConnection ? = null internal var connectedToRedis: Boolean = false var listener: InternalServiceListener? = null private val redisPubSubListener = object : RedisPubSubListener<String, String> { override fun message(s: String, s2: String) { val task = Runnable { try { Rotor.onMessageReceived(JSONObject(s2)) } catch (e: JSONException) { e.printStackTrace() } } Handler(applicationContext.mainLooper).post(task) } override fun message(s: String, k1: String, s2: String) { // nothing to do here } override fun subscribed(s: String, l: Long) { moment = Date().time connectedToRedis = true if (listener != null) { val task = Runnable { listener!!.connected() } Handler(applicationContext.mainLooper).post(task) } } override fun psubscribed(s: String, l: Long) { // nothing to do here } override fun unsubscribed(s: String, l: Long) { moment = 0 connectedToRedis = false if (listener != null) { val task = Runnable { listener!!.connected() } Handler(applicationContext.mainLooper).post(task) } } override fun punsubscribed(s: String, l: Long) { // nothing to do here } } override fun onCreate() { super.onCreate() val policy = StrictMode.ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(policy) startConnection() } private fun startConnection() { listener?.reconnecting() if (client == null) { if (url == null) { url = Rotor.urlRedis } if (url == null || url?.length == 0) { val shared = applicationContext.getSharedPreferences(PREF_CONFIG, Context.MODE_PRIVATE) url = shared.getString(PREF_URL, null) } else { val shared = applicationContext.getSharedPreferences(PREF_CONFIG, Context.MODE_PRIVATE).edit() shared.putString(PREF_URL, url) shared.apply() } if (url == null) { throw ConnectionException(EXCEPTION_NO_SERVER_URL) } else if (NetworkUtil.getConnectivityStatusString(applicationContext).equals(NetworkUtil.NETWORK_STATUS_NOT_CONNECTED)) { return } client = RedisClient.create(url) connection = client!!.connectPubSub() connection!!.addListener(redisPubSubListener) } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Log.d(TAG, "service start") startService() return Service.START_STICKY } override fun onBind(intent: Intent): IBinder? { Log.d(TAG, "service bound") return binder } override fun onUnbind(intent: Intent): Boolean { Log.d(TAG, "service unbound") return super.onUnbind(intent) } override fun onDestroy() { Log.d(TAG, "service destroyed") connection?.removeListener(redisPubSubListener) super.onDestroy() } fun startService() { if (!connectedToRedis && !NetworkUtil.getConnectivityStatusString(applicationContext).equals(NetworkUtil.NETWORK_STATUS_NOT_CONNECTED)) { initialized = true if (client != null && connection != null) { connection?.subscribe(Rotor.id) } } else if (connectedToRedis && !NetworkUtil.getConnectivityStatusString(applicationContext).equals(NetworkUtil.NETWORK_STATUS_NOT_CONNECTED)) { if (listener != null) { val task = Runnable { listener?.connected() } Handler(applicationContext.mainLooper).post(task) } } } fun stopService() { if (connectedToRedis && !NetworkUtil.getConnectivityStatusString(applicationContext).equals(NetworkUtil.NETWORK_STATUS_NOT_CONNECTED)) { connection?.unsubscribe(Rotor.id) } } /* fun setServiceConnection(sc: ServiceConnection) { Log.d(TAG, "serviceConnection set") this.sc = sc } fun setListener(listener: InternalServiceListener) { this@RotorService.listener = listener if (initializing) { this@RotorService.listener.connected() } }*/ fun getMoment(): Long? { return moment } fun getServiceConnection(): ServiceConnection ? { return this.sc } inner class FBinder : Binder() { val service: RotorService get() = this@RotorService } }<file_sep>/core/src/main/java/com/rotor/core/interfaces/InternalServiceListener.kt package com.rotor.core.interfaces /** * Created by efraespada on 11/03/2018. */ public interface InternalServiceListener { fun connected() fun reconnecting() }<file_sep>/notifications/src/main/java/com/rotor/notifications/model/Notification.java package com.rotor.notifications.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.HashMap; /** * Created by efraespada on 19/03/2018. */ public class Notification { @SerializedName("id") @Expose String id; @SerializedName("time") @Expose Long time; @SerializedName("content") @Expose Content content; @SerializedName("sender") @Expose Sender sender; @SerializedName("receivers") @Expose HashMap<String, Receiver> receivers; public Notification() { // nothing to do here } public Notification(String id, Long time, Content content, Sender sender, HashMap<String, Receiver> receivers) { this.id = id; this.time = time; this.content = content; this.sender = sender; this.receivers = receivers; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } public Sender getSender() { return sender; } public void setSender(Sender sender) { this.sender = sender; } public HashMap<String, Receiver> getReceivers() { return receivers; } public void setReceivers(HashMap<String, Receiver> receivers) { this.receivers = receivers; } } <file_sep>/app/src/main/java/com/rotor/chappy/model/mpv/ReferencePresenter.java package com.rotor.chappy.model.mpv; public interface ReferencePresenter<T> extends BasePresenter { void prepareFor(String id, Class<T> clazz); void sync(String id); void remove(String id); } <file_sep>/notifications/src/main/java/com/rotor/notifications/model/Content.java package com.rotor.notifications.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.StringEscapeUtils; /** * Created by efraespada on 19/03/2018. */ public class Content { @SerializedName("id") @Expose String id; @SerializedName("room") @Expose String room; @SerializedName("requestCode") @Expose int requestCode; @SerializedName("title") @Expose String title; @SerializedName("body") @Expose String body; @SerializedName("channel") @Expose String channel; @SerializedName("channelDescription") @Expose String channelDescription; @SerializedName("photoSmall") @Expose String photoSmall; @SerializedName("photo") @Expose String photo; public Content() { // nothing to do here } public Content(int requestCode, String title, String body, String room, String channel, String channelDescription, String photoSmall, String photo) { this.requestCode = requestCode; this.room = room; this.title = StringEscapeUtils.escapeJava(title); this.body = StringEscapeUtils.escapeJava(body); this.channel = channel; this.channelDescription = channelDescription; this.photoSmall = photoSmall; this.photo = photo; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getChannelDescription() { return channelDescription; } public void setChannelDescription(String channelDescription) { this.channelDescription = channelDescription; } public String getPhotoSmall() { return photoSmall; } public void setPhotoSmall(String photoSmall) { this.photoSmall = photoSmall; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public int getRequestCode() { return requestCode; } public void setRequestCode(int requestCode) { this.requestCode = requestCode; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } } <file_sep>/database/src/main/java/com/rotor/database/Database.kt package com.rotor.database import android.os.Handler import android.util.Log import cc.duduhuo.util.digest.Digest import com.efraespada.jsondiff.JSONDiff import com.rotor.core.Builder import com.rotor.core.Rotor import com.rotor.core.interfaces.BuilderFace import com.rotor.database.abstr.Reference import com.rotor.database.interfaces.QueryCallback import com.rotor.database.models.KReference import com.rotor.database.models.PrimaryReferece import com.rotor.database.models.PrimaryReferece.Companion.ACTION_NEW_OBJECT import com.rotor.database.models.PrimaryReferece.Companion.ACTION_REFERENCE_REMOVED import com.rotor.database.models.PrimaryReferece.Companion.EMPTY_OBJECT import com.rotor.database.models.PrimaryReferece.Companion.NULL import com.rotor.database.models.PrimaryReferece.Companion.OS import com.rotor.database.models.PrimaryReferece.Companion.PATH import com.rotor.database.request.* import com.rotor.database.utils.ReferenceUtils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.apache.commons.lang3.StringEscapeUtils import org.json.JSONObject import java.util.* /** * Created by efrainespada on 12/03/2018. */ class Database { companion object { private val TAG: String = Database::class.java.simpleName!! @JvmStatic private var pathMap: HashMap<String, KReference<*>> ? = null val api by lazy { ReferenceUtils.service(Rotor.urlServer!!) } @JvmStatic fun initialize() { pathMap.let { pathMap = HashMap() } Rotor.prepare(Builder.DATABASE, object: BuilderFace { override fun onMessageReceived(jsonObject: JSONObject) { try { if (jsonObject.has("data")) { val data = jsonObject.get("data") as JSONObject if (data.has("info") && data.has(PATH)) { val info = data.getString("info") val path = data.getString(PATH) if (ACTION_NEW_OBJECT.equals(info)) { if (pathMap!!.containsKey(path)) { val handler = Handler() handler.postDelayed({ sync(path) }, 200) } } else if (ACTION_REFERENCE_REMOVED.equals(info)) { if (pathMap!!.containsKey(path)) { val handler = Handler() handler.postDelayed({ removePrim(path) }, 200) } } } else if (data.has(PATH)) { val path = data.getString(PATH) if (pathMap!!.containsKey(path)) { pathMap!![path]!!.onMessageReceived(data) } } } } catch (e: Exception) { e.printStackTrace() } } }) } @JvmStatic fun <T> listen(database: String, path: String, reference: Reference<T>) { if (pathMap == null) { Log.e(TAG, "Use Database.initialize(Context context, String urlServer, String token, StatusListener) before create real time references") return } if (Rotor.rotorService == null || Rotor.rotorService?.getMoment() == null) { Rotor.statusListener.reconnecting() return } val blowerCreation = Date().time if (pathMap!!.containsKey(path)) { Log.d(TAG, "Listener already added for: $path") pathMap!![path]!!.addBlower(blowerCreation, reference) pathMap!![path]!!.loadCachedReference() return } Log.d(TAG, "Creating reference: $path") val objectReference = KReference<T>(Rotor.context!!, database, path, reference, Rotor.rotorService!!.getMoment() as Long) pathMap!![path] = objectReference objectReference.loadCachedReference() syncWithServer(path) } @JvmStatic fun sha1(value: String) : String { return JSONDiff.hash(StringEscapeUtils.unescapeJava(value)) } @JvmStatic private fun syncWithServer(path: String) { var content = ReferenceUtils.getElement(path) if (content == null) { content = PrimaryReferece.EMPTY_OBJECT } api.createReference(CreateListener("listen_reference", pathMap!!.get(path)!!.databaseName, path, Rotor.id!!, OS, sha1(content), content.length)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } @JvmStatic fun unlisten(path: String) { if (pathMap!!.containsKey(path)) { api.removeListener(RemoveListener("unlisten_reference", pathMap!!.get(path)!!.databaseName, path, Rotor.id!!)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } } @JvmStatic fun remove(path: String) { if (pathMap!!.containsKey(path)) { api.removeReference(RemoveReference("remove_reference", pathMap!!.get(path)!!.databaseName, path, Rotor.id!!)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } } @JvmStatic private fun refreshToServer(path: String, differences: String, len: Int, clean: Boolean) { if (differences == PrimaryReferece.EMPTY_OBJECT) { return } api.refreshToServer(UpdateToServer("update_reference", pathMap!!.get(path)!!.databaseName, path, Rotor.id!!, "android", differences, len, clean)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } @JvmStatic fun refreshFromServer(path: String, content: String) { if (PrimaryReferece.EMPTY_OBJECT.equals(content)) { Log.e(TAG, "no content: $EMPTY_OBJECT") return } api.refreshFromServer(UpdateFromServer("update_reference_from", pathMap!!.get(path)!!.databaseName, path, Rotor.id!!, "android", content)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> result.status?.let { Log.e(TAG, result.status) } }, { error -> error.printStackTrace() } ) } @JvmStatic fun sync(path: String) { sync(path, false) } @JvmStatic fun sync(path: String, clean: Boolean) { if (pathMap!!.containsKey(path)) { val result = pathMap!![path]!!.getDifferences(clean) val diff = result[1] as String val len = result[0] as Int if (!EMPTY_OBJECT.equals(diff)) { refreshToServer(path, diff, len, clean) } else { val blower = pathMap!![path]!!.getLastest() val value = pathMap!![path]!!.getReferenceAsString() if (value.equals(EMPTY_OBJECT) || value.equals(NULL)) { blower.onCreate() } } } } @JvmStatic fun removePrim(path: String) { if (pathMap!!.containsKey(path)) { pathMap!![path]!!.remove() pathMap!!.remove(path) ReferenceUtils.removeElement(path) Database.unlisten(path) } } @JvmStatic fun query(database: String, path: String, query: String, mask: String, callback: QueryCallback) { api.query(Rotor.id!!, database, path, query, mask) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> callback.response(result) }, { error -> error.printStackTrace() }) } } }<file_sep>/notifications/src/main/java/com/rotor/notifications/interfaces/Server.kt package com.rotor.notifications.interfaces import com.rotor.database.request.* import com.rotor.notifications.request.NotificationGetter import com.rotor.notifications.request.NotificationSender import io.reactivex.Observable import retrofit2.http.Body import retrofit2.http.Headers import retrofit2.http.POST /** * Created by efraespada on 14/03/2018. */ interface Server { @Headers("Content-Type: application/json") @POST("/") fun sendNotification(@Body notificationSender: NotificationSender) : Observable<SyncResponse> @Headers("Content-Type: application/json") @POST("/") fun getNotifications(@Body notificationGetter: NotificationGetter) : Observable<SyncResponse> }<file_sep>/app/src/main/java/com/rotor/chappy/services/ProfileRepository.java package com.rotor.chappy.services; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.rotor.chappy.App; import com.rotor.chappy.model.Location; import com.rotor.chappy.model.User; import com.rotor.chappy.model.mpv.BasePresenter; import com.rotor.chappy.model.mpv.MapReferenceView; import com.rotor.chappy.model.mpv.ProfilePresenter; import com.rotor.chappy.model.mpv.ProfileView; import com.rotor.chappy.model.mpv.ProfilesView; import com.rotor.chappy.model.mpv.ReferenceView; import com.rotor.chappy.model.mpv.RelationProfilesView; import com.rotor.chappy.model.mpv.RelationView; import com.rotor.database.Database; import com.rotor.database.abstr.Reference; import java.util.HashMap; import java.util.Map; public class ProfileRepository { private static final Map<String, User> users = new HashMap<>(); private static final Map<String, RelationProfilesView> map = new HashMap<>(); public ProfileRepository() { // nothing to do here } public void listen(final String path, final ProfilePresenter presenter, final ProfilesView referenceView) { if (map.containsKey(path)) { RelationProfilesView relationView = map.get(path); relationView.addView(presenter, referenceView); map.put(path, relationView); } else { RelationProfilesView relationView = new RelationProfilesView(path); relationView.addView(presenter, referenceView); map.put(path, relationView); } implListen(path); } public <T> void listen(final String path, final ProfilePresenter presenter, final ProfileView referenceView) { if (map.containsKey(path)) { RelationProfilesView relationView = map.get(path); relationView.addView(presenter, referenceView); map.put(path, relationView); } else { RelationProfilesView relationView = new RelationProfilesView(path); relationView.addView(presenter, referenceView); map.put(path, relationView); } implListen(path); } private void implListen(final String path) { Database.listen(App.databaseName, path, new Reference<User>(User.class) { @Override public void onCreate() { RelationProfilesView rV = map.get(path); ProfileView rF = rV.activeView(); if (rF != null) { rF.onCreateUser(); } ProfilesView rFM = rV.activeMapView(); if (rFM != null) { rFM.onCreateUser(path); } } @Override public void onChanged(@NonNull User user) { users.put("/users/" + user.getUid(), user); RelationProfilesView rV = map.get(path); ProfileView rF = rV.activeView(); if (rF != null) { rF.onUserChanged(user); } ProfilesView rFM = rV.activeMapView(); if (rFM != null) { rFM.onUserChanged(path, user); } } @Nullable @Override public User onUpdate() { RelationProfilesView rV = map.get(path); ProfileView rF = rV.activeView(); if (rF != null) { return rF.onUpdateUser(); } else { ProfilesView rFM = rV.activeMapView(); if (rFM != null) { return rFM.onUpdateUser(path); } else { return users.get(path); } } } @Override public void onDestroy() { RelationProfilesView rV = map.get(path); ProfileView rF = rV.activeView(); if (rF != null) { rF.onDestroyUser(); } ProfilesView rFM = rV.activeMapView(); if (rFM != null) { rFM.onDestroyUser(path); } } @Override public void progress(int i) { RelationProfilesView rV = map.get(path); ProfileView rF = rV.activeView(); if (rF != null) { rF.userProgress(i); } ProfilesView rFM = rV.activeMapView(); if (rFM != null) { rFM.userProgress(path, i); } } }); } public void sync(String id) { Database.sync(id); } public void remove(String id) { Database.remove(id); } public static void addLocationTo(String id, Location location) { users.get(id).getLocations().put(location.getId(), location); Database.sync(id); } public static User getUser(String id) { if (map.containsKey(id)) { RelationProfilesView rV = map.get(id); ProfileView rF = rV.activeView(); if (rF != null) { return rF.onUpdateUser(); } else { ProfilesView rFM = rV.activeMapView(); if (rFM != null) { return rFM.onUpdateUser(id); } else { return users.get(id); } } } else return null; } public static void setUser(String id, User user) { users.put(id, user); if (map.containsKey(id)) { RelationProfilesView rV = map.get(id); ProfileView rF = rV.activeView(); if (rF != null) { rF.onUserChanged(user); } else { ProfilesView rFM = rV.activeMapView(); if (rFM != null) { rFM.onUserChanged(id, user); } } } } } <file_sep>/database/src/main/java/com/rotor/database/request/RemoveReference.kt package com.rotor.database.request /** * Created by efraespada on 11/03/2018. */ data class RemoveReference(val method: String, val database: String, val path: String, val token: String)<file_sep>/notifications/src/main/java/com/rotor/notifications/enums/Method.kt package com.rotor.notifications.enums /** * Created by efraespada on 18/03/2018. */ enum class Method(methodName: String) { ADD("add"), REMOVE("remove"); val methodName: String init { this.methodName = methodName } fun getMethod() : String { return methodName } }<file_sep>/database/src/main/java/com/rotor/database/models/KReference.kt package com.rotor.database.models import android.content.Context import com.google.common.reflect.TypeToken import com.rotor.database.abstr.Reference import com.rotor.database.utils.ReferenceUtils import java.lang.reflect.Type /** * Created by efraespada on 14/03/2018. */ class KReference<T>(context: Context, database: String, path: String, reference: Reference<*>, moment: Long) : PrimaryReferece<Reference<T>>(context, database, path) { private val clazz: Class<T> init { blowerMap[moment] = reference as Reference<T> this.clazz = reference.clazz() } override fun getLastest(): Reference<T> { var lastest: Long = 0 var blower: Reference<T>? = null // TODO limit list of blowers for (entry in blowerMap.entries) { if (lastest < entry.key) { lastest = entry.key blower = entry.value } } return blower!! } override fun progress(value: Int) { for (entry in blowerMap.entries) { entry.value.progress(value) } } fun addBlower(creation: Long, blower: Reference<*>) { blowerMap[creation] = blower as Reference<T> } override fun getReferenceAsString(): String { var value: String ? if (getLastest().onUpdate() == null) { if (stringReference != null && stringReference!!.length > EMPTY_OBJECT.length) { value = stringReference } else { value = EMPTY_OBJECT } } else { value = gson.toJson(getLastest().onUpdate(), clazz) } return value!! } override fun loadCachedReference() { stringReference = ReferenceUtils.getElement(path) if (stringReference != null && stringReference!!.length > EMPTY_OBJECT.length) { blowerResult(stringReference!!) } } override fun blowerResult(value: String) { for (entry in blowerMap.entries) { entry.value.onChanged(gson.fromJson(value, getType())) } } override fun remove() { ReferenceUtils.removeElement(path) for (entry in blowerMap.entries) { entry.value.onDestroy() } } fun getType(): Type { return TypeToken.of(clazz).type } }
adb316498382da60830b65bec615ebed86b5e52c
[ "Markdown", "Java", "Kotlin", "Gradle" ]
36
Java
rotorlab/chappy-android-sample
19d083505a5ff497ceb1e4e16bb8761395cce89e
c98751cdae4c5f4bd0cd64c7bd2c87764aa214e2
refs/heads/master
<repo_name>sd031/laravel-tricks<file_sep>/app/lang/en/tricks.php <?php return array( 'trick' => 'Trick', );<file_sep>/app/lang/en/user.php <?php return array( 'my_favorites' => 'My Favorites', 'profile' => 'Profile', 'settings' => 'Settings', );<file_sep>/app/lang/en/search.php <?php return array( 'search_results_for' => 'Search results for ":term"', ); <file_sep>/app/lang/en/home.php <?php return array( 'about_tricks_website' => 'About Laravel-Tricks website', 'error' => 'Error', 'welcome' => 'Welcome', 'login' => 'Login', 'registration' => 'Registration', );
e8e25003f4e7eb41b2b5a3739a3dba342fc646aa
[ "PHP" ]
4
PHP
sd031/laravel-tricks
e32647c8732b041c2d718308f74246517a665657
9e36afe68adb483a3df671c4ba0fc33dfa77dbbb
refs/heads/master
<file_sep># Sudoku Sudoku is a sudoku puzzle solver written in C++ that allows the user to solve plaintext sudoku files or solves them automatically. This program was written for an assignment in CSE20212 (Fundamentals of Computing II) at the University of Notre Dame. #### Input Valid input files come in the following form: 9 lines of 9 numbers separated by a space, an example below. ```txt 4 0 8 7 0 0 1 0 2 0 0 0 3 4 0 0 5 0 0 1 0 0 5 0 0 0 0 0 0 0 8 0 0 6 0 0 0 8 4 0 0 0 2 7 0 0 0 2 0 0 5 0 0 0 0 0 0 0 8 0 0 4 0 0 9 0 0 2 4 0 0 0 3 0 6 0 0 7 8 0 1 ``` This repository comes with 3 sample puzzles of various difficulties, conveniently named "easy", "medium" and "hard" in the `puzzles` directory. #### Startup To build, enter `make` in the repository root. This will result in a binary file named `main`. After running `main`, the user will be prompted to input a filename. For convenience, the contents of the `puzzles` directory is displayed. After selecting a puzzle file, you will be prompted to either play (manually solve the puzzle) or solve (have the program solve it automatically). #### Playing When play is selected, the program enters a turn-like state. Each turn, the user selects a (valid) row and column, and if the coordinates do not represent a part of the original puzzle, you may enter a number to put into that cell. The program will not let you change the origianl puzzle or enter a non-valid number (for example, a 3 in a row that already had a 3). You may re-enter numbers in cells if they do not belong to the original puzzle. If you fill the entire board with numbers, by definition you have solved the puzzle, but there is an additional congratulatory message. When in play mode, enter "-1" as the desired number to exit the program, or simply press CTRL + C. #### Solving Sudoku uses a singleton algorithm to try all possible ways to deduce a correct number placement, and places the definite numbers it finds in a board. Sudoku can solve any puzzle that doesn't have any ambiguous moves, that is, it must have a deterministic solution. When solve is selected, the board will be solved and updated in "runs" through the board. The display will refresh after each run to give the user an idea of how the program is solving the puzzle. After the puzzle has been solver, the number of runs will be displayed alongside the solved puzzle. Example of a solved puzzle: ![Solved Puzzle](https://github.com/benedictb/Sudoku/blob/master/img/sudoku.png) <file_sep>/* <NAME> bbecker5 lab5 */ #ifndef PUZZLE #define PUZZLE #include <iostream> #include <fstream> #include <stdlib.h> #include <vector> using namespace std; template <typename T> class Puzzle{ public: Puzzle(int, string); ~Puzzle(); void display(); int getSize(); vector< vector<T> >* getBoard(); //returns a pointer to the board, needed for the sudoku game class private: vector< vector<T> > board; int size; //useful for the display function }; template <typename T> vector< vector<T> >* Puzzle<T>::getBoard(){ return &board; } template <typename T> int Puzzle<T>::getSize(){ return size; } template <typename T> Puzzle<T>::Puzzle(int boardSize, string filename){ size = boardSize; T temp; for(int i=0; i<size;i++){ //put in size size-sized vectors (sorry) board.push_back(vector<T>(size)); } ifstream dataFile (filename.c_str()); //need the filename to be a c_str for it to work for (int i=0; i<size; i++){ //read in the data for (int j=0; j<size; j++){ dataFile >> temp; board[i][j] = temp; } } dataFile.close(); } template <typename T> Puzzle<T>::~Puzzle(){} template <typename T> void Puzzle<T>::display(){ //this is mostly just formatting it to have the index and grid system("clear"); for (int i=0;i<size;i++){ cout << "(" << i + 1 << ")| "; for (int j=0;j<size;j++){ if (board[i][j] == 0 || board[i][j] == '0' ){ cout << " "; } else { cout << board[i][j]; } cout << " "; if (j==2 || j==5){ cout << "|";} } if (i==2 || i ==5){ cout <<endl<< " -----------------------"; } cout << endl; } cout << "--------------------------"<< endl; cout << " 1 2 3 4 5 6 7 8 9 " << endl; } #endif <file_sep>/* <NAME> bbecker5 lab5 */ #include <iostream> #include <fstream> #include <vector> #include <stdlib.h> #include <unistd.h> #include "Sudoku.h" using namespace std; Sudoku::Sudoku(string filename) : puz(9,filename), constPuz(9,filename){ vector<vector <int> > vect; vector<int> intVect; for(int i=0;i<9;i++){ //insert vectors for the columns solData.push_back(vect); for (int j=0;j<9;j++){ solData[i].push_back(intVect); //insert vectors for the data solData[i][j].push_back((*puz.getBoard())[i][j]); //initialize the actual "solution" to be what is currently on the board for (int k=1;k<10;k++){//set data to 0 solData[i][j].push_back(0); } } } } Sudoku::~Sudoku(){} void Sudoku::play(){ while (1){ //display the board, take in input, and then see if the game is over puz.display(); if (input()){return;} if (gamecheck()) {return;} } } int Sudoku::getQuad(int r, int c){ int val = 0; /*returns the "coordinates" of the top left corner of the minigrid that the (r,c) pair is in. Is extracted using r = val/10 and c = val%10 */ if (r<3){ val+=0; } else if(r<6){ val+=30; } else if (r<9){ val+=60; } else { return -1;} if (c<3){ val+=0; } else if(c<6){ val+=3; } else if (c<9){ val+=6; } else { return -1;} return val; } int Sudoku::checkQuad(int quad, int input){ int r = quad/10; //extract the coordinates from the quad number int c= quad%10; for(int i=0;i<3;i++){ //looping through all 9 points, see if the input is already in the minigrid for (int j=0;j<3;j++){ if((*puz.getBoard())[r+i][c+j] == (input)){return 0;} //checks the coordinate against the input } } return 1; //if no matches, return true } int Sudoku::checkCol(int c, int input){ //checks to see if the input number is already in the column for (int i=0;i<9;i++){ if ((*puz.getBoard())[i][c] == input) {return 0;} } return 1; } int Sudoku::checkRow(int r, int input){ //checks to see if the input number is in the row for (int i=0;i<9;i++){ if ((*puz.getBoard())[r][i] == input) {return 0;} } return 1; } int Sudoku::validPlacement(int r,int c, int input){ //checks the three constraints for a given (r,c) pair and input if (!(checkQuad(getQuad(r,c),input))) {return 0;} //gets the quad and checks the quad in the same call if (!(checkCol(c,input))) {return 0;} if (!(checkRow(r,input))) {return 0;} return 1; } int Sudoku::gamecheck(){ for(int i=0;i<9;i++){ for (int j=0;j<9;j++){ if ((*puz.getBoard())[i][j] == 0) //because of the detailed validPlacement function, if there is no 0's left, then the game has been won return 0; } } cout << endl << "Congrats! You solved the puzzle!" << endl; return 1; //return true to exit the program } int Sudoku::input(){ int r,c,input, movable=0; puz.display(); while(movable==0){ //needs to be "changable" spot, blank in the original puzzle cout << "Please pick a row: "; cin >> r; r--; //for array numbering while ((r < 0) || (r>8)){ //has to be in bounds or else seg fault cout<< endl<< "Please chooose a valid entry: "; cin >> r; r--; } puz.display(); //same as row cout << "Please pick a column: "; cin >> c; c--; while ((c < 0) || (c>8)){ cout<< endl<< "Please chooose a valid entry: "; cin >> c; c--; } puz.display(); if (isMovable(r,c)){ //checks to see if it is a movable value, if it is, then the loop is exited movable =1; } else { cout << endl<< "Sorry, this was part of the original puzzle and cannot be changed" << endl; } } puz.display(); cout << "Please pick your number: "; cin >> input; if (input==-1) {return 1;} //-1 exits the program while ((input < -1) || (input>9) || !(validPlacement(r,c,input))) { //needs to be a valid input, checked by the validPlacement function cout<< endl<< "Please chooose a valid entry: "; cin >> input; if (input==-1) {return 1;} } (*puz.getBoard())[r][c] = input; return 0; //everything worked out fine is 0 in this case } int Sudoku::isMovable(int r, int c){ //checks to see if the coordinates are changeable by referencing the backup copy of the puzzle if ((*constPuz.getBoard())[r][c] == 0){ return 1; } return 0; } //The implementation for the solver is below void Sudoku::updateSolData(){ //this updates the possible positions for each unfilled slot. This gets called before all of the algorithms to make sure //that they dont write over each other or write the wrong data for(int i=0;i<9;i++){ //looping through all 9 points, see if the input is already in the minigrid for (int j=0;j<9;j++){ if (solData[i][j][0]==0){ //if it is unfilled, update the data for (int k=1;k<10;k++){ if (validPlacement(i,j,k)){ //if the number can be placed here, make it a 1, otherwise make it a zero solData[i][j][k]=1; } else { solData[i][j][k]=0; //this refreshes the data } } } } } } void Sudoku::uniqueFiller(){ //if there is only one possibility for a square, place that one possibility. for(int i=0;i<9;i++){ //looping through all 9 points, see if the input is already in the minigrid for (int j=0;j<9;j++){ if (solData[i][j][0]==0 && numOfOnes(solData[i][j])==1){ //I update both of these because different functions use both. solData[i][j][0]=findTheOne(solData[i][j]); //update the soldata (*puz.getBoard())[i][j] = findTheOne(solData[i][j]); //update the real board } } } } int Sudoku::numOfOnes(vector<int> vect){ //finds the number of 1's in a vector, returns that number int s=0; for (int i=1;i<10;i++){ if (vect[i]==1){s++;} } return s; } int Sudoku::findTheOne(vector<int> vect){ //returns the first index of the vector that has a 1 (besides 0). for (int i=1;i<10;i++){ if (vect[i]==1){return i;} } return -1; //returns -1 if none were found } void Sudoku::SingletonCol(int col){ int possibleArr[10]={0}; //initialize the data array to 0's. size 10 so that things match up for (int row=0;row<9;row++){ //go through rows if (solData[row][col][0]==0){ //if cell is zero, record possibilities into possibleArr for (int val=1;val<10;val++){ if (solData[row][col][val]==1) { possibleArr[val]++; } } } } for (int val=1;val<10;val++){ //for all the possible vals in possibleArr if(possibleArr[val]==1){ //if there is only one place to put that number for(int row=0; row<9;row++){ //find the cell if(solData[row][col][val]==1 && (solData[row][col][0]==0)){ solData[row][col][0]=val; //and put it into the cell (*puz.getBoard())[row][col] = val; updateSolData(); //very important to update solData each time I found out. Keeps things current break; //leave (just to save a little computing) } } } } } void Sudoku::SingletonRow(int row){ //basically the same implimentation as column, but with a row int possibleArr[10]={0}; for (int col=0;col<9;col++){ if (solData[row][col][0]==0){ for (int val=1;val<10;val++){ if (solData[row][col][val]==1){ possibleArr[val]++; } } } } for (int val=1;val<10;val++){ if(possibleArr[val]==1){ for(int col=0; col<9; col++){ if(solData[row][col][val]==1 && (solData[row][col][0]==0)){ solData[row][col][0]=val; (*puz.getBoard())[row][col] = val; updateSolData(); break; } } } } } void Sudoku::SingletonGrid(int grid){ //similar to row and col singleton, but in this case there is another for loop because the section //being looped through is 2d instead of 1d int possibleArr[10]={0}; int row = grid/10; int col=grid%10; for (int r=0;r<3;r++){ for (int c=0; c<3;c++){ if (solData[row+r][col+c][0]==0){ //starting coordinates + the offset for (int val=1;val<10;val++){ if (solData[row+r][col+c][val]==1){ possibleArr[val]++; } } } } } for (int val=1;val<10;val++){ if (possibleArr[val]==1){ for (int r=0;r<3;r++){ for (int c=0;c<3;c++){ if (solData[row+r][col+c][val]==1 && (solData[row+r][col+c][0]==0)){ solData[row+r][col+c][0]=val; (*puz.getBoard())[row+r][col+c] = val; updateSolData(); break; } } } } } } void Sudoku::solver(){ int gridIDs[9] = {0,3,6,30,33,36,60,63,66}; //possible grid numbers. See getQuad and checkQuad for more info int counter=0; //bonus feature that counts number of turns needed to solve the puzzle puz.display(); //displays it initially updateSolData(); //load the data while (gamecheck()==0){ //while the puzzle hasn't been solved...keep working uniqueFiller(); //first fill up with the unique numbers updateSolData(); for (int i=0;i<9;i++){ //run singleton through all the columns SingletonCol(i); } for (int i=0;i<9;i++){ //run singleton through all the rows SingletonRow(i); } for (int i=0;i<9;i++){ //blah blah all the minigrids SingletonGrid(gridIDs[i]); } counter++; //counts each loop usleep(750000); //pause: so it looks the computer is working hard solving this (it's not) puz.display(); //display this round } puz.display(); //display the final puzzle and print the number of rounds it took to solve cout << "It took " << counter << " rounds to solve this one." << endl; return; }<file_sep>/* <NAME> bbecker5 lab5 */ #include <iostream> #include <fstream> #include <vector> #include <stdlib.h> #include "Puzzle.cpp" #include "Sudoku.h" using namespace std; int main(void){ string filename; char choice; system("clear"); system("ls puzzles | grep .txt"); //display the txts in the folder cout << endl << "During the game, input -1 to quit"; cout <<endl<< "Filename? "; cin >> filename; filename = string("puzzles/") + filename; Sudoku puz(filename); //instantiate a puzzle int cout << "Would you like to play or solve? Enter p or s." << endl; cin >> choice; if (choice == 'p'){ puz.play(); //play the game } else if (choice == 's'){ puz.solver(); //solve the puzzle } } <file_sep>/* <NAME> bbecker5 lab5 */ #ifndef SUDOKU #define SUDOKU #include <iostream> #include <fstream> #include <stdlib.h> #include <vector> #include <string> #include "Puzzle.cpp" using namespace std; class Sudoku{ public: Sudoku(string filename); //constructor that takes in the name of a file ~Sudoku(); void play(); //play the game int getQuad(int r, int c); //get the "quadrant" of two coordinates int checkQuad(int quad, int input); //see if a number is in a "quadrant" int validPlacement(int r,int c, int input); //see if the input is a valid placement int gamecheck(); //check to see if the game is over int checkRow(int r,int input); //check to see if the input is valid in this row int checkCol(int c, int input); //check to see if the input is valid in this column int input();//input a number, row and column int isMovable(int r, int c); //is this placement allowed to change? //these are the new functions for solving soduku void updateSolData(); //update the 3d vector void uniqueFiller(); //fill in the single possibility cells int numOfOnes(vector<int> vect); //return the number of 1's in a vector int findTheOne(vector<int> vect); //return the first index with a 1 in the vector void SingletonCol(int col); //does singleton for a col void SingletonRow(int row); //same for a row void SingletonGrid(int grid); //same for a minigrid void solver(); //incorporates all of these functions to solve the puzzle private: Puzzle<int> puz; //puzzle board Puzzle<int> constPuz; //backup puzzle for checking changability vector< vector< vector<int> > > solData; //holds data necessary for solving the puzzle //solData is a 9X9X10 matrix that holds the actual board in the 0th index of the third dimension, and the possibilities of each //cell in the remaining 9 cells }; #endif <file_sep>CC= g++ CFLAGS= -c -Wall -o $@ $^ TARGETS= main SOURCES= Puzzle.o Sudoku.o all: $(TARGETS) sampleCharPuzzle: $(SOURCES) sampleCharPuzzle.o g++ Puzzle.o sampleCharPuzzle.o -o sampleCharPuzzle sampleIntPuzzle: $(SOURCES) sampleIntPuzzle.o g++ Puzzle.o sampleIntPuzzle.o -o sampleIntPuzzle main: $(SOURCES) main.o g++ Puzzle.o Sudoku.o main.o -o main %.o: %.cpp $(CC) $(CFLAGS) clean: rm -f $(TARGETS) *.o
b13078ef4f2f451822f687c6097d3cdc324a3dfd
[ "Markdown", "Makefile", "C++" ]
6
Markdown
benedictb/Sudoku
6d245f71ca8dc18132819735dfb8343e28ac60ba
ef8b62c7a5f246dd256764b5beb84dc85a81e212
refs/heads/master
<file_sep>''' Created on 7 Jan 2015 @author: murrayking ''' from __future__ import print_function import glob import os import zipfile rootDir = "/Users/murrayking/Downloads/terr50_cesh_gb/data/nt" outPutDir = "/Users/murrayking/Documents/peeblescontours" # os.chdir(rootDir) # for file in glob.glob("*.zip"): # zf = os.path.join(rootDir, file) # with zipfile.ZipFile(zf, "r") as z: # z.extractall(outPutDir) # #merge os.chdir(outPutDir) files = glob.glob("*_line.shp") print(len(files)) for i in range(0, len(files)): if i==0: os.system("pwd ") print(files[i]) os.system("ogr2ogr file_merged.shp " + files[i]) else: os.system("ogr2ogr -update -append file_merged.shp "+ files[i] +" -nln file_merged") <file_sep>''' Created on 31 Jan 2015 @author: murray ''' import re import xml.etree.ElementTree as ET from os.path import expanduser home = expanduser("~") #IMPORTANT remove xmlns from kml files baseDir = home + '/map-mobile/app/src/main/assets/' blueroute = [baseDir + "blue-route.kml","blue_loc_names","blue_loc_coords"] redroute = [baseDir + "red-route.kml","red_loc_names","red_loc_coords"] testredroute = [baseDir + "test-red-route.kml","red_loc_names","red_loc_coords"] blackroute = [baseDir + "black-route.kml","black_loc_names","black_loc_coords"] testblackroute = [baseDir + "test-black-route.kml","black_loc_names","black_loc_coords"] innersBaseDir = home + '/map-mobile/app/src/inners/assets/' redrouteinners = [ innersBaseDir + "innersxc.kml","red_inners_loc_names","red_inners_loc_coords"] downhillinners = [ innersBaseDir + "inners_downhill.kml","inners_downhill_loc_names","inners_downhill_loc_coords"] route = downhillinners names = [] coords = [] root = ET.parse(route[0]) def printOutXml(myid, els): print '<string-array name="{0}">'.format(myid) for e in els: print '<item>{0}</item>'.format(e) print '</string-array>' for e in root.findall('./Document/Folder/Placemark'): # How to make decisions based on attributes even in 2.6: name = e.find("ExtendedData/SchemaData/SimpleData[@name='routelabel']") if name is not None: names.append(name.text) linestring = e.find("LineString/coordinates"); match = re.match('^[-+]?[0-9]*\.?[0-9]+.[-+]?[0-9]*\.?[0-9]+', linestring.text) coords.append( match.group(0)) printOutXml(route[1], names) printOutXml(route[2], coords) <file_sep>''' Created on 1 Mar 2015 @author: murray ''' import os from os.path import expanduser import sys, getopt import subprocess def main(argv): helpText = 'CreateTileMillTrailMbtiles.py -s <mapscale> -c <trailcenter>' mapscale = '2.5' trailcenter = 'inners' try: opts, args = getopt.getopt(argv, "hs:c:", ["scale=", "trailcenter="]) except getopt.GetoptError: print helpText sys.exit(2) for opt, arg in opts: if opt == '-h': print helpText sys.exit() elif opt in ("-s", "--scale"): mapscale = arg elif opt in ("-c", "--trailcenter"): trailcenter = arg print 'MapScale is "', mapscale print 'Trail Center is "', trailcenter createTiles(mapscale, trailcenter) def createTiles(mapscale, trailcenter): home = expanduser("~") mbtilesDir = home + "/merge-mbtiles/" os.system("rm -rf " + mbtilesDir) os.system("mkdir " + mbtilesDir) os.chdir('/Users/murray/Applications/TileMill.app/Contents/Resources') def createInnersTileCreationCommands(): createCentralTilesInners = './index.js export OSMBright ~/merge-mbtiles/central.mbtiles --minzoom=0 --maxzoom=18 --format=mbtiles --bbox="-3.061,55.5807,-3.0059,55.6202" --scale=' + mapscale +' --metatile=15' createSurroundingTilesInners = './index.js export OSMBright ~/merge-mbtiles/surrounding.mbtiles --minzoom=0 --maxzoom=14 --format=mbtiles --bbox="-3.2195,55.5069,-2.8144,55.6965" --scale=' + mapscale +' --metatile=15' return (createCentralTilesInners, createSurroundingTilesInners) def createGlentressTileCreationCommands(): createCentralTilesGlentress = './index.js export OSMBright ~/merge-mbtiles/central.mbtiles --minzoom=0 --maxzoom=18 --format=mbtiles --bbox="-3.1756,55.6437,-3.103,55.6908" --scale=' + mapscale +' --metatile=15' createSurroundingTilesGlentress = './index.js export OSMBright ~/merge-mbtiles/surrounding.mbtiles --minzoom=0 --maxzoom=14 --format=mbtiles --bbox="-3.2338,55.6082,-3.0326,55.7161" --scale=' + mapscale +' --metatile=15' return (createCentralTilesGlentress, createSurroundingTilesGlentress) creationCommands = {"inners": createInnersTileCreationCommands, "glentress": createGlentressTileCreationCommands} (createCentralTiles, createSurroundingTiles) = creationCommands[trailcenter]() print os.system(createCentralTiles) print os.system(createSurroundingTiles) centralMbtilesFile = mbtilesDir + "central.mbtiles" surroundingMbtilesFile = mbtilesDir + "surrounding.mbtiles" centralTilesDir = "centralTiles" centralTilesFullPathDir = mbtilesDir + centralTilesDir surroundingTilesDir = "surroundingTiles" surroundingTilesFullPathDir = mbtilesDir + surroundingTilesDir finalMbtilesFile = mbtilesDir + "maptiles.mbtiles" os.system("rm -rf " + surroundingTilesFullPathDir) proc = subprocess.Popen(["/usr/local/bin/mb-util " + centralMbtilesFile + " " + centralTilesFullPathDir ], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out, err proc = subprocess.Popen(["/usr/local/bin/mb-util " + surroundingMbtilesFile + " " + surroundingTilesFullPathDir ], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out, err os.chdir(mbtilesDir) os.system('rsync -a ' + centralTilesDir + '/ ' + surroundingTilesDir + '/') proc = subprocess.Popen(["/usr/local/bin/mb-util " + surroundingTilesFullPathDir + " " + finalMbtilesFile ], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() if __name__ == "__main__": main(sys.argv[1:]) <file_sep>''' Created on 23 Jan 2015 @author: murrayking ''' import os import PIL.Image from PIL import Image abdLoc = '/home/murray/Android/Sdk/platform-tools/adb' os.system( abdLoc +" shell screencap -p /sdcard/screen.png") os.system( abdLoc +" pull /sdcard/screen.png") os.system( abdLoc +" shell rm /sdcard/screen.png") os.system("pwd") i = 1 while os.path.exists('/home/murray/workspace/pythonscripts/androidhelp/screenshot%s.png' % i): i += 1 outfile = '/home/murray/workspace/pythonscripts/androidhelp/screenshot%s.png' % i infile = '/home/murray/workspace/pythonscripts/androidhelp/screen.png' os.system("cp " + infile + " " + outfile);<file_sep>''' Created on 31 Jan 2015 @author: murray ''' import xml.etree.ElementTree as ET root = ET.parse("/home/murray/testkml.kml") result = '' for e in root.findall('./Document/Folder/Placemark'): # How to make decisions based on attributes even in 2.6: print 'name' name = e.find("name") if name is not None: print name.text linestring = e.find("LineString/coordinates"); print linestring.text if e.attrib.get('name') == 'foo': result = e.text break <file_sep>''' Created on 31 Dec 2014 @author: murray ''' import re import sys from os.path import expanduser home = expanduser("~") innersxcgpx = home + "/DropBox/innersxc.tcx" innersdownhillgpx = home + "/DropBox/innersdownhill.tcx" currentgpx = innersdownhillgpx def _vec2d_dist(p1, p2): return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 def _vec2d_sub(p1, p2): return (p1[0]-p2[0], p1[1]-p2[1]) def _vec2d_mult(p1, p2): return p1[0]*p2[0] + p1[1]*p2[1] def ramerdouglas(line, dist): """Does Ramer-Douglas-Peucker simplification of a curve with `dist` threshold. `line` is a list-of-tuples, where each tuple is a 2D coordinate Usage is like so: >>> myline = [(0.0, 0.0), (1.0, 2.0), (2.0, 1.0)] >>> simplified = ramerdouglas(myline, dist = 1.0) """ if len(line) < 3: return line (begin, end) = (line[0], line[-1]) if line[0] != line[-1] else (line[0], line[-2]) distSq = [] for curr in line[1:-1]: tmp = ( _vec2d_dist(begin, curr) - _vec2d_mult(_vec2d_sub(end, begin), _vec2d_sub(curr, begin)) ** 2 / _vec2d_dist(begin, end)) distSq.append(tmp) maxdist = max(distSq) if maxdist < dist ** 2: return [begin, end] pos = distSq.index(maxdist) return (ramerdouglas(line[:pos + 2], dist) + ramerdouglas(line[pos + 1:], dist)[1:]) with open(currentgpx) as myfile: data=myfile.read().replace('\n', '') i = 0 list = []; test='' matches = re.findall("<DistanceMeters>([0-9]+)[.0-9]*</DistanceMeters>.*?<AltitudeMeters>([0-9.]+)</AltitudeMeters>", data) del matches[0] print len(matches) myline = [] for m in matches: mytuple = (float(m[0])/1000, float(m[1]) ) myline.append( mytuple) simplified = ramerdouglas(myline, dist = 0.03) print len(simplified) for m in simplified: print '<item>' + str(m[0]) + ',' + str(m[1]) + '</item>'; if __name__ == '__main__': pass<file_sep>''' Created on 13 Jan 2015 @author: murrayking ''' from owslib.csw import CatalogueServiceWeb datagov = 'http://csw.data.gov.uk/geonetwork/srv/en/csw' inspireportal = 'http://inspire-geoportal.ec.europa.eu/GeoportalProxyWebServices/resources/OGCCSW202/AT?service=CSW&version=2.0.2&request=GetCapabilities' localhost = 'http://localhost:8000/?service=CSW' # from owslib.csw import CatalogueServiceWeb # # print(csw.identification.type) # csw.getrecords2(keywords=['birds','fowl'], maxrecords=20) # print csw.results # # for rec in csw.records: # print csw.records[rec].title # print csw.results # csw.getrecords(bbox=[-179, -77, 180, 80], maxrecords=20, startposition=10) # for rec in csw.records: # print csw.records[rec].title csw = CatalogueServiceWeb(datagov, version='2.0.2') from owslib.csw import CatalogueServiceWeb import os recobjs = [] # records from owslib.fes import PropertyIsEqualTo, PropertyIsLike, BBox birds_query = PropertyIsEqualTo('csw:AnyText', 'tree') csw.getrecords2(constraints=[birds_query], maxrecords=20, outputschema='http://www.isotc211.org/2005/gmd') print csw.results for k, v in csw.records.iteritems(): print(v.xml) <file_sep>''' Created on 19 Jan 2015 @author: murrayking ''' import re duffRecordName = "/records//duffRen/ame" operationOver = "/records//addddd/sdfsd" old = "/records//?([^/]*)$" newreg = "/records//?(.*?)/$" recordName = re.findall(old, duffRecordName) print recordName if "/" in recordName: print 'remove trailing /' print "and escape here" # Check POST/PUT.GET operation = re.findall("/records//?[^/]+/[^/]+$",operationOver) print operation # It is an operation over a record asset # Path has subdirectories error <file_sep>from owslib.wms import WebMapService wms = WebMapService('http://localhost:8000/?service=CSW&version=2.0.2&request=GetCapabilities', version='2.0.2') print(wms.identification.type) <file_sep>''' Created on 4 Dec 2014 @author: murrayking ''' import requests import sqlite3 import re import glob import os.path def readMbtileDBAndWriteToFiles(): conn = sqlite3.connect('/home/murray/glentressfull.mbtiles') with conn: conn.row_factory = sqlite3.Row cur = conn.cursor() cur.execute("SELECT * FROM tiles") rows = cur.fetchall() ext = ".png" for row in rows: (z,x,y) = (row["zoom_level"], row["tile_column"], row["tile_row"]) ymax = 1 << z; invertedY = ymax - y -1; tileName = "z%sx%sy%s" % (z,x,invertedY) print tileName tileName = tileName + ext tileName = "/home/murray/temp-tiles/" + tileName with open(tileName, 'wb') as output_file: output_file.write(row["tile_data"]) #uploadToDataStore(tileName); def uploadTiles(): files = glob.glob("/home/murray/temp-tiles/*png") for f in files: uploadToDataStore(f) def uploadToDataStore(tileName): #r = requests.get('http://google.com') #unicode.capitalize() print tileName url = 'http://praxis-cab-89616.appspot.com/index.jsp' #url = 'http://localhost:8888/index.jsp' txtParsePostUrl = requests.get(url) match = re.search(r'action="(.*?)"', txtParsePostUrl.text) # If-statement after search() tests if it succeeded postUrl = None if match: postUrl = match.group(1) ## 'found word:cat' else: print 'did not find' files = {'file': (os.path.basename(tileName), open(tileName, 'rb'), 'image/png')} r = requests.post(postUrl, files=files) #readMbtileDBAndWriteToFiles() uploadTiles() <file_sep>''' Created on 1 Jan 2015 @author: murray ''' import re import sys colorred = '501400FF' colorblue = '50F03214' colorblack = '50000000' #Find all coordinates with open('/home/murray/map-mobile/app/src/main/assets/black-route.kml') as fp: cords = '' for line in fp: m = re.search("<coordinates>(.*?)</coordinates>", line) if m: cords += m.groups()[0] + ',' kmlbody =''' <?xml version="1.0" encoding="utf-8" ?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document id="root_doc"> <Schema name="green_route" id="green_route"> <SimpleField name="id" type="int"></SimpleField> </Schema> <Folder><name>green_route</name> <Placemark> <Style><LineStyle><color>{color}</color><width>14</width></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style> <ExtendedData><SchemaData schemaUrl="#green_route"> <SimpleData name="id">2</SimpleData> </SchemaData></ExtendedData> <LineString><altitudeMode>relativeToGround</altitudeMode><coordinates>{co}</coordinates></LineString> </Placemark> </Folder> </Document></kml>''' kmlbody =kmlbody.format(co=cords, color=colorblack) print kmlbody<file_sep>''' Created on 12 Jan 2015 @author: murrayking from owslib.csw import CatalogueServiceWeb >>> csw = CatalogueServiceWeb('http://geodiscover.cgdi.ca/wes/serviceManagerCSW/csw') >>> csw.identification.type ''' datagov = 'http://csw.data.gov.uk/geonetwork/srv/en/csw' inspireportal = 'http://inspire-geoportal.ec.europa.eu/GeoportalProxyWebServices/resources/OGCCSW202/AT?service=CSW&version=2.0.2&request=GetCapabilities' localhost = 'http://localhost:8000/?service=CSW' gogeo = 'http://gogeo-at.edina.ac.uk/geonetwork/srv/en/csw?request=GetCapabilities&version=2.0.2&service=CSW' scotsdi = 'http://scotgovsdi.edina.ac.uk/geonetwork/srv/en/csw?request=GetCapabilities&version=2.0.2&service=CSW' # from owslib.csw import CatalogueServiceWeb # csw = CatalogueServiceWeb(datagov, version='2.0.2') # print(csw.identification.type) # csw.getrecords(keywords=['birds','fowl'], maxrecords=20) # print csw.results # # for rec in csw.records: # print csw.records[rec].title # print csw.results # csw.getrecords(bbox=[-179, -77, 180, 80], maxrecords=20, startposition=10) # for rec in csw.records: # print csw.records[rec].title from owslib.csw import CatalogueServiceWeb import os recobjs = [] # records pagesize=10 # if init raises error, this might not be a CSW csw = CatalogueServiceWeb(gogeo, timeout=60) outPutDir = "/Users/murrayking/Documents/Gogeo2" # get all supported typenames of metadata # so we can harvest the entire CSW # try for ISO, settle for Dublin Core csw_typenames = 'csw:Record' csw_outputschema = 'http://www.opengis.net/cat/csw/2.0.2' grop = csw.get_operation_by_name('GetRecords') if all(['gmd:MD_Metadata' in grop.parameters['typeNames']['values'], 'http://www.isotc211.org/2005/gmd' in grop.parameters['outputSchema']['values']]): csw_typenames = 'gmd:MD_Metadata' csw_outputschema = 'http://www.isotc211.org/2005/gmd' # now get all records # get total number of records to loop against try: csw.getrecords2(typenames=csw_typenames, resulttype='hits', outputschema=csw_outputschema) matches = csw.results['matches'] except: # this is a CSW, but server rejects query raise RuntimeError(csw.response) if pagesize > matches: pagesize = matches def makeGetRecordsCall(csw, csw_typenames, r, pagesize, csw_outputschema): def getrecords2(): return csw.getrecords2(typenames=csw_typenames, startposition=r, maxrecords=pagesize, outputschema=csw_outputschema, esn='full') return getrecords2 failureStartAtRecord=22611 # loop over all catalogue records incrementally for r in range(failureStartAtRecord, matches+1, pagesize): getrecords = makeGetRecordsCall(csw, csw_typenames, r, pagesize, csw_outputschema) try: getrecords() except Exception, err: # this is a CSW, but server rejects query #retry again just incase try: getrecords() except Exception, err: getrecords() # this is a CSW, but server rejects query for k, v in csw.records.iteritems(): if csw_typenames == 'gmd:MD_Metadata': print(v.xml) print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") fn = outPutDir + "/" + k +".xml" dn = os.path.dirname(fn) if not os.path.exists(dn): os.makedirs(dn) print(fn) print("Number of records" + str(r)) with open(fn, "w") as text_file: text_file.write(v.xml) else: print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") print("NOt iso record ignore")
00ee021fc7a3e71343cd92024f4b06046ddc6385
[ "Python" ]
12
Python
murrayk/pythonscripts
9a227371ab9ace3c53140c9ebf3a9129ce2f5dd0
cee4837dc3696302acf233a5f328b33378d2117f
refs/heads/master
<repo_name>BrunoSilver/Hamilton<file_sep>/aula1/src/main/java/com/usjt/aula1/controller/TempoController.java package com.usjt.aula1.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import com.usjt.aula1.model.Tempo; import com.usjt.aula1.repository.TempoRepository; @Controller public class TempoController { @Autowired private TempoRepository tempRepo; @GetMapping("/listar") public ModelAndView listar() { ModelAndView mv = new ModelAndView("listar"); mv.addObject(new Tempo()); List<Tempo> tempos = tempRepo.findAll(); mv.addObject("tempos", tempos); return mv; } } <file_sep>/aula2/src/main/java/com/usjt/aula1/service/TempoService.java package com.usjt.aula1.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.usjt.aula1.model.Tempo; import com.usjt.aula1.repository.TempoRepository; @Service public class TempoService { @Autowired private TempoRepository tempRepo; public List<Tempo> listar() { return tempRepo.findAll(); } public void cadastrar(Tempo tempo) { tempRepo.save(tempo); } }
b0cd926b6750145ba42b004897b032f3a29ff01c
[ "Java" ]
2
Java
BrunoSilver/Hamilton
883c0399ca2b73cabd450aaa34affb8b312f4020
f2a768f96433e3d86e95929ff0a615adc1e4c22e
refs/heads/master
<repo_name>Okwori/hierarchy<file_sep>/src/test/java/com/kontrola/controller/HierarchyControllerTest.java package com.kontrola.controller; import com.kontrola.controller.rest.HierarchyRestController; import com.kontrola.error.HierarchyErrorHandler; import com.kontrola.model.Hierarchy; import com.kontrola.service.HierarchyService; import de.bechte.junit.runners.context.HierarchicalContextRunner; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static com.kontrola.controller.TestDoubles.stub; import static com.kontrola.controller.WebTestConfig.objectMapperHttpMessageConverter; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(HierarchicalContextRunner.class) @Category(UnitTest.class) public class HierarchyControllerTest { private MockMvc mockMvc; @Autowired private HierarchyService hierarchyService; private static final Long nodeId = 1L; @Before public void configureTheSystemUnderTest() { hierarchyService = stub(HierarchyService.class); mockMvc = MockMvcBuilders.standaloneSetup(new HierarchyRestController(hierarchyService)) .setControllerAdvice(new HierarchyErrorHandler()) .setMessageConverters(objectMapperHttpMessageConverter()) .build(); } public class AddNode { private final String URL_ADD_NODE = "http://localhost:8080/hierarchy/addNode"; private Hierarchy hierarchy; private final String REQUEST_PARAMETER_NODE_NAME = "nodeName"; private final String REQUEST_PARAMETER_NODE_NAME_VALUE = "simon34"; private final String REQUEST_PARAMETER_OLD_NODE_NAME = "oldNode"; private final String REQUEST_PARAMETER_PARENT_NODE_NAME = "parentNodeName"; private final String REQUEST_PARAMETER_PARENT_NODE_NAME_VALUE = "CEO"; public class WhenNodeIsNull { @Before public void createEmptyInput() { hierarchy = new Hierarchy(); hierarchy.setName(null); hierarchy.setParent(null); } @Test public void HttpStatusCodeBadRequest() throws Exception { mockMvc.perform(get(URL_ADD_NODE) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(WebTestUtil.convertObjectToJsonBytes(hierarchy)) ) .andExpect(status().isBadRequest()); } @Test public void NullNodeHttpStatusCodeBadRequest() throws Exception { mockMvc.perform(get(URL_ADD_NODE) .param(REQUEST_PARAMETER_NODE_NAME, hierarchy.getName()) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(WebTestUtil.convertObjectToJsonBytes(hierarchy)) ) .andExpect(status().isBadRequest()); } } public class WhenParentNodeNotFound { @SuppressWarnings("Duplicates") @Before public void configureTestCases() { Hierarchy parent = new Hierarchy("CEO"); Hierarchy child = new Hierarchy("CFO"); Hierarchy child2 = new Hierarchy("CMO"); parent.setParent(null); child.setParent(parent); child2.setParent(parent); hierarchyService.save(parent); hierarchyService.save(child); hierarchyService.save(child2); } @Test public void shouldReturnHttpStatusCodeCreated() throws Exception { mockMvc.perform(get(URL_ADD_NODE) .param(REQUEST_PARAMETER_NODE_NAME, REQUEST_PARAMETER_NODE_NAME_VALUE) .param(REQUEST_PARAMETER_PARENT_NODE_NAME, REQUEST_PARAMETER_PARENT_NODE_NAME_VALUE) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(WebTestUtil.convertObjectToJsonBytes(hierarchy)) ) .andExpect(status().isOk()); } // @Test // public void shouldReturn500ErrorWhenParentNodeIsNotFound() throws Exception { // mockMvc.perform(get(URL_ADD_NODE) // .param(REQUEST_PARAMETER_NODE_NAME, REQUEST_PARAMETER_NODE_NAME_VALUE) // .param(REQUEST_PARAMETER_PARENT_NODE_NAME, "grtgrgvrtg455") // .contentType(MediaType.APPLICATION_JSON_UTF8) // .content(WebTestUtil.convertObjectToJsonBytes(hierarchy)) // ) // .andExpect(status().isInternalServerError()); // } // } } public class Delete { public class WhenHierarchyIsFound { static final String URL_DELETE = "/hierarchy/deleteNode/"; static final String URL_DELETE_PARAM = "name"; String nodeName = ""; @SuppressWarnings("Duplicates") @Before public void returnDeleted() { // Hierarchy deleted = hierarchyService.getOne(nodeId); Hierarchy parent = new Hierarchy("CEO"); Hierarchy child = new Hierarchy("CFO"); Hierarchy child2 = new Hierarchy("CMO"); parent.setParent(null); child.setParent(parent); child2.setParent(parent); hierarchyService.save(parent); hierarchyService.save(child); hierarchyService.save(child2); } @Test public void shouldReturnHttpStatusCodeOk() throws Exception { nodeName = "CFO"; mockMvc.perform(get(URL_DELETE) .param(URL_DELETE_PARAM, nodeName)) .andExpect(status().isOk()); } // @Test // public void shouldReturnHierarchyTreeAsJson() throws Exception { // mockMvc.perform(get(URL_DELETE) // .param(URL_DELETE_PARAM, nodeName)) // .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); // } // @Test // public void shouldReturnCorrectInformation() throws Exception { // mockMvc.perform(get("http://localhost:8080/hierarchy/get")) // .andExpect(jsonPath("$", is("CEO"))) // // } // TODO More TEST! } } } <file_sep>/src/main/java/com/kontrola/Application.java package com.kontrola; public interface Application { } <file_sep>/src/main/java/com/kontrola/model/Hierarchy.java package com.kontrola.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** * Created by <NAME> on consc - 5/10/2018. */ @Entity @Table(name = "hierarchy") @JsonPropertyOrder({"name", "children"}) @JsonIgnoreProperties(ignoreUnknown = true) public class Hierarchy { @JsonIgnore @Id @GeneratedValue @Column(name = "id") private Long id; @Column(name = "name") private String name; @JsonIgnore @ManyToOne @JoinColumn(name = "parent_id") private Hierarchy parent; // @JsonIgnore @JsonProperty("children") @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER) private Set<Hierarchy> subchilds = new HashSet<>(); public Hierarchy() { } public Hierarchy(String name) { this.name = name; } public Hierarchy(String name, Hierarchy parent) { this.name = name; this.parent = parent; } 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 Hierarchy getParent() { return parent; } public void setParent(Hierarchy parent) { this.parent = parent; } // @JsonProperty("parent") @JsonIgnore public String getParentNameNotNul() throws NullPointerException { if (getParent() == null) return null; return getParent().getName(); } public Set<Hierarchy> getSubchilds() { return subchilds; } public void setSubchilds(Set<Hierarchy> subchilds) { this.subchilds = subchilds; } } <file_sep>/README.md # Kontrola Hierarchy App. - Sample [SpringMVC][2] + [Thymeleaf][4] + [D3][5] + [MySQL][6] [2]: https://github.com/spring-projects [4]: https://github.com/thymeleaf/thymeleaf-spring [5]: https://github.com/d3/d3 [6]: https://www.mysql.com/ ## Prerequisites Java 8, Maven and MySQL ## Running To start a web server for the application, run: mvn test tomcat7:run Runs on: locahost:8080 Swaggger UI localhost:8080/swagger-ui.html ## License Copyright © 2018 <NAME>
c473bc6eb6791e48cac4500e18672758a5eb5907
[ "Markdown", "Java" ]
4
Java
Okwori/hierarchy
27f3628093b05ce9e6eea10c81a9eaa83c8fc446
c19b90424113988848031e88a00569ad04516bf8
refs/heads/master
<repo_name>ifa6/p2<file_sep>/pkg/kv-consul/README.md pp-kv-consul ============ The platform requires an interface to a k/v store that provides a consistent view of the data. It only needs to be available for changes. If it is not available, applications running on the platform should be unaffected. This implementation is backed by Consul. <file_sep>/pkg/runit/runit_service.go package runit import ( "bytes" "os/exec" "github.com/square/p2/pkg/util" ) type SV struct { Bin string } var DefaultSV = &SV{"/usr/bin/sv"} type Service struct { Path string Name string } func (sv *SV) execOnService(service *Service, toRun string) (string, error) { cmd := exec.Command(sv.Bin, toRun, service.Path) buffer := bytes.Buffer{} cmd.Stdout = &buffer err := cmd.Run() if err != nil { return buffer.String(), util.Errorf("Could not %s service %s: %s", toRun, service.Name, err) } return buffer.String(), nil } func (sv *SV) Start(service *Service) (string, error) { return sv.execOnService(service, "start") } func (sv *SV) Stop(service *Service) (string, error) { return sv.execOnService(service, "stop") } <file_sep>/pkg/artifact/app_manifest.go package artifact import ( "io/ioutil" "os" "gopkg.in/yaml.v2" ) type AppManifest struct { Ports map[int][]string `yaml:"ports"` } func ManifestFromPath(path string) (*AppManifest, error) { f, err := os.Open(path) if err != nil { return nil, err } bytes, err := ioutil.ReadAll(f) if err != nil { return nil, err } return ManifestFromBytes(bytes) } func ManifestFromBytes(bytes []byte) (*AppManifest, error) { manifest := &AppManifest{} if err := yaml.Unmarshal(bytes, manifest); err != nil { return nil, err } return manifest, nil } <file_sep>/pkg/config/config_test.go package config import ( "os" "path" "runtime" "testing" ) func testFilePath() string { _, filename, _, _ := runtime.Caller(1) return path.Join(path.Dir(filename), "fake_config_file.yaml") } func readTestFile() *Config { cfg, err := LoadConfigFile(testFilePath()) if err != nil { panic(err.Error()) } return cfg } func TestConfigFileCanReadStringKeys(t *testing.T) { app := readTestFile().ReadString("app") if app != "multicurse" { t.Fatal("Expected config to be able to read the app name") } } func TestConfigCanBeReadFromEnvironment(t *testing.T) { prev := os.Getenv("CONFIG_PATH") os.Setenv("CONFIG_PATH", testFilePath()) defer os.Setenv("CONFIG_PATH", prev) cfg, err := LoadFromEnvironment() if err != nil { t.Fatalf("An error occurred while trying to load the test configuration: %s", err) } app := cfg.ReadString("app") if app != "multicurse" { t.Fatal("Expected environment-backed config to be able to read the app name") } } <file_sep>/Rakefile def e(cmd) puts cmd system(cmd) || abort("Error running `#{cmd}`") end task :godep_check do system("which godep") || abort("You do not have godep installed. Run `go get github.com/tools/godep` and ensure that it's on your PATH") end desc 'Get deps for all projects.' task :deps => :godep_check do e "go get -v -t ./..." e "godep save ./..." end desc 'Build all projects' task :build => :godep_check do e "godep go build -v ./..." end desc 'Test all projects' task :test => [:godep_check, :build] do e "godep go test -timeout 10s -v ./..." end desc 'Update all dependencies' task :update => :godep_check do e "go get -u -t -v ./..." e "godep update .../..." end desc 'Install all built binaries' task :install => :godep_check do e "godep go install ./..." end desc 'By default, gather dependencies, build and test' task :default => [:deps, :test, :install] <file_sep>/pkg/pods/hoist_executable.go package pods import ( "github.com/square/p2/pkg/runit" ) type HoistExecutable struct { runit.Service execPath string } <file_sep>/README.md # Platypus Platform: Tools for Scalable Software Deployment [![Build Status](https://travis-ci.org/square/p2.svg?branch=master)](https://travis-ci.org/square/p2) This is a collection of tools intended to allow huge fleets of machines to participate in safe, flexible and scalable deployment models. **This project is still under development and should not be used for anything in production yet. We are not seeking external contributors at this time** # Playing Around To build the tools in `pp`, run `rake build`. The `bin` subdirectory contains agents and executables, the `pkg` directory contains useful libraries for Go. We strongly believe in small things that do one thing well. # License [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) <file_sep>/pkg/kv-consul/watch.go package ppkv import ( "time" "github.com/armon/consul-api" ) type KV interface { List(string, *consulapi.QueryOptions) (consulapi.KVPairs, *consulapi.QueryMeta, error) } // Modified code stolen from https://github.com/ryanbreen/fsconsul/blob/master/watch.go#L172 func Watch( kv KV, prefix string, opts consulapi.QueryOptions, // pass-by-value since we're going to be modifying it pairCh chan<- consulapi.KVPairs, errCh chan<- error, quitCh <-chan struct{}) { // Get the initial list of k/v pairs. We don't do a retryableList // here because we want a fast fail if the initial request fails. pairs, meta, err := kv.List(prefix, &opts) if err != nil { errCh <- err return } // Send the initial list out right away pairCh <- pairs // Loop forever (or until quitCh is closed) and watch the keys // for changes. curIndex := meta.LastIndex for { select { case <-quitCh: return default: } pairs, meta, err = retryableList( func() (consulapi.KVPairs, *consulapi.QueryMeta, error) { opts.WaitIndex = curIndex return kv.List(prefix, &opts) }) if err != nil { errCh <- err continue } pairCh <- pairs curIndex = meta.LastIndex } } // This function is able to call KV listing functions and retry them. // We want to retry if there are errors because it is safe (GET request), // and erroring early is MUCH more costly than retrying over time and // delaying the configuration propagation. func retryableList(f func() (consulapi.KVPairs, *consulapi.QueryMeta, error)) (consulapi.KVPairs, *consulapi.QueryMeta, error) { i := 0 for { p, m, e := f() if e != nil { if i >= 3 { return nil, nil, e } i++ // Reasonably arbitrary sleep to just try again... It is // a GET request so this is safe. time.Sleep(time.Duration(i*2) * time.Second) } return p, m, e } } <file_sep>/pkg/pods/hoist_launchable_test.go package pods import ( "fmt" "io/ioutil" "os" "path" "runtime" "strings" "testing" "github.com/square/p2/pkg/runit" "github.com/square/p2/pkg/util" . "github.com/anthonybishopric/gotcha" ) type fakeCurl struct { url string outPath string } func (fc *fakeCurl) File(url string, outPath string, args ...interface{}) error { fc.url = url fc.outPath = outPath f, err := os.OpenFile(outPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) defer f.Close() if err != nil { return err } f.Write([]byte("test worked!")) return nil } func TestInstall(t *testing.T) { tempDir := os.TempDir() testPath := path.Join(tempDir, "test_launchable.tar.gz") testLocation := "http://someserver/test_launchable.tar.gz" os.Remove(testPath) launchableStanzas := getLaunchableStanzasFromTestManifest() podId := getPodIdFromTestManifest() for _, stanza := range launchableStanzas { fc := new(fakeCurl) launchable := &HoistLaunchable{testLocation, stanza.LaunchableId, podId, fc.File, tempDir} launchable.Install() Assert(t).AreEqual(fc.url, testLocation, "The correct url wasn't set for the curl library") Assert(t).AreEqual(fc.outPath, testPath, "The correct url wasn't set for the curl library") fileContents, err := ioutil.ReadFile(testPath) Assert(t).IsNil(err, "Didn't expect an error when reading the test file") Assert(t).AreEqual(string(fileContents), "test worked!", "Test file didn't have the expected contents") } } func TestInstallDir(t *testing.T) { tempDir := os.TempDir() testLocation := "http://someserver/test_launchable_abc123.tar.gz" launchable := &HoistLaunchable{testLocation, "testLaunchable", "testPod", new(fakeCurl).File, tempDir} installDir := launchable.InstallDir() expectedDir := path.Join(tempDir, "installs", "test_launchable_abc123") Assert(t).AreEqual(installDir, expectedDir, "Install dir did not have expected value") } func FakeHoistLaunchableForDir(dirName string) *HoistLaunchable { _, filename, _, _ := runtime.Caller(0) launchableInstallDir := path.Join(path.Dir(filename), dirName) launchable := &HoistLaunchable{"testLaunchable.tar.gz", "testLaunchable", "testPod", new(fakeCurl).File, launchableInstallDir} return launchable } func TestMultipleExecutables(t *testing.T) { executables, err := FakeHoistLaunchableForDir("multiple_script_test_hoist_launchable").Executables(runit.DefaultBuilder) Assert(t).IsNil(err, "Error occurred when obtaining runit services for launchable") expectedServicePaths := []string{"/var/service/testPod__testLaunchable__script1", "/var/service/testPod__testLaunchable__script2"} Assert(t).AreEqual(2, len(executables), "Found an unexpected number of runit services") Assert(t).AreEqual(executables[0].Path, expectedServicePaths[0], "Runit service paths from launchable did not match expected") Assert(t).AreEqual(executables[1].Path, expectedServicePaths[1], "Runit service paths from launchable did not match expected") } func TestSingleRunitService(t *testing.T) { executables, err := FakeHoistLaunchableForDir("single_script_test_hoist_launchable").Executables(runit.DefaultBuilder) Assert(t).IsNil(err, "Error occurred when obtaining runit services for launchable") expectedServicePaths := []string{"/var/service/testPod__testLaunchable__script1"} Assert(t).AreEqual(len(executables), 1, "Found an unexpected number of runit services") Assert(t).AreEqual(executables[0].Path, expectedServicePaths[0], "Runit service paths from launchable did not match expected") } func TestDisable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("successful_scripts_test_hoist_launchable") disableOutput, err := hoistLaunchable.Disable() Assert(t).IsNil(err, "Got an unexpected error when calling disable on the test hoist launchable") expectedDisableOutput := "disable invoked\n" Assert(t).AreEqual(disableOutput, expectedDisableOutput, "Did not get expected output from test disable script") } func TestFailingDisable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("failing_scripts_test_hoist_launchable") disableOutput, err := hoistLaunchable.Disable() Assert(t).IsNotNil(err, "Expected disable to fail for this test, but it didn't") expectedDisableOutput := "Error: this script failed\n" Assert(t).AreEqual(disableOutput, expectedDisableOutput, "Did not get expected output from test disable script") } // providing a disable script is optional, make sure we don't error func TestNonexistentDisable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("nonexistent_scripts_test_hoist_launchable") disableOutput, err := hoistLaunchable.Disable() Assert(t).IsNil(err, "Got an unexpected error when calling disable on the test hoist launchable") expectedDisableOutput := "" Assert(t).AreEqual(disableOutput, expectedDisableOutput, "Did not get expected output from test disable script") } func TestEnable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("successful_scripts_test_hoist_launchable") enableOutput, err := hoistLaunchable.Enable() Assert(t).IsNil(err, "Got an unexpected error when calling enable on the test hoist launchable") expectedEnableOutput := "enable invoked\n" Assert(t).AreEqual(enableOutput, expectedEnableOutput, "Did not get expected output from test enable script") } func TestFailingEnable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("failing_scripts_test_hoist_launchable") enableOutput, err := hoistLaunchable.Enable() Assert(t).IsNotNil(err, "Expected enable to fail for this test, but it didn't") expectedEnableOutput := "Error: this script failed\n" Assert(t).AreEqual(enableOutput, expectedEnableOutput, "Did not get expected output from test enable script") } // providing an enable script is optional, make sure we don't error func TestNonexistentEnable(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("nonexistent_scripts_test_hoist_launchable") enableOutput, err := hoistLaunchable.Enable() Assert(t).IsNil(err, "Got an unexpected error when calling enable on the test hoist launchable") expectedEnableOutput := "" Assert(t).AreEqual(enableOutput, expectedEnableOutput, "Did not get expected output from test enable script") } func TestStop(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("multiple_script_test_hoist_launchable") sv := runit.SV{util.From(runtime.Caller(0)).ExpandPath("fake_sv")} err := hoistLaunchable.Stop(runit.DefaultBuilder, &sv) Assert(t).IsNil(err, "Got an unexpected error when attempting to stop runit services") } func TestFailingStop(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("multiple_script_test_hoist_launchable") sv := runit.SV{util.From(runtime.Caller(0)).ExpandPath("erring_sv")} err := hoistLaunchable.Stop(runit.DefaultBuilder, &sv) Assert(t).IsNotNil(err, "Expected sv stop to fail for this test, but it didn't") } func FakeServiceBuilder() *runit.ServiceBuilder { testDir := os.TempDir() fakeSBBinPath := util.From(runtime.Caller(0)).ExpandPath("fake_servicebuilder") configRoot := path.Join(testDir, "/etc/servicebuilder.d") os.MkdirAll(configRoot, 0755) _, err := os.Stat(configRoot) if err != nil { panic("unable to create test dir") } stagingRoot := path.Join(testDir, "/var/service-stage") os.MkdirAll(stagingRoot, 0755) runitRoot := path.Join(testDir, "/var/service") os.MkdirAll(runitRoot, 0755) return &runit.ServiceBuilder{ ConfigRoot: configRoot, StagingRoot: stagingRoot, RunitRoot: runitRoot, Bin: fakeSBBinPath, } } func TestStart(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("multiple_script_test_hoist_launchable") serviceBuilder := FakeServiceBuilder() sv := runit.SV{util.From(runtime.Caller(0)).ExpandPath("fake_sv")} executables, err := hoistLaunchable.Executables(serviceBuilder) err = hoistLaunchable.Start(serviceBuilder, &sv) outFilePath := path.Join(serviceBuilder.ConfigRoot, "testPod__testLaunchable.yaml") Assert(t).IsNil(err, "Got an unexpected error when attempting to start runit services") expectedLines := []string{ fmt.Sprintf("%s:", executables[0].Name), " run:", fmt.Sprintf(" - %s", executables[0].execPath), fmt.Sprintf("%s:", executables[1].Name), " run:", fmt.Sprintf(" - %s", executables[1].execPath), "", } expected := strings.Join(expectedLines, "\n") f, err := os.Open(outFilePath) defer f.Close() bytes, err := ioutil.ReadAll(f) Assert(t).IsNil(err, "Got an unexpected error reading the servicebuilder yaml file") Assert(t).AreEqual(string(bytes), expected, "Servicebuilder yaml file didn't have expected contents") } func TestFailingStart(t *testing.T) { hoistLaunchable := FakeHoistLaunchableForDir("multiple_script_test_hoist_launchable") serviceBuilder := FakeServiceBuilder() sv := runit.SV{util.From(runtime.Caller(0)).ExpandPath("erring_sv")} executables, _ := hoistLaunchable.Executables(serviceBuilder) err := hoistLaunchable.Start(serviceBuilder, &sv) outFilePath := path.Join(serviceBuilder.ConfigRoot, "testPod__testLaunchable.yaml") Assert(t).IsNotNil(err, "Expected an error starting runit services") expectedLines := []string{ fmt.Sprintf("%s:", executables[0].Name), " run:", fmt.Sprintf(" - %s", executables[0].execPath), fmt.Sprintf("%s:", executables[1].Name), " run:", fmt.Sprintf(" - %s", executables[1].execPath), "", } expected := strings.Join(expectedLines, "\n") f, err := os.Open(outFilePath) defer f.Close() bytes, err := ioutil.ReadAll(f) Assert(t).IsNil(err, "Got an unexpected error reading the servicebuilder yaml file") Assert(t).AreEqual(string(bytes), expected, "Servicebuilder yaml file didn't have expected contents") } <file_sep>/pkg/kv-consul/kv.go package ppkv import ( "encoding/json" "errors" "path" "github.com/armon/consul-api" ) type Client struct { kv *consulapi.KV } func NewClient() (*Client, error) { client, err := consulapi.NewClient(consulapi.DefaultConfig()) if err != nil { return nil, err } return &Client{ kv: client.KV(), }, nil } func (c *Client) List(query string) (map[string]interface{}, error) { xs, _, err := c.kv.List(query, nil) if err != nil { return nil, err } ret := map[string]interface{}{} for _, x := range xs { var value interface{} keyName := path.Base(x.Key) err := json.Unmarshal(x.Value, &value) if err != nil { return nil, err } ret[keyName] = value } return ret, nil } func (c *Client) Get(query string, ret interface{}) error { data, _, err := c.kv.Get(query, nil) if err != nil { return err } if data == nil { return errors.New("key not present") } if err := json.Unmarshal(data.Value, &ret); err != nil { return err } return nil } func (c *Client) DeleteTree(query string) error { _, err := c.kv.DeleteTree(query, nil) return err } func (c *Client) Put(key string, value interface{}) error { body, err := json.Marshal(value) if err != nil { return err } node := &consulapi.KVPair{ Key: key, Value: body, } _, err = c.kv.Put(node, nil) return err } <file_sep>/pkg/pods/manifest_parser_test.go package pods import ( "bytes" "path" "runtime" "testing" . "github.com/anthonybishopric/gotcha" ) func TestPodManifestCanBeRead(t *testing.T) { _, filename, _, _ := runtime.Caller(0) testPath := path.Join(path.Dir(filename), "test_manifest.yaml") manifest, err := PodManifestFromPath(testPath) Assert(t).IsNil(err, "Should not have failed to get pod manifest.") Assert(t).AreEqual("hello", manifest.Id, "Id read from manifest didn't have expected value") Assert(t).AreEqual(manifest.LaunchableStanzas["app"].Location, "http://localhost:8000/foo/bar/baz/hello_abc123_vagrant.tar.gz", "Location read from manifest didn't have expected value") Assert(t).AreEqual("hoist", manifest.LaunchableStanzas["app"].LaunchableType, "LaunchableType read from manifest didn't have expected value") Assert(t).AreEqual("hello", manifest.LaunchableStanzas["app"].LaunchableId, "LaunchableId read from manifest didn't have expected value") Assert(t).AreEqual("staging", manifest.Config["ENVIRONMENT"], "Should have read the ENVIRONMENT from the config stanza") hoptoad := manifest.Config["hoptoad"].(map[interface{}]interface{}) Assert(t).IsTrue(len(hoptoad) == 3, "Should have read the hoptoad value from the config stanza") } func TestPodManifestCanBeWritten(t *testing.T) { manifest := PodManifest{ Id: "thepod", LaunchableStanzas: make(map[string]LaunchableStanza), Config: make(map[string]interface{}), } launchable := LaunchableStanza{ LaunchableType: "hoist", LaunchableId: "web", Location: "https://localhost:4444/foo/bar/baz.tar.gz", } manifest.LaunchableStanzas["my-app"] = launchable manifest.Config["ENVIRONMENT"] = "staging" buff := bytes.Buffer{} manifest.Write(&buff) expected := `id: thepod launchables: my-app: launchable_type: hoist launchable_id: web location: https://localhost:4444/foo/bar/baz.tar.gz config: ENVIRONMENT: staging ` Assert(t).AreEqual(expected, buff.String(), "Expected the manifest to marshal to the given yaml") } <file_sep>/pkg/intent/intent.go // Package intent provides a kv-store agnostic way to watch a path for changes to // a collection of pods. package intent import ( "github.com/armon/consul-api" "github.com/square/p2/pkg/kv-consul" "github.com/square/p2/pkg/pods" "github.com/square/p2/pkg/util" ) type WatchOptions struct { Token string } type IntentWatcher struct { Opts WatchOptions ConsulOpts *consulapi.Config WatchFn func(ppkv.KV, string, consulapi.QueryOptions, chan<- consulapi.KVPairs, chan<- error, <-chan struct{}) } func NewWatcher(opts WatchOptions) *IntentWatcher { return &IntentWatcher{ Opts: opts, ConsulOpts: consulapi.DefaultConfig(), WatchFn: ppkv.Watch, } } // Watch the kv-store for changes to any pod under the given path. All pods will be returned // if any of them change; it is up to the client to ignore unchanged pods sent via this channel. // Clients that respond to changes to pod manifests should be capable // of acting on multiple changes at once. The quit channel is used to terminate watching on the // spawned goroutine. The error channel should be observed for errors from the underlying watcher. // If an error occurs during watch, it is the caller's responsibility to quit the watcher. func (i *IntentWatcher) WatchPods(path string, quit <-chan struct{}, errChan chan<- error, podCh chan<- pods.PodManifest) error { client, err := consulapi.NewClient(i.ConsulOpts) if err != nil { return util.Errorf("Could not initialize consul client: %s", err) } opts := consulapi.QueryOptions{Token: i.Opts.Token} defer close(podCh) defer close(errChan) kvPairCh := make(chan consulapi.KVPairs) kvQuitCh := make(chan struct{}) defer close(kvQuitCh) kvErrCh := make(chan error) go i.WatchFn(client.KV(), path, opts, kvPairCh, kvErrCh, kvQuitCh) for { select { case <-quit: kvQuitCh <- struct{}{} return nil case err := <-kvErrCh: errChan <- err case rawManifests := <-kvPairCh: for _, pair := range rawManifests { manifest, err := pods.PodManifestFromBytes(pair.Value) if err != nil { errChan <- util.Errorf("Could not parse pod manifest at %s: %s", pair.Key, err) } else { podCh <- *manifest } } } } } <file_sep>/pkg/intent/intent_test.go package intent import ( "errors" "testing" . "github.com/anthonybishopric/gotcha" "github.com/armon/consul-api" "github.com/square/p2/pkg/kv-consul" "github.com/square/p2/pkg/pods" ) func makePodKv(key string, value string) *consulapi.KVPair { return &consulapi.KVPair{ Key: key, Value: []byte(value), } } func happyWatch(kv ppkv.KV, prefix string, opts consulapi.QueryOptions, kvCh chan<- consulapi.KVPairs, errCh chan<- error, quitCh <-chan struct{}) { for { kvPairs := consulapi.KVPairs{} kvPairs = append(kvPairs, makePodKv("foo", `id: thepod launchables: my-app: launchable_type: hoist launchable_id: foo location: https://localhost:4444/foo/bar/baz/baz.tar.gz config: ENVIRONMENT: staging `, )) select { case <-quitCh: return case kvCh <- kvPairs: } } } func partiallyHappyWatch(kv ppkv.KV, prefix string, opts consulapi.QueryOptions, kvCh chan<- consulapi.KVPairs, errCh chan<- error, quitCh <-chan struct{}) { for { kvPairs := consulapi.KVPairs{} kvPairs = append(kvPairs, makePodKv("foo", `id: thepod launchables: my-app: launchable_type: hoist launchable_id: foo location: https://localhost:4444/foo/bar/baz/baz.tar.gz config: ENVIRONMENT: staging `, )) kvPairs = append(kvPairs, makePodKv("invalid", "invalid")) select { case <-quitCh: return case kvCh <- kvPairs: } } } func errorWatch(kv ppkv.KV, prefix string, opts consulapi.QueryOptions, kvCh chan<- consulapi.KVPairs, errCh chan<- error, quitCh <-chan struct{}) { for { select { case <-quitCh: return case errCh <- errors.New("ERROR"): } } } func TestHappyPathPodWatch(t *testing.T) { i := IntentWatcher{WatchOptions{}, consulapi.DefaultConfig(), happyWatch} path := "/nodes/ama1.dfw.square" quit := make(chan struct{}) defer close(quit) errChan := make(chan error) podCh := make(chan pods.PodManifest) go i.WatchPods(path, quit, errChan, podCh) select { case err := <-errChan: t.Fatalf("Should not have resulted in an error: %s", err) case manifest := <-podCh: Assert(t).AreEqual("thepod", manifest.Id, "The ID of the manifest should have matched the document") } } func TestErrorPath(t *testing.T) { i := IntentWatcher{WatchOptions{}, consulapi.DefaultConfig(), errorWatch} path := "/nodes/ama1.dfw.square" quit := make(chan struct{}) defer close(quit) errChan := make(chan error) podCh := make(chan pods.PodManifest) go i.WatchPods(path, quit, errChan, podCh) select { case err := <-errChan: Assert(t).AreEqual("ERROR", err.Error(), "The error should have been returned") case <-podCh: t.Fatal("Should not have received any manifests") } } // This tests the case where an error occurs when parsing a single func TestErrorsAndPodsReturned(t *testing.T) { i := IntentWatcher{WatchOptions{}, consulapi.DefaultConfig(), partiallyHappyWatch} path := "/nodes/ama1.dfw.square" quit := make(chan struct{}) defer close(quit) errChan := make(chan error) podCh := make(chan pods.PodManifest) go i.WatchPods(path, quit, errChan, podCh) var foundErr, foundManifests bool x := 0 for x < 2 { select { case err := <-errChan: Assert(t).IsNotNil(err, "The error should have been returned") foundErr = true x += 1 case manifest := <-podCh: Assert(t).AreEqual("thepod", manifest.Id, "The ID of the manifest should have matched the document") Assert(t).IsFalse(foundManifests, "should not have found more than one manifest") foundManifests = true x += 1 } } Assert(t).IsTrue(foundErr, "Should have seen at least one parsing error") Assert(t).IsTrue(foundManifests, "Should have seen at least one manifest") } <file_sep>/pkg/config/config.go // Package config provides convenience facilities for Golang-based pods to read their // configuration files provided either by the environment or a custom path. package config import ( "errors" "io/ioutil" "os" "gopkg.in/yaml.v1" ) type Config struct { unpacked map[interface{}]interface{} } func LoadFromEnvironment() (*Config, error) { env := os.Getenv("CONFIG_PATH") if env == "" { return nil, errors.New("No value was found for the environment variable CONFIG_PATH") } return LoadConfigFile(env) } func LoadConfigFile(filepath string) (*Config, error) { config := &Config{} contents, err := ioutil.ReadFile(filepath) if err != nil { return nil, err } yaml.Unmarshal(contents, &config.unpacked) return config, nil } func (c *Config) ReadString(key string) string { readVal := c.Read(key) if readVal == nil { return "" } return readVal.(string) } func (c *Config) Read(key string) interface{} { return c.unpacked[key] } <file_sep>/pkg/pods/pod.go package pods import ( "fmt" "os" "path" "github.com/nareix/curl" "github.com/square/p2/pkg/runit" "github.com/square/p2/pkg/util" ) type Pod struct { podManifest *PodManifest } func PodFromManifestPath(path string) (*Pod, error) { podManifest, err := PodManifestFromPath(path) if err != nil { return nil, err } return &Pod{podManifest}, nil } func (pod *Pod) Halt() error { launchables, err := getLaunchablesFromPodManifest(pod.podManifest) if err != nil { return err } for _, launchable := range launchables { err = launchable.Halt(runit.DefaultBuilder, runit.DefaultSV) // TODO: make these configurable if err != nil { return err } } return nil } func (pod *Pod) Launch() error { launchables, err := getLaunchablesFromPodManifest(pod.podManifest) if err != nil { return err } for _, launchable := range launchables { err = launchable.Launch(runit.DefaultBuilder, runit.DefaultSV) // TODO: make these configurable if err != nil { return err } } return nil } func getLaunchablesFromPodManifest(podManifest *PodManifest) ([]HoistLaunchable, error) { launchableStanzas := podManifest.LaunchableStanzas if len(launchableStanzas) == 0 { return nil, util.Errorf("Pod must provide at least one launchable, none found") } launchables := make([]HoistLaunchable, len(launchableStanzas)) var i int = 0 for _, launchableStanza := range launchableStanzas { launchable, err := getLaunchable(launchableStanza, podManifest.Id) if err != nil { return nil, err } launchables[i] = *launchable i++ } return launchables, nil } func PodHomeDir(podId string) string { return path.Join("/data", "pods", podId) } // This assumes all launchables are Hoist artifacts, we will generalize this at a later point func (pod *Pod) Install() error { // if we don't want this to run as root, need another way to create pods directory podsHome := path.Join("/data", "pods") err := os.MkdirAll(podsHome, 0755) if err != nil { return err } podHome := path.Join(podsHome, pod.podManifest.Id) os.Mkdir(podHome, 0755) // this dir needs to be owned by different user at some point launchables, err := getLaunchablesFromPodManifest(pod.podManifest) if err != nil { return err } for _, launchable := range launchables { err := launchable.Install() if err != nil { return err } } return nil } func getLaunchable(launchableStanza LaunchableStanza, podId string) (*HoistLaunchable, error) { if launchableStanza.LaunchableType == "hoist" { launchableRootDir := path.Join(PodHomeDir(podId), launchableStanza.LaunchableId) return &HoistLaunchable{launchableStanza.Location, launchableStanza.LaunchableId, podId, curl.File, launchableRootDir}, nil } else { return nil, fmt.Errorf("%s is not supported yet", launchableStanza.LaunchableType) } } <file_sep>/pkg/pods/pod_test.go package pods import ( "path" "runtime" "testing" . "github.com/anthonybishopric/gotcha" ) func getTestPod() *Pod { _, filename, _, _ := runtime.Caller(0) testPath := path.Join(path.Dir(filename), "test_manifest.yaml") pod, _ := PodFromManifestPath(testPath) return pod } func getLaunchableStanzasFromTestManifest() map[string]LaunchableStanza { return getTestPod().podManifest.LaunchableStanzas } func getPodIdFromTestManifest() string { return getTestPod().podManifest.Id } func TestGetLaunchable(t *testing.T) { launchableStanzas := getLaunchableStanzasFromTestManifest() podId := getPodIdFromTestManifest() Assert(t).AreNotEqual(0, len(launchableStanzas), "Expected there to be at least one launchable stanza in the test manifest") for _, stanza := range launchableStanzas { launchable, _ := getLaunchable(stanza, podId) Assert(t).AreEqual("hello", launchable.id, "LaunchableId did not have expected value") Assert(t).AreEqual("http://localhost:8000/foo/bar/baz/hello_abc123_vagrant.tar.gz", launchable.location, "Launchable location did not have expected value") } } <file_sep>/pkg/pods/hoist_launchable.go package pods import ( "archive/tar" "bytes" "compress/gzip" "io" "io/ioutil" "os" "os/exec" "path" "strings" "time" "github.com/square/p2/pkg/runit" ) // A HoistLaunchable represents a particular install of a hoist artifact. type HoistLaunchable struct { location string id string podId string fetchToFile func(string, string, ...interface{}) error rootDir string } func (hoistLaunchable *HoistLaunchable) Halt(serviceBuilder *runit.ServiceBuilder, sv *runit.SV) error { // probably want to do something with output at some point _, err := hoistLaunchable.Disable() if err != nil { return err } // probably want to do something with output at some point err = hoistLaunchable.Stop(serviceBuilder, sv) if err != nil { return err } return nil } func (hoistLaunchable *HoistLaunchable) Launch(serviceBuilder *runit.ServiceBuilder, sv *runit.SV) error { // Should probably do something with output at some point // probably want to do something with output at some point err := hoistLaunchable.Start(serviceBuilder, sv) if err != nil { return err } _, err = hoistLaunchable.Enable() if err != nil { return err } return nil } func (hoistLaunchable *HoistLaunchable) Disable() (string, error) { output, err := hoistLaunchable.invokeBinScript("disable") // providing a disable script is optional, ignore those errors if err != nil && !os.IsNotExist(err) { return output, err } return output, nil } func (hoistLaunchable *HoistLaunchable) Enable() (string, error) { output, err := hoistLaunchable.invokeBinScript("enable") // providing an enable script is optional, ignore those errors if err != nil && !os.IsNotExist(err) { return output, err } return output, nil } func (hoistLaunchable *HoistLaunchable) invokeBinScript(script string) (string, error) { cmdPath := path.Join(hoistLaunchable.InstallDir(), "bin", script) _, err := os.Stat(cmdPath) if err != nil { return "", err } cmd := exec.Command(cmdPath) buffer := bytes.Buffer{} cmd.Stdout = &buffer err = cmd.Run() if err != nil { return buffer.String(), err } return buffer.String(), nil } func (hoistLaunchable *HoistLaunchable) Stop(serviceBuilder *runit.ServiceBuilder, sv *runit.SV) error { executables, err := hoistLaunchable.Executables(serviceBuilder) if err != nil { return err } for _, executable := range executables { _, err := sv.Stop(&executable.Service) if err != nil { // TODO: FAILURE SCENARIO (what should we do here?) // 1) does `sv stop` ever exit nonzero? // 2) should we keep stopping them all anyway? return err } } return nil } func (hoistLaunchable *HoistLaunchable) Start(serviceBuilder *runit.ServiceBuilder, sv *runit.SV) error { // if the service is new, building the runit services also starts them, making the sv start superfluous but harmless err := hoistLaunchable.BuildRunitServices(serviceBuilder) if err != nil { return err } executables, err := hoistLaunchable.Executables(serviceBuilder) if err != nil { return err } for _, executable := range executables { maxRetries := 3 var err error for i := 0; i < maxRetries; i++ { _, err = sv.Start(&executable.Service) if err == nil { break } <-time.After(1) } if err != nil { return err } } return nil } func (hoistLaunchable *HoistLaunchable) BuildRunitServices(serviceBuilder *runit.ServiceBuilder) error { sbName := strings.Join([]string{hoistLaunchable.podId, "__", hoistLaunchable.id}, "") sbTemplate := runit.NewSBTemplate(sbName) executables, err := hoistLaunchable.Executables(serviceBuilder) if err != nil { return err } for _, executable := range executables { sbTemplate.AddEntry(executable.Name, []string{executable.execPath}) } _, err = serviceBuilder.Write(sbTemplate) if err != nil { return err } _, err = serviceBuilder.Rebuild() if err != nil { return err } return nil } func (hoistLaunchable *HoistLaunchable) Executables(serviceBuilder *runit.ServiceBuilder) ([]HoistExecutable, error) { binLaunchPath := path.Join(hoistLaunchable.InstallDir(), "bin", "launch") binLaunchInfo, err := os.Stat(binLaunchPath) if err != nil { return nil, err } // we support bin/launch being a file, or a directory, so we have to check // ideally a launchable will have just one launch script someday (can't be // a dir) if !(binLaunchInfo.IsDir()) { serviceNameComponents := []string{hoistLaunchable.podId, "__", hoistLaunchable.id} serviceName := strings.Join(serviceNameComponents, "") servicePath := path.Join(serviceBuilder.RunitRoot, serviceName) runitService := &runit.Service{servicePath, serviceName} executable := &HoistExecutable{*runitService, binLaunchPath} return []HoistExecutable{*executable}, nil } else { services, err := ioutil.ReadDir(binLaunchPath) if err != nil { return nil, err } executables := make([]HoistExecutable, len(services)) for i, service := range services { serviceNameComponents := []string{hoistLaunchable.podId, "__", hoistLaunchable.id, "__", service.Name()} serviceName := strings.Join(serviceNameComponents, "") servicePath := path.Join(serviceBuilder.RunitRoot, serviceName) execPath := path.Join(binLaunchPath, service.Name()) runitService := &runit.Service{servicePath, serviceName} executable := &HoistExecutable{*runitService, execPath} executables[i] = *executable } return executables, nil } } func (hoistLaunchable *HoistLaunchable) Install() error { installDir := hoistLaunchable.InstallDir() if _, err := os.Stat(installDir); err == nil { return nil } outPath := path.Join(os.TempDir(), hoistLaunchable.Name()) err := hoistLaunchable.fetchToFile(hoistLaunchable.location, outPath) if err != nil { return err } fd, err := os.Open(outPath) if err != nil { return err } defer fd.Close() err = extractTarGz(fd, installDir) if err != nil { return err } return nil } func (hoistLaunchable *HoistLaunchable) Name() string { _, fileName := path.Split(hoistLaunchable.location) return fileName } func (*HoistLaunchable) Type() string { return "hoist" } func (hoistLaunchable *HoistLaunchable) InstallDir() string { launchableFileName := hoistLaunchable.Name() launchableName := launchableFileName[:len(launchableFileName)-len(".tar.gz")] return path.Join(hoistLaunchable.rootDir, "installs", launchableName) // need to generalize this (no /data/pods assumption) } func extractTarGz(fp *os.File, dest string) (err error) { fz, err := gzip.NewReader(fp) if err != nil { return err } defer fz.Close() tr := tar.NewReader(fz) for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { return err } fpath := path.Join(dest, hdr.Name) if hdr.FileInfo().IsDir() { continue } else { dir := path.Dir(fpath) os.MkdirAll(dir, 0755) f, err := os.OpenFile( fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, hdr.FileInfo().Mode()) if err != nil { return err } defer f.Close() _, err = io.Copy(f, tr) if err != nil { return err } } } return nil } <file_sep>/pkg/logging/logging.go package logger import ( "github.com/Sirupsen/logrus" ) type P2Logger struct { host string topic string logger logrus.Logger } <file_sep>/pkg/pods/manifest_parser.go package pods import ( "fmt" "io" "io/ioutil" "os" "github.com/square/p2/pkg/util" "gopkg.in/yaml.v2" ) type LaunchableStanza struct { LaunchableType string `yaml:"launchable_type"` LaunchableId string `yaml:"launchable_id"` Location string `yaml:"location"` } type PodManifest struct { Id string `yaml:"id"` LaunchableStanzas map[string]LaunchableStanza `yaml:"launchables"` Config map[string]interface{} `yaml:"config"` } func PodManifestFromPath(path string) (*PodManifest, error) { f, err := os.Open(path) if err != nil { return nil, err } bytes, err := ioutil.ReadAll(f) if err != nil { return nil, err } return PodManifestFromBytes(bytes) } func PodManifestFromBytes(bytes []byte) (*PodManifest, error) { podManifest := &PodManifest{} if err := yaml.Unmarshal(bytes, podManifest); err != nil { return nil, fmt.Errorf("Could not read pod manifest: %s", err) } return podManifest, nil } func (manifest *PodManifest) Write(out io.Writer) error { bytes, err := yaml.Marshal(manifest) if err != nil { return util.Errorf("Could not write manifest for %s: %s", manifest.Id, err) } _, err = out.Write(bytes) if err != nil { return util.Errorf("Could not write manifest for %s: %s", manifest.Id, err) } return nil }
94807a9a80095811b32d316457317f59d233f925
[ "Markdown", "Go", "Ruby" ]
19
Markdown
ifa6/p2
de13094971b4dd8d90392d2a927a16498e6e1b85
8bbcdc34ee8dbd6a7ca28b078f8c0b2c7fde0b7b
refs/heads/master
<repo_name>nsuhanshetty/JanataBazaar<file_sep>/JanataBazaar/View/Register/Winform_PurchaseIndentRegistry.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_PurchaseIndentRegistry : WinformRegister { public Winform_PurchaseIndentRegistry() { InitializeComponent(); } private void Winform_PurchaseIndentRegistry_Load(object sender, EventArgs e) { this.toolStrip1.Items.Add(this.SearchToolStrip); } protected void SearchToolStrip_Click(object sender, System.EventArgs e) { if (DateTime.Compare(dtpFrom.Value.Date, dtpTo.Value.Date) > 0) { MessageBox.Show("From Date of search cannot be greater than To Date of search", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } List<PurchaseIndent> indentList = new List<PurchaseIndent>(); indentList = Builders.PurchaseIndentBuilder.GetIndentList(dtpFrom.Value.Date, dtpTo.Value.Date); if (indentList != null || indentList.Count != 0) { dgvRegister.DataSource = (from item in indentList select new { item.ID, item.DateOfIndent }).ToList(); dgvRegister.Columns["ID"].Visible = false; } else { dgvRegister.DataSource = null; } } protected override void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); new Winform_PurchaseIndentForm(_ID).ShowDialog(); } protected override void NewToolStrip_Click(object sender, System.EventArgs e) { new Winform_PurchaseIndentForm().ShowDialog(); this.SearchToolStrip_Click(this, new EventArgs()); } } } <file_sep>/JanataBazaar/NHibernateHelper.cs using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using JanataBazaar; using NHibernate; namespace JanataBazaar { public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) InitializeSessionFactory(); return _sessionFactory; } } /*Strongly typed NHibernate configuration*/ private static void InitializeSessionFactory() { //todo: toget connection info from appsetting. _sessionFactory = Fluently.Configure() .Database(MySQLConfiguration.Standard.ConnectionString(c => c .Server("localhost") .Database("janatabazaardb") .Username("sa") .Password("<PASSWORD>")).ShowSql()) //(c => c.FromAppSetting("ConnectionString")) // Modify your ConnectionString .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>()) //.ExposeConfiguration(cfg => new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Create(true, true)) .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } } <file_sep>/JanataBazaar/View/Details/Winform_PurchaseIndentForm.cs using JanataBazaar.Builders; using JanataBazaar.Models; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_PurchaseIndentForm : Winform_Details { //PurchaseIndent PurchaseIndent; List<PurchaseItemIndent> purchaseIndentList; PurchaseIndent indent; public Winform_PurchaseIndentForm() { InitializeComponent(); } public Winform_PurchaseIndentForm(int _ID) { InitializeComponent(); indent = Builders.PurchaseIndentBuilder.GetPurchaseIndent(_ID); this.purchaseIndentList = indent.IndentItemsList.ToList(); } private void Winform_PurchaseIndentForm_Load(object sender, EventArgs e) { if (purchaseIndentList == null) { purchaseIndentList = new List<PurchaseItemIndent>(); var itemInReserveList = PurchaseIndentBuilder.GetItemsInReserve(); foreach (var item in itemInReserveList) { purchaseIndentList.Add(new PurchaseItemIndent(item.Item, item.StockQuantity)); } purchaseIndentList = PurchaseIndentBuilder.GetItemAvgConsumption(purchaseIndentList); } LoadDGV(); FillDGV(); } private void LoadDGV() { //todo: also add minimum_ReserveStock this.dgvRegister.Columns.Add("colSINo", "SI.No"); this.dgvRegister.Columns.Add("colParticular", "Particular"); this.dgvRegister.Columns.Add("colBrand", "Brand"); this.dgvRegister.Columns.Add("colInHandStock", "Stock In Hand Quantity"); this.dgvRegister.Columns.Add("colAvgConsume", "Average Monthly Consumption"); this.dgvRegister.Columns.Add("colPeriod", "Period for which Stock required"); this.dgvRegister.Columns.Add("colRemark", "Remarks"); } private void FillDGV() { dgvRegister.Rows.Clear(); foreach (var item in purchaseIndentList) { int index = purchaseIndentList.IndexOf(item); dgvRegister.Rows.Add(); dgvRegister.Rows[index].Cells["colSINo"].Value = index + 1; dgvRegister.Rows[index].Cells["colParticular"].Value = item.Item.Name; dgvRegister.Rows[index].Cells["colBrand"].Value = item.Item.Brand; dgvRegister.Rows[index].Cells["colInHandStock"].Value = item.InHandStock; dgvRegister.Rows[index].Cells["colAvgConsume"].Value = item.AvgConsumption; dgvRegister.Rows[index].Cells["colPeriod"].Value = item.StockPeriod; dgvRegister.Rows[index].Cells["colRemark"].Value = item.Remark; } } //private void cmbSection_SelectedIndexChanged(object sender, EventArgs e) //{ // //get items where stock less their stock(packetquant * itemsperpack) // //if (string.IsNullOrEmpty(cmbSection.Text)) // //{ // // dgvRegister.DataSource = ""; // // return; // //} // //display Itemname, Brand, Quantity unit, current stock, Expected Reserve // dgvRegister.DataSource = ReportsBuilder.GetPIFReport(); // if (dgvRegister.Rows.Count == 0) // UpdateStatus("No Results Found"); // else // UpdateStatus(dgvRegister.Rows.Count + " Results Found"); //} private void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; new Winform_PurchaseIndentDetails(purchaseIndentList[e.RowIndex]).ShowDialog(); FillDGV(); } private void UpdatePurchaseIndentList(int index, PurchaseItemIndent indent) { purchaseIndentList[index] = indent; FillDGV(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { if (purchaseIndentList != null && purchaseIndentList.Count != 0) { if (indent == null) { indent = new PurchaseIndent(); indent.DateOfIndent = dtpIndentDate.Value.Date; } UpdateStatus("Saving", 50); indent.IndentItemsList = purchaseIndentList; bool success = Savers.PurchaseIndentSavers.SavePurchaseIndent(indent); if (success) { UpdateStatus("Purchase Indent Saved", 100); this.Close(); } else UpdateStatus("Error saving Purchase Indent", 100); } } protected override void CancelToolStrip_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/JanataBazaar/View/Register/Winform_AddCustomer.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.Models; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_AddCustomer : WinformRegister { public Winform_AddCustomer() { InitializeComponent(); } protected override void NewToolStrip_Click(object sender, EventArgs e) { new Details.Winform_CustomerDetails().ShowDialog(); } private void txtName_TextChanged(object sender, System.EventArgs e) { if (string.IsNullOrEmpty(txtMobNo.Text) && string.IsNullOrEmpty(txtName.Text)) { dgvRegister.DataSource = null; return; } UpdateStatus("Searching", 50); LoadRegisterDgv(); } public void LoadRegisterDgv() { dgvRegister.DataSource = (from cust in (PeoplePracticeBuilder.GetCustomerList(txtName.Text, txtMobNo.Text)) select new { cust.ID, cust.Name, cust.Mobile_No }).ToList(); if (dgvRegister.RowCount == 0) UpdateStatus("No Results found.", 100); else UpdateStatus(dgvRegister.RowCount + " Results found.", 100); } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { DialogResult _dialogResult = MessageBox.Show("Do you want to Add Customer " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Add Customer Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (_dialogResult == DialogResult.No) return; Customer _cust = new Customer(); var ID = dgvRegister.Rows[e.RowIndex].Cells["ID"].Value; _cust = PeoplePracticeBuilder.GetCustomerInfo(int.Parse(ID.ToString())); Winform_SaleDetails saleDetail = Application.OpenForms["Winform_SaleDetails"] as Winform_SaleDetails; if (saleDetail != null) saleDetail.UpdateCustomerControls(_cust); this.Close(); } } } <file_sep>/JanataBazaar/View/Register/Winform_SCFRegister.cs using JanataBazaar.Builders; using JanataBazaar.Models; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_SCFRegister : WinformRegister { List<ItemPricing> itemlist = new List<ItemPricing>(); List<PurchaseOrder> orderList = new List<PurchaseOrder>(); public Winform_SCFRegister() { InitializeComponent(); } private void Winform_SCFRegister_Load(object sender, EventArgs e) { //List<string> sectList = ItemDetailsBuilder.GetSectionsList(); //sectList.Add(""); //cmbSection.DataSource = sectList; //cmbSection.DisplayMember = "Name"; ////cmbSection.ValueMember = "ID"; //cmbSection.Text = ""; cmbDuration.SelectedIndex = 0; this.toolStrip1.Items.Add(this.SearchToolStrip); } //private void txtName_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(txtName.Text) && string.IsNullOrEmpty(txtBrand.Text)) // { // dgvRegister.DataSource = ""; // return; // } // itemlist = (ReportsBuilder.GetSCFReport(rdbCredit.Checked, txtSCF.Text,txtVendorName.Text, txtName.Text, txtBrand.Text, cmbSection.Text)); // dgvRegister.DataSource = (from itm in itemlist // select new // { // itm.Item.Name, // itm.Item.Brand, // PackageType = itm.Package.Name, // itm.PackageQuantity, // itm.QuantityPerPack, // itm.PurchaseValue, // TotalPurchase = itm.TotalPurchaseValue, // itm.Wholesale, // TotalWholesale = itm.TotalWholesaleValue, // itm.Retail, // TotalResale = itm.TotalResaleValue // }).ToList(); // if (itemlist == null) // UpdateStatus("No Results Found"); // else // UpdateStatus(itemlist.Count + " Results Found", 100); //} protected override void toolStripButtonPrint_Click(object sender, System.EventArgs e) { //new Reports.Report_SCF(itemlist).ShowDialog(); } private void cmbDuration_SelectedIndexChanged(object sender, EventArgs e) { bool isActive = (cmbDuration.Text == "Custom") ? true : false; dtpTo.Enabled = isActive; dtpFrom.Enabled = isActive; nudDuration.Enabled = !isActive; } protected void SearchToolStrip_Click(object sender, System.EventArgs e) { DateTime toDate = new DateTime(); DateTime fromDate = new DateTime(); dgvItemRegister.DataSource = null; dgvVATDetails.Rows.Clear(); dgvVATDetails.Columns.Clear(); bool isCredit = rdbCredit.Checked; int duration; int.TryParse(nudDuration.Value.ToString(), out duration); duration = duration == 0 ? 1 : duration; #region SetDuration if (cmbDuration.Text == "Custom") { if (DateTime.Compare(dtpFrom.Value.Date, dtpTo.Value.Date) > 0) { MessageBox.Show("From date cannot be greater than To date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } toDate = dtpTo.Value.Date; fromDate = dtpFrom.Value.Date; } else if (cmbDuration.Text == "Month") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddMonths(-duration); } else if (cmbDuration.Text == "Week") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-7 * duration); } else if (cmbDuration.Text == "Day") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-duration); } #endregion SetDuration orderList = (ReportsBuilder.GetSCFReport(rdbCredit.Checked, txtSCF.Text, txtVendorName.Text, toDate, fromDate)); if (orderList.Count == 0) { dgvRegister.DataSource = null; UpdateStatus("No Results Found"); } else { dgvRegister.DataSource = (from ord in orderList select new { ord.ID, ord.SCFNo, PurchaseDate = ord.DateOfPurchase.ToString("dd/MMM/yyyy"), InvoiceDate = ord.DateOfInvoice.ToString("dd/MMM/yyyy"), SuppplierName = ord.Vendor.Name, ord.TotalPurchasePrice, ord.TotalWholesalePrice, ord.TotalResalePrice, RevisionID = ord.Revision.ID }).ToList(); dgvRegister.Columns["ID"].Visible = false; dgvRegister.Columns["RevisionID"].Visible = false; dgvItemRegister.DataSource = null; UpdateStatus(orderList.Count + " Results Found", 100); } } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; int _ordID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); itemlist = ReportsBuilder.GetOrderList(_ordID); dgvItemRegister.DataSource = (from itm in itemlist select new { //itm.Purchase.SCFNo, Particulars = itm.Item.Name, itm.Item.Brand, //PackageType = itm.Package.Name, itm.PackageQuantity, itm.QuantityPerPack, itm.VATPercent, VAT_Amount = itm.VAT, itm.PurchaseValue, TotalPurchase = itm.TotalPurchaseValue, itm.Wholesale, TotalWholesale = itm.TotalWholesaleValue, itm.Retail, TotalResale = itm.TotalResaleValue }).ToList(); /*Vat Statement*/ dgvVATDetails.Rows.Clear(); dgvVATDetails.Columns.Clear(); //get all the percentages for a particular revision int revisionID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["RevisionID"].Value.ToString()); List<decimal> vatPercentList = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(revisionID); PurchaseOrder order = orderList[e.RowIndex]; //create dictionary for each percentage with sum of all percenatage Dictionary<decimal, decimal> vatPercentageSum = new Dictionary<decimal, decimal>(); foreach (decimal percent in vatPercentList) { if (percent == 0) continue; decimal sumVATPercent = itemlist.Where(i => i.VATPercent == percent).Select(i => i.VAT).Sum(); vatPercentageSum.Add(percent, sumVATPercent); } var rdOffList = new List<decimal>(); foreach (var item in itemlist) { rdOffList.Add(item.VAT - (item.Basic * (item.VATPercent / 100))); } //create dictionary for each percentage with sum of all basic Dictionary<decimal, decimal> vatPurchaseSum = new Dictionary<decimal, decimal>(); foreach (decimal percent in vatPercentList) { decimal sumVATPercent = itemlist.Where(i => i.VATPercent == percent).Select(i => i.PurchaseValue).Sum(); vatPurchaseSum.Add(percent, sumVATPercent); } LoadDGVAddColumns(vatPercentList); LoadDGVAddValues(order, vatPercentageSum, vatPurchaseSum, rdOffList); } private void LoadDGVAddColumns(List<decimal> vatPercentList) { foreach (var percent in vatPercentList) { if (percent == 0) continue; dgvVATDetails.Columns.Add("col" + percent + "%", percent + "%"); } foreach (var percent in vatPercentList) { if (percent == 0) { dgvVATDetails.Columns.Add("colExempted", "Excempted"); continue; } dgvVATDetails.Columns.Add("col" + percent + "Value", percent + "%_Amount"); } dgvVATDetails.Columns["colExempted"].DisplayIndex = dgvVATDetails.Columns.Count - 1; dgvVATDetails.Columns.Add("colPosRodOff", "+"); dgvVATDetails.Columns.Add("colNegRodOff", "-"); dgvVATDetails.Columns.Add("colTotalAmount", "TotalAmount"); } private void LoadDGVAddValues(PurchaseOrder order, Dictionary<decimal, decimal> vatPercentageSum, Dictionary<decimal, decimal> vatBasicSum, List<decimal> rdOffList) { dgvVATDetails.Rows.Add(); foreach (var item in vatPercentageSum) { dgvVATDetails.Rows[0].Cells["col" + item.Key + "%"].Value = item.Value; } foreach (var item in vatBasicSum) { if (item.Key == 0) { dgvVATDetails.Rows[0].Cells["colExempted"].Value = item.Value; continue; } dgvVATDetails.Rows[0].Cells["col" + item.Key + "Value"].Value = item.Value; } dgvVATDetails.Rows[0].Cells["colPosRodOff"].Value = rdOffList.Where(i => i > 0).Sum().ToString("#.##"); dgvVATDetails.Rows[0].Cells["colNegRodOff"].Value = rdOffList.Where(i => i < 0).Sum().ToString("#.##"); dgvVATDetails.Rows[0].Cells["colTotalAmount"].Value = order.TotalPurchasePrice; } } } <file_sep>/JanataBazaar/Datasets/dsRebate.cs namespace JanataBazaar.Datasets { public partial class dsRebate { } } namespace JanataBazaar.Datasets { public partial class dsRebate { } } <file_sep>/JanataBazaar/Mappers/SaleMapping.cs using FluentNHibernate.Mapping; using JanataBazaar.Model; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Mappers { class SaleMapping : ClassMap<Sale> { public SaleMapping() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.IsCredit); References(x => x.Customer).Class<Customer>() .Columns("CustomerID") .Cascade.None(); References(x => x.Member).Class<Member>() .Columns("MemberID") .Cascade.None(); Map(x => x.TotalRebate); Map(x => x.PaidAmount); Map(x => x.TransportCharge); Map(x => x.BalanceAmount); Map(x => x.TotalAmount); Map(x => x.DateOfSale); HasMany(x => x.Items).KeyColumn("SaleID") .Inverse() .Cascade.All(); } } class SaleItemMapping : ClassMap<SaleItem> { public SaleItemMapping() { Id(x => x.ID).GeneratedBy.Identity(); References(x => x.Sale).Class<Sale>() .Columns("SaleID") .Cascade.None(); References(x => x.Item).Class<Item>() .Columns("ItemID") .Cascade.None(); Map(x => x.Quantity); Map(x => x.Price); Map(x => x.TotalPrice); Map(x => x.StockCount); } } } <file_sep>/JanataBazaar/View/Register/Winform_SalesSummary.cs using JanataBazaar.Datasets; using JanataBazaar.Models; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_SalesSummary : WinformRegister { List<Sale> saleSummaryList; public Winform_SalesSummary() { InitializeComponent(); } private void cmbDuration_SelectedIndexChanged(object sender, EventArgs e) { bool isActive = (cmbDuration.Text == "Custom") ? true : false; dtpTo.Enabled = isActive; dtpFrom.Enabled = isActive; nudDuration.Enabled = !isActive; } protected void SearchToolStrip_Click(object sender, System.EventArgs e) { DateTime toDate = new DateTime(); DateTime fromDate = new DateTime(); bool isCredit = rdbCredit.Checked; int duration; int.TryParse(nudDuration.Value.ToString(),out duration); duration = duration == 0 ? 1 : duration; #region SetDuration if (cmbDuration.Text == "Custom") { if (DateTime.Compare(dtpFrom.Value.Date, dtpTo.Value.Date) > 0) { MessageBox.Show("From date cannot be greater than To date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } toDate = dtpTo.Value.Date; fromDate = dtpFrom.Value.Date; } else if (cmbDuration.Text == "Month") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddMonths(- duration); } else if (cmbDuration.Text == "Week") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-7 * duration); } else if (cmbDuration.Text == "Day") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(- duration); } #endregion SetDuration dgvRegister.Rows.Clear(); saleSummaryList = Builders.SaleItemBuilder.GetSalesSummary(isCredit, fromDate, toDate, txtName.Text, txtConsumeID.Text); if (saleSummaryList.Count != 0) { dgvRegister.Rows.Clear(); foreach (var item in saleSummaryList) { int index = saleSummaryList.IndexOf(item); dgvRegister.Rows.Add(); dgvRegister.Rows[index].Cells["colSINo"].Value = index + 1; dgvRegister.Rows[index].Cells["colSaleNo"].Value = item.ID; dgvRegister.Rows[index].Cells["colsaleAmount"].Value = item.TotalAmount; dgvRegister.Rows[index].Cells["colRebateAmount"].Value = item.TotalRebate; dgvRegister.Rows[index].Cells["colGrossAmount"].Value = item.TotalAmount + item.TotalRebate; dgvRegister.Rows[index].Cells["colbillAge"].Value = DateTime.Compare(DateTime.Today.Date, item.DateOfSale.Date); } } } protected override void NewToolStrip_Click(object sender, System.EventArgs e) { new Winform_SaleDetails().ShowDialog(); SearchToolStrip_Click(this, new System.EventArgs()); } private void Winform_SalesSummary_Load(object sender, EventArgs e) { cmbDuration.SelectedIndex = 0; this.toolStrip1.Items.Add(this.SearchToolStrip); LoadDGV(); } private void LoadDGV() { dgvRegister.Columns.Add("colSINo", "SI_No."); dgvRegister.Columns.Add("colVendName", "Vendor Name"); dgvRegister.Columns.Add("colSaleNo", "Bill_No."); dgvRegister.Columns.Add("colsaleAmount", "Sale Amount"); dgvRegister.Columns.Add("colRebateAmount", "Rebate Amount"); dgvRegister.Columns.Add("colGrossAmount", "Gross Amount"); dgvRegister.Columns.Add("colbillAge", "Age Of Bill"); } protected override void toolStripButtonPrint_Click(object sender, System.EventArgs e) { new Winform_ReportViewer(saleSummaryList).ShowDialog(); } } } <file_sep>/JanataBazaar/Program.cs using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar { class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { ILog log = LogManager.GetLogger(typeof(Program)); log.Info("Application Janata Bazaar Started"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Winform_MainMenu()); } } } <file_sep>/JanataBazaar/View/Details/Winform_SaleItemDetails.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_SaleItemDetails : Winform_Details { int index=0; SaleItem saleItem; public Winform_SaleItemDetails() { InitializeComponent(); } public Winform_SaleItemDetails(SaleItem _saleItem, int index) { InitializeComponent(); this.index = index; saleItem = _saleItem; txtBrand.Text = _saleItem.Item.Brand; txtCommodity.Text = _saleItem.Item.Name; txtPrice.Text = _saleItem.Price.ToString(); txtTotalPrice.Text = _saleItem.TotalPrice.ToString(); nudQuantity.Maximum = _saleItem.StockCount; nudQuantity.Value = _saleItem.Quantity; } private void nudQuantity_ValueChanged(object sender, EventArgs e) { txtTotalPrice.Text = (decimal.Parse(nudQuantity.Value.ToString()) * decimal.Parse(txtPrice.Text)).ToString(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { ProcessTabKey(true); saleItem.Quantity = int.Parse(nudQuantity.Value.ToString()); saleItem.TotalPrice = (decimal.Parse(nudQuantity.Value.ToString()) * decimal.Parse(txtPrice.Text)); Winform_SaleDetails saleDetails = Application.OpenForms["Winform_SaleDetails"] as Winform_SaleDetails; if (saleDetails != null) saleDetails.UpdateSaleItemList(saleItem, index); this.Close(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/JanataBazaar/View/Register/Winform_AddVendor.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_AddVendor : WinformRegister { public Winform_AddVendor() { InitializeComponent(); } protected override void NewToolStrip_Click(object sender, EventArgs e) { new Details.Winform_VendorDetails().ShowDialog(); } private void txtName_TextChanged(object sender, System.EventArgs e) { UpdateStatus("Searching", 50); LoadRegisterDgv(); } public void LoadRegisterDgv() { dgvRegister.DataSource = (from vend in (PeoplePracticeBuilder.GetVendorsList(txtName.Text, txtMobNo.Text)) select new { vend.ID, vend.Name, vend.MobileNo }).ToList(); if (dgvRegister.RowCount == 0) UpdateStatus("No Results found.", 100); else UpdateStatus(dgvRegister.RowCount + " Results found.", 100); } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { DialogResult _dialogResult = MessageBox.Show("Do you want to Add Vendor " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Add Vendor Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (_dialogResult == DialogResult.No) return; Vendor _vend = new Vendor(); var ID = dgvRegister.Rows[e.RowIndex].Cells["ID"].Value; _vend = PeoplePracticeBuilder.GetVendorInfo(int.Parse(ID.ToString())); Winform_PurchaseBill purchaseBill = Application.OpenForms["Winform_PurchaseBill"] as Winform_PurchaseBill; if (purchaseBill != null) purchaseBill.UpdateVendorControls(_vend); this.Close(); } } } <file_sep>/JanataBazaar/Utilities/Validation.cs using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Windows.Forms; namespace JanataBazaar.Utilities { internal class Validation { #region 'Validation /// <summary> /// Converts Input to Title Case /// </summary> /// <param name="input"></param> /// <returns></returns> public static string ToTitleCase(string input) { if (String.IsNullOrEmpty(input)) return String.Empty; //else return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()); } /// <summary> /// checks if the container with controls editted /// </summary> /// <param name="container"></param> /// <param name="Recurse">true -> if control has parent container else false </param> /// <returns>bool</returns> public static bool IsInEdit(Control controls, bool Recurse = false) { foreach (Control ctrol in controls.Controls) { if (ctrol is TextBox && ctrol.Text != "") return true; if (Recurse) { if ((ctrol is TabPage || ctrol is Panel || ctrol is GroupBox) && IsInEdit(ctrol, Recurse)) return true; } } //else return false; } //todo: add the following function to winform_abstract //todo: rewrite the code to fetch using foreach() txt's first and image later - use linq with lambdha /// <summary> /// checks if the container sent has any controls with no value /// </summary> /// <param name="container"></param> /// <param name="Recurse">true -> if control has parent container else false </param> /// <param name="ExceptionControl">it consists the name of control that has to be treated as an exception by default it has</param> /// <returns></returns> public static bool IsNullOrEmpty(Control container, Boolean Recurse, List<string> ExceptionControl = null) { //todo: include error provider instead of messagebox if (ExceptionControl == null) ExceptionControl = new List<string>(); foreach (Control ctrol in container.Controls) { if ((ctrol is TextBox || ctrol is RichTextBox) && string.IsNullOrEmpty(ctrol.Text) && !ExceptionControl.Contains(ctrol.Name)) { MessageBox.Show("Textbox " + ctrol.Name + " is Mandatory and cannot be empty.." + Environment.NewLine + "Please try again.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); ctrol.Focus(); return true; } if (ctrol is PictureBox && ((PictureBox)ctrol).Image == null && !ExceptionControl.Contains(ctrol.Name)) { MessageBox.Show(ctrol.Name + " Image is Mandatory and cannot be empty." + Environment.NewLine + "Please insert and try again.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return true; } if (ctrol is ComboBox && string.IsNullOrEmpty(((ComboBox)ctrol).Text) && !ExceptionControl.Contains(ctrol.Name)) { MessageBox.Show("ComboBox " + ctrol.Name + " is Mandatory and cannot be empty." + Environment.NewLine + "Please insert and try again.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return true; } if (Recurse) { if ((ctrol is TabPage || ctrol is Panel || ctrol is GroupBox) && (!ExceptionControl.Contains(ctrol.Name)) && IsNullOrEmpty(ctrol, Recurse, ExceptionControl)) return true; } } return false; } public static DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; } #endregion 'Validation } }<file_sep>/JanataBazaar/Savers/ItemDetailsSavers.cs using JanataBazaar.Models; using NHibernate.Linq; using System; using log4net; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Savers { class ItemDetailsSavers { static ILog log = LogManager.GetLogger(typeof(ItemDetailsSavers)); public static int SaveSection(Section section) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) try { session.SaveOrUpdate(section); tx.Commit(); log.Info("Section Saved"); return section.ID; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return 0; } } } public static int SaveItem(Item _item) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) try { session.SaveOrUpdate(_item); tx.Commit(); log.Info("Item Saved"); return _item.ID; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return 0; } } } public static bool IsItemBilled(int itemID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { bool isBilled = session.Query<ItemPricing>().Any(i => i.Item.ID == itemID); return isBilled; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return true; } } } } public static bool DeleteItem(int itemID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { var _item = session.Get<Item>(itemID); session.Delete(_item); tx.Commit(); return true; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return false; } } } } } class PackageDetailsSavers { static ILog log = LogManager.GetLogger(typeof(ItemDetailsSavers)); public static int SavePackage(Package _pack) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { session.SaveOrUpdate(_pack); tx.Commit(); log.Info("Package type Saved"); return _pack.ID; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return 0; } } } } } } <file_sep>/JanataBazaar/Mappers/PurchaseOrderMapping.cs using FluentNHibernate.Mapping; using JanataBazaar.Model; using JanataBazaar.Models; namespace JanataBazaar.Mappers { class PurchaseOrderMapping : ClassMap<PurchaseOrder> { public PurchaseOrderMapping() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.SCFNo); Map(x => x.IRNNo); //Map(x => x.BillNo); References<VATRevision>(x => x.Revision).Class<VATRevision>() .Columns("RevisionID") .Cascade.None(); Map(x => x.DateOfPurchase); Map(x => x.DateOfInvoice); Map(x => x.IsCredit); References(x => x.Vendor).Class<Vendor>() .Columns("VendorID") .Cascade.None(); Map(x => x.TotalPurchasePrice); Map(x => x.TotalWholesalePrice); Map(x => x.TotalResalePrice); HasMany(x => x.ItemPriceList).KeyColumn("PurchaseID") .Inverse() .Cascade.All(); } } } <file_sep>/JanataBazaar/Builders/PurchaseIndentBuilder.cs using JanataBazaar.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class PurchaseIndentBuilder { public static List<ItemSKU> GetItemsInReserve() { Item itemAlias = null; ItemSKU itemSKUAlias = null; using (var session = NHibernateHelper.OpenSession()) { List<ItemSKU> list = session.QueryOver<ItemSKU>(() => itemSKUAlias) .JoinAlias(() => itemSKUAlias.Item, () => itemAlias) .Where(() => itemAlias.InReserve == true) .List().ToList(); return list; } } public static List<PurchaseItemIndent> GetItemAvgConsumption(List<PurchaseItemIndent> indentList) { using (var session = NHibernateHelper.OpenSession()) { foreach (var item in indentList) { Sale saleAlias = null; SaleItem saleItemAlias = null; int consumPerYear = session.QueryOver(() => saleAlias) .JoinAlias(() => saleAlias.Items, () => saleItemAlias) .Where(() => saleItemAlias.Item == item.Item) .Where(s => s.DateOfSale <= DateTime.Today.Date.AddYears(-1) && s.DateOfSale <= DateTime.Today.Date) .RowCount(); item.AvgConsumption = consumPerYear == 0 ? 0 : consumPerYear / 12; } } return indentList; } public static List<PurchaseIndent> GetIndentList(DateTime fromDate, DateTime toDate) { using (var session = NHibernateHelper.OpenSession()) { List<PurchaseIndent> list = session.QueryOver<PurchaseIndent>() .Where(p => p.DateOfIndent >= fromDate && p.DateOfIndent <= toDate) .List().ToList(); return list; } } public static PurchaseIndent GetPurchaseIndent(int _ID) { using (var session = NHibernateHelper.OpenSession()) { PurchaseIndent indent = session.QueryOver<PurchaseIndent>() .Where(x => x.ID == _ID) .SingleOrDefault(); indent.IndentItemsList = session.QueryOver<PurchaseItemIndent>() .Where(x => x.PurchaseIndent == indent) .Fetch(x => x.Item).Eager .Future() .ToList(); return indent; } } } }<file_sep>/JanataBazaar/View/Register/Winform_VATRevisionRegister.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using NHibernate.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using JanataBazaar.View.Details; namespace JanataBazaar.View.Register { public partial class Winform_VATRevisionRegister : WinformRegister { public Winform_VATRevisionRegister() { InitializeComponent(); } private void VATRevisionRegister_Load(object sender, EventArgs e) { //get the vatrevision dates and laod the combobox. //var revisionList = Builders.VATRevisionBuilder.GetVATRevisionList(); //var revisionDates = revisionList.Select(x => x.DateOfRevision.ToString("dd/MMM/yyyy")); dgvRegister.Columns.Add("colRevisionDate", "Date Of Revision"); dgvRegister.Columns.Add("ID", "ID"); //DataGridViewButtonColumn btnCol = new DataGridViewButtonColumn(); //btnCol.Name = "colDelete"; //btnCol.HeaderText = "Click To Delete"; //dgvRegister.Columns.Add(btnCol); LoadDGV(); } private void LoadDGV() { dgvRegister.DataSource = null; //dgvRegister.Columns.Clear(); dgvRegister.Rows.Clear(); //dgvRegister.Columns.Add("colRevisionDate", "Date Of Revision"); //dgvRegister.Columns.Add("ID", "ID"); dgvRegister.Columns["ID"].Visible = false; //DataGridViewButtonColumn btnCol = new DataGridViewButtonColumn(); //btnCol.Name = "colDelete"; //btnCol.HeaderText = "Click To Delete"; //dgvRegister.Columns.Add(btnCol); //dgvRegister.Columns["colDelete"].Visible = false; var revisionList = (from rev in Builders.VATRevisionBuilder.GetVATRevisionList() select new { rev.DateOfRevision, rev.ID }); if (revisionList != null && revisionList.Count() != 0) { foreach (var item in revisionList) { var index = dgvRegister.Rows.Add(); dgvRegister.Rows[index].Cells["colRevisionDate"].Value = item.DateOfRevision.ToString("dd/MMM/yy"); dgvRegister.Rows[index].Cells["ID"].Value = item.ID.ToString(); dgvRegister.Columns["colDelete"].Visible = true; dgvRegister.Columns["colDelete"].DisplayIndex = dgvRegister.Columns.Count - 1; } } UpdateStatus(revisionList.Count() + " results found."); } protected override void NewToolStrip_Click(object sender, System.EventArgs e) { new Winform_VATDetails().ShowDialog(); } private void cmbRevisionDate_SelectedIndexChanged(object sender, EventArgs e) { //todo: Fetch the vat percents where date of Revision = cmb.text } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; var percentageList = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString())); dgvPercentView.Rows.Clear(); if (percentageList != null) { if (dgvPercentView.Columns.Count == 0) dgvPercentView.Columns.Add("colPercentage", "Percentage"); for (int i = 0; i < percentageList.Count; i++) { dgvPercentView.Rows.Add(); dgvPercentView.Rows[i].Cells[0].Value = percentageList[i]; } } } protected override void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; { new Winform_VATDetails(int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString())).ShowDialog(); LoadDGV(); } } } } <file_sep>/JanataBazaar/View/Details/Winform_MemberDetails.cs using JanataBazaar.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_MemberDetails : Winform_Details { Member member; public Winform_MemberDetails() { InitializeComponent(); } public Winform_MemberDetails(Member _member) { InitializeComponent(); member = _member; /*Load Controls*/ txtAddress.Text = _member.Address; txtEmailID.Text = _member.Email; txtMobNo.Text = _member.Mobile_No; txtName.Text = _member.Name; txtPhoneNo.Text = _member.Phone_No; txtMemberNo.Text = _member.MemberNo; txtPLFNo.Text = _member.PLFNo; } #region _Validations private void txtEmailID_Validating(object sender, CancelEventArgs e) { if (txtEmailID.Text == String.Empty) return; string errorMsg = ""; Match _match = Regex.Match(txtEmailID.Text, "^[A-Za-z0-9._%+-]+@[A-Za-z0-9._%+-]+\\.[A-Za-z]{2,6}$"); errorMsg = _match.Success ? "" : "e-mail address must be valid e-mail address format.\n" + "For example '<EMAIL>' "; errorProvider1.SetError(txtEmailID, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtName.Select(0, txtEmailID.TextLength); } } private void txtMobNo_Validating(object sender, CancelEventArgs e) { Match _match = Regex.Match(txtMobNo.Text, "\\d{10}$"); string errorMsg = _match.Success ? "" : "Invalid Input for Mobile Number\n" + "For example '9880123456'"; errorProvider1.SetError(txtMobNo, errorMsg); //bool isUnique = PeoplePracticeBuilder.IsCustomerMobileNoUnique(txtMobNo.Text); //!isUnique?"Mobile Number entered is a Duplicate. Kindly Check again"; if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtMobNo.Select(0, txtMobNo.TextLength); } //Check if mobile no is unique } private void txtName_Validated(object sender, EventArgs e) { txtName.Text = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(txtName.Text); } private void txtName_Validating(object sender, CancelEventArgs e) { Match _match = Regex.Match(txtName.Text, "^[a-zA-Z\\s]+$"); string errorMsg = _match.Success ? "" : "Invalid Input for Name\n" + "For example '<NAME>'"; errorProvider1.SetError(txtName, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtName.Select(0, txtName.TextLength); } } private void txtPhoneNo_Validating(object sender, CancelEventArgs e) { if (txtPhoneNo.Text == String.Empty) return; Match _match = Regex.Match(txtPhoneNo.Text, "\\d{10}$"); string errorMsg = _match.Success ? "" : "Invalid Input for Phone Number\n" + " For example '8012345678'"; errorProvider1.SetError(txtPhoneNo, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtPhoneNo.Select(0, txtPhoneNo.TextLength); } } #endregion _Validations protected override void SaveToolStrip_Click(object sender, EventArgs e) { UpdateStatus("Saving Member", 50); string[] input = { "txtPhoneNo", "txtAddress", "txtEmailID" }; if (Utilities.Validation.IsNullOrEmpty(this, true, new List<string>(input))) { return; } if (member == null) member = new Member(txtName.Text, txtMobNo.Text, txtPhoneNo.Text, txtMemberNo.Text, txtPLFNo.Text, txtAddress.Text, txtEmailID.Text); else { member.Name = txtName.Text; member.Mobile_No = txtMobNo.Text; member.Phone_No = txtPhoneNo.Text; member.MemberNo = txtMemberNo.Text; member.PLFNo = txtPLFNo.Text; member.Address = txtAddress.Text; member.Email = txtEmailID.Text; } bool success = Savers.PeoplePracticeSaver.SaveMemberInfo(member); if (success) { UpdateStatus("Saved", 100); this.Close(); return; } UpdateStatus("Error in saving Member", 100); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsInEdit(this, true)) { var _dialogResult = MessageBox.Show("Do you want to Exit?", "Exit Member Details", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (_dialogResult == DialogResult.No) return; }; this.Close(); } } } <file_sep>/JanataBazaar/Models/PeoplePractice.cs //using Newtonsoft.Json; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.Drawing; namespace JanataBazaar.Model { #region Customer/Staff/Group //[JsonObject(MemberSerialization.OptIn)] //public class Customer //{ // //[JsonIgnore] // public virtual int ID { get; set; } // [JsonProperty(PropertyName = "name")] // public virtual string Name { get; set; } // [JsonProperty(PropertyName = "mobile_no")] // public virtual string Mobile_No { get; set; } // [JsonProperty(PropertyName = "phone_no")] // public virtual string Phone_No { get; set; } // [JsonProperty(PropertyName = "address")] // public virtual string Address { get; set; } // [JsonProperty(PropertyName = "email")] // public virtual string Email { get; set; } // //[JsonIgnore] // public virtual Image Image { get; set; } // public virtual int ReferralID { get; set; } // //public object updated_at { get; set; } // public Customer() { } // public Customer(string _name, string _mobileNo, string _phoneNo, string _address, string _email) // { // //this.ID = _id; // this.Name = _name; // this.Mobile_No = _mobileNo; // this.Phone_No = _phoneNo; // this.Address = _address; // this.Email = _email; // } //} //public class CustomerList //{ // public List<Customer> Customers { get; set; } //} //public class Staff //{ // public virtual int ID { get; set; } // public virtual string Name { get; set; } // public virtual string Mobile_No { get; set; } // public virtual string Phone_No { get; set; } // public virtual string Address { get; set; } // public virtual Image Image { get; set; } // public virtual bool IsTemporary { get; set; } // public Staff() { } // public Staff(string name, string mobNo, string phNo, string address="", bool isTempo=true) // { // this.Name = name; // this.Mobile_No = mobNo; // this.Phone_No = phNo; // this.Address = address; // this.IsTemporary = isTempo; // } //} //public class Group //{ // public int GroupID { get; set; } // public string Name { get; set; } // public List<Customer> CustomerList { get; set; } //} #endregion Customer/Staff/Group public class Vendor { public virtual int ID { get; set; } public virtual string TIN { get; set; } public virtual string PLP { get; set; } public virtual string CST { get; set; } public virtual string Name { get; set; } public virtual string MobileNo { get; set; } public virtual string PhoneNo { get; set; } public virtual string Address { get; set; } public virtual Bank Bank { get; set; } public virtual string AccNo { get; set; } public virtual string IFSCCode { get; set; } public virtual string BankUserName { get; set; } public virtual int DurationCount { get; set; } public virtual bool DurationTerm { get; set; } public Vendor() { } public Vendor(string name, string mobno, string phoneno, string address, string bankusername, string accno, string IfscNo, int dCount, bool inDays, string tin = "", string plp = "", string cst = "") { this.TIN = tin; this.PLP = plp; this.CST = cst; this.Name = name; this.MobileNo = mobno; this.PhoneNo = phoneno; this.Address = address; this.BankUserName = bankusername; this.AccNo = accno; //this.BankName = bankname; this.IFSCCode = IfscNo; this.DurationCount = dCount; this.DurationTerm = inDays; } } public class Person { public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual string Mobile_No { get; set; } public virtual string Phone_No { get; set; } public virtual string Address { get; set; } public virtual string Email { get; set; } } public class Customer : Person { //public virtual int ID { get; set; } //public virtual string Name { get; set; } //public virtual string Mobile_No { get; set; } //public virtual string Phone_No { get; set; } //public virtual string Address { get; set; } //public virtual string Email { get; set; } public virtual string AccountNo { get; set; } public virtual string PLFNo { get; set; } public Customer() { } public Customer(string _name, string _mobileNo, string _phoneNo, string _accNo, string _plfNo, string _address = "", string _email = "") { this.Name = _name; this.Mobile_No = _mobileNo; this.Phone_No = _phoneNo; this.Address = _address; this.Email = _email; this.AccountNo = _accNo; this.PLFNo = _plfNo; } } public class Member:Person { //public virtual int ID { get; set; } //public virtual string Name { get; set; } //public virtual string Mobile_No { get; set; } //public virtual string Phone_No { get; set; } //public virtual string Address { get; set; } //public virtual string Email { get; set; } public virtual string MemberNo { get; set; } public virtual string PLFNo { get; set; } public Member() { } public Member(string _name, string _mobileNo, string _phoneNo, string _memNo, string _plfNo, string _address = "", string _email = "") { this.Name = _name; this.Mobile_No = _mobileNo; this.Phone_No = _phoneNo; this.Address = _address; this.Email = _email; this.MemberNo = _memNo; this.PLFNo = _plfNo; } } }<file_sep>/JanataBazaar_TestCases/Builder/PeoplePracticeBuilderTest.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using JanataBazaar.Builders; using JanataBazaar.Model; namespace JanataBazaar_TestCases.Builder { public class PeoplePracticeBuilderTest { [TestCase("", "")] public void GetVendorsList(string name, string mobileno) { IList<Vendor> vendList = PeoplePracticeBuilder.GetVendorsList(name, mobileno); Assert.IsTrue(vendList.Count != 0); } } } <file_sep>/JanataBazaar/View/Details/Winform_ItemDetails.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_ItemDetails : Winform_Details { Item item; public Winform_ItemDetails() { InitializeComponent(); } public Winform_ItemDetails(Item _item) { InitializeComponent(); this.item = _item; cmbName.Text = item.Name; cmbUnit.Text = item.QuantityUnit; cmbBrand.Text = item.Brand; txtReserve.Text = item.ReserveStock.ToString(); } private void Winfrom_ItemDetails_Load(object sender, EventArgs e) { //todo : make the extraction faster this.toolStripParent.Items.Add(this.AddSectionToolStrip); AutoCompletionSource(Builders.ItemDetailsBuilder.GetNamesList(), cmbName); AutoCompletionSource(Builders.ItemDetailsBuilder.GetBrandsList(), cmbBrand); AutoCompletionSource(Builders.ItemDetailsBuilder.GetUnitList(), cmbUnit); List<string> sectList = Builders.ItemDetailsBuilder.GetSectionsList(); cmbSection.DataSource = sectList; cmbSection.DisplayMember = "Name"; if (item != null) { cmbSection.SelectedIndex = sectList.IndexOf(item.Section.Name);//item.Section.ID; } } private void AutoCompletionSource(List<string> srcList, ComboBox cmb) { var autoCollection = new AutoCompleteStringCollection(); autoCollection.AddRange(srcList.ToArray()); cmb.AutoCompleteCustomSource = autoCollection; cmb.AutoCompleteMode = AutoCompleteMode.Suggest; cmb.AutoCompleteSource = AutoCompleteSource.CustomSource; } private void AddSectionToolStrip_Click(object sender, EventArgs e) { new Winform_AddSection().ShowDialog(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { ProcessTabKey(true); List<string> except = new List<string> { "cmbBrand" }; if (Utilities.Validation.IsNullOrEmpty(this, true, except)) return; UpdateStatus("Saving", 25); if (Builders.ItemDetailsBuilder.ItemExists(cmbName.Text, cmbBrand.Text, cmbUnit.Text, cmbSection.Text) && item.ID == 0) { errorProvider1.SetError(cmbName, "Item is a Duplicate as it already exists"); cmbName.Select(0, cmbName.Text.Length); UpdateStatus("Error in Saving Item", 100); return; } UpdateStatus("Saving..", 50); if (Utilities.Validation.IsNullOrEmpty(this, false)) return; Section sect = Builders.ItemDetailsBuilder.GetSection(cmbSection.Text); if (item ==null || item.ID == 0) item = new Item(cmbName.Text, cmbUnit.Text, sect, cmbBrand.Text, int.Parse(txtReserve.Text)); else { item.Name = cmbName.Text; item.Brand = cmbBrand.Text; item.QuantityUnit = cmbUnit.Text; item.ReserveStock = string.IsNullOrEmpty(txtReserve.Text)? 0: int.Parse(txtReserve.Text); } if (Savers.ItemDetailsSavers.SaveItem(item) == 0) { UpdateStatus("Error in Saving Item", 100); return; } UpdateStatus("Item Saved.", 100); Close(); } //private void chkIsExempted_CheckedChanged(object sender, EventArgs e) //{ // txtVATPerc.Enabled = !chkIsExempted.Checked; // if (txtVATPerc.Enabled) // txtVATPerc.Validating += new CancelEventHandler(this.txtBox_Validating); // else // txtVATPerc.Validating += null; //} //private void cmbVATPerc_Validating(object sender, CancelEventArgs e) //{ // TextBox txtBox = (TextBox)sender; // string _errorMsg; // Match _match = Regex.Match(txtBox.Text, "^[0-9]*\\.?[0-9]*$"); // _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '2.2'" : ""; // errorProvider1.SetError(txtBox, _errorMsg); // if (_errorMsg != "") // { // e.Cancel = true; // txtBox.Select(0, txtBox.Text.Length); // } //} private void txtBox_Validating(object sender, CancelEventArgs e) { Control ctrl = (Control)sender; errorProvider1.SetError(ctrl, ""); if (String.IsNullOrEmpty(ctrl.Text)) { errorProvider1.SetError(ctrl, "Value cannot be null"); e.Cancel = true; } } private void txtName_Validated(object sender, EventArgs e) { cmbName.Text = Utilities.Validation.ToTitleCase(cmbName.Text.ToLower()); } } } <file_sep>/JanataBazaar/View/Details/Winform_CustomerDetails.cs using JanataBazaar.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text.RegularExpressions; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_CustomerDetails : Winform_Details { Customer _cust; public Winform_CustomerDetails() { InitializeComponent(); } public Winform_CustomerDetails(Customer _cust) { InitializeComponent(); this._cust = _cust; /*Load Controls*/ txtAddress.Text = _cust.Address; txtEmailID.Text = _cust.Email; txtMobNo.Text = _cust.Mobile_No; txtName.Text = _cust.Name; txtPhoneNo.Text = _cust.Phone_No; txtAccountNo.Text = _cust.AccountNo; txtPLFNo.Text = _cust.PLFNo; } #region _Validations private void txtEmailID_Validating(object sender, CancelEventArgs e) { if (txtEmailID.Text == String.Empty) return; string errorMsg = ""; Match _match = Regex.Match(txtEmailID.Text, "^[A-Za-z0-9._%+-]+@[A-Za-z0-9._%+-]+\\.[A-Za-z]{2,6}$"); errorMsg = _match.Success ? "" : "e-mail address must be valid e-mail address format.\n" + "For example '<EMAIL>' "; errorProvider1.SetError(txtEmailID, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtName.Select(0, txtEmailID.TextLength); } } private void txtMobNo_Validating(object sender, CancelEventArgs e) { Match _match = Regex.Match(txtMobNo.Text, "\\d{10}$"); string errorMsg = _match.Success ? "" : "Invalid Input for Mobile Number\n" + "For example '9880123456'"; errorProvider1.SetError(txtMobNo, errorMsg); //bool isUnique = PeoplePracticeBuilder.IsCustomerMobileNoUnique(txtMobNo.Text); //!isUnique?"Mobile Number entered is a Duplicate. Kindly Check again"; if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtMobNo.Select(0, txtMobNo.TextLength); } //Check if mobile no is unique } private void txtName_Validated(object sender, EventArgs e) { txtName.Text = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(txtName.Text); } private void txtName_Validating(object sender, CancelEventArgs e) { Match _match = Regex.Match(txtName.Text, "^[a-zA-Z\\s]+$"); string errorMsg = _match.Success ? "" : "Invalid Input for Name\n" + "For example '<NAME>'"; errorProvider1.SetError(txtName, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtName.Select(0, txtName.TextLength); } } private void txtPhoneNo_Validating(object sender, CancelEventArgs e) { if (txtPhoneNo.Text == String.Empty) return; Match _match = Regex.Match(txtPhoneNo.Text, "\\d{10}$"); string errorMsg = _match.Success ? "" : "Invalid Input for Phone Number\n" + " For example '8012345678'"; errorProvider1.SetError(txtPhoneNo, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtPhoneNo.Select(0, txtPhoneNo.TextLength); } } #endregion _Validations protected override void SaveToolStrip_Click(object sender, EventArgs e) { UpdateStatus("Saving Customer", 50); string[] input = { "txtPhoneNo", "txtAddress", "txtEmailID" }; if (Utilities.Validation.IsNullOrEmpty(this, true, new List<string>(input))) { return; } if (_cust == null) _cust = new Customer(txtName.Text, txtMobNo.Text, txtPhoneNo.Text, txtAccountNo.Text, txtPLFNo.Text, txtAddress.Text, txtEmailID.Text); else { _cust.Name = txtName.Text; _cust.Mobile_No = txtMobNo.Text; _cust.Phone_No = txtPhoneNo.Text; _cust.AccountNo = txtAccountNo.Text; _cust.PLFNo = txtPLFNo.Text; _cust.Address = txtAddress.Text; _cust.Email = txtEmailID.Text; } bool success = Savers.PeoplePracticeSaver.SaveCustomerInfo(_cust); if (success) { UpdateStatus("Saved", 100); this.Close(); return; } UpdateStatus("Error in saving Customer", 100); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsInEdit(this, true)) { var _dialogResult = MessageBox.Show("Do you want to Exit?", "Exit Customer Details", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (_dialogResult == DialogResult.No) return; }; this.Close(); } } }<file_sep>/JanataBazaar/View/Details/Winform_PurchaseIndentDetails.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_PurchaseIndentDetails : Winform_Details { PurchaseItemIndent indent; public Winform_PurchaseIndentDetails(PurchaseItemIndent indent) { InitializeComponent(); this.indent = indent; txtParticular.Text = indent.Item.Name; txtAvgConsume.Text = indent.AvgConsumption.ToString(); txtStockInHand.Text = indent.InHandStock.ToString(); nudDuration.Value = indent.StockPeriod; txtRemarks.Text = indent.Remark; } protected override void SaveToolStrip_Click(object sender, EventArgs e) { int duration; int.TryParse(nudDuration.Value.ToString(),out duration); indent.StockPeriod = duration == 0 ? 1 : duration; indent.Remark = txtRemarks.Text; this.Close(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/JanataBazaar/View/Winform_ReportViewer.cs using JanataBazaar.Datasets; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View { public partial class Winform_ReportViewer : Form { List<Sale> salesSummaryList; public Winform_ReportViewer(List<Sale> salesSummaryList) { InitializeComponent(); this.salesSummaryList = salesSummaryList; } private void Winform_ReportViewer_Load(object sender, EventArgs e) { //get datatable from list //var list = (from sale in salesSummaryList // select new // { // SI_No = salesSummaryList.IndexOf(sale) + 1, // Bill_No = sale.ID, // sale.TotalAmount, // sale.TotalRebate, // GrossAmount = sale.TotalAmount + sale.TotalRebate, // AgeOfBill = DateTime.Compare(DateTime.Today.Date, sale.DateOfSale.Date) // }).ToList(); // DataTable dt = ToDataTable(list); //var testvar = dt.Rows[0]["AgeOfBill"];. //dt = ToDataTable(list); dsRebate ds = new dsRebate(); var dt = new dsRebate.dtRebateDataTable();// ds.Tables["dtRebate"]; foreach (var sale in salesSummaryList) { int index = salesSummaryList.IndexOf(sale); dt.Rows.Add(); dt.Rows[index]["SI_No"] = salesSummaryList.IndexOf(sale) + 1; dt.Rows[index]["Bill_No"] = sale.ID; dt.Rows[index]["TotalAmount"] = sale.TotalAmount; dt.Rows[index]["TotalRebate"] = sale.TotalRebate; dt.Rows[index]["GrossAmount"] = sale.TotalAmount + sale.TotalRebate; dt.Rows[index]["AgeOfBill"] = DateTime.Compare(DateTime.Today.Date, sale.DateOfSale.Date); } //ds.Tables.Add(dt); this.dsRebateBindingSource.DataSource = dt; this.reportViewer1.RefreshReport(); } public static DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; } } } <file_sep>/JanataBazaar/View/Details/Winform_VATDetails.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_VATDetails : Winform_Details { List<decimal> vatList = new List<decimal>(); VATRevision vatRevision; List<VATPercent> vatPercentList; //private object dgvOrderItems; public Winform_VATDetails() { InitializeComponent(); } public Winform_VATDetails(int _ID) { InitializeComponent(); //get VAT Percentages based on the _ID VATRevision _vatRevision = Builders.VATRevisionBuilder.GetVATRevisionInfo(_ID); //load the controls this.vatRevision = _vatRevision; dtpFromYear.Value = vatRevision.DateOfRevision; this.vatPercentList = vatRevision.VATList.ToList(); } private void Winform_VATDetails_Load(object sender, EventArgs e) { // dtpToYear.Value = dtpFromYear.Value.AddYears(1); //fetch the VAT values from the previous term table // else if (this.vatRevision == null) { vatPercentList = new List<VATPercent>(); vatPercentList.Add(new VATPercent(0)); } LoadDGV(); } private void btnAdd_Click(object sender, EventArgs e) { errorProvider1.SetError(txtVatPercent, ""); if (string.IsNullOrEmpty(txtVatPercent.Text)) { errorProvider1.SetError(txtVatPercent, "VAT Percent cannot be empty."); return; } decimal percentValue = decimal.Parse(txtVatPercent.Text); if (vatPercentList.Any(x => x.Percent == percentValue)) { MessageBox.Show("VAT Percentage of the entered value already exists in the list", "Duplicate VAT value", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } else { //update the vatlist to add to vatPercentList.Add(new VATPercent(percentValue)); LoadDGV(); } txtVatPercent.Text = ""; } private void LoadDGV() { dgvPercentList.DataSource = (from vat in vatPercentList orderby vat.Percent ascending select new { vat.ID, VATPercentage = vat.Percent }).ToList(); dgvPercentList.Columns["ID"].Visible = false; if (dgvPercentList.Rows.Count == 0) { dgvPercentList.Columns["colDelete"].Visible = false; return; } else { dgvPercentList.Columns["colDelete"].DisplayIndex = dgvPercentList.Columns.Count - 1; dgvPercentList.Columns["colDelete"].Visible = true; } //dgvPercentList.Rows.Clear(); //if (vatList.Count == 0) //{ // dgvPercentList.Columns["colDelete"].Visible = true; // return; //} //foreach (var per in vatPercentList) //{ // var index = dgvPercentList.Rows.Add(); // dgvPercentList.Rows[index].Cells["colPercent"].Value = per.Percent; //} //dgvPercentList.Columns["colDelete"].DisplayIndex = dgvPercentList.Columns.Count - 1; //dgvPercentList.Columns["colDelete"].Visible = true; } protected override void SaveToolStrip_Click(object sender, EventArgs e) { errorProvider1.SetError(dtpFromYear, ""); int _ID = vatRevision == null ? 0 : vatRevision.ID; if (vatPercentList.Count == 0) MessageBox.Show("VAT percentage List cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //todo: Verfiy what can be the constraints on RevisionDate //else if (DateTime.Compare(dtpFromYear.Value.Date, DateTime.Today.Date) < 0) //{ // errorProvider1.SetError(dtpFromYear, "Revision Date cannot be less than today"); // return; //} else if (Savers.VATPercentSavers.IsUniqueRevisionDate(dtpFromYear.Value.Date, _ID)) { MessageBox.Show("The Date of Revision already exists. Enter a different Date and try again", "Duplicate Revision Date", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } /*Add Or Updating Existing VAT Revisions.*/ if (vatRevision == null) { vatRevision = new VATRevision(dtpFromYear.Value.Date, vatPercentList); } else { vatRevision.DateOfRevision = dtpFromYear.Value.Date; vatRevision.VATList = vatPercentList; } bool success = Savers.VATPercentSavers.SaveVATRevision(vatRevision); if (success) { UpdateStatus("VAT Revision added successfully", 100); this.Close(); } else { UpdateStatus("Error saving VAT Revision", 100); } //} } protected override void CancelToolStrip_Click(object sender, EventArgs e) { this.Close(); } private void dgvPercentList_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; if (dgvPercentList.Columns["colDelete"].Index == e.ColumnIndex) { DialogResult dr = MessageBox.Show("Do you want to delete the VAT percentage?", "Delete VAT Percentage", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) return; //todo:Delete from db bool success = false; if (vatPercentList.Count != 0 && e.RowIndex + 1 <= vatPercentList.Count) { if (vatPercentList[e.RowIndex].ID != 0) success = Savers.VATPercentSavers.DeletePercentItems(vatPercentList[e.RowIndex].ID); if (success || vatPercentList[e.RowIndex].ID == 0) // "ID == 0" => Not yet Added to the db { vatPercentList.RemoveAt(e.RowIndex); } else { MessageBox.Show("Could not delete the Item. Something Nasty happened!!"); return; } } LoadDGV(); } } private void txtVatPercent_Validating(object sender, CancelEventArgs e) { TextBox txtBox = (TextBox)sender; string _errorMsg; //Check if txt is empty errorProvider1.SetError(txtVatPercent, ""); if (string.IsNullOrEmpty(txtVatPercent.Text)) { _errorMsg = "VAT Percent cannot be empty."; return; } //check if the txt has the right datatype Match _match = Regex.Match(txtBox.Text, "^[0-9]*\\.?[0-9]*$"); _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '2.2'" : ""; errorProvider1.SetError(txtBox, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txtBox.Select(0, txtBox.Text.Length); } } } } <file_sep>/JanataBazaar/Mappers/ItemMapping.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentNHibernate.Mapping; using JanataBazaar.Models; namespace JanataBazaar.Mappers { class ItemTypeMapping : ClassMap<Section> { public ItemTypeMapping() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Name); } } class ItemMapping : ClassMap<Item> { public ItemMapping() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Name); References(x => x.Section).Class<Section>() .Columns("SectionID") .Cascade.None(); Map(x => x.QuantityUnit); Map(x => x.Brand); Map(x => x.ReserveStock); Map(x => x.InReserve); } } class ItemPricingMapping : ClassMap<ItemPricing> { public ItemPricingMapping() { Id(x => x.ID).GeneratedBy.Identity(); References(x => x.Purchase).Class<PurchaseOrder>() .Columns("PurchaseID") .Cascade.None(); References(x => x.Package).Class<Package>() .Columns("PackageID") .Cascade.None(); References(x => x.Item).Class<Item>() .Columns("ItemID") .Cascade.None(); Map(x => x.ManufacturedDate); Map(x => x.ExpiredDate); Map(x => x.Basic); Map(x => x.TransportPercent); Map(x => x.Transport); Map(x => x.MiscPercent); Map(x => x.Misc); Map(x => x.VATPercent); Map(x => x.VAT); Map(x => x.DiscountPercent); Map(x => x.Discount); Map(x => x.WholesaleMargin); Map(x => x.Wholesale); Map(x => x.RetailMargin); Map(x => x.Retail); //Map(x => x.StockQuantity); Map(x => x.PurchaseValue); Map(x => x.QuantityPerPack); Map(x => x.PackageQuantity); Map(x => x.NetWeight); Map(x => x.GrossWeight); Map(x => x.TotalPurchaseValue); Map(x => x.TotalWholesaleValue); Map(x => x.TotalResaleValue); } } class SKUMapping : ClassMap<ItemSKU> { public SKUMapping() { Id(x => x.ID).GeneratedBy.Identity(); References(x => x.Item).Class<Item>() .Columns("ItemID") .Cascade.None(); Map(x => x.ResalePrice); Map(x => x.WholesalePrice); Map(x => x.StockQuantity); } } class PackageMapping : ClassMap<Package> { public PackageMapping() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Name); Map(x => x.Weight); Map(x => x.IsStocked); } } } <file_sep>/JanataBazaar/Savers/PeoplePracticeSaver.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate; using System.Threading.Tasks; using JanataBazaar.Model; using log4net; using JanataBazaar.Models; using NHibernate.Linq; namespace JanataBazaar.Savers { public class PeoplePracticeSaver { static ILog log = LogManager.GetLogger(typeof(PeoplePracticeSaver)); #region Vendor public static bool SaveVendorInfo(Vendor vendor) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.SaveOrUpdate(vendor); transaction.Commit(); return true; } catch (Exception ex) { transaction.Rollback(); log.Error(ex); return false; } } } } public static bool DeleteVendor(int vendorID) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.Delete(session.Get<Vendor>(vendorID)); transaction.Commit(); return true; } catch (Exception ex) { transaction.Rollback(); log.Error(ex); return false; } } } } public static bool IsVendorBilled(int _vendID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { bool isBilled = session.Query<PurchaseOrder>().Any(i => i.Vendor.ID == _vendID); return isBilled; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return true; } } } } #endregion Vendor #region Customer public static bool SaveCustomerInfo(Customer _customer) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { session.SaveOrUpdate(_customer); tx.Commit(); return true; } catch (Exception ex) { log.Error(ex); tx.Rollback(); return false; } } } } public static bool DeleteCustomer(int custID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { Customer cust = session.Get<Customer>(custID); session.Delete(cust); tx.Commit(); return true; } catch (Exception ex) { log.Error(ex); return false; } } } } #endregion Customer #region Member public static bool SaveMemberInfo(Member _member) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { session.SaveOrUpdate(_member); tx.Commit(); return true; } catch (Exception ex) { log.Error(ex); tx.Rollback(); return false; } } } } public static bool DeleteMember(int memID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { Member memb = session.Get<Member>(memID); session.Delete(memb); tx.Commit(); return true; } catch (Exception ex) { log.Error(ex); return false; } } } } #endregion Member } } <file_sep>/JanataBazaar/View/Winform_MainMenu.cs using JanataBazaar.View; using JanataBazaar.View.Details; using JanataBazaar.View.Register; using System; using System.Windows.Forms; namespace JanataBazaar { //using SpindleSoft.Builders; //using SpindleSoft.Helpers; //using SpindleSoft.Model; //using SpindleSoft.Savers; //using SpindleSoft.Views; public partial class Winform_MainMenu : Form { private enum SearchStates { Order, Customer, Alteration, Sales } private SearchStates searchState { get; set; } public Winform_MainMenu() { InitializeComponent(); } private void bulkSMSToolStripMenuItem_Click(object sender, EventArgs e) { } private void addOrdersToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_OrderDetails().ShowDialog(); } private void sendSMSToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_SMSSend().ShowDialog(); } private void searchOrderToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_OrderRegister().ShowDialog(); } #region SearchTxt private void radioButton2_CheckedChanged(object sender, EventArgs e) { UpdateSearchText("Search Customer Mobile No."); this.searchState = SearchStates.Customer; } private void radioButton1_CheckedChanged(object sender, EventArgs e) { UpdateSearchText("Search Order No."); this.searchState = SearchStates.Order; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { UpdateSearchText("Search Alteration No."); this.searchState = SearchStates.Alteration; } private void rdbSales_CheckedChanged(object sender, EventArgs e) { UpdateSearchText("Search Sale No."); this.searchState = SearchStates.Sales; } private void UpdateSearchText(string _updateText) { lblSearchText.Text = _updateText; txtSearch.Focus(); } #endregion SearchTxt private void Main_Load(object sender, EventArgs e) { /*load delivery dgv*/ /*load alteration dgv*/ } #region toolstrip private void addCustomerToolStripMenuItem1_Click(object sender, EventArgs e) { new Winform_CustomerDetails().ShowDialog(); } private void customerRegisterToolStripMenuItem_Click(object sender, EventArgs e) { new WinForm_CustomerRegister().ShowDialog(); } private void addStaffToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_StaffDetails().ShowDialog(); } private void staffRegisterToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_StaffRegister().ShowDialog(); //todo : salary add advance //todo: salary register must showen based on time interval (week, month, year) } private void addGroupsToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_GroupAdd().ShowDialog(); } private void addAlterationToolStripMenuItem_Click(object sender, EventArgs e) { //new Winform_AlterationsDetails().ShowDialog(); } private void searchAlterationToolStripMenuItem_Click(object sender, EventArgs e) { //new Winform_AlterationRegister().ShowDialog(); } private void viewExpenseToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_ExpenseRegister().ShowDialog(); } private void addExpensesToolStripMenuItem_Click(object sender, EventArgs e) { //new Winform_ExpenseDetails().ShowDialog(); } private void viewSMSRegistryToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_SMSRegister().ShowDialog(); } private void catalogueRegisterToolStripMenuItem_Click(object sender, EventArgs e) { } #endregion toolstrip private void btnAdd_Click(object sender, EventArgs e) { //todo: Shift logic to Controller if (rdbPurchase.Checked) new Winform_PurchaseBill().ShowDialog(); //else if (rdbCustomer.Checked) // new WinForm_CustomerDetails().ShowDialog(); //else if (rdbAlteration.Checked) // new Winform_AlterationsDetails().ShowDialog(); else if (rdbSales.Checked) new Winform_SaleDetails().ShowDialog(); else if (rdbIndent.Checked) new Winform_PurchaseIndentForm().ShowDialog(); } private void salaryRegisterToolStripMenuItem_Click(object sender, EventArgs e) { //link salary to expense } private void importCustomersToolStripMenuItem_Click(object sender, EventArgs e) { //export excel Sheet/ google spreadsheet // } private void cmbSearch_SelectedIndexChanged(object sender, EventArgs e) { //if (String.IsNullOrEmpty(cmbSearch.Text)) // return; //Customer _cust = PeoplePracticeBuilder.GetCustomerInfo(cmbSearch.Text); //_cust.Image = PeoplePracticeBuilder.GetCustomerImage(cmbSearch.Text); ////shouldnt happen but for safety. ////todo: Let customer know that bad has happened //if (_cust == null && _cust.Image == null) return; //new WinForm_CustomerDetails(_cust).ShowDialog(); } private void txtSearch_TextChanged(object sender, EventArgs e) { //if (String.IsNullOrEmpty(txtSearch.Text)) return; //dgvSearch.DataSource = Main_Helper.GetDataSource(this.searchState.ToString(), txtSearch.Text); } private void dgvSearch_CellContentClick(object sender, DataGridViewCellEventArgs e) { //if (searchState.ToString() == "Customer") //{ // var mobileNo = dgvSearch.Rows[e.RowIndex].Cells[1].Value.ToString(); // if (String.IsNullOrEmpty(mobileNo)) // return; // Customer _cust = PeoplePracticeBuilder.GetCustomerInfo(mobileNo); // _cust.Image = PeoplePracticeBuilder.GetCustomerImage(mobileNo); // //shouldnt happen but for safety. // //todo: Let customer know that bad has happened // if (_cust == null && _cust.Image == null) return; // new WinForm_CustomerDetails(_cust).ShowDialog(); //} } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } #region Alteration private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e) { /* *Date *Customer Name *MobileNo *send sms //*postpone - 2mrw */ /*get pending and today's Alterations*/ } private void dgvUpCominAlt_CellContentClick(object sender, DataGridViewCellEventArgs e) { /* *Date *Customer Name *MobileNo *send sms *pick Order */ /*get upcoming's Alteration*/ } #endregion Alteration #region Order private void dgvDeliverToday_CellContentClick(object sender, DataGridViewCellEventArgs e) { /* *Date *Customer Name *MobileNo *send sms //*postpone - 2mrw */ /*get pending and today's orders*/ } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { /* *Date *Customer Name *MobileNo *send sms *pick Order */ /*get upcoming's orders*/ } #endregion Order private void addCatalogueToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_SaleDetails().ShowDialog(); } private void stockCheckToolStripMenuItem1_Click(object sender, EventArgs e) { new Winform_ItemRegistry().ShowDialog(); } private void addVendorToolStripMenuItem2_Click(object sender, EventArgs e) { new Winform_VendorDetails().ShowDialog(); } private void vendorRegisterToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_VendorRegister().ShowDialog(); } private void addItemToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_ItemDetails().ShowDialog(); } private void SalesRegisterToolStripMenuItem_Click(object sender, EventArgs e) { // new Winform_SalesRegister().ShowDialog(); } private void addPurchaseBillToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_PurchaseBill().ShowDialog(); } private void purchaseIndentToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_PurchaseIndentForm().ShowDialog(); } private void stockControlFormToolStripMenuItem1_Click(object sender, EventArgs e) { new Winform_SCFRegister().ShowDialog(); } private void vATRevisionToolStripMenuItem_Click(object sender, EventArgs e) { } private void vATRevisionRegistryToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_VATRevisionRegister().ShowDialog(); } private void addvToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_VATDetails().ShowDialog(); } private void addMemberDetailsToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_MemberDetails().ShowDialog(); } private void memberRegisterToolStripMenuItem_Click(object sender, EventArgs e) { new WinForm_MemberRegister().ShowDialog(); } private void priceVariationStatementToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_PriceVariationRegister().ShowDialog(); } private void salesSummaryToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_SalesSummary().ShowDialog(); } private void invoiceControlFormToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_ICFRegister().ShowDialog(); } private void purchaseIndentFormToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_PurchaseIndentForm().ShowDialog(); } private void purchaseIndentRegisterToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_PurchaseIndentRegistry().ShowDialog(); } private void vatStatementToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_VATStatementRegister().ShowDialog(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new Winform_About().ShowDialog(); } } } <file_sep>/JanataBazaar/Models/Purchase.cs using JanataBazaar.Model; using System; using System.Collections.Generic; namespace JanataBazaar.Models { public class PurchaseOrder { public virtual int ID { get; set; } public virtual string SCFNo { get; set; } public virtual string IRNNo { get; set; } //public virtual string BillNo { get; set; } public virtual VATRevision Revision { get; set; } public virtual DateTime DateOfPurchase { get; set; } public virtual DateTime DateOfInvoice { get; set; } public virtual bool IsCredit { get; set; } public virtual Vendor Vendor { get; set; } public virtual decimal TotalPurchasePrice { get; set; } public virtual decimal TotalWholesalePrice { get; set; } public virtual decimal TotalResalePrice { get; set; } //public virtual decimal TotalPurchasePriceAlt { get; set; } //public virtual decimal TotalWholesalePriceAlt { get; set; } //public virtual decimal TotalResalePriceAlt { get; set; } public virtual IList<ItemPricing> ItemPriceList { get; set; } //public virtual IList<ItemPricing> Price { get; set; } public PurchaseOrder() { } public PurchaseOrder(bool _billType, string _SCFNo, string _IRNNo, string _billNo, VATRevision _revision, Vendor _vendor, DateTime _dop, DateTime _doi, decimal totPurchase, decimal totWholesale, decimal totResale) { this.IsCredit = _billType; this.SCFNo = SCFNo; this.IRNNo = IRNNo; //this.BillNo = _billNo; this.Revision = _revision; this.Vendor = _vendor; this.DateOfPurchase = _dop; this.DateOfInvoice = _doi; this.TotalPurchasePrice = totPurchase; this.TotalWholesalePrice = totWholesale; this.TotalResalePrice = totResale; } } } <file_sep>/JanataBazaar/Mappers/PeoplePracticeMapper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JanataBazaar.Model; using FluentNHibernate.Mapping; using JanataBazaar.Models; namespace JanataBazaar.Mappers { class PeoplePracticeMapper { } class VendorMapper : ClassMap<Vendor> { public VendorMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.TIN); Map(x => x.PLP); Map(x => x.CST); Map(x => x.Name); Map(x => x.MobileNo); Map(x => x.PhoneNo); Map(x => x.Address); References(x => x.Bank).Class<Bank>() .Columns("BankID") .Cascade.None(); ; Map(x => x.IFSCCode); Map(x => x.BankUserName); Map(x => x.AccNo); Map(x => x.DurationTerm); Map(x => x.DurationCount); } } class BankMapping : ClassMap<Bank> { public BankMapping() { Id(x => x.ID); Map(x => x.Name); } } class CustomerMapper : ClassMap<Customer> { public CustomerMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Name); Map(x => x.Mobile_No); Map(x => x.Phone_No); Map(x => x.Email); Map(x => x.Address); Map(x => x.AccountNo); Map(x => x.PLFNo); } } class MemberMapper : ClassMap<Member> { public MemberMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Name); Map(x => x.Mobile_No); Map(x => x.Phone_No); Map(x => x.Email); Map(x => x.Address); Map(x => x.MemberNo); Map(x => x.PLFNo); } } } <file_sep>/JanataBazaar/View/Details/Winform_PackageDetails.cs using System; using JanataBazaar.Models; using System.Windows.Forms; using System.Text.RegularExpressions; namespace JanataBazaar.View.Details { public partial class Winform_PackageDetails : Winform_Details { Package package; public Winform_PackageDetails() { InitializeComponent(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsNullOrEmpty(this, true)) return; txtPackageName_Validating(txtPackageName, new System.ComponentModel.CancelEventArgs()); if (errorProvider1.GetError(txtPackageName) != "") return; txtPackageName.Text = Utilities.Validation.ToTitleCase(txtPackageName.Text); if (Builders.PackageDetailsBuilder.PackageExists(txtPackageName.Text)) { errorProvider1.SetError(txtPackageName, "Package Type is a Duplicate as it already exists"); txtPackageName.Select(0, txtPackageName.TextLength); UpdateStatus("Error in Saving Package Type", 100); return; } package = new Package(txtPackageName.Text,int.Parse(txtWeight.Text), chkIsStocked.Checked); if (Savers.PackageDetailsSavers.SavePackage(package) == 0) { UpdateStatus("Error in Saving Package.", 100); return; } UpdateStatus("Package Saved.", 100); this.Close(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsInEdit(txtPackageName, false)) { var _dialogResult = MessageBox.Show("Do you want to Exit?", "Exit Package Details", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (_dialogResult == DialogResult.No) return; }; this.Close(); } private void txtPackageName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { TextBox txt = (TextBox)sender; string errorMsg = ""; if (string.IsNullOrEmpty(txt.Text)) errorMsg = "Package type Cannot be Empty"; else { Match _match = Regex.Match(txt.Text, "^[a-zA-Z\\s]+$"); errorMsg = _match.Success ? "" : "Invalid Input\n" + "For example 'ABCabc'"; } errorProvider1.SetError(txt, errorMsg); if (errorMsg != "") { e.Cancel = true; txt.Select(0, txt.Text.Length); return; } } private void txtWeight_Validating(object sender, System.ComponentModel.CancelEventArgs e) { TextBox txt = (TextBox)sender; string _errorMsg; if (string.IsNullOrEmpty(txt.Text)) { _errorMsg = "Invalid Amount input data type.\nExample: '5'"; } else { Match _match = Regex.Match(txt.Text, "^[0-9]*\\.?[0-9]*$"); _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '5'" : ""; } errorProvider1.SetError(txt, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txt.Select(0, txt.Text.Length); } } } } <file_sep>/JanataBazaar/Models/SaleItem.cs using JanataBazaar.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Models { public class SaleItem { public virtual int ID { get; set; } public virtual Sale Sale { get; set; } public virtual Item Item { get; set; } public virtual int Quantity { get; set; } public virtual decimal Price { get; set; } public virtual decimal TotalPrice { get; set; } public virtual int StockCount { get; set; } public SaleItem() { } public SaleItem(Item _item, decimal _price, int _stockCount, int _quantity = 0, decimal _totalPrice = 0) { this.Item = _item; this.Price = _price; this.StockCount = _stockCount; this.Quantity = _quantity; this.TotalPrice = _totalPrice; } } public class Sale { public virtual int ID { get; set; } public virtual bool IsCredit{ get; set; } public virtual IList<SaleItem> Items { get; set; } public virtual Customer Customer { get; set; } public virtual Member Member { get; set; } public virtual decimal PaidAmount { get; set; } public virtual decimal TotalRebate { get; set; } public virtual decimal TransportCharge { get; set; } public virtual decimal BalanceAmount { get; set; } public virtual decimal TotalAmount { get; set; } public virtual DateTime DateOfSale { get; set; } public Sale() { } public Sale(List<SaleItem> _items,bool _IsCredit, decimal _paidAmount, decimal _totalAmount,DateTime _dateOfSale, decimal _rebate, Customer _customer = null, Member _member = null,decimal _transportCharge = 0, decimal _balanceAmount = 0) { this.Items = _items; this.IsCredit = _IsCredit; this.Customer = _customer; this.Customer = _customer; this.Member = _member; this.TransportCharge = _transportCharge; this.PaidAmount = _paidAmount; this.BalanceAmount = _balanceAmount; this.TotalAmount = _totalAmount; this.DateOfSale = _dateOfSale; this.TotalRebate = _rebate; } } } <file_sep>/JanataBazaar/Reports/Report_SCF.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.Reports { public partial class Report_SCF : Form { List<ItemPricing> itemList; public Report_SCF() { InitializeComponent(); } public Report_SCF(List<ItemPricing> _itemList) { InitializeComponent(); this.itemList = _itemList; } private void Report_SCF_Load(object sender, EventArgs e) { Datasets.DataSet_SCF.DataTable_SCFDataTable dt = new Datasets.DataSet_SCF.DataTable_SCFDataTable(); var index =0; foreach (var item in itemList) { dt.Rows.Add(); dt.Rows[index]["Name"] = item.Item.Name; dt.Rows[index]["Brand"] = item.Item.Brand; if (item.Package != null) { dt.Rows[index]["PackageType"] = item.Package.Name; dt.Rows[index]["PackageQuantity"] = item.PackageQuantity; } dt.Rows[index]["QuantityPerPack"] = item.QuantityPerPack; dt.Rows[index]["PurchaseValue"] = item.PurchaseValue; dt.Rows[index]["TotalPurchase"] = item.TotalPurchaseValue; dt.Rows[index]["Wholesale"] = item.Wholesale; dt.Rows[index]["TotalWholesale"] = item.TotalWholesaleValue; dt.Rows[index]["Retail"] = item.Retail; dt.Rows[index]["TotalResale"] = item.TotalResaleValue; index++; } this.dataSetSCFBindingSource.DataSource = dt; this.reportViewer1.RefreshReport(); } } } <file_sep>/JanataBazaar_TestCases/Savers/VendorSaverTest.cs using NUnit.Framework; using JanataBazaar.Model; using JanataBazaar.Savers; namespace JanataBazaar_Test { public class VendorSaverTest { [TestCase("VendorNo1", "9999999999", "9999999999", "Address_UserName1", "Bankusername1", "AccnoUserNo1", "IFSCNo_User1", 7, true, "TIN_user1", "PLP_user1", "CST_user1")] [TestCase("VendorNo2", "8888888888", "7777777777", "Address_UserName2", "Bankusername2", "AccnoUserNo2", "IFSCNo_User2", 7, true, "", "", "")] public static void SaveVendorsList_Test(string name, string mobno, string phoneno, string address, string bankusername, string accno, string bankname, string IfscNo, int dCount, bool inDays, string tin = "", string plp = "", string cst = "") { Vendor vendor = new Vendor(name, mobno, phoneno, address, bankname, accno, IfscNo, dCount, inDays, tin, plp, cst); bool response = PeoplePracticeSaver.SaveVendorInfo(vendor); Assert.AreEqual(true, response); } } } <file_sep>/JanataBazaar/Builders/ReportsBuilder.cs using JanataBazaar.Model; using JanataBazaar.Models; using NHibernate; using NHibernate.Criterion; using NHibernate.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class ReportsBuilder { /*Stock Control Form*/ public static List<PurchaseOrder> GetSCFReport(bool isCredit, string SCFNo, string nameOfSupplier, DateTime toDate, DateTime fromDate) { //ItemPricing itemPricingAlias = null; //Item itemAlias = null; //Section sectionAlias = null; PurchaseOrder purchaseOrderAlias = null; Vendor vendorAlias = null; using (var session = NHibernateHelper.OpenSession()) { List<PurchaseOrder> list = (session.QueryOver<PurchaseOrder>(() => purchaseOrderAlias) //.JoinAlias(() => itemPricingAlias.Item, () => itemAlias) .JoinAlias(() => purchaseOrderAlias.Vendor, () => vendorAlias) //.JoinAlias(() => itemPricingAlias.Purchase, () => purchaseOrderAlias) //.JoinAlias(() => itemAlias.Section, () => sectionAlias) //.Fetch(i => i.Package).Eager //.Fetch(i => i.Purchase).Eager .Fetch(i => i.Revision).Eager .Where(() => purchaseOrderAlias.IsCredit == isCredit) .Where(() => purchaseOrderAlias.DateOfInvoice.Date >= fromDate.Date && purchaseOrderAlias.DateOfInvoice.Date <= toDate.Date) .Where(() => purchaseOrderAlias.SCFNo.IsLike(SCFNo + "%")) .Where(() => vendorAlias.Name.IsLike(nameOfSupplier + "%")) .Take(15) .List()).ToList<PurchaseOrder>(); return list; } } public static List<ItemPricing> GetOrderList(int _ordNo) { PurchaseOrder purchaseOrderAlias = null; ItemPricing itemPricingAlias = null; Item itemAlias = null; using (var session = NHibernateHelper.OpenSession()) { List<ItemPricing> _itemlist = (session.QueryOver<ItemPricing>(() => itemPricingAlias) .JoinAlias(() => itemPricingAlias.Purchase, () => purchaseOrderAlias) .JoinAlias(() => itemPricingAlias.Item, () => itemAlias) .Where(() => purchaseOrderAlias.ID == _ordNo).List()).Take(15).ToList<ItemPricing>(); return _itemlist; } } /*Stock Control Form*/ public static List<ItemPricing> GetICFReport(bool isCredit, string ICFNo, string nameOfSupplier, DateTime toDate, DateTime fromDate, string name = "", string brand = "", string section = "") { ItemPricing itemPricingAlias = null; Item itemAlias = null; Section sectionAlias = null; PurchaseOrder purchaseOrderAlias = null; Vendor vendorAlias = null; using (var session = NHibernateHelper.OpenSession()) { List<ItemPricing> list = (session.QueryOver(() => itemPricingAlias) .JoinAlias(() => itemPricingAlias.Item, () => itemAlias) .JoinAlias(() => itemPricingAlias.Purchase, () => purchaseOrderAlias) .JoinAlias(() => purchaseOrderAlias.Vendor, () => vendorAlias) .JoinAlias(() => itemAlias.Section, () => sectionAlias) .Fetch(i => i.Package).Eager //.Fetch(i => i.Purchase).Eager //.Fetch(i => i.Purchase.Vendor).Eager .Where(() => purchaseOrderAlias.IsCredit == isCredit) .Where(() => purchaseOrderAlias.DateOfInvoice.Date >= fromDate.Date && purchaseOrderAlias.DateOfInvoice.Date <= toDate.Date) .Where(() => purchaseOrderAlias.IRNNo.IsLike(ICFNo + "%")) .Where(() => vendorAlias.Name.IsLike(nameOfSupplier + "%")) .Where(() => itemAlias.Name.IsLike(name + "%")) .Where(() => itemAlias.Brand.IsLike(brand + "%")) .Where(() => sectionAlias.Name.IsLike(section + "%")) //.Select(() => purchaseOrderAlias.IRNNo) .List()).ToList(); return list; } } /*Purchase Indent Form*/ public static IList GetPIFReport() { Item itemAlias = null; Section sectionAlias = null; ItemPricing itemSKUAlias = null; using (var session = NHibernateHelper.OpenSession()) { IList list = (from itm in (session.QueryOver<ItemPricing>(() => itemSKUAlias) .JoinAlias(() => itemSKUAlias.Item, () => itemAlias) .JoinAlias(() => itemAlias.Section, () => sectionAlias) //.Where(() => sectionAlias.Name == section) .Where(() => itemAlias.InReserve == true) .List()) select new { itm.Item.Name, itm.Item.Brand, itm.PackageQuantity, itm.QuantityPerPack, itm.Item.QuantityUnit, itm.Item.ReserveStock, itm.Item.InReserve }).ToList(); ; return list; } } } }<file_sep>/JanataBazaar/View/Register/Winform_ICFRegister.cs using JanataBazaar.Builders; using JanataBazaar.Models; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_ICFRegister : WinformRegister { List<ItemPricing> itemlist; public Winform_ICFRegister() { InitializeComponent(); } private void Winform_ICFRegister_Load(object sender, EventArgs e) { List<string> sectList = ItemDetailsBuilder.GetSectionsList(); sectList.Add(""); cmbSection.DataSource = sectList; cmbSection.DisplayMember = "Name"; //cmbSection.ValueMember = "ID"; cmbSection.Text = ""; cmbDuration.SelectedIndex = 0; this.toolStrip1.Items.Add(this.SearchToolStrip); } private void cmbDuration_SelectedIndexChanged(object sender, EventArgs e) { bool isActive = (cmbDuration.Text == "Custom") ? true : false; dtpTo.Enabled = isActive; dtpFrom.Enabled = isActive; nudDuration.Enabled = !isActive; } protected void SearchToolStrip_Click(object sender, System.EventArgs e) { DateTime toDate = new DateTime(); DateTime fromDate = new DateTime(); bool isCredit = rdbCredit.Checked; int duration; int.TryParse(nudDuration.Value.ToString(), out duration); duration = duration == 0 ? 1 : duration; #region SetDuration if (cmbDuration.Text == "Custom") { if (DateTime.Compare(dtpFrom.Value.Date, dtpTo.Value.Date) > 0) { MessageBox.Show("From date cannot be greater than To date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } toDate = dtpTo.Value.Date; fromDate = dtpFrom.Value.Date; } else if (cmbDuration.Text == "Month") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddMonths(-duration); } else if (cmbDuration.Text == "Week") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-7 * duration); } else if (cmbDuration.Text == "Day") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-duration); } #endregion SetDuration itemlist = (ReportsBuilder.GetICFReport(rdbCredit.Checked, txtICF.Text, txtVendorName.Text, toDate, fromDate, txtName.Text, txtBrand.Text, cmbSection.Text)); if (itemlist == null) { dgvRegister.DataSource = null; UpdateStatus("No Results Found"); } else { dgvRegister.DataSource = (from itm in itemlist select new { ICF_No = itm.Purchase.IRNNo, Supplier = itm.Purchase.Vendor.Name, //Supplier_BillNo = itm.Purchase.BillNo, itm.Purchase.DateOfInvoice.Date, itm.Purchase.TotalPurchasePrice, itm.Purchase.TotalWholesalePrice, itm.Purchase.TotalResalePrice }).ToList(); UpdateStatus(itemlist.Count + " Results Found", 100); } } } } <file_sep>/JanataBazaar/Builders/PurchaseBillBuilder.cs using JanataBazaar.Models; using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class PurchaseBillBuilder { public static List<string> GetPackageTypes() { using (var session = NHibernateHelper.OpenSession()) { List<string> packageTypes=new List<string>(); packageTypes.Add(""); packageTypes.AddRange((from pack in session.Query<Package>() select pack.Name).Distinct().ToList()); return packageTypes; } } //public static List<string> GetVatPerventages(DateTime vatRevisonDate) //{ // using (var session = NHibernateHelper.OpenSession()) // { // var percentageList = session.QueryOver<VATPercent>() // } //} public static List<PurchaseOrder> GetPurchaseOrderList(DateTime fromDate, DateTime toDate, bool isCredit) { using (var session = NHibernateHelper.OpenSession()) { PurchaseOrder purchaseOrderAlias = null; List<PurchaseOrder> purchaseOrderList = session.QueryOver<PurchaseOrder>(() => purchaseOrderAlias) .Fetch(p => p.Vendor).Eager .Fetch(p => p.Revision).Eager .Where(() => purchaseOrderAlias.IsCredit == isCredit) .Where(() => purchaseOrderAlias.DateOfInvoice.Date >= fromDate.Date && purchaseOrderAlias.DateOfInvoice.Date <= toDate.Date) .List().ToList(); foreach (var item in purchaseOrderList) { var order = session.QueryOver<PurchaseOrder>() .Fetch(o => o.ItemPriceList).Eager .List().ToList(); } return purchaseOrderList; } } public static PurchaseOrder GetPurchaseOrder(int _ID) { using (var session = NHibernateHelper.OpenSession()) { var purchaseOrder = session.QueryOver<PurchaseOrder>() .Fetch(p=>p.ItemPriceList).Eager.Future() .Where(p => p.ID == _ID) .SingleOrDefault(); purchaseOrder.ItemPriceList = session.QueryOver<ItemPricing>() .Fetch(p => p.Item).Eager.Future() .Where(p => p.ID == _ID) .ToList(); return purchaseOrder; } } } } <file_sep>/JanataBazaar/View/Register/WinForm_CustomerRegister.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class WinForm_CustomerRegister : WinformRegister { public WinForm_CustomerRegister() { InitializeComponent(); } private void WinForm_CustomerRegister_Load(object sender, EventArgs e) { txtName_TextChanged(this, new EventArgs()); } #region Events protected override void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1 || e.ColumnIndex == -1) return; Winform_SaleDetails saleDetail = Application.OpenForms["Winform_SaleDetails"] as Winform_SaleDetails; if (saleDetail != null) { DialogResult _dialogResult = MessageBox.Show("Do you want to Add Customer " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Add Customer Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); Person _customer = PeoplePracticeBuilder.GetCustomerInfo(_ID); saleDetail.UpdateCustomerControls(_customer); this.Close(); } else { DialogResult _dialogResult = MessageBox.Show("Do you want to Modify the details of Customer " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Modify Customer Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (_dialogResult == DialogResult.No) return; int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); Customer _customer = PeoplePracticeBuilder.GetCustomerInfo(_ID); new Winform_CustomerDetails(_customer).ShowDialog(); txtName_TextChanged(this, new EventArgs()); } } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; if (dgvRegister.Columns["colDelete"].Index == e.ColumnIndex) { var row = dgvRegister.Rows[e.RowIndex]; int custID = int.Parse(row.Cells["ID"].Value.ToString()); DialogResult dr = MessageBox.Show("Do you want to delete Customer " + row.Cells["Name"].Value.ToString(), "Delete Customer", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) return; bool success = Savers.PeoplePracticeSaver.DeleteCustomer(custID); if (success) { txtName_TextChanged(this, new EventArgs()); UpdateStatus("Customer Deleted.", 100); } else { UpdateStatus("Error deleting Customer. ", 100); } } } private void txtName_TextChanged(object sender, EventArgs e) { dgvRegister.DataSource = null; dgvRegister.Columns["colDelete"].Visible = false; if (string.IsNullOrEmpty(txtAccNo.Text) && string.IsNullOrEmpty(txtMobNo.Text) && string.IsNullOrEmpty(txtName.Text)) return; UpdateStatus("Searching", 50); List<Customer> custList = new List<Customer>(); custList = PeoplePracticeBuilder.GetCustomerList(txtName.Text, txtMobNo.Text, txtAccNo.Text); if (custList != null && custList.Count != 0) { dgvRegister.DataSource = (from cust in custList select new { cust.ID, cust.Name, cust.Mobile_No, cust.AccountNo }).ToList(); dgvRegister.Columns["ID"].Visible = false; dgvRegister.Columns["colDelete"].Visible = true; dgvRegister.Columns["colDelete"].DisplayIndex = dgvRegister.Columns.Count - 1; } UpdateStatus((dgvRegister.RowCount == 0) ? "No Results Found" : dgvRegister.RowCount + " Results Found", 100); } protected override void NewToolStrip_Click(object sender, System.EventArgs e) { new Winform_CustomerDetails().ShowDialog(); } #endregion Events } } <file_sep>/JanataBazaar/Models/VATRevision.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Models { public class VATRevision { public virtual int ID { get; set; } public virtual DateTime DateOfRevision { get; set; } public virtual IList<VATPercent> VATList { get; set; } public VATRevision() {} public VATRevision(DateTime dateOfRevision, List<VATPercent> vatList) { this.VATList = vatList; this.DateOfRevision = dateOfRevision; } } public class VATPercent { public virtual int ID { get; set; } public virtual VATRevision VATRevision { get; set; } public virtual decimal Percent { get; set; } public VATPercent() { } public VATPercent(decimal _percent) { this.Percent = _percent; } } } <file_sep>/JanataBazaar/View/Register/WinformRegister.cs using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class WinformRegister : Form { public WinformRegister() { InitializeComponent(); } protected virtual void UpdateStatus(string statusText = "Enter Details to Search.", int statusValue = 0) { toolStrip_Label.Text = statusText; toolStripProgressBar1.Value = statusValue; } protected virtual void NewToolStrip_Click(object sender, System.EventArgs e) { } protected virtual void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { } protected virtual void dgvRegister_DataError(object sender, DataGridViewDataErrorEventArgs e) { } protected virtual void toolStripButtonPrint_Click(object sender, System.EventArgs e) { } protected virtual void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { } } } <file_sep>/JanataBazaar/Savers/PurchaseIndentSavers.cs using JanataBazaar.Models; using log4net; using System; using System.Collections.Generic; using NHibernate.Util; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Savers { class PurchaseIndentSavers { static ILog log = LogManager.GetLogger(typeof(PurchaseIndentSavers)); public static bool SavePurchaseIndent(PurchaseIndent indent) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { indent.IndentItemsList.ForEach(x => x.PurchaseIndent = indent); session.SaveOrUpdate(indent); tx.Commit(); return true; } catch (Exception ex) { log.Info("Saving Purchase Indent Failed."); log.Error(ex); tx.Rollback(); return false; } } } } } } <file_sep>/JanataBazaar/View/Details/WinForm_Abstract.cs using System; using System.Windows.Forms; namespace JanataBazaar.Views.Details { #if DEBUG public partial class WinForm_Abstract : Form { #else public abstract partial class Winform_DetailsFormat: Form { #endif public WinForm_Abstract() { InitializeComponent(); } private void Winform_DetailsFormat_Load(object sender, EventArgs e) { } protected virtual void SaveToolStrip_Click(object sender, EventArgs e) { } protected virtual void CancelToolStrip_Click(object sender, EventArgs e) { } protected virtual void UpdateStatus(string statusText, int statusValue=0) { toolStrip_Label.Text = statusText; toolStripProgressBar1.Value = statusValue; } } }<file_sep>/JanataBazaar/Datasets/DataSet_SCF.cs namespace JanataBazaar.Datasets { public partial class DataSet_SCF { } } namespace JanataBazaar.Datasets { public partial class DataSet_SCF { } } <file_sep>/JanataBazaar/View/Details/Winform_VendorDetails.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.Models; using JanataBazaar.Savers; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_VendorDetails : JanataBazaar.View.Details.Winform_Details { Vendor _vendor; public Winform_VendorDetails(Vendor vendor) { InitializeComponent(); this._vendor = vendor; txtName.Text = _vendor.Name; txtMobNo.Text = _vendor.MobileNo; txtPhoneNo.Text = _vendor.PhoneNo; txtAddress.Text = _vendor.Address; txtTin.Text = _vendor.TIN; txtPLP.Text = _vendor.PLP; txtCST.Text = _vendor.CST; txtBankUserName.Text = _vendor.BankUserName; txtIfscCode.Text = _vendor.IFSCCode; txtAccNo.Text = _vendor.AccNo; //cmbBankName.Text = _vendor.BankName; udDuration.Value = _vendor.DurationCount; if (_vendor.DurationTerm) rdbDays.Checked = true; else rdbMonth.Checked = true; } public Winform_VendorDetails() { InitializeComponent(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { List<string> exceptionList = new List<string> { "txtCST", "txtPLP", "txtTin", "txtPhoneNo", "txtMobNo", "txtBankUserName", "txtIfscCode", "txtAccNo", "cmbBankName" }; if (Utilities.Validation.IsNullOrEmpty(this, true, exceptionList)) return; UpdateStatus("fetching Vendor Details..", 33); if (this._vendor == null) this._vendor = new Vendor(); _vendor.BankUserName = txtBankUserName.Text; if (!IsNullOrEmpty(cmbBankName.Text) && !PeoplePracticeBuilder.IfBankExits(cmbBankName.Text)) this._vendor.Bank = new Bank(cmbBankName.Text); else if (!string.IsNullOrEmpty(cmbBankName.Text)) this._vendor.Bank = PeoplePracticeBuilder.GetBankNames(cmbBankName.Text); _vendor.IFSCCode = txtIfscCode.Text; _vendor.AccNo = txtAccNo.Text; _vendor.Name = txtName.Text; _vendor.Address = txtAddress.Text; _vendor.MobileNo = txtMobNo.Text; _vendor.PhoneNo = txtPhoneNo.Text; _vendor.TIN = txtTin.Text; _vendor.PLP = txtPLP.Text; _vendor.CST = txtCST.Text; _vendor.DurationCount = int.Parse(udDuration.Value.ToString()); _vendor.DurationTerm = rdbDays.Checked; UpdateStatus("Saving..", 66); bool response = PeoplePracticeSaver.SaveVendorInfo(this._vendor); if (response) { UpdateStatus("Saved.", 100); this.Close(); } else UpdateStatus("Error Saving Vendor Details.", 100); //Winform_VendorsRegister addSaleReg = Application.OpenForms["Winform_VendorsRegister"] as Winform_VendorsRegister; //if (addSaleReg != null) // addSaleReg.LoadDgv(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (JanataBazaar.Utilities.Validation.IsInEdit(this, true)) { var _dialogResult = MessageBox.Show("Do you want to Exit?", "Exit Vendor Details", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (_dialogResult == DialogResult.No) return; }; this.Close(); } #region Validation private void txtName_Validating(object sender, CancelEventArgs e) { Match _match = Regex.Match(txtName.Text, "^[a-zA-Z\\s]+$"); string errorMsg = _match.Success ? "" : "Invalid Input for Name\n" + "For example '<NAME>'"; errorProvider1.SetError(txtName, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtName.Select(0, txtName.TextLength); } } private void txtMobNo_Validating(object sender, CancelEventArgs e) { if (String.IsNullOrEmpty(txtMobNo.Text)) return; var txtBox = (TextBox)sender; Match _match = Regex.Match(txtBox.Text, "\\d{10}$"); string errorMsg = _match.Success ? "" : "Invalid Input for Contact Number\n" + "For example '9880123456/08000000'"; errorProvider1.SetError(txtBox, errorMsg); if (errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtBox.Select(0, txtBox.TextLength); } } private void txtPhoneNo_Validating(object sender, CancelEventArgs e) { if (String.IsNullOrEmpty(txtPhoneNo.Text)) return; txtMobNo_Validating(txtPhoneNo, new CancelEventArgs()); } private void txtName_Validated(object sender, EventArgs e) { txtName.Text = Utilities.Validation.ToTitleCase(txtName.Text.ToLower()); } #endregion Validation private void Winform_VendorDetails_Load(object sender, EventArgs e) { //todo: Load the bank names List<Bank> BankList = PeoplePracticeBuilder.GetBankNames(); cmbBankName.DataSource = BankList; cmbBankName.DisplayMember = "Name"; cmbBankName.ValueMember = "ID"; string[] bankNames = BankList.Select(x => x.Name).ToArray(); var nameCollection = new AutoCompleteStringCollection(); nameCollection.AddRange(bankNames); cmbBankName.AutoCompleteCustomSource = nameCollection; cmbBankName.AutoCompleteMode = AutoCompleteMode.Suggest; cmbBankName.AutoCompleteSource = AutoCompleteSource.ListItems; cmbBankName.Text = ""; if (this._vendor != null && this._vendor.Bank != null) cmbBankName.SelectedText = this._vendor.Bank.Name; } } } <file_sep>/JanataBazaar/Builders/PriceVariationBuilder.cs using JanataBazaar.Models; using NHibernate.Criterion; using NHibernate.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class PriceVariationBuilder { public static List<object[]> GetPriceVariationItems() { using (var session = NHibernateHelper.OpenSession()) { ItemSKU itemSKUAlias = null; Item itemAlias = null; Section sectionAlias = null; var results = session.QueryOver(() => itemSKUAlias) .JoinAlias(() => itemSKUAlias.Item, () => itemAlias) .JoinAlias(() => itemAlias.Section, () => sectionAlias) .SelectList(list => list .SelectGroup(() => itemAlias.ID) .Select(() => itemAlias.Name) .Select(() => itemAlias.Brand) .Select(() => itemAlias.QuantityUnit)) .Where(() => sectionAlias.Name == "Consumerable" || sectionAlias.Name == "Grocery") .Where(Restrictions.Gt(Projections.Count(Projections.Property(() => itemAlias.ID)), 1)) .List<object[]>(); return results.ToList(); } } public static List<ItemSKU> GetPriceVariation(int _ID) { using (var session = NHibernateHelper.OpenSession()) { var itemSKUList = (from itemsku in (session.Query<ItemSKU>() .Where(itemsku => itemsku.Item.ID == _ID) .Fetch(x => x.Item)) select itemsku) .ToList(); return itemSKUList; } } } } <file_sep>/JanataBazaar/View/Register/Winform_VATStatementRegister.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_VATStatementRegister : WinformRegister { List<PurchaseOrder> purchaseOrderList; int currRowIndex = -1; public Winform_VATStatementRegister() { InitializeComponent(); } protected void SearchToolStrip_Click(object sender, System.EventArgs e) { DateTime toDate = new DateTime(); DateTime fromDate = new DateTime(); bool isCredit = rdbCredit.Checked; int duration; int.TryParse(nudDuration.Value.ToString(), out duration); duration = duration == 0 ? 1 : duration; #region SetDuration if (cmbDuration.Text == "Custom") { if (DateTime.Compare(dtpFrom.Value.Date, dtpTo.Value.Date) > 0) { MessageBox.Show("From date cannot be greater than To date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } toDate = dtpTo.Value.Date; fromDate = dtpFrom.Value.Date; } else if (cmbDuration.Text == "Month") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddMonths(-duration); } else if (cmbDuration.Text == "Week") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-7 * duration); } else if (cmbDuration.Text == "Day") { toDate = DateTime.Today.Date; fromDate = DateTime.Today.Date.AddDays(-duration); } #endregion SetDuration dgvRegister.DataSource = null; purchaseOrderList = Builders.PurchaseBillBuilder.GetPurchaseOrderList(fromDate, toDate, isCredit); if (purchaseOrderList.Count != 0) { dgvRegister.DataSource = (from item in purchaseOrderList select new { SI_No = purchaseOrderList.IndexOf(item) + 1, //item.BillNo, BillDate = item.DateOfInvoice.Date.ToString("dd/MMM/yyyy"), SupplierName = item.Vendor.Name, item.SCFNo, TotalAmount = item.TotalPurchasePrice, item.Vendor.TIN, RevisionID = item.Revision.ID }).ToList(); dgvRegister.Columns["RevisionID"].Visible = false; } } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1 || currRowIndex == e.RowIndex) return; currRowIndex = e.RowIndex; dgvVATDetails.Rows.Clear(); dgvVATDetails.Columns.Clear(); //get all the percentages for a particular revision int revisionID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["RevisionID"].Value.ToString()); List<decimal> vatPercentList = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(revisionID); PurchaseOrder order = purchaseOrderList[e.RowIndex]; //create dictionary for each percentage with sum of all percenatage Dictionary<decimal, decimal> vatPercentageSum = new Dictionary<decimal, decimal>(); foreach (decimal percent in vatPercentList) { if (percent == 0) continue; decimal sumVATPercent = order.ItemPriceList.Where(i => i.VATPercent == percent).Select(i => i.VAT).Sum(); vatPercentageSum.Add(percent, sumVATPercent); } var rdOffList = new List<decimal>(); foreach (var item in order.ItemPriceList) { rdOffList.Add(item.VAT - (item.Basic * (item.VATPercent / 100))); } //create dictionary for each percentage with sum of all basic Dictionary<decimal, decimal> vatPurchaseSum = new Dictionary<decimal, decimal>(); foreach (decimal percent in vatPercentList) { decimal sumVATPercent = order.ItemPriceList.Where(i => i.VATPercent == percent).Select(i => i.PurchaseValue).Sum(); vatPurchaseSum.Add(percent, sumVATPercent); } LoadDGVAddColumns(vatPercentList); LoadDGVAddValues(order, vatPercentageSum, vatPurchaseSum, rdOffList); } private void LoadDGVAddColumns(List<decimal> vatPercentList) { foreach (var percent in vatPercentList) { if (percent == 0) continue; dgvVATDetails.Columns.Add("col" + percent + "%", percent + "%"); } foreach (var percent in vatPercentList) { if (percent == 0) { dgvVATDetails.Columns.Add("colExempted", "Excempted"); continue; } dgvVATDetails.Columns.Add("col" + percent + "Value", percent + "%_Amount"); } dgvVATDetails.Columns["colExempted"].DisplayIndex = dgvVATDetails.Columns.Count - 1; dgvVATDetails.Columns.Add("colPosRodOff", "+"); dgvVATDetails.Columns.Add("colNegRodOff", "-"); dgvVATDetails.Columns.Add("colTotalAmount", "TotalAmount"); } private void LoadDGVAddValues(PurchaseOrder order, Dictionary<decimal, decimal> vatPercentageSum, Dictionary<decimal, decimal> vatBasicSum, List<decimal> rdOffList) { dgvVATDetails.Rows.Add(); foreach (var item in vatPercentageSum) { dgvVATDetails.Rows[0].Cells["col" + item.Key + "%"].Value = item.Value; } foreach (var item in vatBasicSum) { if (item.Key == 0) { dgvVATDetails.Rows[0].Cells["colExempted"].Value = item.Value; continue; } dgvVATDetails.Rows[0].Cells["col" + item.Key + "Value"].Value = item.Value; } //decimal totalPurchaseValue = 0; //foreach (var item in order.ItemPriceList) //{ // var _basic = item.Basic; // totalPurchaseValue += (_basic * item.TransportPercent) + (_basic * item.MiscPercent) + (_basic * item.VATPercent) - (_basic * item.DiscountPercent); //} dgvVATDetails.Rows[0].Cells["colPosRodOff"].Value = rdOffList.Where(i => i > 0).Sum().ToString("#.##"); dgvVATDetails.Rows[0].Cells["colNegRodOff"].Value = rdOffList.Where(i => i < 0).Sum().ToString("#.##"); dgvVATDetails.Rows[0].Cells["colTotalAmount"].Value = order.TotalPurchasePrice; } private void Winform_VATStatementRegister_Load(object sender, EventArgs e) { cmbDuration.SelectedIndex = 0; this.toolStrip1.Items.Add(SearchToolStrip); } private void cmbDuration_SelectedIndexChanged(object sender, EventArgs e) { bool isActive = (cmbDuration.Text == "Custom") ? true : false; dtpTo.Enabled = isActive; dtpFrom.Enabled = isActive; nudDuration.Enabled = !isActive; } } } <file_sep>/JanataBazaar/View/Details/Winform_AddSection.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_AddSection : Winform_Details { public Winform_AddSection() { InitializeComponent(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { UpdateStatus("Saving", 25); string errorMsg = ""; if (string.IsNullOrEmpty(txtSectionName.Text)) { errorMsg = "Section Name is Mandatory and Cannot be Empty."; } else { Match _match = Regex.Match(txtSectionName.Text, "^[a-zA-Z\\s]+$"); errorMsg = _match.Success ? "" : "Invalid Input for Name\n" + "For example 'ABCabc'"; } if (errorMsg == "" && Builders.ItemDetailsBuilder.SectionExists(txtSectionName.Text)) { errorMsg = "Section Name is a Duplicate as it already Exists."; } errorProvider1.SetError(txtSectionName, errorMsg); if (errorMsg != "") { txtSectionName.Select(0, txtSectionName.TextLength); UpdateStatus(); return; } UpdateStatus("Saving", 50); if (Savers.ItemDetailsSavers.SaveSection(new Models.Section(Utilities.Validation.ToTitleCase(txtSectionName.Text))) == 0) { UpdateStatus("Error Saving Section", 100); } UpdateStatus("Section Saved", 100); this.Close(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsInEdit(txtSectionName, false)) { var _dialogResult = MessageBox.Show("Do you want to Exit?", "Exit Section Details", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (_dialogResult == DialogResult.No) return; }; this.Close(); } } } <file_sep>/JanataBazaar/Savers/ItemSKUSavers.cs using JanataBazaar.Models; using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Savers { class ItemSKUSavers { static ILog log = LogManager.GetLogger(typeof(ItemSKUSavers)); public static bool SaveSKUInfo(ItemSKU skuItem) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { session.SaveOrUpdate(skuItem); tx.Commit(); return true; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return false; } } } } public static bool UpdateSKUList(ItemSKU _skuItem, List<ItemSKU> toDeleteSKUItemList) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { session.SaveOrUpdate(_skuItem); //Delete SKU foreach (var skuItem in toDeleteSKUItemList) { /* skuItem.StockQuantity = 0; session.SaveOrUpdate(skuItem); */ session.Delete(skuItem); } tx.Commit(); return true; } catch (Exception ex) { tx.Rollback(); log.Error(ex); return false; } } } } } } <file_sep>/JanataBazaar/View/Register/WinForm_MemberRegister.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class WinForm_MemberRegister : WinformRegister { public WinForm_MemberRegister() { InitializeComponent(); } private void WinForm_MemberRegister_Load(object sender, EventArgs e) { txtName_TextChanged(this, new EventArgs()); } #region Events protected override void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1 || e.ColumnIndex == -1) return; Winform_SaleDetails saleDetail = Application.OpenForms["Winform_SaleDetails"] as Winform_SaleDetails; if (saleDetail != null) { DialogResult _dialogResult = MessageBox.Show("Do you want to Add Member " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Add Member Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); Person _member = PeoplePracticeBuilder.GetMemberInfo(_ID); saleDetail.UpdateCustomerControls(_member); this.Close(); } else { DialogResult _dialogResult = MessageBox.Show("Do you want to Modify the details of Member " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells["Name"].Value), "Modify Member Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (_dialogResult == DialogResult.No) return; int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); Member _member = PeoplePracticeBuilder.GetMemberInfo(_ID); new Winform_MemberDetails(_member).ShowDialog(); txtName_TextChanged(this, new EventArgs()); } } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; if (dgvRegister.Columns["colDelete"].Index == e.ColumnIndex) { int memtID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); DialogResult dr = MessageBox.Show("Do you want to delete Member " + memtID, "Delete Member", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) return; bool success = Savers.PeoplePracticeSaver.DeleteMember(memtID); if (success) { txtName_TextChanged(this, new EventArgs()); UpdateStatus("Member Deleted.", 100); } else { UpdateStatus("Error deleting Member. ", 100); } } } private void txtName_TextChanged(object sender, EventArgs e) { dgvRegister.DataSource = null; dgvRegister.Columns["colDelete"].Visible = false; if (string.IsNullOrEmpty(txtMemNo.Text) && string.IsNullOrEmpty(txtMobNo.Text) && string.IsNullOrEmpty(txtName.Text)) return; UpdateStatus("Searching", 50); List<Member> membList = new List<Member>(); membList = PeoplePracticeBuilder.GetMemberList(txtName.Text, txtMobNo.Text, txtMemNo.Text); if (membList != null && membList.Count != 0) { dgvRegister.DataSource = (from memb in membList select new { memb.ID, memb.Name, MobileNo = memb.Mobile_No, memb.MemberNo }).ToList(); dgvRegister.Columns["ID"].Visible = false; dgvRegister.Columns["colDelete"].Visible = true; dgvRegister.Columns["colDelete"].DisplayIndex = dgvRegister.Columns.Count - 1; } UpdateStatus((dgvRegister.RowCount == 0) ? "No Results Found" : dgvRegister.RowCount + " Results Found", 100); } #endregion Events } } <file_sep>/JanataBazaar/Builders/ItemDetailsBuilder.cs using JanataBazaar.Models; using NHibernate.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { public class ItemDetailsBuilder { public static bool SectionExists(string sectionName) { using (var session = NHibernateHelper.OpenSession()) { return session.Query<Section>().Any(x => x.Name == sectionName); } } public static List<string> GetNamesList() { using (var session = NHibernateHelper.OpenSession()) { return (from _item in session.Query<Item>() select _item.Name).Distinct().ToList(); } } public static List<string> GetBrandsList() { using (var session = NHibernateHelper.OpenSession()) { return (from _item in session.Query<Item>() select _item.Brand).Distinct().ToList(); } } public static Section GetSection(string _name) { using (var session = NHibernateHelper.OpenSession()) { Section sect = (from _sect in session.Query<Section>() where _sect.Name == _name select _sect).SingleOrDefault(); return sect; } } public static List<string> GetSectionsList() { using (var session = NHibernateHelper.OpenSession()) { return (from sect in session.Query<Section>() select sect.Name).ToList(); } } //public static List<Section> GetSectionsList() //{ // using (var session = NHibernateHelper.OpenSession()) // { // return session.Query<Section>().ToList(); // } //} public static List<string> GetUnitList() { using (var session = NHibernateHelper.OpenSession()) { return (from _item in session.Query<Item>() select _item.QuantityUnit).Distinct().ToList(); } } public static IList GetItemsList(string name, string sectionName, string brand = "") { using (var session = NHibernateHelper.OpenSession()) { Item itemAlias = null; Section sectionAlias = null; IList itemList = (from item in (session.QueryOver(() => itemAlias) .JoinAlias(() => itemAlias.Section, () => sectionAlias) .Where(NHibernate.Criterion.Restrictions.On(() => itemAlias.Name).IsLike(name + "%")) .Where(NHibernate.Criterion.Restrictions.On(() => itemAlias.Brand).IsLike(brand + "%")) .Where(() => sectionAlias.Name == sectionName) .List()) select new { item.ID, item.Name, item.Brand, item.QuantityUnit }) .ToList(); return itemList; } } public static bool ItemExists(string name, string brand, string unit, string sectionName) { using (var session = NHibernateHelper.OpenSession()) { int sectID = (from sect in session.Query<Section>() where sect.Name == sectionName select sect.ID).SingleOrDefault(); return session.Query<Item>().Any(x => (x.Name == name && x.QuantityUnit == unit && x.Brand == brand && x.Section.ID == sectID)); } } public static Item GetItemInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { var _item = session.QueryOver<Item>() .Where(x => x.ID == _ID) .Fetch(s => s.Section).Eager .Future().SingleOrDefault(); return _item; } } } public class PackageDetailsBuilder { public static bool PackageExists(string packageName) { using (var session = NHibernateHelper.OpenSession()) { return session.Query<Package>().Any(x => x.Name == packageName); } } public static Package GetPackage(string packageName) { using (var session = NHibernateHelper.OpenSession()) { Package pack = (from _pack in session.Query<Package>() where _pack.Name == packageName select _pack).FirstOrDefault(); return pack; } } } public class ItemPricingBuilder { public static ItemPricing GetItemPricingInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { var _item = session.QueryOver<ItemPricing>() .Where(x => x.ID == _ID) .Fetch(i => i.Item).Eager .Future().SingleOrDefault(); return _item; } } } public class ItemSKUBuilder { public static ItemSKU GetItemSKUInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { var _item = session.QueryOver<ItemSKU>() .Where(x => x.ID == _ID) .Fetch(i => i.Item).Eager .Future().SingleOrDefault(); return _item; } } public static ItemSKU GetItemSKUBasedOnPrice(int _ID, decimal resalePrice, decimal wholesalePrice) { using (var session = NHibernateHelper.OpenSession()) { var _item = session.QueryOver<ItemSKU>() .Where(x => x.ID == _ID) .Where(x => x.ResalePrice == resalePrice && x.WholesalePrice == wholesalePrice) .Fetch(i => i.Item).Eager .Future().SingleOrDefault(); return _item; } } } } <file_sep>/JanataBazaar/View/Details/Winform_ItemSKUDetails.cs using JanataBazaar.Models; using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_ItemSKUDetails : Winform_Details { List<string> exceptList = new List<string> { "txtBasic", "txtWholePercent", "txtRetailPercent", "txtTotalBasic" }; Item item; Package pack; int Index; int revisionID; #region Properties public decimal Basic { get; set; } private decimal _trans; public decimal Trans { get { txtTrans.Text = _trans.ToString(); return _trans; } set { _trans = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); } } private decimal _transpercent; public decimal TransPercent { get { //txtTransPercent.Text = _transpercent.ToString(); return _transpercent; } set { _transpercent = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtTransPercent.Text = _transpercent.ToString("#.##"); } } private decimal _totalTrans; public decimal TotalTrans { get { return _totalTrans; } set { _totalTrans = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtTotalTrans.Text = _totalTrans.ToString(); } } private decimal _misc; public decimal Misc { get { txtMisc.Text = _misc.ToString(); return _misc; } set { _misc = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); } } private decimal _miscpercent; public decimal MiscPercent { get { return _miscpercent; } set { _miscpercent = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtMiscPercent.Text = _miscpercent.ToString(); } } private decimal _totalMisc; public decimal TotalMisc { get { return _totalMisc; } set { _totalMisc = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtTotalMisc.Text = _totalMisc.ToString(); } } private decimal _vat; public decimal VAT { get; set; } private decimal _vatpercent; public decimal VATPercent { get { //txtVAT.Text = _vat.ToString(); return _vatpercent; } set { _vatpercent = value; } } private decimal _disc; public decimal Discount { get { txtDisc.Text = _disc.ToString(); return _disc; } set { _disc = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); } } private decimal _discpercent; public decimal DiscountPercent { get { return _discpercent; } set { _discpercent = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtDiscPercent.Text = _discpercent.ToString(); } } private decimal _totalDisc; public decimal TotalDiscount { get { return _totalDisc; } set { _totalDisc = value == 0 ? 0 : decimal.Parse(value.ToString("#.##")); txtTotalDiscount.Text = _totalDisc.ToString(); } } private decimal _purchaseRate; public decimal PurchaseRate { get { return _purchaseRate; } set { _purchaseRate = value; txtPurchaseRate.Text = _purchaseRate.ToString(); txtTotalPurcPrice.Text = (_purchaseRate * nudItemsPerPack.Value * nudNoPacks.Value).ToString("#.##"); } } private decimal _purchaseValue; public decimal PurchaseValue { get { //decimal _purchaseValue = ((Basic + Trans + Misc + VAT) - Discount); return _purchaseValue; } set { _purchaseValue = value; PurchaseRate = _purchaseValue; } } private decimal _wRate; public decimal WRate { get; set; } private decimal _wRatepercent; public decimal WRatePercent { get { return _wRatepercent; } set { //WRate = (value != 0 ? (PurchaseRate * (value / 100)) : 0) + PurchaseRate; _wRatepercent = value; } } private decimal _rRate; public decimal RRate { get; set; } private decimal _rRatepercent; public decimal RRatePercent { get { return _rRatepercent; } set { // RRate = (value != 0 ? (WRate * (value / 100)) : 0) + WRate; _rRatepercent = value; } } #endregion private void UpdateTransSet(decimal _percent, decimal _value, decimal _total) { if (_percent != 0) { TransPercent = _percent; Trans = Basic * (TransPercent / 100); TotalTrans = (Trans * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_value != 0) { Trans = _value; TransPercent = (Trans * 100) / Basic; TotalTrans = (Trans * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_total != 0) { TotalTrans = _total; Trans = (_total / (nudItemsPerPack.Value * nudNoPacks.Value)); TransPercent = (Trans * 100) / Basic; } } private void UpdateVATSet(decimal _value) { txtTotalVAT.Text = _value == 0 ? "0" : (_value * (nudItemsPerPack.Value * nudNoPacks.Value)).ToString("#.##"); lblVATRdOff.Text = (_value - decimal.Parse(txtVATMarginPrice.Text)).ToString("#.##"); } private void UpdateMiscSet(decimal _percent, decimal _value, decimal _total) { if (_percent != 0) { MiscPercent = _percent; Misc = Basic * (MiscPercent / 100); TotalMisc = (Misc * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_value != 0) { Misc = _value; MiscPercent = (Misc * 100) / Basic; TotalMisc = (Misc * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_total != 0) { TotalMisc = _total; Misc = (_total / (nudItemsPerPack.Value * nudNoPacks.Value)); MiscPercent = (Misc * 100) / Basic; } } private void UpdateDiscSet(decimal _percent, decimal _value, decimal _total) { if (_percent != 0) { DiscountPercent = _percent; Discount = Basic * (DiscountPercent / 100); TotalDiscount = (Discount * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_value != 0) { Discount = _value; DiscountPercent = (Discount * 100) / Basic; TotalDiscount = (Discount * (nudItemsPerPack.Value * nudNoPacks.Value)); } else if (_total != 0) { TotalDiscount = _total; Discount = (_total / (nudItemsPerPack.Value * nudNoPacks.Value)); DiscountPercent = (Discount * 100) / Basic; } } public Winform_ItemSKUDetails(int index = 0, int revisionID = 0) { InitializeComponent(); var packageTypes = Builders.PurchaseBillBuilder.GetPackageTypes(); cmbPackType.DataSource = packageTypes; //string[] packAutoCol = packageTypes.ToArray(); //AutoCompleteStringCollection packAuto = new AutoCompleteStringCollection(); //packAuto.AddRange(packAutoCol); //cmbPackType.AutoCompleteSource = AutoCompleteSource.ListItems; //cmbPackType.AutoCompleteMode = AutoCompleteMode.Suggest; this.Index = index; this.revisionID = revisionID; if (revisionID != 0) { cmbVATPercent.DataSource = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(revisionID); //cmbVATPercent.DisplayMember = "Percent"; } } public Winform_ItemSKUDetails(int index, int revisionID, ItemPricing itemsku = null) { InitializeComponent(); this.Index = index; this.revisionID = revisionID; //set combobox is set to default. if (revisionID != 0) { cmbVATPercent.DataSource = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(revisionID); //cmbVATPercent.DisplayMember = "Percent"; } cmbPackType.DataSource = Builders.PurchaseBillBuilder.GetPackageTypes(); //load controls this.item = itemsku.Item; UpdateItemDetailControls(this.item); if (itemsku.ManufacturedDate != DateTime.MinValue) { chkDOM.Checked = true; dtpDOM.Enabled = true; dtpDOM.Value = itemsku.ManufacturedDate; } if (itemsku.ExpiredDate != DateTime.MinValue) { chkDOE.Checked = true; dtpDOE.Enabled = true; dtpDOE.Value = itemsku.ExpiredDate; } this.pack = itemsku.Package; if (this.pack != null) cmbPackType.SelectedIndex = cmbPackType.Items.IndexOf(this.pack.Name); nudNoPacks.Value = itemsku.PackageQuantity; nudItemsPerPack.Value = itemsku.QuantityPerPack; txtNetWght.Text = itemsku.NetWeight.ToString(); txtGrossWght.Text = itemsku.GrossWeight.ToString(); txtBasic.Text = itemsku.Basic.ToString(); this.Basic = itemsku.Basic; txtTotalBasic.Text = (this.Basic * (nudNoPacks.Value * nudItemsPerPack.Value)).ToString("#.##"); txtTransPercent.Text = itemsku.TransportPercent.ToString(); //txtTrans.Text = itemsku.Transport.ToString(); UpdateTransSet(itemsku.TransportPercent, 0, 0); txtMiscPercent.Text = itemsku.MiscPercent.ToString(); //txtMisc.Text = itemsku.Misc.ToString(); UpdateMiscSet(itemsku.MiscPercent, 0, 0); txtDiscPercent.Text = itemsku.DiscountPercent.ToString(); ///txtDisc.Text = itemsku.Discount.ToString(); UpdateDiscSet(itemsku.DiscountPercent, 0, 0); cmbVATPercent.SelectedIndex = cmbVATPercent.Items.IndexOf(itemsku.VATPercent); txtVAT.Text = itemsku.VAT.ToString("#.##"); txtTotalVAT.Text = (itemsku.VAT * nudItemsPerPack.Value * nudNoPacks.Value).ToString("#.##"); //this.VATPercent = itemsku.VATPercent; //this.MiscPercent = itemsku.MiscPercent; //this.DiscountPercent = itemsku.DiscountPercent; //this.TransPercent = itemsku.TransportPercent; //this.VAT = itemsku.VAT; //this.Misc = itemsku.Misc; //this.Discount = itemsku.Discount; //this.Trans = itemsku.Transport; //UpdateRates(); UpdateRates(); this.PurchaseRate = itemsku.PurchaseValue; this.WRatePercent = itemsku.WholesaleMargin; this.WRate = itemsku.Wholesale; this.RRatePercent = itemsku.RetailMargin; this.RRate = itemsku.Retail; txtPurchaseRate.Text = itemsku.PurchaseValue.ToString(); //PurchaseRate = itemsku.PurchaseValue; txtWholePercent.Text = itemsku.WholesaleMargin.ToString(); txtWholeMarginPrice.Text = ((WRatePercent != 0 ? (PurchaseRate * (WRatePercent / 100)) : 0) + PurchaseRate).ToString("#.##"); txtWholeRate.Text = itemsku.Wholesale.ToString(); UpdateWSaleSet(); txtRetailPercent.Text = itemsku.RetailMargin.ToString(); txtRetailMarginPrice.Text = ((RRatePercent != 0 ? (WRate * (RRatePercent / 100)) : 0) + WRate).ToString("#.##"); txtRetailRate.Text = itemsku.Retail.ToString(); UpdateRSaleSet(); } private void Winform_Item_Load(object sender, EventArgs e) { this.toolStripParent.Items.Add(this.AddSectionToolStrip); this.toolStripParent.Items.Add(this.AddPackageToolStrip); //if (revisionID != 0) //{ // cmbVATPercent.DataSource = Builders.VATRevisionBuilder.GetVATRevisionPercentageList(revisionID); // cmbVATPercent.DisplayMember = "Percent"; //} } private void AddPackageToolStrip_Click(object sender, EventArgs e) { new Winform_PackageDetails().ShowDialog(); cmbPackType.DataSource = Builders.PurchaseBillBuilder.GetPackageTypes(); } private void chkDOM_CheckedChanged(object sender, EventArgs e) { dtpDOM.Enabled = chkDOM.Checked; } private void chkDOE_CheckedChanged(object sender, EventArgs e) { dtpDOE.Enabled = chkDOE.Checked; } #region Validation private void txtValueDecimal_Validating(object sender, CancelEventArgs e) { TextBox txt = (TextBox)sender; string _errorMsg; if (string.IsNullOrEmpty(txt.Text)) { if (!exceptList.Contains(txt.Name)) return; _errorMsg = "Invalid Amount input data type.\nExample: '1100'"; } else { Match _match = Regex.Match(txt.Text, "^[0-9]*\\.?[0-9]*$"); _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '1100'" : ""; } errorProvider1.SetError(txt, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txt.Select(0, txt.Text.Length); } } private void txtValueInt_Validating(object sender, CancelEventArgs e) { string _errorMsg = ""; TextBox txt = (TextBox)sender; if (string.IsNullOrEmpty(txt.Text)) { if (!exceptList.Contains(txt.Name)) return; _errorMsg = "Invalid Amount input data value.\nExample: '10'"; } else { Match _match = Regex.Match(txt.Text, "^[0-9]*$"); _errorMsg = !_match.Success ? "Invalid input data type.\nExample: '10'" : ""; } errorProvider1.SetError(txt, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txt.Select(0, txt.Text.Length); } } #region PercentValidated //on validated update only the property //updating control must be done seprately to encourage "Sepration Of Concerns." private void txtTransPercent_Validated(object sender, EventArgs e) { TransPercent = (decimal.TryParse(txtTransPercent.Text, out _trans) ? _trans : 0); //Trans = TransPercent == 0 ? 0 : Basic * (TransPercent / 100); //TotalTrans = (Trans * (nudItemsPerPack.Value * nudNoPacks.Value)); UpdateTransSet(TransPercent, 0, 0); UpdateRates(); } private void txtMiscPercent_Validated(object sender, EventArgs e) { MiscPercent = (decimal.TryParse(txtMiscPercent.Text, out _misc) ? _misc : 0); //Misc = MiscPercent != 0 ? Basic * (MiscPercent / 100) : 0; //TotalMisc = (Misc * (nudItemsPerPack.Value * nudNoPacks.Value)); UpdateMiscSet(MiscPercent, 0, 0); UpdateRates(); } private void txtDiscPercent_Validated(object sender, EventArgs e) { DiscountPercent = (decimal.TryParse(txtDiscPercent.Text, out _disc) ? _disc : 0); //Discount = DiscountPercent != 0 ? Basic * (DiscountPercent / 100) : 0; //TotalDiscount = (Discount * (nudItemsPerPack.Value * nudNoPacks.Value)); UpdateDiscSet(DiscountPercent, 0, 0); UpdateRates(); } private void txtWholePercent_Validated(object sender, EventArgs e) { WRatePercent = (decimal.TryParse(txtWholePercent.Text, out _wRate) ? _wRate : 0); WRate = (WRatePercent != 0 ? (PurchaseRate * (WRatePercent / 100)) : 0) + PurchaseRate; txtWholeRate.Text = txtWholeMarginPrice.Text = WRate.ToString("#.##"); txtTotalWSalePrice.Text = (WRate * (nudItemsPerPack.Value * nudNoPacks.Value)).ToString("#.##"); } private void txtRetailPercent_Validated(object sender, EventArgs e) { RRatePercent = (decimal.TryParse(txtRetailPercent.Text, out _rRate) ? _rRate : 0); RRate = (RRatePercent != 0 ? (WRate * (RRatePercent / 100)) : 0) + WRate; txtRetailRate.Text = txtRetailMarginPrice.Text = RRate.ToString("#.##"); txtTotalRSalePrice.Text = (RRate * (nudItemsPerPack.Value * nudItemsPerPack.Value)).ToString("#.##"); } #endregion PercentValidated #region ratesValidated private void txtBasic_Validated(object sender, EventArgs e) { decimal _basic; Basic = decimal.TryParse(txtBasic.Text, out _basic) ? _basic : 0; var totalItem = nudItemsPerPack.Value * nudNoPacks.Value; txtTotalBasic.Text = (Basic * totalItem).ToString("#.##"); if (!string.IsNullOrEmpty(cmbVATPercent.Text)) { VATPercent = decimal.Parse(cmbVATPercent.Text); txtVAT.Text = VAT.ToString("#.##"); } txtValues_Validated(this, new EventArgs()); UpdateRates(); } private void txtTotalBasic_Validated(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtTotalBasic.Text)) return; var totalItem = nudItemsPerPack.Value * nudNoPacks.Value; txtBasic.Text = (decimal.Parse(txtTotalBasic.Text) / totalItem).ToString("#.#####"); txtBasic_Validated(this, new EventArgs()); } private void txtValues_Validated(object sender, EventArgs e) { Trans = (decimal.TryParse(txtTrans.Text, out _trans) ? _trans : 0); UpdateTransSet(0, Trans, 0); Misc = (decimal.TryParse(txtMisc.Text, out _misc) ? _misc : 0); UpdateMiscSet(0, Misc, 0); VAT = (decimal.TryParse(txtVAT.Text, out _vat) ? _vat : 0); UpdateVATSet(VAT); Discount = (decimal.TryParse(txtDisc.Text, out _disc) ? _disc : 0); UpdateDiscSet(0, Discount, 0); UpdateRates(); } private void txtPurchaseRate_Validated(object sender, EventArgs e) { PurchaseRate = decimal.Parse(txtPurchaseRate.Text); txtWholePercent_Validated(this, new EventArgs()); txtRetailPercent_Validated(this, new EventArgs()); } private void txtWholeRate_Validated(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtWholeRate.Text)) return; WRate = decimal.Parse(txtWholeRate.Text); txtRetailPercent_Validated(this, new EventArgs()); UpdateWSaleSet(); } private void UpdateWSaleSet() { decimal wsaleMargin = !string.IsNullOrEmpty(txtWholeMarginPrice.Text) && decimal.TryParse(txtWholeMarginPrice.Text, out wsaleMargin) ? wsaleMargin : 0; lblWRateRdOff.Text = (WRate - wsaleMargin).ToString("#.##"); txtTotalWSalePrice.Text = (WRate * (nudItemsPerPack.Value * nudNoPacks.Value)).ToString("#.##"); } private void txtRetailRate_Validated(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtRetailRate.Text)) return; RRate = decimal.Parse(txtRetailRate.Text); UpdateRSaleSet(); } private void UpdateRSaleSet() { decimal rsaleMargin = !string.IsNullOrEmpty(txtRetailMarginPrice.Text) && decimal.TryParse(txtRetailMarginPrice.Text, out rsaleMargin) ? rsaleMargin : 0; lblRRateRdOff.Text = (RRate - rsaleMargin).ToString("##.##"); txtTotalRSalePrice.Text = (RRate * (nudItemsPerPack.Value * nudNoPacks.Value)).ToString("#.##"); } #endregion ratesValidated #endregion private void AddSectionToolStrip_Click(object sender, EventArgs e) { new Register.Winform_ItemRegistry().ShowDialog(); } private void UpdateRates() { PurchaseValue = ((Basic + Trans + Misc + VAT) - Discount); txtWholePercent_Validated(this, new EventArgs()); txtRetailPercent_Validated(this, new EventArgs()); } public void UpdateItemDetailControls(Item _item) { this.item = _item; txtName.Text = item.Name; txtUnit.Text = item.QuantityUnit; txtSection.Text = item.Section.Name; txtBrand.Text = _item.Brand; //chkIsExempted.Checked = _item.IsVatExempted; //txtVATPercent.Text = _item.VatPercent.ToString(); //txtVAT.Enabled = !chkIsExempted.Checked; //VATPercent = _item.VatPercent; //txtVAT.Text = VAT.ToString(); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { this.ProcessTabKey(true); List<string> exceptList = new List<string>() { "txtDisc", "txtDiscPercent","txtTotalDiscount" ,"txtMisc", "txtMiscPercent","txtTotalMisc" ,"txtTrans", "txtTransPercent","txtTotalTrans" ,"txtVAT", "cmbVATPercent","txtTotalVAT", "txtBrand","cmbPackType","txtNoPacks","txtNetWght","txtGrossWght" }; if (Utilities.Validation.IsNullOrEmpty(this, true, exceptList)) return; ItemPricing _itemPrice = new ItemPricing(); _itemPrice.Item = item; _itemPrice.Basic = Basic; _itemPrice.Discount = Discount; _itemPrice.DiscountPercent = DiscountPercent; if (chkDOM.Checked == true) _itemPrice.ManufacturedDate = dtpDOM.Value; if (chkDOE.Checked == true) _itemPrice.ExpiredDate = dtpDOE.Value; _itemPrice.Transport = Trans; _itemPrice.TransportPercent = TransPercent; _itemPrice.Misc = Misc; _itemPrice.MiscPercent = MiscPercent; _itemPrice.VAT = chkIsExempted.Checked == true ? 0 : VAT; _itemPrice.VATPercent = chkIsExempted.Checked == true ? 0 : VATPercent; _itemPrice.Discount = Discount; _itemPrice.DiscountPercent = DiscountPercent; _itemPrice.Wholesale = WRate; _itemPrice.WholesaleMargin = WRatePercent; _itemPrice.Retail = RRate; _itemPrice.RetailMargin = RRatePercent; _itemPrice.PurchaseValue = PurchaseRate; if (this.pack != null) _itemPrice.Package = this.pack; _itemPrice.PackageQuantity = int.Parse(nudNoPacks.Value.ToString()); _itemPrice.QuantityPerPack = int.Parse(nudItemsPerPack.Value.ToString()); _itemPrice.NetWeight = string.IsNullOrEmpty(txtNetWght.Text) ? 0 : int.Parse(txtNetWght.Text); _itemPrice.GrossWeight = string.IsNullOrEmpty(txtGrossWght.Text) ? 0 : int.Parse(txtGrossWght.Text); Winform_PurchaseBill purchaseBill = Application.OpenForms["Winform_PurchaseBill"] as Winform_PurchaseBill; if (purchaseBill != null) purchaseBill.UpdateSKUItemList(this.Index, _itemPrice); UpdateStatus("ItemSKU Saved", 100); this.Close(); } private void txtNetWght_Validated(object sender, EventArgs e) { if (!string.IsNullOrEmpty(cmbPackType.Text)) this.pack = Builders.PackageDetailsBuilder.GetPackage(cmbPackType.Text); if (string.IsNullOrEmpty(txtNetWght.Text)) return; txtGrossWght.Text = (int.Parse(txtNetWght.Text) + (this.pack != null ? this.pack.Weight : 0)).ToString(); } private void chkIsExempted_CheckedChanged(object sender, EventArgs e) { cmbVATPercent.Enabled = !chkIsExempted.Checked; cmbVATPercent.SelectedIndex = 0; //txtVAT.Enabled = false; //if (txtVATPerc.Enabled) // txtVATPerc.Validating += new CancelEventHandler(this.txtBox_Validating); //else // txtVATPerc.Validating += null; } private void cmbVATPercent_SelectedIndexChanged(object sender, EventArgs e) { VATPercent = decimal.Parse(cmbVATPercent.Text); VAT = VATPercent != 0 ? Basic * (VATPercent / 100) : 0; lblVATRdOff.Text = "0"; txtVAT.Text = txtVATMarginPrice.Text = VAT == 0 ? "0" : VAT.ToString("#.##"); txtTotalVAT.Text = VAT == 0 ? "0" : (VAT * nudItemsPerPack.Value * nudNoPacks.Value).ToString("#.##"); UpdateRates(); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { if (Utilities.Validation.IsInEdit(this, true)) { DialogResult dr = MessageBox.Show("Continue to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dr == DialogResult.Yes) this.Close(); } } private void txtTotalTrans_Validated(object sender, EventArgs e) { TotalTrans = (decimal.TryParse(txtTotalTrans.Text, out _totalTrans) ? _totalTrans : 0); UpdateTransSet(0, 0, TotalTrans); TotalMisc = (decimal.TryParse(txtTotalMisc.Text, out _totalMisc) ? _totalMisc : 0); UpdateMiscSet(0, 0, TotalMisc); TotalDiscount = (decimal.TryParse(txtTotalDiscount.Text, out _totalDisc) ? _totalDisc : 0); UpdateDiscSet(0, 0, TotalDiscount); UpdateRates(); } } } <file_sep>/JanataBazaar/View/Details/Winform_PurchaseBill.cs using JanataBazaar.Model; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text.RegularExpressions; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_PurchaseBill : Winform_Details { Vendor vend = new Vendor(); List<ItemPricing> ItemPriceList = new List<ItemPricing>(); PurchaseOrder purchaseOrder = new PurchaseOrder(); int RevisionID; //private object txtWholeMarginPrice; public Winform_PurchaseBill() { InitializeComponent(); } private void Winform_PurchaseBill_Load(object sender, EventArgs e) { //get the revision date based on Invoice date RevisionID = Builders.VATRevisionBuilder.GetRevisionDate(dtpInvoiceDate.Value.Date); this.toolStripParent.Items.Add(this.AddVendorToolStrip); } public void UpdateVendorControls(Vendor _vend) { this.vend = _vend; txtVendorName.Text = _vend.Name; errorProvider1.SetError(txtVendorName, ""); } private void AddVendorToolStrip_Click(object sender, EventArgs e) { new Register.Winform_AddVendor().ShowDialog(); } private void AddPackageToolStrip_Click(object sender, EventArgs e) { new Winform_PackageDetails().ShowDialog(); } private void dgvDetails_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; if (dgvProdDetails.Columns["ColProduct"].Index == e.ColumnIndex) { if (e.RowIndex < ItemPriceList.Count) { new Winform_ItemSKUDetails(e.RowIndex, RevisionID, ItemPriceList[e.RowIndex]).ShowDialog(); } else { new Winform_ItemSKUDetails(e.RowIndex, RevisionID).ShowDialog(); } } else if (dgvProdDetails.Columns["ColDel"].Index == e.ColumnIndex) { if (dgvProdDetails.Rows[e.RowIndex].IsNewRow) return; else { DialogResult dr = MessageBox.Show("Do you want to Delete Item " + ItemPriceList[e.RowIndex].Item.Name, "Delete Order", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dr == DialogResult.No) return; ItemPriceList.RemoveAt(e.RowIndex); dgvProdDetails.Rows.RemoveAt(e.RowIndex); CalculatePaymentDetails(); } } } internal void UpdateSKUItemList(int index, ItemPricing _itemsku) { if (ItemPriceList.Count == 0 || ItemPriceList.Count <= index) ItemPriceList.Add(_itemsku); else ItemPriceList[index] = _itemsku; var _row = dgvProdDetails.Rows[index]; _row.Cells["ColProduct"].Value = _itemsku.Item.Name; _row.Cells["ColPurchaseValue"].Value = _itemsku.PurchaseValue.ToString("#.##"); var wROff = (_itemsku.Wholesale - (((_itemsku.WholesaleMargin * _itemsku.PurchaseValue) / 100) + _itemsku.PurchaseValue)); //_row.Cells["colWSaleROff"].Value = (wROff == 0 ? "0" : wROff.ToString("#.##")); _row.Cells["ColWholesaleValue"].Value = _itemsku.Wholesale.ToString("#.##"); var rROff = (_itemsku.Retail - (((_itemsku.RetailMargin * _itemsku.Wholesale) / 100) + _itemsku.Wholesale)); _row.Cells["ColResaleVal"].Value = _itemsku.Retail.ToString("#.##"); //_row.Cells["colRSaleROff"].Value = (rROff == 0 ? "0" : rROff.ToString("#.##")); _row.Cells["colItemUnit"].Value = _itemsku.Item.QuantityUnit; _row.Cells["colVatPercent"].Value = _itemsku.VATPercent; _row.Cells["colVat"].Value = _itemsku.VAT; if (_itemsku.Package != null) _row.Cells["ColPackageType"].Value = _itemsku.Package.Name; _row.Cells["ColPackQuantity"].Value = _itemsku.PackageQuantity; _row.Cells["colItemPerPack"].Value = _itemsku.QuantityPerPack; _itemsku.TotalPurchaseValue = (_itemsku.PackageQuantity * (_itemsku.QuantityPerPack * _itemsku.PurchaseValue)); _itemsku.TotalWholesaleValue = (_itemsku.PackageQuantity * (_itemsku.QuantityPerPack * _itemsku.Wholesale)); _itemsku.TotalResaleValue = (_itemsku.PackageQuantity * (_itemsku.QuantityPerPack * _itemsku.Retail)); _row.Cells["colTotalBasic"].Value = (_itemsku.Basic * _itemsku.PackageQuantity * _itemsku.QuantityPerPack).ToString("#.##"); _row.Cells["ColTotPurchaseVal"].Value = _itemsku.TotalPurchaseValue.ToString("#.##"); _row.Cells["ColTotWholesaleVal"].Value = _itemsku.TotalWholesaleValue.ToString("#.##"); _row.Cells["ColTotResaleVal"].Value = _itemsku.TotalResaleValue.ToString("#.##"); CalculatePaymentDetails(); dgvProdDetails.NotifyCurrentCellDirty(true); dgvProdDetails.NotifyCurrentCellDirty(false); } private void CalculatePaymentDetails() { purchaseOrder.TotalPurchasePrice = 0; purchaseOrder.TotalWholesalePrice = 0; purchaseOrder.TotalResalePrice = 0; foreach (var item in ItemPriceList) { purchaseOrder.TotalPurchasePrice += item.TotalPurchaseValue; purchaseOrder.TotalWholesalePrice += item.TotalWholesaleValue; purchaseOrder.TotalResalePrice += item.TotalResaleValue; } txtTotalPurchasePrice.Text = purchaseOrder.TotalPurchasePrice.ToString("#.##"); txtTotalWholesalePrice.Text = purchaseOrder.TotalWholesalePrice.ToString("#.##"); txtTotalResalePrice.Text = purchaseOrder.TotalResalePrice.ToString("#.##"); txtTotalPurchasePrice_ROff.Text = purchaseOrder.TotalPurchasePrice.ToString("#.##"); txtTotalWholesalePrice_ROff.Text = purchaseOrder.TotalWholesalePrice.ToString("#.##"); txtTotalResalePrice_ROff.Text = purchaseOrder.TotalResalePrice.ToString("#.##"); lblPPriceRdOff.Text = ""; lblRPriceRdOff.Text = ""; lblWPriceRdOff.Text = ""; } //private void dgvDetails_RowLeave(object sender, DataGridViewCellEventArgs e) //{ // if (dgvProdDetails.Rows[e.RowIndex].IsNewRow) return; // if (IsNullOrEmpty(dgvProdDetails.Rows[e.RowIndex].Cells["colItemPerPack"].Value)) // { // dgvProdDetails.Rows[e.RowIndex].Cells["colItemPerPack"].ErrorText = "Quantity Cannot be Empty"; // return; // } // //calculate total // foreach (System.Windows.Forms.DataGridViewRow row in dgvProdDetails.Rows) // { // } //} //private void dgvDetails_CellEndEdit(object sender, DataGridViewCellEventArgs e) //{ // if (!ValidateQuantities(e)) return; // if (skuList.Count > e.RowIndex) // { // var _itemSKU = skuList[e.RowIndex]; // var _row = dgvProdDetails.Rows[e.RowIndex]; // _row.Cells["ColPackQuantity"].Value = _itemSKU.PackageQuantity = GetCellValue(_row.Cells["ColPackQuantity"]); // _row.Cells["colItemPerPack"].Value = _itemSKU.QuantityPerPack = GetCellValue(_row.Cells["colItemPerPack"]); // _itemSKU.TotalPurchaseValue = (_itemSKU.PackageQuantity * (_itemSKU.QuantityPerPack * _itemSKU.PurchaseValue)); // _itemSKU.TotalWholesaleValue = (_itemSKU.PackageQuantity * (_itemSKU.QuantityPerPack * _itemSKU.Wholesale)); // _itemSKU.TotalResaleValue = (_itemSKU.PackageQuantity * (_itemSKU.QuantityPerPack * _itemSKU.Retail)); // _row.Cells["ColTotPurchaseVal"].Value = _itemSKU.TotalPurchaseValue; // _row.Cells["ColTotWholesaleVal"].Value = _itemSKU.TotalWholesaleValue; // _row.Cells["ColTotResaleVal"].Value = _itemSKU.TotalResaleValue; // skuList[e.RowIndex] = _itemSKU; // } //} private bool ValidateQuantities(DataGridViewCellEventArgs e) { if (e.ColumnIndex == dgvProdDetails.Columns["ColPackQuantity"].Index || e.ColumnIndex == dgvProdDetails.Columns["colItemPerPack"].Index) { string _errorMsg; var cell = dgvProdDetails.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cell.Value == null) { return false; } Match _match = Regex.Match(cell.Value.ToString(), "^[0-9]*\\.?[0-9]*$"); _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '1100'" : ""; if (_errorMsg != "") { cell.ErrorText = _errorMsg; return false; } else cell.ErrorText = ""; } return true; } private int GetCellValue(DataGridViewCell cell) { var cellVal = cell.Value; if (IsNullOrEmpty(cellVal) || int.Parse(cellVal.ToString()) == 0) return 1; else return int.Parse(cellVal.ToString()); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { #region validate if (DateTime.Compare(dtpPurchaseDate.Value.Date, dtpInvoiceDate.Value.Date) > 0) { MessageBox.Show("Date of Purchase cannot be greater than Date of Invoice.", "Invalid Date Of Purchase", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (string.IsNullOrEmpty(txtVendorName.Text)) { errorProvider1.SetError(txtVendorName, "Supplier Details Is Mandatory"); return; } else if (ItemPriceList == null || ItemPriceList.Count == 0) { MessageBox.Show("Add items to Purchase Grid.", "Purchase Grid Empty", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (Utilities.Validation.IsNullOrEmpty(this, true)) return; #endregion validate DialogResult dr = MessageBox.Show("Purchase Order once placed cannot be altered. Do you want to Continue?", "Save Purchase Order", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dr == DialogResult.No) return; purchaseOrder.IsCredit = rdbCredit.Checked ? true : false; purchaseOrder.SCFNo = txtSCF.Text; purchaseOrder.IRNNo = txtInvoiceNo.Text; //purchaseOrder.BillNo = txtBillNo.Text; purchaseOrder.Revision = Builders.VATRevisionBuilder.GetVATRevisionInfo(RevisionID); purchaseOrder.Vendor = vend; purchaseOrder.DateOfPurchase = dtpPurchaseDate.Value; purchaseOrder.DateOfInvoice = dtpInvoiceDate.Value; purchaseOrder.TotalPurchasePrice = decimal.Parse(txtTotalPurchasePrice_ROff.Text); purchaseOrder.TotalWholesalePrice = decimal.Parse(txtTotalWholesalePrice_ROff.Text); purchaseOrder.TotalResalePrice = decimal.Parse(txtTotalResalePrice_ROff.Text); purchaseOrder.ItemPriceList = ItemPriceList; bool success = Savers.PurchaseOrderSaver.SaverPurchaseOrder(purchaseOrder); if (success) { UpdateStatus("Purchase Order Saved", 100); this.Close(); } else UpdateStatus("Error saving Purchase Bill", 100); } private void dtpInvoiceDate_ValueChanged(object sender, EventArgs e) { //MessageBox.Show("Changing Invoice dates will effect the item pricing "); RevisionID = Builders.VATRevisionBuilder.GetRevisionDate(dtpInvoiceDate.Value.Date); } private void txtValueDecimal_Validating(object sender, CancelEventArgs e) { TextBox txt = (TextBox)sender; string _errorMsg; Match _match = Regex.Match(txt.Text, "^[0-9]*\\.?[0-9]*$"); _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '1100'" : ""; errorProvider1.SetError(txt, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txt.Select(0, txt.Text.Length); } } private void txtTotalPurchasePrice_ROff_Validated(object sender, EventArgs e) { decimal psaleMargin = !string.IsNullOrEmpty(txtTotalPurchasePrice.Text) && decimal.TryParse(txtTotalPurchasePrice.Text, out psaleMargin) ? psaleMargin : 0; decimal totalPurchasePrice = !string.IsNullOrEmpty(txtTotalPurchasePrice_ROff.Text) && decimal.TryParse(txtTotalPurchasePrice_ROff.Text, out totalPurchasePrice) ? totalPurchasePrice : 0; lblPPriceRdOff.Text = (totalPurchasePrice - psaleMargin).ToString("#.##"); } private void txtTotalWholesalePrice_ROff_Validated(object sender, EventArgs e) { decimal wsaleMargin = !string.IsNullOrEmpty(txtTotalWholesalePrice.Text) && decimal.TryParse(txtTotalWholesalePrice.Text, out wsaleMargin) ? wsaleMargin : 0; decimal totalWholePrice = !string.IsNullOrEmpty(txtTotalWholesalePrice_ROff.Text) && decimal.TryParse(txtTotalWholesalePrice_ROff.Text, out totalWholePrice) ? totalWholePrice : 0; lblWPriceRdOff.Text = (totalWholePrice - wsaleMargin).ToString("#.##"); } private void txtTotalResalePrice_ROff_Validated(object sender, EventArgs e) { decimal rsaleMargin = !string.IsNullOrEmpty(txtTotalResalePrice.Text) && decimal.TryParse(txtTotalResalePrice.Text, out rsaleMargin) ? rsaleMargin : 0; decimal totalRetailPrice = !string.IsNullOrEmpty(txtTotalResalePrice_ROff.Text) && decimal.TryParse(txtTotalResalePrice_ROff.Text, out totalRetailPrice) ? totalRetailPrice : 0; lblRPriceRdOff.Text = (totalRetailPrice - rsaleMargin).ToString("#.##"); } protected override void CancelToolStrip_Click(object sender, EventArgs e) { base.CancelToolStrip_Click(sender, e); } } } <file_sep>/JanataBazaar/Mappers/VATRevisionMApper.cs using FluentNHibernate.Mapping; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Mappers { class VATRevisionMapper : ClassMap<VATRevision> { public VATRevisionMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.DateOfRevision); HasMany(x => x.VATList).KeyColumn("VATRevisionID") .Inverse() .Cascade.All(); } } class VATPercentMapper : ClassMap<VATPercent> { public VATPercentMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.Percent); References(x => x.VATRevision).Class<VATRevision>() .Columns("VATRevisionID") .Cascade.None(); } } } <file_sep>/JanataBazaar/Models/PurchaseIndent.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Models { public class PurchaseItemIndent { public virtual int ID { get; set; } public virtual Item Item { get; set; } public virtual PurchaseIndent PurchaseIndent { get; set; } public virtual int InHandStock { get; set; } public virtual int AvgConsumption { get; set; } public virtual int StockPeriod { get; set; } public virtual string Remark { get; set; } public PurchaseItemIndent() { } public PurchaseItemIndent(Item _item, int _InhandStock) { this.Item = _item; this.InHandStock = _InhandStock; this.AvgConsumption = 0; this.StockPeriod = 1; this.Remark = ""; } } public class PurchaseIndent { public virtual int ID { get; set; } public virtual IList<PurchaseItemIndent> IndentItemsList { get; set; } public virtual DateTime DateOfIndent { get; set; } } } <file_sep>/JanataBazaar/View/Register/Winform_VendorRegister.cs using JanataBazaar.Builders; using System; using System.Linq; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_VendorRegister : WinformRegister { public Winform_VendorRegister() { InitializeComponent(); } protected override void NewToolStrip_Click(object sender, EventArgs e) { new Details.Winform_VendorDetails().ShowDialog(); } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dgvRegister.Columns["colDelete"].Index == e.ColumnIndex) { var row = dgvRegister.Rows[e.RowIndex]; int _vendID = int.Parse(row.Cells["ID"].Value.ToString()); DialogResult dr = MessageBox.Show("Do you want to delete Vendor " + row.Cells["Name"].Value.ToString(), "Delete Vendor", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) return; bool isBilled = Savers.PeoplePracticeSaver.IsVendorBilled(_vendID); if (isBilled) { MessageBox.Show("Vendor is already billed and cannot be deleted", "Cannot delete Vendor", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } bool success = Savers.PeoplePracticeSaver.DeleteVendor(_vendID); if (success) { txtName_TextChanged(this, new EventArgs()); UpdateStatus("Vendor Deleted.", 100); } else { UpdateStatus("Error deleting Vendor. ", 100); } } else { DialogResult _dialogResult = MessageBox.Show("Do you want to Modify the details of Vendor " + Convert.ToString(dgvRegister.Rows[e.RowIndex].Cells[1].Value), "Modify Customer Details", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (_dialogResult == DialogResult.No) return; int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); Model.Vendor _vendor = PeoplePracticeBuilder.GetVendorInfo(_ID); new Details.Winform_VendorDetails(_vendor).ShowDialog(); txtName_TextChanged(this, new EventArgs()); } } private void txtName_TextChanged(object sender, EventArgs e) { if (txtName.Text == "" && txtMobNo.Text == "") return; LoadDgv(); } public void LoadDgv() { UpdateStatus("Searching", 50); dgvRegister.DataSource = (from vend in (PeoplePracticeBuilder.GetVendorsList(txtName.Text, txtMobNo.Text)) select new { vend.ID, vend.Name, vend.MobileNo }).ToList(); if (dgvRegister.RowCount == 0) { dgvRegister.Columns["colDelete"].Visible = false; UpdateStatus("No Results found.", 100); } else { UpdateStatus(dgvRegister.RowCount + " Results found.", 100); dgvRegister.Columns["colDelete"].Visible = true; dgvRegister.Columns["colDelete"].DisplayIndex = dgvRegister.Columns.Count - 1; } } } } <file_sep>/JanataBazaar/Builders/VATRevisionBuilder.cs using JanataBazaar.Models; using log4net; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class VATRevisionBuilder { static ILog log = LogManager.GetLogger(typeof(VATRevisionBuilder)); public static VATRevision GetVATRevisionInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { VATRevision revAlias = null; VATRevision revision = session.QueryOver<VATRevision>(() => revAlias) .Where(() => revAlias.ID == _ID) .SingleOrDefault(); VATPercent vatPercentAlias = null; revision.VATList = (session.QueryOver<VATPercent>(() => vatPercentAlias) .Fetch(o => o.VATRevision).Eager .Where(() => vatPercentAlias.VATRevision.ID == _ID).List()); return revision; } } public static List<VATRevision> GetVATRevisionList() { using (var session = NHibernateHelper.OpenSession()) { List<VATRevision> revList = session.QueryOver<VATRevision>() .OrderBy(v => v.DateOfRevision).Desc .List() as List<VATRevision>; return revList; } } public static List<decimal> GetVATRevisionPercentageList(int _revisionID) { using (var session = NHibernateHelper.OpenSession()) { VATPercent vatPercentAlias = null; var percentList = (from rev in (session.QueryOver<VATPercent>(() => vatPercentAlias) .Fetch(o => o.VATRevision).Eager .Where(() => vatPercentAlias.VATRevision.ID == _revisionID) .OrderBy(()=> vatPercentAlias.Percent).Asc .List()) select rev.Percent).ToList(); //var percentList = (from rev in list // select new { rev.Percent }).ToList(); return percentList; } } public static int GetRevisionDate(DateTime invoiceDate) { using (var session = NHibernateHelper.OpenSession()) { try { var revision = session.QueryOver<VATRevision>() .Where(v => v.DateOfRevision.Date <= invoiceDate.Date) .OrderBy(v => v.DateOfRevision).Desc .Take(1).SingleOrDefault(); return revision.ID; } catch (Exception ex) { log.Error(ex); return 0; } } } } } <file_sep>/JanataBazaar/Builders/SaleItemBuilder.cs using JanataBazaar.Model; using JanataBazaar.Models; using NHibernate.Criterion; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { class SaleItemBuilder { public static IList GetSaleItem(string _name = null, string _brand = null, string _section = null) { IList saleItemList; ItemSKU itemSKUAlias = null; Item itemAlias = null; Section sectionAlias = null; using (var session = NHibernateHelper.OpenSession()) { //name - InStock Package- items/pack - Wholesaleprice/item saleItemList = (from itm in (session.QueryOver<ItemSKU>(() => itemSKUAlias) .JoinAlias(() => itemSKUAlias.Item, () => itemAlias) .JoinAlias(() => itemAlias.Section, () => sectionAlias) .Where(() => itemAlias.Name.IsLike(_name + "%")) .Where(() => itemAlias.Brand.IsLike(_brand + "%")) .Where(() => sectionAlias.Name.IsLike(_section + "%")) .Take(15) .List()) select new { itm.ID, itm.Item.Name, itm.Item.Brand, itm.StockQuantity, itm.WholesalePrice }) .ToList(); return saleItemList; } } public static List<Sale> GetSalesSummary(bool isCredit, DateTime fromDate, DateTime toDate, string _consumerName, string _consumerID) { using (var session = NHibernateHelper.OpenSession()) { Sale saleAlias = null; List<Sale> salesSummaryList; if (isCredit) { Customer customerAlias = null; salesSummaryList = session.QueryOver<Sale>(() => saleAlias) .JoinAlias(() => saleAlias.Customer, () => customerAlias) .Where(() => saleAlias.IsCredit == isCredit) .Where(s => s.DateOfSale.Date >= fromDate.Date && s.DateOfSale.Date <= toDate.Date) //.Where(Restrictions.Between("DateOfSale", fromDate, toDate)) .Where(Restrictions.On(() => customerAlias.Name).IsLike(_consumerName + "%")) .Where(Restrictions.On(() => customerAlias.AccountNo).IsLike(_consumerID + "%")) .List() as List<Sale>; } else { Member memberAlias = null; salesSummaryList = session.QueryOver<Sale>(() => saleAlias) .JoinAlias(() => saleAlias.Member, () => memberAlias) .Where(() => saleAlias.IsCredit == isCredit) .Where(s => s.DateOfSale.Date >= fromDate.Date && s.DateOfSale.Date <= toDate.Date) .Where(Restrictions.On(() => memberAlias.Name).IsLike(_consumerName + "%")) .Where(Restrictions.On(() => memberAlias.MemberNo).IsLike(_consumerID + "%")) .List() as List<Sale>; } return salesSummaryList; } } //public static Dictionary<int, decimal> GetRebateList(List<Sale> saleSummaryList) //{ // using (var session = NHibernateHelper.OpenSession()) // { // Dictionary<int, decimal> _rebateList = new Dictionary<int, decimal>(); // foreach (var sale in saleSummaryList) // { // //get the sum of all the saleitems.retail value. // ItemSKU itemSKUAlias = null; // SaleItem saleItemAlias = null; // List<ItemSKU> skuItemList = session.QueryOver<ItemSKU>() // .JoinAlias(() => saleItemAlias.Item, () => itemSKUAlias) // .Where(() => saleItemAlias.Sale == sale) // .List().ToList(); // } // } //} } } <file_sep>/JanataBazaar/View/Details/Winform_MergePriceVariation.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_MergePriceVariation : Form { Item item; List<ItemSKU> highSKUList; List<ItemSKU> lowerSKUList; List<ItemSKU> selHPrice = new List<ItemSKU>(); List<ItemSKU> selLPrice = new List<ItemSKU>(); public Winform_MergePriceVariation() { InitializeComponent(); } public Winform_MergePriceVariation( Item _item) { InitializeComponent(); this.item = _item; txtName.Text = _item.Name; txtUnit.Text = _item.QuantityUnit; txtBrand.Text = _item.Brand; LoadSKUList(); LoadDGV(); } private void LoadSKUList() { highSKUList = new List<ItemSKU>(); lowerSKUList = new List<ItemSKU>(); var itemSKUList = Builders.PriceVariationBuilder.GetPriceVariation(this.item.ID); if (itemSKUList == null || itemSKUList.Count == 0) return; //take the highest and add it in the dgvHighPrice var skuHigh = itemSKUList.OrderByDescending(i => i.ResalePrice).FirstOrDefault(); highSKUList.Add(skuHigh); //add the rest into dgvLowerPrice itemSKUList.Remove(skuHigh); lowerSKUList.AddRange(itemSKUList); } private void LoadDGV() { FillDataGrid(true, dgvHigherPrice, highSKUList); FillDataGrid(false, dgvLowerPrice, lowerSKUList); } private void FillDataGrid(bool IsHigh, DataGridView dgv, List<ItemSKU> skuItemList) { List<String> colNames = new List<string>() { "ID", "colStock", "colWholePrice", "colResalePrice" }; string colPrefix = IsHigh ? "h" : "l"; dgv.Rows.Clear(); foreach (var item in skuItemList) { int index = skuItemList.IndexOf(item); dgv.Rows.Add(); dgv.Rows[index].Cells[colPrefix + colNames[0]].Value = item.ID; dgv.Rows[index].Cells[colPrefix + colNames[1]].Value = item.StockQuantity; dgv.Rows[index].Cells[colPrefix + colNames[2]].Value = item.WholesalePrice; dgv.Rows[index].Cells[colPrefix + colNames[3]].Value = item.ResalePrice; } //dgv.Columns["ID"].Visible = false; } private void btnMergeRight_Click(object sender, EventArgs e) { //check if atleast one chkbox is selected in LowerPrice if (selLPrice.Count < 1) { MessageBox.Show("Atleast one Item must be selected in the higher prices to be merged OR transferred to the lower price grid.", "Select Items", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //check selected chk is only one in dgvHigherPrice else if (selHPrice.Count > 1) { MessageBox.Show("Only one desired Item to be merged with must be selected in the lower prices. ", "Select Items", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (selHPrice.Count == 0) { foreach (var _row in selLPrice) { //int index = _row.Index; highSKUList.Add(_row); lowerSKUList.Remove(_row); //selLPrice.Remove(_row); } selLPrice.Clear(); LoadDGV(); } else if (selHPrice.Count == 1) { //builders..UpdateSKUQuantity(toSKU, fromSKUList) //foreach chk add into list of sku "listToMerge" //foreach sku in list add sum quantity as toBeMergedquantity //add the "toBeMergedquantity" to desired sku //delete sku in listToMerge sku's var row = selHPrice[0]; DialogResult dr = MessageBox.Show("Continue merging selected items from higher Price grid with item of resale value " + row.ResalePrice.ToString() + " in the lower prices? ", "Merge Items", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.No) return; var mergeWithSKUItem = row; List<ItemSKU> tobeMergedSKUItemList = new List<ItemSKU>(); foreach (var _row in selLPrice) { tobeMergedSKUItemList.Add(_row); } bool success = UpdateSKUQuantity(mergeWithSKUItem, tobeMergedSKUItemList); if (success) { LoadSKUList(); LoadDGV(); selLPrice.Clear(); } } } private void btnMergerLeft_Click(object sender, EventArgs e) { //check if atleast one chkbox is selected in LowerPrice if (selHPrice.Count < 1) { MessageBox.Show("Atleast one Item must be selected in the higher prices to be merged OR transferred with the lower price grid.", "Select Items", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //check selected chk is only one in dgvHigherPrice else if (selLPrice.Count > 1) { MessageBox.Show("Only one desired Item to be merged with must be selected in the higher prices. ", "Select Items", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (selLPrice.Count == 0) { foreach (var _row in selHPrice) { //int index = _row.Index; lowerSKUList.Add(_row); highSKUList.Remove(_row); //selLPrice.Remove(_row); } selHPrice.Clear(); LoadDGV(); } else if (selLPrice.Count == 1) { //builders..UpdateSKUQuantity(toSKU, fromSKUList) //foreach chk add into list of sku "listToMerge" //foreach sku in list add sum quantity as toBeMergedquantity //add the "toBeMergedquantity" to desired sku //delete sku in listToMerge sku's var row = selLPrice[0]; DialogResult dr = MessageBox.Show("Continue merging selected items from lower Price grid with item of resale value " + row.ResalePrice.ToString() + " in the higher prices? ", "Merge Items", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.No) return; var mergeWithSKUItem = row; List<ItemSKU> tobeMergedSKUItemList = new List<ItemSKU>(); foreach (var _row in selHPrice) { tobeMergedSKUItemList.Add(_row); } selLPrice.Clear(); bool success = UpdateSKUQuantity(mergeWithSKUItem, tobeMergedSKUItemList); if (success) { LoadSKUList(); LoadDGV(); selHPrice.Clear(); } } } private bool UpdateSKUQuantity(ItemSKU toSKU, List<ItemSKU> fromSKUList) { foreach (var item in fromSKUList) { toSKU.StockQuantity += item.StockQuantity; } bool success = Savers.ItemSKUSavers.UpdateSKUList(toSKU, fromSKUList); if (success) return true; return false; } private void dgvLowerPrice_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; var dgv = (DataGridView)sender; string colPrefix = dgv.Name == "dgvLowerPrice" ? "l" : "h"; var selectedRow = (DataGridViewCheckBoxCell)dgv.Rows[e.RowIndex].Cells[colPrefix + "colSelect"]; //selectedRow.Value = (selectedRow.Value != null && (CheckState)selectedRow.Value == CheckState.Checked) ? CheckState.Unchecked : CheckState.Checked; if ((selectedRow.Value != null && (CheckState)selectedRow.Value == CheckState.Checked)) { selectedRow.Value = CheckState.Unchecked; if (colPrefix == "h") { int ID = int.Parse(dgvHigherPrice.Rows[e.RowIndex].Cells[colPrefix + "ID"].Value.ToString()); ItemSKU itemSKU = highSKUList.Where(x => x.ID == ID).SingleOrDefault(); selHPrice.Remove(itemSKU); } else { int ID = int.Parse(dgvLowerPrice.Rows[e.RowIndex].Cells[colPrefix + "ID"].Value.ToString()); ItemSKU itemSKU = lowerSKUList.Where(x => x.ID == ID).SingleOrDefault(); selLPrice.Remove(itemSKU); } } else { selectedRow.Value = CheckState.Checked; if (colPrefix == "h") { int ID = int.Parse(dgvHigherPrice.Rows[e.RowIndex].Cells[colPrefix + "ID"].Value.ToString()); ItemSKU itemSKU = highSKUList.Where(x => x.ID == ID).SingleOrDefault(); selHPrice.Add(itemSKU); } else { int ID = int.Parse(dgvLowerPrice.Rows[e.RowIndex].Cells[colPrefix + "ID"].Value.ToString()); ItemSKU itemSKU = lowerSKUList.Where(x => x.ID == ID).SingleOrDefault(); selLPrice.Add(itemSKU); } } } } } <file_sep>/JanataBazaar/Models/Item.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Models { public class Section { public virtual int ID { get; set; } public virtual string Name { get; set; } public Section() { } public Section(string _name) { this.Name = _name; } } public class Item { public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual Section Section { get; set; } public virtual string QuantityUnit { get; set; } public virtual string Brand { get; set; } public virtual bool InReserve { get; set; } public virtual int ReserveStock { get; set; } public Item() { } public Item(string _name, string _quantityUnit, Section _section, string _brand, int _ReserveStock) { this.Name = _name; this.QuantityUnit = _quantityUnit; this.Section = _section; this.Brand = _brand; this.ReserveStock = _ReserveStock; } } public class ItemPricing { public virtual int ID { get; set; } public virtual PurchaseOrder Purchase { get; set; } public virtual Item Item { get; set; } public virtual DateTime ManufacturedDate { get; set; } public virtual DateTime ExpiredDate { get; set; } public virtual decimal Basic { get; set; } public virtual decimal TransportPercent { get; set; } public virtual decimal Transport { get; set; } public virtual decimal MiscPercent { get; set; } public virtual decimal Misc { get; set; } public virtual decimal VATPercent { get; set; } public virtual decimal VAT { get; set; } public virtual decimal DiscountPercent { get; set; } public virtual decimal Discount { get; set; } public virtual decimal WholesaleMargin { get; set; } public virtual decimal Wholesale { get; set; } public virtual decimal RetailMargin { get; set; } public virtual decimal Retail { get; set; } public virtual decimal PurchaseValue { get; set; } public virtual Package Package { get; set; } public virtual int QuantityPerPack { get; set; } public virtual int PackageQuantity { get; set; } public virtual int NetWeight { get; set; } public virtual int GrossWeight { get; set; } //public virtual int StockQuantity { get; set; } public virtual decimal TotalPurchaseValue { get; set; } public virtual decimal TotalWholesaleValue { get; set; } public virtual decimal TotalResaleValue { get; set; } public ItemPricing() { } public ItemPricing(decimal _basic, decimal _transportPercent, decimal _transport, decimal _miscPercent, decimal _misc, decimal _vatPercent, decimal _vat, decimal _discountPercent, decimal _discount, decimal _wholesaleMargin, decimal _wholesale, decimal _retailMargin, decimal _retail, decimal _purchaseValue, PurchaseOrder _purchase, Item item, int _netWeight, int _grossWeight, DateTime _manufactureDate, DateTime _expiredDate) { this.Basic = _basic; this.TransportPercent = _transportPercent; this.Transport = _transport; this.MiscPercent = _miscPercent; this.Misc = _misc; this.VAT = _vat; this.VATPercent = _vatPercent; this.DiscountPercent = _discountPercent; this.Discount = Discount; this.WholesaleMargin = _wholesaleMargin; this.Wholesale = _wholesale; this.Retail = _retail; this.RetailMargin = _retailMargin; this.Purchase = _purchase; this.PurchaseValue = _purchaseValue; this.Item = item; this.NetWeight = _netWeight; this.GrossWeight = _grossWeight; this.ManufacturedDate = _manufactureDate; this.ExpiredDate = _expiredDate; } } public class ItemSKU { public virtual int ID { get; set; } public virtual Item Item { get; set; } public virtual int StockQuantity { get; set; } public virtual decimal WholesalePrice { get; set; } public virtual decimal ResalePrice { get; set; } public ItemSKU() { } public ItemSKU(Item item, int _stockQuantity, decimal _resalePrice, decimal _wholesalePrice) { this.Item = item; this.StockQuantity = _stockQuantity; this.ResalePrice = _resalePrice; this.WholesalePrice = _wholesalePrice; } } public class Package { public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual int Weight { get; set; } public virtual bool IsStocked { get; set; } public Package() { } public Package(string _name, int _weight, bool _isStocked) { this.Name = _name; this.Weight = _weight; this.IsStocked = _isStocked; } } } <file_sep>/JanataBazaar/Mappers/PurchaseIndentMapper.cs using FluentNHibernate.Mapping; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Mappers { class PurchaseIndentMapper: ClassMap<PurchaseIndent> { public PurchaseIndentMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.DateOfIndent); HasMany<PurchaseItemIndent>(x=>x.IndentItemsList).KeyColumn("PurchaseIndentID") .Inverse() .Cascade.All(); } } class PurchaseItemIndentMapper : ClassMap<PurchaseItemIndent> { public PurchaseItemIndentMapper() { Id(x => x.ID).GeneratedBy.Identity(); Map(x => x.InHandStock); Map(x => x.AvgConsumption); Map(x => x.Remark); Map(x => x.StockPeriod); References(x => x.Item).Class<Item>() .Columns("ItemID") .Cascade.None(); References(x => x.PurchaseIndent).Class<PurchaseIndent>() .Columns("PurchaseIndentID") .Cascade.None(); } } } <file_sep>/JanataBazaar/Savers/SaleDetailsSaver.cs using JanataBazaar.Models; using log4net; using NHibernate.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Savers { class SaleDetailsSaver { static ILog log = LogManager.GetLogger(typeof(SaleDetailsSaver)); public static bool SaveSaleDetails(Sale sale, List<ItemSKU> skuList) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { sale.Items.ForEach(x => x.Sale = sale); foreach (SaleItem saleitem in sale.Items) { int index = sale.Items.IndexOf(saleitem); ItemSKU skuitem = skuList[index]; skuitem.StockQuantity -= saleitem.Quantity; skuitem.Item.InReserve = (skuitem.Item.ReserveStock > skuitem.StockQuantity) ? true : false; session.SaveOrUpdate(skuitem); } session.SaveOrUpdate(sale); tx.Commit(); } catch (Exception ex) { tx.Rollback(); log.Info("Purchase Order Failed."); log.Error(ex); return false; } return true; } } } } } <file_sep>/JanataBazaar/Savers/PurchaseOrderSaver.cs using JanataBazaar.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using NHibernate.Util; namespace JanataBazaar.Savers { class PurchaseOrderSaver { static ILog log = LogManager.GetLogger(typeof(PurchaseOrderSaver)); public static bool SaverPurchaseOrder(PurchaseOrder order) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { //update itemprice and also check if item is inReserve foreach (var itemprice in order.ItemPriceList) { itemprice.Purchase = order; if (itemprice.Item.InReserve && itemprice.Item.ReserveStock < (itemprice.PackageQuantity * itemprice.QuantityPerPack)) itemprice.Item.InReserve = false; } // update/create skuItem. foreach (var priceItem in order.ItemPriceList) { ItemSKU skuItem; skuItem = Builders.ItemSKUBuilder.GetItemSKUBasedOnPrice(priceItem.Item.ID, priceItem.Retail, priceItem.Wholesale); if (skuItem != null) skuItem.StockQuantity += priceItem.QuantityPerPack * priceItem.PackageQuantity; else skuItem = new ItemSKU(priceItem.Item, priceItem.QuantityPerPack * priceItem.PackageQuantity, priceItem.Retail, priceItem.Wholesale); session.SaveOrUpdate(skuItem); } session.SaveOrUpdate(order); tx.Commit(); log.Info("Purchase Order Added."); } catch (Exception ex) { tx.Rollback(); log.Error(ex); return false; } return true; } } } } } <file_sep>/JanataBazaar/Savers/VATPercentSavers.cs using JanataBazaar.Models; using log4net; using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Savers { class VATPercentSavers { static ILog log = LogManager.GetLogger(typeof(VATPercentSavers)); public static bool SaveVATRevision(VATRevision vatRevision) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { foreach (var item in vatRevision.VATList) { item.VATRevision = vatRevision; } session.SaveOrUpdate(vatRevision); tx.Commit(); log.Info("VAT Revisied"); } catch (Exception ex) { log.Error(ex); return false; } return true; } } } public static bool DeletePercentItems(int _ID) { using (var session = NHibernateHelper.OpenSession()) { using (var tx = session.BeginTransaction()) { try { var percentItem = session.Get<VATPercent>(_ID); session.Delete(percentItem); tx.Commit(); log.Info("VAT Percent Deleted"); } catch (Exception ex) { log.Error(ex); return false; } return true; } } } public static bool IsUniqueRevisionDate(DateTime revisionDate, int _ID = 0) { using (var session = NHibernateHelper.OpenSession()) { try { // VATRevision vatRevision = null; var exists = session.Query<VATRevision>() .Count(x => (x.DateOfRevision.Date == revisionDate.Date) && (x.ID != _ID)) > 0; // .And(x => x.ID == _ID) // .SingleOrDefault(); return exists; } catch (Exception) { throw; } } } } } <file_sep>/JanataBazaar/View/Register/Winform_PriceVariationRegister.cs using JanataBazaar.View.Details; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Register { public partial class Winform_PriceVariationRegister : WinformRegister { public Winform_PriceVariationRegister() { InitializeComponent(); } private void Winform_PriceVariationRegister_Load(object sender, EventArgs e) { dgvRegister.Columns.Clear(); dgvRegister.Rows.Clear(); dgvStockPriceDetails.DataSource = null; dgvRegister.Columns.Add("ID", "ID"); dgvRegister.Columns.Add("Name", "Name"); dgvRegister.Columns.Add("Brand", "Brand"); dgvRegister.Columns.Add("QuantityUnit", "QuantityUnit"); List<object[]> priceVariationList = Builders.PriceVariationBuilder.GetPriceVariationItems(); if (priceVariationList != null && priceVariationList.Count != 0) { foreach (var item in priceVariationList) { int index = priceVariationList.IndexOf(item); dgvRegister.Rows.Add(); dgvRegister.Rows[index].Cells["ID"].Value = item[0]; dgvRegister.Rows[index].Cells["Name"].Value = item[1]; dgvRegister.Rows[index].Cells["Brand"].Value = item[2]; dgvRegister.Rows[index].Cells["QuantityUnit"].Value = item[3]; } } } protected override void dgvRegister_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; dgvStockPriceDetails.DataSource = null; int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); var itemSKUList = Builders.PriceVariationBuilder.GetPriceVariation(_ID); if (itemSKUList != null && itemSKUList.Count != 0) { dgvStockPriceDetails.DataSource = (from itemsku in itemSKUList select new { itemsku.ID, itemsku.StockQuantity, itemsku.WholesalePrice, itemsku.ResalePrice }).ToList(); } } protected override void dgvRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; //pass the item int _ID = int.Parse(dgvRegister.Rows[e.RowIndex].Cells["ID"].Value.ToString()); var item = Builders.ItemDetailsBuilder.GetItemInfo(_ID); new Winform_MergePriceVariation(item).ShowDialog(); Winform_PriceVariationRegister_Load(this, new EventArgs()); } } } <file_sep>/JanataBazaar/View/Details/Winform_Details.cs using System; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_Details : Form { public Winform_Details() { InitializeComponent(); } protected virtual void SaveToolStrip_Click(object sender, EventArgs e) { } protected virtual void CancelToolStrip_Click(object sender, EventArgs e) { DialogResult dr = MessageBox.Show("Continue to Exit?","Exit",MessageBoxButtons.YesNo,MessageBoxIcon.Stop); if (DialogResult.Yes == dr) { this.Close(); } } protected virtual void UpdateStatus(string statusText= "Enter Details and Click Save.", int statusValue = 0) { toolStrip_Label.Text = statusText; toolStripProgressBar1.Value = statusValue; if (statusValue == 100) MessageBox.Show(statusText,"Status",MessageBoxButtons.OK,MessageBoxIcon.Information); } protected virtual bool IsNullOrEmpty(object obj) { return (obj == null || obj.ToString() == ""); } private void Winform_Details_Load(object sender, EventArgs e) { } } } <file_sep>/JanataBazaar/Builders/PeoplePracticeBuilder.cs using JanataBazaar.Model; using JanataBazaar.Models; using log4net; using NHibernate.Criterion; using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JanataBazaar.Builders { public class PeoplePracticeBuilder { static ILog log = LogManager.GetLogger(typeof(PeoplePracticeBuilder)); #region Vendor public static Vendor GetVendorInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { try { var vendor = session.QueryOver<Vendor>() .Where(x => x.ID == _ID) .Fetch(x => x.Bank).Eager .Future().SingleOrDefault(); return vendor; } catch (Exception ex) { log.Error(ex); return null; } } } public static List<Vendor> GetVendorsList(string name = "", string mobileno = "") { using (var session = NHibernateHelper.OpenSession()) { Vendor vend= null; List<Vendor> vendorList = session.QueryOver<Vendor>(() => vend) .Where(NHibernate.Criterion.Restrictions.On(() => vend.Name).IsLike(name + "%")) .Where(NHibernate.Criterion.Restrictions.On(() => vend.MobileNo).IsLike(mobileno + "%")) .List() as List<Vendor>; return vendorList; } } public static List<Bank> GetBankNames() { using (var session = NHibernateHelper.OpenSession()) { try { List<Bank> bankList = session.Query<Bank>().ToList(); log.Info("Fetching Bank Names successfull"); return bankList; } catch (Exception ex) { log.Error(ex); return null; } } } #endregion Vendor #region Customer public static Customer GetCustomerInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { try { return session.Get<Customer>(_ID); } catch (Exception ex) { log.Error(ex); return null; } } } public static List<Customer> GetCustomerList(string name = "", string mobileno = "", string accno = "") { using (var session = NHibernateHelper.OpenSession()) { Customer cust= null; List<Customer> custList = session.QueryOver<Customer>(() => cust) .Where(Restrictions.On(() => cust.Name).IsLike(name + "%")) .Where(Restrictions.On(() => cust.Mobile_No).IsLike(mobileno + "%")) .Where(Restrictions.On(() => cust.AccountNo).IsLike(accno + "%")) .List() as List<Customer>; return custList; } } #endregion Customer #region Member public static Member GetMemberInfo(int _ID) { using (var session = NHibernateHelper.OpenSession()) { try { return session.Get<Member>(_ID); } catch (Exception ex) { log.Error(ex); return null; } } } public static List<Member> GetMemberList(string name = "", string mobileno = "", string membno = "") { using (var session = NHibernateHelper.OpenSession()) { Member cust = null; List<Member> membList = session.QueryOver<Member>(() => cust) .Where(Restrictions.On(() => cust.Name).IsLike(name + "%")) .Where(Restrictions.On(() => cust.Mobile_No).IsLike(mobileno + "%")) .Where(Restrictions.On(() => cust.MemberNo).IsLike(membno + "%")) .List() as List<Member>; return membList; } } #endregion Member public static bool IfBankExits(string name) { using (var session = NHibernateHelper.OpenSession()) { try { bool exists = session.Query<Bank>().Any(x => x.Name == name); return exists; } catch (Exception ex) { log.Error(ex); return false; } } } public static Bank GetBankNames(string name) { using (var session = NHibernateHelper.OpenSession()) { try { Bank bank = session.Query<Bank>() .Where(x => x.Name == name).SingleOrDefault(); log.Info("Fetching Bank Names successfull"); return bank; } catch (Exception ex) { log.Error(ex); return null; } } } } } <file_sep>/JanataBazaar/View/Details/Winform_SaleDetails.cs using JanataBazaar.Builders; using JanataBazaar.Model; using JanataBazaar.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace JanataBazaar.View.Details { public partial class Winform_SaleDetails : Winform_Details { List<SaleItem> saleItemList = new List<SaleItem>(); List<ItemSKU> skuItemList = new List<ItemSKU>(); Customer cust; Member memb; #region Property private decimal amntPaid = 0; private decimal balAmnt = 0; private decimal totalAmnt = 0; private decimal transCharge = 0; public decimal AmountPaid { get { return amntPaid; } set { amntPaid = value; txtAmntPaid.Text = amntPaid.ToString(); BalanceAmount = TotalAmount - AmountPaid - TransportCharge; } } public decimal BalanceAmount { get { return balAmnt; } set { balAmnt = value; txtBalanceAmnt.Text = balAmnt.ToString(); } } public decimal TotalAmount { get { return totalAmnt; } set { totalAmnt = value; txtTotAmnt.Text = totalAmnt.ToString(); } } public decimal TransportCharge { get { return transCharge; } set { transCharge = value; } } #endregion Property public Winform_SaleDetails() { InitializeComponent(); } private void Winform_SaleDetails_Load(object sender, EventArgs e) { this.toolStripParent.Items.Add(this.AddCustomerToolStrip); List<string> sectList = ItemDetailsBuilder.GetSectionsList(); cmbSrcSection.DataSource = sectList; cmbSrcSection.DisplayMember = "Name"; //cmbSrcSection.ValueMember = "ID"; } private void AddCustomerToolStrip_Click(object sender, EventArgs e) { AddConsumerDetails(); } private void AddConsumerDetails() { this.cust = null; this.memb = null; this.UpdateCustomerControls(new Person()); if (rdbMember.Checked) new Register.WinForm_MemberRegister().ShowDialog(); else new Register.WinForm_CustomerRegister().ShowDialog(); } private void txtSrcName_TextChanged(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtSrcBrand.Text) && string.IsNullOrEmpty(txtSrcName.Text)) { dgvSearch.DataSource = null; return; } dgvSearch.DataSource = SaleItemBuilder.GetSaleItem(txtSrcName.Text, txtSrcBrand.Text, cmbSrcSection.Text); dgvSearch.Columns["ID"].Visible = false; } private void dgvSearch_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { #region Validation if (e.RowIndex == -1) return; int _ID = int.Parse(dgvSearch.Rows[e.RowIndex].Cells["ID"].Value.ToString()); /*Check if item is in stock*/ bool inStock = int.Parse(dgvSearch.Rows[e.RowIndex].Cells["StockQuantity"].Value.ToString()) > 0; if (!inStock) { MessageBox.Show("Item cannot be added as its not in stock.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } /*Get Selected Item Info*/ ItemSKU itemsku = ItemSKUBuilder.GetItemSKUInfo(_ID); if (itemsku == null) return; /*If Item already exists*/ bool itemExists = saleItemList.Any(i => i.ID == itemsku.ID); if (itemExists) { MessageBox.Show("Item selected already exists in the sale", "Item already Exists", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } #endregion Validation skuItemList.Add(itemsku); SaleItem saleItem = new SaleItem(itemsku.Item, itemsku.WholesalePrice, itemsku.StockQuantity, 1, itemsku.WholesalePrice); saleItemList.Add(saleItem); dgvSaleItem.Rows.Add(); var _index = dgvSaleItem.Rows.Count - 1; PopulateDgvSaleItem(saleItem, _index); } private void PopulateDgvSaleItem(SaleItem itemsku, int index) { /* sale item grid * name - Brand - quantity - price - total amount */ dgvSaleItem.Rows[index].Cells["colItemName"].Value = itemsku.Item.Name; dgvSaleItem.Rows[index].Cells["colBrand"].Value = itemsku.Item.Brand; dgvSaleItem.Rows[index].Cells["colID"].Value = itemsku.ID; dgvSaleItem.Rows[index].Cells["colQuantity"].Value = itemsku.Quantity; //todo: Ask Minimum wholesale quantity dgvSaleItem.Rows[index].Cells["colPrice"].Value = itemsku.Price; dgvSaleItem.Rows[index].Cells["colTotalPrice"].Value = itemsku.TotalPrice; CalculatePaymentDetails(); } private void CalculatePaymentDetails() { decimal total = 0; foreach (DataGridViewRow dr in dgvSaleItem.Rows) { if (dr.IsNewRow || dr.Cells["colPrice"].Value == null || dr.Cells["colQuantity"].Value == null) continue; total += (decimal.Parse(dr.Cells["colQuantity"].Value.ToString()) * decimal.Parse(dr.Cells["colPrice"].Value.ToString())); } decimal amntPaid = 0; decimal.TryParse(txtAmntPaid.Text, out amntPaid); AmountPaid = amntPaid; TotalAmount = total + TransportCharge; BalanceAmount = TotalAmount - AmountPaid; } internal void UpdateSaleItemList(SaleItem saleItem, int index) { saleItemList[index] = saleItem; PopulateDgvSaleItem(saleItem, index); } protected override void SaveToolStrip_Click(object sender, EventArgs e) { #region _validation if (this.cust == null && this.memb == null) { MessageBox.Show("Adding Consumer details is Mandatory.", "Add Consumer", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (this.saleItemList.Count == 0) { MessageBox.Show("Sale Item cart cannot be empty.", "Add Items to Cart", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } #endregion _validation UpdateStatus("Saving..", 25); decimal totalRebate = 0; foreach (var item in skuItemList) { int index = skuItemList.IndexOf(item); totalRebate += (item.ResalePrice - item.WholesalePrice) * saleItemList[index].Quantity; } /*Prepare Model*/ Sale sale = new Sale(this.saleItemList, rdbCredit.Checked, AmountPaid, TotalAmount, dtpDateOfSale.Value.Date, totalRebate,this.cust, this.memb, TransportCharge, BalanceAmount); UpdateStatus("Saving..", 50); //deduct the total stock on save bool success = Savers.SaleDetailsSaver.SaveSaleDetails(sale, skuItemList); if (success) { UpdateStatus("Sale Saved.", 100); this.Close(); return; } } protected override void CancelToolStrip_Click(object sender, EventArgs e) { } private void dgvSaleItem_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; new Winform_SaleItemDetails(saleItemList[e.RowIndex], e.RowIndex).ShowDialog(); } public void UpdateCustomerControls(Person _person) { if (rdbMember.Checked) this.memb = PeoplePracticeBuilder.GetMemberInfo(_person.ID); else this.cust = PeoplePracticeBuilder.GetCustomerInfo(_person.ID); txtName.Text = _person.Name; txtPhoneNo.Text = _person.Phone_No; txtMobNo.Text = _person.Mobile_No; } private void txtAmntPaid_Validating(object sender, CancelEventArgs e) { decimal amntPaid, totAmnt; decimal.TryParse(txtAmntPaid.Text, out amntPaid); decimal.TryParse(txtTotAmnt.Text, out totAmnt); Match _match = Regex.Match(txtAmntPaid.Text, "^\\d*$"); string _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '1100'" : ""; if (_errorMsg == "" && amntPaid > totAmnt) _errorMsg = "Amount Paid cannot be greater than Total Amount"; errorProvider1.SetError(txtAmntPaid, _errorMsg); if (_errorMsg != "") { // Cancel the event and select the text to be corrected by the user. e.Cancel = true; txtAmntPaid.Text = ""; AmountPaid = 0; return; } else if (!string.IsNullOrEmpty(txtAmntPaid.Text)) { //TotalAmount = totAmnt; AmountPaid = int.Parse(txtAmntPaid.Text); } } private void rdbCash_CheckedChanged(object sender, EventArgs e) { if (rdbCash.Checked) rdbMember.Checked = true; else rdbCustomer.Checked = true; } private void rdbMember_CheckedChanged(object sender, EventArgs e) { bool _checked = rdbMember.Checked; rdbCash.Checked = _checked; rdbCredit.Checked = !_checked; if (!string.IsNullOrEmpty(txtName.Text)) AddConsumerDetails(); } private void txtTransCharge_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrEmpty(txtTransCharge.Text)) return; Match _match = Regex.Match(txtTransCharge.Text, "^\\d*$"); string _errorMsg = !_match.Success ? "Invalid Amount input data type.\nExample: '1100'" : ""; errorProvider1.SetError(txtTransCharge, _errorMsg); if (_errorMsg != "") { e.Cancel = true; txtTransCharge.Text = ""; TransportCharge = 0; return; } TransportCharge = decimal.Parse(txtTransCharge.Text); CalculatePaymentDetails(); } } }
7e2388dd91ba6c229aa17227ca15cd609e4cab78
[ "C#" ]
66
C#
nsuhanshetty/JanataBazaar
2d7bb8f765490df47fd485f6bad58f62906c378a
ece7cc558067c8a2ccb16843524a1387ca14cbbf
refs/heads/main
<repo_name>harshaldevv/TwoPassAssembler<file_sep>/cofinal.py #function to check if the symbol already exists or not def notExists(symbol,paramter,_boolean): mil_gaya = 0 symbolFileReading = open("SYMTAB.txt","r") for lines in symbolFileReading: line = lines line = line[:-1] splitline = line.split('\t') if (splitline[0] == symbol): mil_gaya +=1 break if (mil_gaya >0): _boolean = False return int(_boolean) else: #return 1; return int(_boolean) symbolFileReading.close() #returns the number of bytes in decimal format def cal_bytes(mnemonic,operand): found=0 noOfBytes=-1 if(mnemonic=="RESW" or mnemonic=="RESB" or mnemonic=="WORD" or mnemonic=="BYTE"): found=1 if(mnemonic=="RESW"): operand = int(operand) noOfBytes = operand*3 elif(mnemonic=="RESB"): operand = int(operand) noOfBytes = operand elif(mnemonic=="WORD"): noOfBytes = 3 elif(mnemonic=="BYTE"): length=len(operand)-3 if(operand[0]=='X'): if(length%2==0): noOfBytes=length/2 else: noOfBytes = (length/2)+1 elif(operand[0]=='C'): noOfBytes=length if(found==0): opcode = open("OPCODE.txt","r") #opcode file for opLine in opcode: op= opLine.split('\t') if(mnemonic==op[0]): found=1 noOfBytes=op[1] break opcode.close() if(found==0): noOfBytes=-1 noOfBytes = int(noOfBytes) return noOfBytes #this function will return the opcode of the operand def returnOpcode(shortForm,paramter): alpha = paramter mil_gaya = 0 opCodeFile = open("OPCODE.txt","r") #opening the opcode file for lines in opCodeFile: line = lines line = line[:-1] op = line.split("\t") if (shortForm == op[0]): opcode = op[2] mil_gaya+=1 break if (mil_gaya==1): return opcode else: return alpha #this function will return the ascii code of the character under the scrutiny of our eyes. def returnASCII(paramter,character): mil_gaya = 0 alpha = paramter asciiFileOpen = open("ASCII.txt","r") for lines in asciiFileOpen: line = lines line = line[:-1] lineSplit = line.split('\t') if(lineSplit[1] == str(character)): mil_gaya += -1 asciiCode = lineSplit[0] break if (mil_gaya <0): return asciiCode else: return alpha #this function will return the address of the label def returnAddress(paramter,label): symbolFileReading = open("SYMTAB.txt","r") # to read the address. of the label mil_gaya = 0 alpha = paramter for lines in symbolFileReading: line = lines line = line[:-1] splitline = line.split("\t") if(splitline[0] == label): mil_gaya+=1 tAdd = splitline[1] break symbolFileReading.close() if(mil_gaya>0): return tAdd else: return alpha #*********************************************************************************# #INITIATING EXECUTION #*********************************************************************************# FileName=input("File name: ") assemF=open(FileName,"r") #assembly code file addF=open("aCODE.txt","w") #file that stores addresses in assembly code labelF = open("SYMTAB.txt","w") #file that stores labels in the assembly code begin = assemF.readline(); #assumption: first line of the code is the start statement while(begin[0]=='.'): begin = assemF.readline(); begin = begin[:-1] Line1 = begin.split('\t') #print (Line1) addHex = Line1[2] #value of address in hex #addf add = int(addHex,16) #converted the value in decimal addHD= addHex #duplicate containing hex value #add1 # """we are converting the first address into decimal and after adding the right number of bytes we will convert it back to hexadecimal""" print("\n") for i in assemF: line = i line = line[:-1] line1 = line.split('\t') if(line[0]!='.'): if(line1[1]=="END"): break nBytes=0 if(len(line1)==3): nBytes = cal_bytes(line1[1],line1[2]) #returns no of bytes in decimal #harshal else: nBytes = cal_bytes(line1[1],0) if(nBytes==-1): error= "Error: Invalid mnemonic " + line1[1] print(error) input() exit(0) # ENTRY INTO SYMTAB #harshal if(line1[0]!=''): u=True #if label is not empty if(notExists(line1[0],-1,u)): #checks if the label is already present or not #harshal sym = line1[0] + "\t" + addHD #store the zeroth element and the second element in the sym tab or else report the error #print(symbol) labelF.write(sym) labelF.write("\n") labelF.flush() else: error= "Error: " + line1[0] + " - Multiple declaration " print(error) input() exit(0) #WRITING INSTRUCTIONS ALONG WITH ASSIGNED ADDRESSES lineWrite= addHD + "\t" + line #check if \n is a part of line #Add1 is hex #print(writeLine) #PRINTS ON-SCREEN addF.write(lineWrite) #writes into file #harshal addF.write("\n") addF.flush() #CALCULATION OF NEXT ADDRESS add = add + nBytes #performs decimal addition addHD="{0:b}".format(add) #str(format(add,'04x')) #converts to hex before storing 4x length = 4-len(addHD) addHD = "0"*length + addHD labelF.close() assemF.close() addF.close() #temporary file with appropriate addresses and SYMTAB have been created #***********************************************************************# assemFI = open("aCODE.txt","r") #assembly code file with addresses #harsal obcd = open("objCODE.txt","w") #to store the assembly file with object code #harshal ob = open("sic.o","w") #to store only the object code #harshal assemFI.seek(0) for i in assemFI: line = i line = line[:-1] line2 = line.split('\t') address=line2[0] label = line2[1] sym = line2[2] u=0 if(len(line2)==4): operand = line2[3] else: u=1 int1=0 int2=1 int3=2 if(sym!="RESW" and sym!="RESB"): if(sym=="BYTE"): #OBJECT CODING for sym: BYTE array = operand.split('\'') if(array[0]=="X"): objLine = array[1] elif(array[0]=="C"): list1 = list(array[1]) objLine = "" for char in list1: asciic= returnASCII(-1,char) if (asciic==-1): print("Error: Invalid character in BYTE") input() exit(0) objLine = asciic +asciic elif(sym=="WORD"): #OBJECT CODING for sym: WORD """operand = int(operand) objLine = "{0:b}".format(operand)#str(format(operand,'#010b'))[2:] #6 length = 4-len(objLine)""" objLine=" " elif(sym=="RSUB"): #OBJECT CODING for sym: RSUB opcode = returnOpcode(sym,-1) if(opcode==-1): print("Error: Opcode for RSUB could not be found") input() exit(0) else: int2=3 objLine = opcode + "0000" else: #OBJECT CODING for all other mnemonics opcode = returnOpcode(sym,-1) if(opcode==-1): error="Error: Opcode for " + sym + " not found" print(error) input() exit(0) opsplit = operand.split(',') length = len(opsplit) dirAdd =returnAddress(-1,opsplit[0]) if(dirAdd==-1): error="Error: Directed address of " + opsplit[0] + " not found" print(error) input() exit(0) if(length==2 and opsplit[1]=="X"): string=dirAdd a = string[:1] b = string[1:] a = int(a) a = a + 8 a = "{0:b}".format(a)#str(format(a,'#010b'))[2:] length = 4-len(a) a="0"*length + a dirAdd = a+b objLine = opcode + " "+ dirAdd if(sym=="RSUB"): write = line[0:4] + "\t\t"+ objLine elif (sym=="WORD"): write=" " else: write = line[0:4] + "\t" + objLine obcd.write(write) #object code along with instructions obcd.write("\n") ob.write(objLine) #only object code file ob.write("\n") else: print("") """x = line.find("\t") y = line[0:x+1] alpha = line alpha = alpha[::-1] beta = alpha.find("\t") gamma = alpha[0:beta+1] obcd.write(line) obcd.write("\n")""" assemFI.close() obcd.close() ob.close() """we have written the onj code in apt files now""" #***************************************************************************# objCode = open("objCODE.txt","r") for i in objCode: line = i[:-1] print(line) #output file with apt addresses and codes generated #*****************************************************************************# get = input() <file_sep>/README.md # TwoPassAssembler Assignment Details ( CSE112 ( Computer Organisation) at IIIT D ( second semester of my B.Tech[2019-2023])) The project requires you to design an Assembler which takes a text file as an input, which contains the Assembly code. The assembler must be able to translate the assembly code into machine code. The machine code generated must also be saved in a separate text file. There are no Macros and Procedures to be assembled. Decide your own error reporting strategy. Assume all operands are declared at the end of instructions, sequentially and in order of their appearance in the code. Each operand occupies one word. The Two pass assembler was an assignment given in CSE112 ( Computer Organisation) at IIIT D ( second semester of my B.Tech[2019-2023]) A documentation (pdf) has also been added so that the assignment is understandble incase any doubt arises or to refer to incase you are doing the same project ( or assignment :P ) Hope it helps whosoever is reading it
7d3aae79e41dd95ecc0737111519c0851f161002
[ "Markdown", "Python" ]
2
Python
harshaldevv/TwoPassAssembler
9afee48da9ddb66242c4ac3b152f2d2ab6316a03
62b69dd1a50b13b2f6b81f068e332c7a0b65eafc
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var pool = mysql.createPool({ host:'localhost', user:'root', password:'<PASSWORD>', database:'baobei' }) /* GET home page. */ router.get('/list', function(req, res, next) { pool.query('SELECT * FROM word',function(err,rows){ res.header('Access-Control-Allow-Origin','*'); res.send(rows); }) }); router.post('/add',function(req,res){ var tit=req.body.tit; var _m=req.body._m; console.log(2) pool.query('INSERT INTO word(title,message) VALUES("'+tit+'","'+_m+'")',function(err,rows){ res.header('Access-Control-Allow-Origin','*'); res.send(rows) }) }); router.post('/del',function(req,res){ var id=req.body.id; pool.query('DELETE FROM word WHERE id='+id,function(err,rows){ res.header('Access-Control-Allow-Origin','*'); res.send(rows) }) }) module.exports = router;
527f44f58c3f4fa571fb5657bbf486fcafbcd867
[ "JavaScript" ]
1
JavaScript
yangchaoa/liuyanban
dc8bc10b11c2caef49f624e69a85bd9659983389
74e8e1c488059747c1614ae0c8a9de90fbec91f5
refs/heads/master
<repo_name>Danhfg/SCS_exact<file_sep>/README.md # Shortest Commom Superstring (exato) ## Introdução Nesta pasta contém a implementação de dois algoritmos exatos que resolvem o problema da menor superstring comum onde um faz uso da técnica denominada bactracking e o outro faz uso de outra técnia, programação dinâmica juntamente com bitmasking. - [Requisitos](#requisitos) - Requisitos de software necessarios para executar o projeto. - [Compilação e execução](#compilação-e-execução) - Explicao das etapas de compilacao e execucao do projeto. - [Autores](#autores) - Autores do projeto. ## Requisitos Compilador C++ 11 (__g++__). Obs.: Para usuários Linux, o g++ eh nativo, faltando apenas atualiza-lo para a versao 11. Porém, caso deseje usar o g++ no Windows será necessário instalar-lo por meio do MinGW. ## Compilação e execução Obs.: Todos os códigos digitados no terminal deverão ser na respectiva pasta raiz do programa. Execute na linha de terminal para a compilação e criação do objetos ``` $ make ``` Ou, caso deseje apagar os objetos e os executáveis, digite ``` $ make clean ``` Em seguida, serão criados os seguintes arquivos binários (executáveis): | Nome do executável: | Descrição: | | ---------- | ------------- | |`backtracking` | Algoritmo exato que usa backtracking. |`dynamicPrograming` |Algoritmo exato que usa programação dinâmica com bitmasking. Diante disso, para executar o arquivo binário `servidor` basta: ``` $ ./bin/backtracking ``` E, para executar o arquivo binário `dynamicPrograming` basta: ``` $ ./bin/dynamicPrograming ``` ## Autores | Name: | Github: | Email: | | ---------- | ------------- | ------------- | |`<NAME>` | https://github.com/Danhfg |_<EMAIL>_ |`<NAME>` | https://github.com/Samuellucas97 |_<EMAIL>_ <file_sep>/include/backtracking.h #ifndef BACKTRACKING_H #define BACKTRACKING_H #include <string> #include <vector> int overlap(std::string a, std::string b, int min_length = 5); void backtranckingSCS( std::vector<std::string> a, size_t n, size_t depth,std::vector<bool> used, std::vector<std::string> curr, std::string stringThatLevel, std::string * shortest, int * iter); #endif<file_sep>/src/dynamicProgramming.cpp #include <iostream> #include <algorithm> /// min #include <cmath> /// pow #include "dynamicProgramming.h" /** * https://stackoverflow.com/questions/874134/find-out-if-string-ends-with-another-string-in-c * Obs.: Em C++ 20 já existe esse método */ inline bool ends_with(std::string const & value, std::string const & ending) { if (ending.size() > value.size()) return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } void populateOverlaps( std::vector<std::vector<int>> &overlaps, std::vector<std::string> &reads) { int N = reads.size(); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j){ if ( i != j) { int min = std::min(reads[i].length(), reads[j].length()); for (int k = min; k >=0; --k) { if (ends_with(reads[i], reads[j].substr(0, k))) { overlaps[i][j] = k; break; } } } } } } void bitMask(std::vector<std::vector<int>> &dp, std::vector<std::vector<int>> &parent, std::vector<std::vector<int>> &overlaps, int N) { for (int mask = 0; mask < (1 << N); ++mask) { for (int bit = 0; bit < N; ++bit) { if (((mask >> bit) & 1) > 0) { int pmask = mask ^ (1 << bit); if ( pmask == 0) continue; for (int i = 0; i < N; ++i) { if (((pmask >> i) & 1) > 0 ) { int val = dp[pmask][i] + overlaps[i][bit]; if ( val > dp[mask][bit]) { dp[mask][bit] = val; parent[mask][bit] = i; } } } } } } } std::string scsWithDynamicPrograming(std::vector<std::string> reads) { int N = reads.size(); // // 1o Passo std::vector<std::vector<int>> overlaps(N, std::vector<int>(N)); populateOverlaps(overlaps, reads); // // 2o Passo std::vector<std::vector<int>> dp(1 << N, std::vector<int>(N)); std::vector<std::vector<int>> parent(1 << N, std::vector<int>(N, -1)); bitMask(dp, parent, overlaps, N); // 3o Passo std::vector<int> perm(N); std::vector<bool> seen(N); int t = 0; int mask = (1 << N) - 1; int p =0; for (int j = 0; j < N; ++j) { if (dp[(1<<N) - 1][j] > dp[(1<<N) - 1][p]){} p = j; } while (p != -1) { perm[t++] = p; seen[p] = true; int p2 = parent[mask][p]; mask = mask ^(1 << p); p = p2; } for (int i = 0; i < t/2; ++i) { int v = perm[i]; perm[i] = perm[t-1-i]; perm[t-1-i] = v; } for (int i = 0; i < N; ++i) { if (!seen[i]) perm[t++] = i; } std::string answer(reads[perm[0]]); for (int i = 1; i < N; ++i) { int overlap = overlaps[perm[i-1]][perm[i]]; answer += (reads[perm[i]].substr(overlap)); } return answer; } int main() { std::vector<std::string> palavras; palavras.push_back("ccd"); palavras.push_back("bbc"); palavras.push_back("abb"); palavras.push_back("ddddddd"); std::cout << "A resposta:" << scsWithDynamicPrograming(palavras); }<file_sep>/include/dynamicProgramming.h #ifndef DYNAMICPROGRAMMING_H #define DYNAMICPROGRAMMING_H #include <string> #include <vector> bool ends_with(std::string const & value, std::string const & ending); void populateOverlaps( std::vector<std::vector<int>> &overlaps, std::vector<std::string> &reads); void bitMask(std::vector<std::vector<int>> &dp, std::vector<std::vector<int>> &parent, std::vector<std::vector<int>> &overlaps, int N); std::string scsWithDynamicPrograming(std::vector<std::string> reads); #endif<file_sep>/Makefile RM = rm -rf #Compilador CC=g++ #Variaveis para os subdiretorios #LIB_DIR=./lib Não haverá pois nenhuma biblioteca será usada INC_DIR=./include SRC_DIR=./src OBJ_DIR=./build BIN_DIR=./bin #Opcoes de compilacao CFLAGS= -Wall -pedantic -ansi -std=c++11 #Garante que os alvos desta lista não sejam confundidos com arquivos de mesmo nome .PHONY: all clean debug #Ao final da compilacão, remove os arquivos objetos all: init dynamicProgramming backtracking debug: CFLAGS += -g -O0 debug: dynamicProgramming backtracking # Cria a pasta/diretório bin e a obj init: @mkdir -p $(OBJ_DIR)/ @mkdir -p $(BIN_DIR) # Alvo (target) para a construcao do executavel questao01 # Define os arquivos dynamicProgramming.o, calcula.o, perimetro.o, volume.o e main.o como dependencias dynamicProgramming: CFLAGS+= -I$(INC_DIR)/ dynamicProgramming: $(OBJ_DIR)/dynamicProgramming.o @echo "=============" @echo "Ligando o alvo $@" @echo "=============" $(CC) $(CFLAGS) -o $(BIN_DIR)/$@ $^ @echo "+++ [Executavel dynamicProgramming criado em $(BIN_DIR)] +++" @echo "=============" # Alvo (target) para a construcao do objeto dynamicProgramming.o # Define os arquivos dynamicProgramming.cpp e dynamicProgramming.h como dependencias. $(OBJ_DIR)/dynamicProgramming.o: $(SRC_DIR)/dynamicProgramming.cpp $(INC_DIR)/dynamicProgramming.h $(CC) -c $(CFLAGS) -o $@ $< # Alvo (target) para a construcao do executavel questao01 # Define os arquivos dynamicProgramming.o, calcula.o, perimetro.o, volume.o e main.o como dependencias backtracking: CFLAGS+= -I$(INC_DIR)/ backtracking: $(OBJ_DIR)/backtracking.o @echo "=============" @echo "Ligando o alvo $@" @echo "=============" $(CC) $(CFLAGS) -o $(BIN_DIR)/$@ $^ @echo "+++ [Executavel backtracking criado em $(BIN_DIR)] +++" @echo "=============" # Alvo (target) para a construcao do objeto dynamicProgramming.o # Define os arquivos dynamicProgramming.cpp e dynamicProgramming.h como dependencias. $(OBJ_DIR)/backtracking.o: $(SRC_DIR)/backtracking.cpp $(CC) -c $(CFLAGS) -o $@ $< #removendo os .o e os binários clean: $(RM) $(BIN_DIR)/* $(RM) $(OBJ_DIR)/* #FIM DO MAKEFILE <file_sep>/src/backtracking_old.cpp #include <iostream> #include <sstream> #include <fstream> #include <string> #include <algorithm> #include "backtracking.h" static bool starts_with(const std::string str, const std::string prefix) { return ((prefix.size() <= str.size()) && std::equal(prefix.begin(), prefix.end(), str.begin())); } int overlap(std::string a, std::string b, int min_length) { /* Retorna o tamanho do maior sufixo ou prefixo que contenha pelo menos min_length. Se não existir sobreposição, returna 0. */ int start = 0; while (1){ start = a.find(b.substr(0,min_length), start); if (start == -1) return 0; if (starts_with(b,a.substr(start,a.size()-1) ) ) return (a.size())-start; start += 1; } } void backtranckingSCS(std::vector<std::string> a, size_t n, size_t depth,std::vector<bool> used, std::vector<std::string> curr, std::string stringThatLevel, std::string * shortest, int * iter){ size_t depth,std::vector<bool> used, std::vector<std::string> curr, std::string stringThatLevel, std::string * shortest) { if (depth == n){ //std::vector<bool>::iterator it = std::find(used.begin(), used.end(), 0); //int index = std::distance(used.begin(), it); //int over = overlap(stringThatLevel, a[index], 1); //stringThatLevel += a[index].substr(over); //int over = overlap(stringThatLevel, curr[n-1], 1); /* std::cout << over; stringThatLevel += curr[n-1].substr(over); if (*shortest != "" and stringThatLevel.size() >= shortest->size()){ return; } else *shortest = stringThatLevel; std::cout << over << "A";*/ *shortest = stringThatLevel; std::cout << "Tamanho da menor superstring atual: " << shortest->size() << std::endl; } for (int i = 0; i < n; ++i) { if (not used[i]) { *iter += 1; curr.push_back(a[i]); used[i] = true; for (auto const& c: curr) { if (c == curr[curr.size()-1]) { std::cout << c; } else std::cout << "|-"; } std::cout << std::endl; for (int i = 0; i < n; ++i) { if (not used[i]) { std::string stringAux = ""; if (stringThatLevel == "") { stringAux = a[i]; backtranckingSCS(a, n, depth+1, used, curr, stringAux, shortest, iter); curr.pop_back(); //std::cout << "Voltando: "; //for (auto const& c: curr) { //std::cout << c << " "; //} //std::cout << std::endl; used[i] = false; } else { stringAux = stringThatLevel; int over = overlap(stringThatLevel, a[i], 1); stringAux += a[i].substr(over); //stringThatLevel = stringThatLevel; if (not (*shortest != "") or stringAux.size() < shortest->size()){ backtranckingSCS(a, n, depth+1, used, curr, stringAux, shortest, iter); //std::cout << "Voltando: "; //for (auto const& c: curr) { //std::cout << c << " "; //} //std::cout << std::endl; if (*shortest != "" and stringAux.size() >= shortest->size()) { return; } curr.pop_back(); used[i] = false; curr.push_back(a[i]); used[i] = true; for (auto const& c: curr) { std::cout << c << " "; } std::cout << std::endl; backtranckingSCS(a, n, depth+1, used, curr, stringAux, shortest); curr.pop_back(); std::cout << "Voltando: "; for (auto const& c: curr) { std::cout << c << " "; } } } return; } int main(int argc, char *argv[]) { std::vector<std::string> a = {"bbbbbbbcdd", "bbbbbbbbcd", "abbbbbbbb", "ddddddd"}; //std::vector<std::string> a = {"ccd", "bbc", "abb", "ddddddd"}; //std::vector<std::string> a = {"abb", "ccddddd", "bbc"}; int main() { std::vector<std::string> a = {"ccd", "bbc", "abb", "ddddddd"}; auto n(a.size()); std::vector<bool> used; for (size_t i = 0; i < n; ++i) { used.push_back(false); } std::vector<std::string> curr; std::string * shortest = new std::string(""); //*shortest = ""; //std::cout << *shortest; int * iter = new int(); *iter = 0; backtranckingSCS(a, n, 0, used, curr, "", shortest, iter); std::cout << "Shortest: "<< *shortest << std::endl; std::cout << "Iterações: "<< *iter << std::endl; return 0; }
b135d238e7870918aa96dcfb937c83031bd1e504
[ "Markdown", "Makefile", "C++" ]
6
Markdown
Danhfg/SCS_exact
61a10a5b6db36d6938b5e7701d1c5f57615b4373
d473739f91f7831ba71e752fc8a710c45f03abf5
refs/heads/master
<file_sep>enum MonthValues { January = 1, February = 4, March = 4, April = 0, May = 2, June = 5, July = 0, August = 3, September = 6, October = 1, November = 4, December = 6, } enum CenturyValues { _1700 = 4, _1800 = 2, _1900 = 0, _2000 = 6, } export enum NumDays { January = 31, February = 28, March = 31, April = 30, May = 31, June = 30, July = 31, August = 31, September = 30, October = 31, November = 30, December = 31, } export enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } export namespace DaysOfWeek { function toString(d: DaysOfWeek): string { switch (d) { case DaysOfWeek.Sunday: return "Sunday"; case DaysOfWeek.Monday: return "Monday"; case DaysOfWeek.Tuesday: return "Tuesday"; case DaysOfWeek.Wednesday: return "Wednesday"; case DaysOfWeek.Thursday: return "Thursday"; case DaysOfWeek.Friday: return "Friday"; case DaysOfWeek.Saturday: return "Saturday"; } } } export enum Months { January, February, March, April, May, June, July, August, September, October, November, December, } export namespace Months { export function toString(m: Months): string { switch (m) { case Months.January: return "January"; case Months.February: return "February"; case Months.March: return "March"; case Months.April: return "April"; case Months.May: return "May"; case Months.June: return "June"; case Months.July: return "July"; case Months.August: return "August"; case Months.September: return "September"; case Months.October: return "October"; case Months.November: return "November"; case Months.December: return "December"; default: throw ("unsupported month: " + m); } } } export function calculateDayOfWeek(day: number, month: Months, year: number): DaysOfWeek { let value = 0; const lastTwo = getLastNDigits(year, 2); // Add the last two digits of the year value += lastTwo; // Divide by 4 and drop the remainder value = Math.floor(value / 4) // Add the day of the month value += day // Add month's key-value value += getMonthValue(month); // Reduce by reduction value value -= getReductionValue(month, year); // Add century value value += getCenturyValue(year); // Add the last two digits of the year (again) value += lastTwo; // Set value as the remainder of value divided by 7; value = value % 7; // Get day of week from remainder of value divided by 7 return getDayOfWeek(value); } export function getNumDays(month: Months, year: number): number { switch (month) { case Months.January: return NumDays.January; case Months.February: if (!isLeapYear(year)) { return NumDays.February; } return NumDays.February + 1; case Months.March: return NumDays.March; case Months.April: return NumDays.April; case Months.May: return NumDays.May; case Months.June: return NumDays.June; case Months.July: return NumDays.July; case Months.August: return NumDays.August; case Months.September: return NumDays.September; case Months.October: return NumDays.October; case Months.November: return NumDays.November; case Months.December: return NumDays.December; default: throw ("invalid month: " + month); } } function getLastNDigits(value: number, n: number): number { const str = value.toString(); const lastN = str.substr(str.length - 2) return parseInt(lastN); } function getMonthValue(month: Months): MonthValues { switch (month) { case Months.January: return MonthValues.January; case Months.February: return MonthValues.February; case Months.March: return MonthValues.March; case Months.April: return MonthValues.April; case Months.May: return MonthValues.May; case Months.June: return MonthValues.June; case Months.July: return MonthValues.July; case Months.August: return MonthValues.August; case Months.September: return MonthValues.September; case Months.October: return MonthValues.October; case Months.November: return MonthValues.November; case Months.December: return MonthValues.December; default: throw ("invalid month: " + month); } } function getCenturyValue(year: number): CenturyValues { if (year < 1700) { throw ("years before 1700 are not supported"); } else if (year < 1800) { return CenturyValues._1700; } else if (year < 1900) { return CenturyValues._1800; } else if (year < 2000) { return CenturyValues._1900; } else if (year < 2100) { return CenturyValues._2000; } else { // Our year is past the 20th century, subtract 400 and try again return getCenturyValue(year - 400); } } function getReductionValue(month: Months, year: number): number { if (!isLeapYear(year)) { return 0; } if (month !== Months.January && month !== Months.February) { return 0; } return 1; } function isLeapYear(year: number): boolean { if (year % 4 !== 0) { return false; } if (year % 100 === 0) { return false; } return true } function getDayOfWeek(n: number): DaysOfWeek { switch (n) { case 1: return DaysOfWeek.Sunday; case 2: return DaysOfWeek.Monday; case 3: return DaysOfWeek.Tuesday; case 4: return DaysOfWeek.Wednesday; case 5: return DaysOfWeek.Thursday; case 6: return DaysOfWeek.Friday; case 0: return DaysOfWeek.Saturday; default: throw ("invalid day of week"); } }
56f82e02858c369db689524428a1362471f69717
[ "TypeScript" ]
1
TypeScript
PathDNA/calendar.ts
c93be686ad6ae383919af804000b12266bd5d8e9
b48ecdcc6c10e40c1d31c98a10d9e80a6111638c
refs/heads/main
<repo_name>uxapb/noteapp<file_sep>/src/pages/About.js import React from 'react' import './pages.css' export const About = () => ( <div className="about"> <h1>Информация</h1> <div className="about-text"> <p> Версия приложения 1.0 </p> <p> Дата создания: 25.12.2020 </p> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vitae rem odit voluptatum inventore quam officia et animi officiis consectetur nostrum.</p> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vitae rem odit voluptatum inventore quam officia et animi officiis consectetur nostrum.</p> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vitae rem odit voluptatum inventore quam officia et animi officiis consectetur nostrum.</p> </div> </div> ); <file_sep>/src/App.js import './App.css'; import {HashRouter, Switch, Route} from 'react-router-dom' import {Home} from './pages/Home.js' import {About} from './pages/About.js' import {Navbar} from './components/navbar' import { Alert } from './components/Alert'; import { AlertState } from './context/alert/AlertState'; import { FirebaseState } from './context/Firebase/FirebaseState'; function App() { return ( <FirebaseState> <AlertState> <HashRouter> <Navbar /> <Alert/> <div className="container"> <Switch> <Route path={'/'} exact component={Home} /> <Route path={'/about'} component={About} /> </Switch> </div> </HashRouter> </AlertState> </FirebaseState> ); } export default App; <file_sep>/src/components/Alert.js import React, {useContext} from 'react' import { AlertContext } from '../context/alert/alertContext'; import './Alert.css' export const Alert = () => { const {alert, hide} = useContext(AlertContext) if (!alert.visible) { return null; } if (alert.visible) { setTimeout(hide, 5000); } return ( <div className={ `alert alert-${alert.type || 'warning'}` }> <div> <strong className="alert-attention">Внимание!</strong> {alert.text} </div> <button className="alert-button" type="button" onClick={hide}> &times; </button> </div> ) }
3d456925fdefa1259af7327bb0526551a13f0d8a
[ "JavaScript" ]
3
JavaScript
uxapb/noteapp
2244cb910fb0913465aa2ae8a8d716315988458a
918ff4850aab519e4b4379f2de6efb968903145f
refs/heads/master
<repo_name>kadusouzaribeiro/BookStore_CarlosEduardo<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/PanelizationSummary.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class PanelizationSummary ( val containsEpubBubbles : Boolean?, val containsImageBubbles : Boolean? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/RemoteRepository.kt package br.com.android.bookstore_carloseduardo.data.remote import androidx.lifecycle.MutableLiveData import br.com.android.bookstore_carloseduardo.data.Resource import br.com.android.bookstore_carloseduardo.data.local.entity.Book import br.com.android.bookstore_carloseduardo.data.local.entity.ResponseBook import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch /** * Created by <NAME> on 20,March,2021 */ class RemoteRepository { val booksList = MutableLiveData<Resource<ResponseBook>>() private val exception = CoroutineExceptionHandler { _, ex -> booksList.postValue(Resource.error(null, ex.message ?: "Error loading API")) } fun getBooksList(limit: Int = 10, offset: Int = 0) = CoroutineScope(IO).launch(exception) { booksList.postValue(Resource.loading(null)) BooksRetrofit.bookApi.getBooks(limit = limit, offset = offset).let { bs -> val total = bs.totalItems ?: 0 with(bs.items) { val resBooks = this.map { Book( id = it.id ?: "", name = it.volumeInfo?.title ?: "", saleInfo = it.saleInfo?.saleability ?: "", authors = it.volumeInfo?.authors.toString(), description = it.volumeInfo?.description ?: "", buyLink = it.saleInfo?.buyLink ?: "", image = it.volumeInfo?.imageLinks?.smallThumbnail ?: "", favorite = false ) } val responseBook = ResponseBook( totalItems = total, books = resBooks ) booksList.postValue(Resource.success(responseBook)) } } } } <file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/viewmodel/BookListViewModel.kt package br.com.android.bookstore_carloseduardo.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import br.com.android.bookstore_carloseduardo.data.Resource import br.com.android.bookstore_carloseduardo.data.local.entity.ResponseBook import br.com.android.bookstore_carloseduardo.data.remote.RemoteRepository class BookListViewModel(private val remoteRepository: RemoteRepository) : ViewModel() { fun observeBooks(): LiveData<Resource<ResponseBook>> { return remoteRepository.booksList } fun getBooksList(limit: Int = 10, offset: Int = 0) { remoteRepository.getBooksList(limit, offset) } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/BooksApi.kt package br.com.android.bookstore_carloseduardo.data.remote import br.com.android.bookstore_carloseduardo.data.remote.dto.BooksSource import retrofit2.http.GET import retrofit2.http.Query /** * Created by <NAME> on 17,March,2021 */ interface BooksApi { @GET("books/v1/volumes") suspend fun getBooks( @Query("q") search: String = "android", @Query("maxResults") limit: Int, @Query("startIndex") offset: Int, ): BooksSource }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/BookApplication.kt package br.com.android.bookstore_carloseduardo import android.app.Application import br.com.android.bookstore_carloseduardo.data.local.LocalRepository import br.com.android.bookstore_carloseduardo.data.local.db.BookDatabase import br.com.android.bookstore_carloseduardo.data.remote.RemoteRepository import br.com.android.bookstore_carloseduardo.viewmodel.BookListViewModel import br.com.android.bookstore_carloseduardo.viewmodel.BooksViewModel import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.android.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.dsl.module /** * Created by <NAME> on 20,March,2021 */ class BookApplication : Application() { var modules = module { single { BookDatabase.getInstance(context = get()) } single { LocalRepository(get()) } single { RemoteRepository()} viewModel { BooksViewModel(get()) } viewModel { BookListViewModel(get()) } } override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@BookApplication) modules(modules) } } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/local/dao/BookDao.kt package br.com.android.bookstore_carloseduardo.data.local.dao import androidx.lifecycle.LiveData import androidx.room.* import br.com.android.bookstore_carloseduardo.data.local.entity.Book /** * Created by <NAME> on 19,March,2021 */ @Dao interface BookDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(data: Book): Long? @Update suspend fun update(data: Book): Int? @Delete suspend fun delete(data: Book) @Query("SELECT * FROM books") fun getAll(): List<Book>? @Query("SELECT * FROM books WHERE id = :id") fun getById(id: String): Book? }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/adapter/BooksAdapter.kt package br.com.android.bookstore_carloseduardo.adapter import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import br.com.android.bookstore_carloseduardo.GlideApp import br.com.android.bookstore_carloseduardo.R import br.com.android.bookstore_carloseduardo.data.local.entity.Book import br.com.android.bookstore_carloseduardo.databinding.ItemBookBinding import br.com.android.bookstore_carloseduardo.listener.BookListener /** * Created by <NAME> on 20,March,2021 */ class BooksAdapter(private val booksList: List<Book>, private val listener: BookListener): RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BooksAdapter.BooksViewHolder { val binding = ItemBookBinding.inflate(LayoutInflater.from(parent.context), parent, false) return BooksViewHolder(binding) } override fun onBindViewHolder(holder: BooksAdapter.BooksViewHolder, position: Int) { with(holder) { with(booksList[position]) { GlideApp.with(holder.itemView.context) .load(image) .placeholder(R.drawable.placeholder) .error(R.drawable.placeholder) .fallback(R.drawable.placeholder) .into(binding.imgBook) binding.txtBookTitle.text = name holder.itemView.setOnClickListener { listener.onSelectBook(this, it) } } } } override fun getItemCount() = booksList.size inner class BooksViewHolder(val binding: ItemBookBinding): RecyclerView.ViewHolder(binding.root) }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/BooksRetrofit.kt package br.com.android.bookstore_carloseduardo.data.remote import android.util.Log import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory /** * Created by <NAME> on 17,March,2021 */ object BooksRetrofit { private const val BASE_URL = "https://www.googleapis.com/" private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private fun getClient(): OkHttpClient { val clientBuilder = OkHttpClient.Builder() val interceptor = HttpLoggingInterceptor { message -> Log.d("Retrofit", message) } interceptor.level = HttpLoggingInterceptor.Level.BODY return clientBuilder.addInterceptor(interceptor).build() } private fun retrofit(): Retrofit { return Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(getClient()) .baseUrl(BASE_URL) .build() } val bookApi: BooksApi by lazy { retrofit().create(BooksApi::class.java) } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/local/LocalRepository.kt package br.com.android.bookstore_carloseduardo.data.local import androidx.lifecycle.MutableLiveData import br.com.android.bookstore_carloseduardo.data.Resource import br.com.android.bookstore_carloseduardo.data.local.db.BookDatabase import br.com.android.bookstore_carloseduardo.data.local.entity.Book import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers.IO /** * Created by <NAME> on 20,March,2021 */ class LocalRepository(private val database: BookDatabase) { val listFavoriteBooks = MutableLiveData<Resource<List<Book>>>() val book = MutableLiveData<Resource<Book>>() private val exceptionList = CoroutineExceptionHandler { _, ex -> listFavoriteBooks.postValue(Resource.error(null, ex.message ?: "Error loading list of books")) } private val exception = CoroutineExceptionHandler { _, ex -> book.postValue(Resource.error(null, ex.message ?: "Error recovering book")) } fun insertBook(book: Book) { CoroutineScope(IO).launch { database.BookDao().insert(book) } } fun deleteBook(book: Book) { CoroutineScope(IO).launch { database.BookDao().delete(book) } } fun getListBooks() = CoroutineScope(IO).launch(exceptionList) { listFavoriteBooks.postValue(Resource.loading(null)) val result = database.BookDao().getAll() result?.let { listFavoriteBooks.postValue(Resource.success(it)) } } fun getBook(id: String) = CoroutineScope(IO).launch(exception) { book.postValue(Resource.loading(null)) val result = database.BookDao().getById(id) result?.let { book.postValue(Resource.success(result)) } } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/ImageLinks.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ImageLinks ( val smallThumbnail : String?, val thumbnail : String? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/VolumeInfo.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class VolumeInfo ( val title : String?, val authors : List<String>?, val publisher : String?, val description : String?, val industryIdentifiers : List<IndustryIdentifiers>?, val readingModes : ReadingModes?, val pageCount : Int?, val printType : String?, val maturityRating : String?, val allowAnonLogging : Boolean?, val contentVersion : String?, val panelizationSummary : PanelizationSummary?, val imageLinks : ImageLinks?, val language : String?, val previewLink : String?, val infoLink : String?, val canonicalVolumeLink : String? )<file_sep>/README.md # BooksStore Application using API from Google Rest API: https://developers.google.com/books/docs/v1/getting_started#REST | Library | Version | | ------ | ------ | | Coroutines | [1.3.6] | | Room | [2.2.6] | | Lifecycle | [2.3.0] | | Moshi | [1.9.2] | | Retrofit | [2.6.4] | | OkHttp | [3.12.10] | | Glide | 4.11.0 | | Koin | 2.2.2 | | Lottie | 3.4.0 |<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/BooksSource.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class BooksSource ( val kind : String?, val totalItems : Int?, val items : List<Items> )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/Pdf.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Pdf ( val isAvailable : Boolean?, val acsTokenLink : String? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/listener/BookListener.kt package br.com.android.bookstore_carloseduardo.listener import android.view.View import br.com.android.bookstore_carloseduardo.data.local.entity.Book /** * Created by <NAME> on 20,March,2021 */ interface BookListener { fun onSelectBook(book: Book, v: View) }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/RetailPrice.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class RetailPrice ( val amount : Double?, val currencyCode : String? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/SearchInfo.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class SearchInfo ( val textSnippet : String? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/ReadingModes.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ReadingModes ( val text : Boolean?, val image : Boolean? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/viewmodel/BooksViewModel.kt package br.com.android.bookstore_carloseduardo.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import br.com.android.bookstore_carloseduardo.data.Resource import br.com.android.bookstore_carloseduardo.data.local.LocalRepository import br.com.android.bookstore_carloseduardo.data.local.entity.Book class BooksViewModel(private val localRepository: LocalRepository) : ViewModel() { fun observeFavoriteBooks(): LiveData<Resource<List<Book>>> = localRepository.listFavoriteBooks fun observeBook(): LiveData<Resource<Book>> = localRepository.book fun getListFavorites() = localRepository.getListBooks() fun getSingleBook(id: String) = localRepository.getBook(id) fun favoriteBook(book: Book) { localRepository.insertBook(book) } fun unfavoriteBook(book: Book) { localRepository.deleteBook(book) } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/SaleInfo.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class SaleInfo ( val country : String?, val saleability : String?, val isEbook : Boolean?, val listPrice : ListPrice?, val retailPrice : RetailPrice?, val buyLink : String?, val offers : List<Offers>? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/local/entity/ResponseBook.kt package br.com.android.bookstore_carloseduardo.data.local.entity /** * Created by <NAME> on 21,March,2021 */ data class ResponseBook( val totalItems: Int, val books: List<Book> )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/Epub.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Epub ( val isAvailable : Boolean? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/IndustryIdentifiers.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class IndustryIdentifiers ( val type : String?, val identifier : String? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/local/db/BookDatabase.kt package br.com.android.bookstore_carloseduardo.data.local.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import br.com.android.bookstore_carloseduardo.data.local.dao.BookDao import br.com.android.bookstore_carloseduardo.data.local.entity.Book /** * Created by <NAME> on 19,March,2021 */ @Database(entities = [Book::class], version = 1) abstract class BookDatabase : RoomDatabase() { abstract fun BookDao(): BookDao companion object { @Volatile private var INSTANCE: BookDatabase? = null fun getInstance(context: Context): BookDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(BookDatabase::class) { val instance = Room.databaseBuilder( context.applicationContext, BookDatabase::class.java, "BookDB.db" ).build() INSTANCE = instance return instance } } } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/Offers.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Offers ( val finskyOfferType : Int?, val listPrice : ListPrice?, val retailPrice : RetailPrice?, val giftable : Boolean? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/ui/BookDetailsFragment.kt package br.com.android.bookstore_carloseduardo.ui import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentContainer import androidx.fragment.app.FragmentManager import androidx.navigation.Navigation import androidx.navigation.fragment.FragmentNavigator import br.com.android.bookstore_carloseduardo.GlideApp import br.com.android.bookstore_carloseduardo.viewmodel.BooksViewModel import br.com.android.bookstore_carloseduardo.R import br.com.android.bookstore_carloseduardo.data.local.entity.Book import br.com.android.bookstore_carloseduardo.databinding.BookDetailsFragmentBinding import org.koin.android.viewmodel.ext.android.sharedViewModel class BookDetailsFragment : Fragment() { private lateinit var binding: BookDetailsFragmentBinding private val viewModel: BooksViewModel by sharedViewModel() private var book: Book? = null companion object { fun newInstance() = BookDetailsFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.book_details_fragment, container, false).also { binding = BookDetailsFragmentBinding.bind(it) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { it -> book = it.getSerializable("B") as Book book?.let { b -> viewModel.getSingleBook(b.id) } } viewModel.observeBook().removeObservers(this) viewModel.observeBook().observe(viewLifecycleOwner, { it.data?.let { b -> if (b.id == book?.id) { book?.favorite = b.favorite } } setDetails() }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { android.R.id.home -> { Navigation.findNavController(requireView()).popBackStack() } R.id.exit -> requireActivity().finish() } return super.onOptionsItemSelected(item) } private fun setDetails() { binding.apply { book?.let { b-> GlideApp.with(this@BookDetailsFragment) .load(b.image) .placeholder(R.drawable.placeholder) .error(R.drawable.placeholder) .fallback(R.drawable.placeholder) .into(imgBook) txtBookTitle.text = b.name txtBookAuthors.text = if (b.authors == "null") "" else b.authors txtBookDescription.text = b.description if (b.saleInfo == "NOT_FOR_SALE") { cvBuy.isEnabled = false imgBookBuy.visibility = View.GONE txtBookBuy.text = b.saleInfo } else { imgBookBuy.visibility = View.VISIBLE txtBookBuy.text = getString(R.string.buy) cvBuy.setOnClickListener { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(b.buyLink) startActivity(i) } } if (b.favorite) { imgBookFavorite.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_yes)) imgBookFavorite.setOnClickListener { b.favorite = false viewModel.unfavoriteBook(b) imgBookFavorite.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_no)) } } else { imgBookFavorite.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_no)) imgBookFavorite.setOnClickListener { b.favorite = true viewModel.favoriteBook(b) imgBookFavorite.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_yes)) } } } } } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/Items.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Items ( val kind : String?, val id : String?, val etag : String?, val selfLink : String?, val volumeInfo : VolumeInfo?, val saleInfo : SaleInfo?, val accessInfo : AccessInfo?, val searchInfo : SearchInfo? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/MainActivity.kt package br.com.android.bookstore_carloseduardo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import br.com.android.bookstore_carloseduardo.data.local.dao.BookDao import org.koin.android.ext.android.inject class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return super.onCreateOptionsMenu(menu) } }<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/local/entity/Book.kt package br.com.android.bookstore_carloseduardo.data.local.entity import androidx.room.Entity import androidx.room.PrimaryKey import br.com.android.bookstore_carloseduardo.data.remote.dto.BooksSource import java.io.Serializable /** * Created by <NAME> on 19,March,2021 */ @Entity(tableName = "books") data class Book( @PrimaryKey val id: String, val name: String, val saleInfo: String, val authors: String, val description: String, val buyLink: String, val image: String, var favorite: Boolean = false, ): Serializable <file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/data/remote/dto/AccessInfo.kt package br.com.android.bookstore_carloseduardo.data.remote.dto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class AccessInfo ( val country : String?, val viewability : String?, val embeddable : Boolean?, val publicDomain : Boolean?, val textToSpeechPermission : String?, val epub : Epub?, val pdf : Pdf?, val webReaderLink : String?, val accessViewStatus : String?, val quoteSharingAllowed : Boolean? )<file_sep>/app/src/main/java/br/com/android/bookstore_carloseduardo/ui/BookListFragment.kt package br.com.android.bookstore_carloseduardo.ui import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.navigation.Navigation import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import br.com.android.bookstore_carloseduardo.R import br.com.android.bookstore_carloseduardo.adapter.BooksAdapter import br.com.android.bookstore_carloseduardo.data.ResponseStatus import br.com.android.bookstore_carloseduardo.data.local.entity.Book import br.com.android.bookstore_carloseduardo.databinding.BookListFragmentBinding import br.com.android.bookstore_carloseduardo.listener.BookListener import br.com.android.bookstore_carloseduardo.viewmodel.BookListViewModel import br.com.android.bookstore_carloseduardo.viewmodel.BooksViewModel import org.koin.android.viewmodel.ext.android.sharedViewModel class BookListFragment : Fragment(), BookListener { private lateinit var binding: BookListFragmentBinding private val viewModel: BookListViewModel by sharedViewModel() private val viewModelBook: BooksViewModel by sharedViewModel() private lateinit var booksAdapter: BooksAdapter var loading = false var limit = 20 var offset = 0 var totalBooks = 0 private val bookList: MutableList<Book> = mutableListOf() companion object { fun newInstance() = BookListFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.book_list_fragment, container, false).also { binding = BookListFragmentBinding.bind(it) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setObservers() viewModel.getBooksList(limit) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.filterFav -> { viewModelBook.getListFavorites() return true } R.id.filterAll -> { viewModel.getBooksList(limit) return true } R.id.exit -> requireActivity().finish() } return super.onOptionsItemSelected(item) } private fun setObservers() { viewModel.observeBooks().observe(viewLifecycleOwner, { when (it.status) { ResponseStatus.LOADING -> { showLoading() } ResponseStatus.SUCCESS -> { it.data?.let { it1 -> if (totalBooks == 0) totalBooks = it1.totalItems it1.books.forEach { b -> if (!bookList.contains(b)) bookList.add(b) } if (bookList.size < totalBooks) { if (loading) { booksAdapter.notifyDataSetChanged() binding.clProgressView.visibility = View.GONE loading = false } else { setBooksList(bookList) } } } } ResponseStatus.ERROR -> { showError(it.message ?: "Error") } } }) viewModelBook.observeFavoriteBooks().observe(viewLifecycleOwner, { when (it.status) { ResponseStatus.LOADING -> { showLoading() } ResponseStatus.SUCCESS -> { it.data?.let { it1 -> setBooksList(it1) } } ResponseStatus.ERROR -> { showError(it.message ?: "Error") } } }) } private fun setBooksList(bookList: List<Book>) { booksAdapter = BooksAdapter(bookList, this) binding.rvBooksList.adapter = booksAdapter binding.clProgressView.visibility = View.GONE val lManager = binding.rvBooksList.layoutManager as GridLayoutManager binding.rvBooksList.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (!loading) { val totalItem = lManager.itemCount val lastCompletelyVisibleItem = lManager.findLastCompletelyVisibleItemPosition() if (!loading && lastCompletelyVisibleItem == totalItem - 1) { loading = true if (limit < 40) limit += 20 if (offset > 0) offset += 20 if (limit == 40 && offset == 0) offset = limit viewModel.getBooksList(limit, offset) } } } }) } private fun showLoading() { binding.clProgressView.visibility = View.VISIBLE } private fun showError(msg: String) { binding.clProgressView.visibility = View.GONE val builder = AlertDialog.Builder(requireContext()) with(builder) { setTitle("Error") setMessage(msg) setPositiveButton("OK") { _: DialogInterface, _: Int -> } show() } } override fun onSelectBook(book: Book, v: View) { val bundle = Bundle() bundle.putSerializable("B", book) Navigation.findNavController(v).navigate(R.id.action_bookList_to_bookDetails, bundle) } }
e1ad74f4dedf076173f6d1c28af03fad5bc9e359
[ "Markdown", "Kotlin" ]
31
Kotlin
kadusouzaribeiro/BookStore_CarlosEduardo
2d2f96045b05ba16ef24b5905e4ea44416bcb175
0466959eab2537b02d6dd2f9bbf6874963597561
refs/heads/master
<repo_name>donaldserafim/capgemini-test<file_sep>/src/app/service/authentication.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { catchError, tap, map } from 'rxjs/operators'; import { Observable, of, throwError } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { User } from '../model/User'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; @Injectable({ providedIn: 'root' }) export class AuthenticationService { constructor(private httpClient: HttpClient) { } authenticate(username, password) { return this.httpClient.post<any>(`http://localhost:8080/login`, { username, password }) .pipe(map(user => { sessionStorage.setItem('username', username) return user; })); } isUserLoggedIn() { let user = sessionStorage.getItem('username') return !(user === null) } logOut() { sessionStorage.removeItem('username') } }<file_sep>/src/app/usuario-detalhe/usuario-detalhe.component.ts import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { ApiService } from '../service/api.service'; import { Usuario } from '../model/Usuario'; @Component({ selector: 'app-usuario-detalhe', templateUrl: './usuario-detalhe.component.html', styleUrls: ['./usuario-detalhe.component.scss'] }) export class UsuarioDetalheComponent implements OnInit { usuario: Usuario = { id: '', nome: '', descricao: ''}; isLoadingResults = true; constructor(private router: Router, private route: ActivatedRoute, private api: ApiService) { } ngOnInit() { this.getUsuario(this.route.snapshot.params['id']); } getUsuario(id) { this.api.getUsuario(id) .subscribe(data => { this.usuario = data; console.log(this.usuario); this.isLoadingResults = false; }); } deleteUsuario(id) { this.isLoadingResults = true; this.api.deleteUsuario(id) .subscribe(res => { this.isLoadingResults = false; this.router.navigate(['/h2-console']); }, (err) => { console.log(err); this.isLoadingResults = false; } ); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UsuariosComponent } from './usuarios/usuarios.component'; import { UsuarioDetalheComponent } from './usuario-detalhe/usuario-detalhe.component'; import { UsuarioNovoComponent } from './usuario-novo/usuario-novo.component'; import { UsuarioEditarComponent } from './usuario-editar/usuario-editar.component'; import { LoginComponent } from './login/login.component'; import { LogoutComponent } from './logout/logout.component'; const routes: Routes = [ { path: 'h2-console', component: UsuariosComponent, data: { title: 'Lista de Usuários' } }, { path: 'usuario-detalhe/:id', component: UsuarioDetalheComponent, data: { title: 'Detalhe do Usuário' } }, { path: 'usuario-novo', component: UsuarioNovoComponent, data: { title: 'Adicionar Usuário' } }, { path: 'usuario-editar/:id', component: UsuarioEditarComponent, data: { title: 'Editar o Usuário' } }, { path: '', redirectTo: '/h2-console', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'logout', component: LogoutComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/README.md Projeto FrontEnd para desafio CNPQ # Build npm install # iniciar servidor ng serve # Endereço http://localhost:4200/ <file_sep>/src/app/usuarios/usuarios.component.ts import { Component, OnInit } from '@angular/core'; import { ApiService } from '../service/api.service'; import { Usuario } from '../model/Usuario'; import { AuthenticationService } from '../service/authentication.service'; @Component({ selector: 'app-usuarios', templateUrl: './usuarios.component.html', styleUrls: ['./usuarios.component.scss'] }) export class UsuariosComponent implements OnInit { displayedColumns: string[] = [ 'nome', 'descricao', 'acao']; dataSource: Usuario[]; isLoadingResults = true; constructor(private _api: ApiService,private loginService:AuthenticationService) { } ngOnInit() { this._api.getUsuarios() .subscribe(res => { this.dataSource = res; console.log(this.dataSource); this.isLoadingResults = false; }, err => { console.log(err); this.isLoadingResults = false; }); } } <file_sep>/src/app/usuario-novo/usuario-novo.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms'; import { ApiService } from '../service/api.service'; @Component({ selector: 'app-usuario-novo', templateUrl: './usuario-novo.component.html', styleUrls: ['./usuario-novo.component.scss'] }) export class UsuarioNovoComponent implements OnInit { usuarioForm: FormGroup; isLoadingResults = false; constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { } ngOnInit() { this.usuarioForm = this.formBuilder.group({ 'nome' : [null, Validators.required], 'descricao' : [null, [Validators.required]], 'ativo': true }); } addUsuario(form: NgForm) { this.isLoadingResults = true; this.api.addUsuario(form) .subscribe(res => { const id = res['id']; this.isLoadingResults = false; this.router.navigate(['/usuario-detalhe', id]); }, (err) => { console.log(err); this.isLoadingResults = false; }); } }
5a6641488af1e58e9bbc759e126af670be50dcce
[ "Markdown", "TypeScript" ]
6
TypeScript
donaldserafim/capgemini-test
d169f195bd7a8559d40ea3410494b823377aad5f
162ee966333de5e1bda967e95dc29b72b48daf57
refs/heads/master
<file_sep>from ims.model.product import Product from flask import request, jsonify from ims import response, db from ims.controller import user_controller def all_product(): try: user_id = request.args.get('user_id') product = Product.query.filter_by(user_id=user_id).all() data = transform(product) return response.ok(data, "") except Exception as e: print(e) def save(): try: name = request.json['name'] quantity = request.json['quantity'] user_id = request.json['user_id'] product = Product(name=name, user_id=user_id) if request.json['quantity']: product.quantity = request.json['quantity'] db.session.add(product) db.session.commit() return response.ok('', 'Successfully save data!') except Exception as e: print(e) def update(pid): try: name = request.json['name'] quantity = request.json['quantity'] product = Product.quey.filter_by(pid=pid).first() product.name = name product.quantity = quantity db.session.commit() return response.ok('', 'Successfully update product!') except Exception as e: print(e) def product(pid): try: product = Product.query.filter_by(pid=pid).first() if not product: return response.bad_request([], 'Empty ...') data = single_transform(product) return response.ok(data, "") except Exception as e: print(e) def delete(pid): try: product = Product.query.filter_by(pid=pid).first() if not product: return response.bad_request([], 'Empty ...') db.session.delete(product) db.session.commit() return response.ok('', 'Successfully delete product!') except Exception as e: print(e) def transform(products): data = [] for product in products: data.append(single_transform(product)) return data def single_transform(product): data = { 'pid': product.pid, 'name': product.name, 'quantity': product.quantity, 'created_at': product.created_at, 'updated_at': product.updated_at, 'user_id': product.user_id, 'user': user_controller.single_transform(product.users, withProduct=False) } return data<file_sep># microservice Tugas Besar Sistem Terdistribusi <file_sep>FLASK_APP=microims.py DB_HOST=localhost DB_DATABASE=microims DB_USERNAME=username DB_PASSWORD=<PASSWORD><file_sep>from ims.model.user import User from ims import response, ims, bcrypt, db from flask import request def login(): try: email = request.json['email'] password = request.json['password'] user = User.query.filter_by(email=email).first() if not user: return response.bad_request([], "Empty ...") if not bcrypt.check_password_hash(user.password, password): return response.bad_request([], 'Your credentials is invalid') data = single_transform(user) return response.ok(data, "") except Exception as e: print(e) def all_user(): try: users = User.query.all() data = transform(users) return response.ok(data, "") except Exception as e: print(e) def user(uid): try: user = User.query.filter_by(uid=uid).first() if not user: return response.bad_request([], 'Empty ...') data = single_transform(user) return response.ok(data, "") except Exception as e: print(e) def save(): try: name = request.json['name'] email = request.json['email'] password = request.json['password'] hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') user = User(name=name, email=email, password=<PASSWORD>_password) db.session.add(user) db.session.commit() return response.ok('', 'Successfully save data!') except Exception as e: print(e) def update(uid): try: name = request.json['name'] email = request.json['email'] password = request.json['password'] hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') user = User.query.filter_by(uid=uid).first() user.name = name user.email = email user.password = <PASSWORD> db.session.commit() return response.ok('', 'Successfully save data!') except Exception as e: print(e) def delete(uid): try: user = User.query.filter_by(uid=uid).first() if not user: return response.bad_request([], 'Empty ...') db.session.delete(user) db.session.commit() return response.ok('', 'Successfully delete data!') except Exception as e: print(e) def single_transform(user, withProduct=True): data = { 'uid': user.uid, 'name': user.name, 'email': user.email } if withProduct: products = [] for product in user.products: products.append({ 'pid': product.pid, 'name': product.name, 'quantity': product.quantity }) data['products'] = products return data def transform(users): data = [] for user in users: data.append(single_transform(user)) return data<file_sep>from ims import db from datetime import datetime from ims.model.user import User class Product(db.Model): pid = db.Column(db.BigInteger, primary_key=True, autoincrement=True) name = db.Column(db.String(200), nullable=False) quantity = db.Column(db.Integer, nullable=False, default=0) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow) user_id = db.Column(db.BigInteger, db.ForeignKey(User.uid)) users = db.relationship("User", backref="user_id") def __repr__(self): return '<Product {}>'.format(self.name)<file_sep>from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_bcrypt import Bcrypt ims = Flask(__name__) ims.config.from_object(Config) db = SQLAlchemy(ims) migrate = Migrate(ims, db) bcrypt = Bcrypt(ims) from ims.model import user, product from ims import routes<file_sep>from ims import ims from ims.controller import user_controller, product_controller from flask import request @ims.route('/') @ims.route('/home') def home(): return "Hello, World!" @ims.route('/register', methods=['POST']) def register(): return user_controller.save() @ims.route('/login', methods=['POST']) def login(): return user_controller.login() @ims.route('/users', methods=['GET']) def users(): return user_controller.all_user() @ims.route('/users/<uid>', methods=['PUT', 'GET', 'DELETE']) def user(uid): if request.method == 'GET': return user_controller.user(uid) elif request.method == 'PUT': return user_controller.update(uid) elif request.method == 'DELETE': return user_controller.delete(uid) @ims.route('/products', methods=['POST', 'GET']) def products(): if request.method == 'GET': return product_controller.all_product() else: return product_controller.save() @ims.route('/products/<pid>', methods=['PUT', 'GET', 'DELETE']) def product(pid): if request.method == 'GET': return product_controller.product(pid) elif request.method == 'PUT': return product_controller.update(pid) elif request.method == 'DELETE': return product_controller.delete(pid)<file_sep>from ims import db from datetime import datetime class User(db.Model): uid = db.Column(db.BigInteger, primary_key=True, autoincrement=True) name = db.Column(db.String(200), nullable=False) email = db.Column(db.String(100), index=True, unique=True, nullable=False) password = db.Column(db.String(100), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow) products = db.relationship("Product", lazy="select", backref=db.backref('products', lazy='joined')) def __repr__(self): return '<User {}>'.format(self.name)
04241efab470efb0ba9f1304feaa6439671c056d
[ "Markdown", "Python", "Shell" ]
8
Python
mumuhkustino/microservice
1a7aa3eb08dfcb402c616944c5be58803868fea3
49d374a76bed955482f7055fa21c0a42c02be8f3
refs/heads/master
<file_sep>package com.music.dao; import java.util.ArrayList; import java.util.List; import com.music.model.*; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class GenreDao { @Resource SessionFactory factory; /*添加genre信息*/ public void AddGenre(Genre genre) throws Exception { Session s = factory.getCurrentSession(); s.save(genre); } /*删除genre信息*/ public void DeleteGenre(Integer genreid) throws Exception { Session s = factory.getCurrentSession(); Object genre = s.load(Genre.class, genreid); s.delete(genre); } /*更新genre信息*/ public void UpdateGenre(Genre genre) throws Exception { Session s = factory.getCurrentSession(); s.update(genre); } /*查询所有genre信息*/ public ArrayList<Genre> QueryAllgenres() { Session s = factory.getCurrentSession(); String hql = "From Genre"; Query q = s.createQuery(hql); List genreList = q.list(); return (ArrayList<Genre>) genreList; } /*根据主键获取对象*/ public Genre GetGenreById(Integer genreid) { Session s = factory.getCurrentSession(); Genre genre = (Genre)s.get(Genre.class, genreid); return genre; } /*根据歌手名字获取对象*/ public Genre GetGenreByName(String genrename) { Session s = factory.getCurrentSession(); String hql = "From Genre genre where 1=1"; if(!genrename.equals("")) hql = hql + " and genre.genrename like '%" + genrename + "%'"; Query q = s.createQuery(hql); Genre genre = (Genre) q.uniqueResult(); return genre; } /*根据查询条件查询*/ public ArrayList<Genre> QuerygenreInfo(String genrename) { Session s = factory.getCurrentSession(); String hql = "From Genre genre where 1=1"; if(!genrename.equals("")) hql = hql + " and genre.genrename like '%" + genrename + "%'"; Query q = s.createQuery(hql); List genreList = q.list(); return (ArrayList<Genre>) genreList; } } <file_sep>package com.music.dao; import java.util.ArrayList; import java.util.List; import com.music.model.*; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class SongDao { @Resource SessionFactory factory; /*添加Song信息*/ public void AddSong(Song song) throws Exception { Session s = factory.getCurrentSession(); s.save(song); } /*删除Song信息*/ public void DeleteSong(Integer songid) throws Exception { Session s = factory.getCurrentSession(); Object song = s.load(Song.class, songid); s.delete(song); } /*更新Song信息*/ public void UpdateSong(Song song) throws Exception { Session s = factory.getCurrentSession(); s.update(song); } /*查询所有Song信息*/ public ArrayList<Song> QueryAllSongs() { Session s = factory.getCurrentSession(); String hql = "From Song"; Query q = s.createQuery(hql); List songList = q.list(); return (ArrayList<Song>) songList; } /*根据主键获取对象*/ public Song GetSongById(Integer songid) { Session s = factory.getCurrentSession(); Song song = (Song)s.get(Song.class, songid); return song; } /*根据查询条件查询*/ public ArrayList<Song> QuerySongInfo(String songname) { Session s = factory.getCurrentSession(); //String hql = "From Song"; String hql = "From Song song where 1=1"; if(!songname.equals("")) hql = hql + " and song.name like '%" + songname + "%'"; Query q = s.createQuery(hql); List songList = q.list(); return (ArrayList<Song>) songList; } public ArrayList<Song> QuerySongsInfo(String songname, Integer genreid) { Session s = factory.getCurrentSession(); String hql = "From Song song where 1=1"; if(null != songname) hql = hql + " and song.name like '%" + songname + "%'"; if(null !=genreid ) hql = hql + " and song.genre.genreid =" + genreid; Query q = s.createQuery(hql); List songList = q.list(); return (ArrayList<Song>) songList; } public ArrayList<Song> QuerySongsInfoBySinger(String singername) { Session s = factory.getCurrentSession(); String hql = "From Song song where 1=1"; if(null != singername) hql = hql + " and song.singer.singername like '%" + singername + "%'"; Query q = s.createQuery(hql); List songList = q.list(); return (ArrayList<Song>) songList; } } <file_sep>package com.music.dao; import java.util.ArrayList; import java.util.List; import com.music.model.*; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AlbumDao { @Resource SessionFactory factory; /*添加Album信息*/ public void AddAlbum(Album album) throws Exception { Session s = factory.getCurrentSession(); s.save(album); } /*删除Album信息*/ public void DeleteAlbum(Integer albumid) throws Exception { Session s = factory.getCurrentSession(); Object album = s.load(Album.class, albumid); s.delete(album); } /*更新Album信息*/ public void UpdateAlbum(Album album) throws Exception { Session s = factory.getCurrentSession(); s.update(album); } /*查询所有Album信息*/ public ArrayList<Album> QueryAllAlbums() { Session s = factory.getCurrentSession(); String hql = "From Album"; Query q = s.createQuery(hql); List albumList = q.list(); return (ArrayList<Album>) albumList; } /*根据主键获取对象*/ public Album GetAlbumById(Integer albumid) { Session s = factory.getCurrentSession(); Album album = (Album)s.get(Album.class, albumid); return album; } /*根据歌手名字获取对象*/ public Album GetAlbumByName(String albumname) { Session s = factory.getCurrentSession(); String hql = "From Album album where 1=1"; if(!albumname.equals("")) hql = hql + " and album.albumname like '%" + albumname + "%'"; Query q = s.createQuery(hql); Album album = (Album) q.uniqueResult(); return album; } /*根据查询条件查询*/ public ArrayList<Album> QueryAlbumInfo(String albumname) { Session s = factory.getCurrentSession(); String hql = "From Album album where 1=1"; if(!albumname.equals("")) hql = hql + " and album.Albumname like '%" + albumname + "%'"; Query q = s.createQuery(hql); List albumList = q.list(); return (ArrayList<Album>) albumList; } } <file_sep>package com.music.model; import java.util.HashSet; import java.util.Set; /** * Singer entity. @author MyEclipse Persistence Tools */ public class Singer implements java.io.Serializable { // Fields private Integer singerid; private String singername; private String introduction; private String singerfilepath; private Set albums = new HashSet(0); private Set songs = new HashSet(0); private Set songs_1 = new HashSet(0); // Constructors /** default constructor */ public Singer() { } /** minimal constructor */ public Singer(String singername) { this.singername = singername; } /** full constructor */ public Singer(String singername, String introduction, String singerfilepath, Set albums, Set songs, Set songs_1) { this.singername = singername; this.introduction = introduction; this.singerfilepath = singerfilepath; this.albums = albums; this.songs = songs; this.songs_1 = songs_1; } // Property accessors public Integer getSingerid() { return this.singerid; } public void setSingerid(Integer singerid) { this.singerid = singerid; } public String getSingername() { return this.singername; } public void setSingername(String singername) { this.singername = singername; } public String getIntroduction() { return this.introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getSingerfilepath() { return this.singerfilepath; } public void setSingerfilepath(String singerfilepath) { this.singerfilepath = singerfilepath; } public Set getAlbums() { return this.albums; } public void setAlbums(Set albums) { this.albums = albums; } public Set getSongs() { return this.songs; } public void setSongs(Set songs) { this.songs = songs; } public Set getSongs_1() { return this.songs_1; } public void setSongs_1(Set songs_1) { this.songs_1 = songs_1; } }
c60461bc4617a037dd52b27cfca7bd85ec3c1480
[ "Java" ]
4
Java
Ewang17/music2
f09ed4a6434431345cdbcdbe02d8ddbacfb2c386
cd867f31a1009a1420775dd188b070f2abf12fdf
refs/heads/main
<file_sep> const refinedData = {}; let query; const city = document.querySelector('.location'); const status = document.querySelector('.status'); const temperature = document.querySelector('.temperature'); const max = document.querySelector('.max'); const min = document.querySelector('.min'); const feel = document.querySelector('.feel'); const humidity = document.querySelector('.humidity'); const userInput = document.querySelector('.userInput'); const form = document.querySelector('form'); const map = document.querySelector('.map'); form.addEventListener('submit', (e) => { e.preventDefault(); getWeather(userInput.value); form.reset(); }); map.addEventListener('mouseenter', () => { document.querySelector('.getLocation').style.display = 'block'; }); map.addEventListener('mouseleave', () => { document.querySelector('.getLocation').style.display = 'none'; }) map.addEventListener('click', () => { function success(position) { console.log(position.coords.latitude); const latitude = position.coords.latitude; const longitude = position.coords.longitude; let userLocation = `lat=${latitude}&lon=${longitude}`; getWeather(userLocation); } function error() { alert(error); } if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(success, error); } else { alert('Geolocation is not supported by your browser'); } }) async function getWeather(location) { var hasNumber = /\d/; if (!hasNumber.test(location)) { location = `q=${location}`; } const API_KEY = '<KEY>' try { const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?${location}&appid=${API_KEY}`, {mode: 'cors'}); const data = await response.json(); const processedData = processData(data); display(processedData); } catch(error) { displayError(); } } function processData(data) { const temp = kelvinToFahrenheit(data.main.temp); refinedData.temperature = { value: temp, unit: 'fahrenheit' }; refinedData.location = data.name; refinedData.country = data.sys.country; refinedData.status = data.weather[0].description refinedData.max = kelvinToFahrenheit(data.main.temp_max); refinedData.min = kelvinToFahrenheit(data.main.temp_min); refinedData.feel = kelvinToFahrenheit(data.main.feels_like); refinedData.humidity = data.main.humidity; return refinedData; } function display(data) { const error = document.querySelector('.error'); error.style.display = 'none'; userInput.style.border = '1px solid rgb(243, 243, 243)'; city.innerHTML = `${data.location}, ${data.country}`; status.innerHTML = data.status; humidity.innerHTML = data.humidity + '%'; temperature.innerHTML = data.temperature.value + '&degF'; max.innerHTML = data.max + '&degF'; min.innerHTML = data.min + '&degF'; feel.innerHTML = data.feel + '&degF'; } const checkbox = document.querySelector("[name=checkbox]"); checkbox.addEventListener('change', toggleTemperature); function toggleTemperature(e) { if (e.target.checked) { temperature.innerHTML = toCelsius(refinedData.temperature.value) + '&degC'; max.innerHTML = toCelsius(refinedData.max) + '&degC'; min.innerHTML = toCelsius(refinedData.min) + '&degC'; feel.innerHTML = toCelsius(refinedData.feel) + '&degC'; } else { temperature.innerHTML = refinedData.temperature.value + '&degF'; max.innerHTML = refinedData.max + '&degF'; min.innerHTML = refinedData.min + '&degF'; feel.innerHTML = refinedData.feel + '&degF'; }; } function displayError() { const error = document.querySelector('.error'); error.style.display = 'block'; userInput.style.border = '2px solid #F44336'; } function toFahrenheit(temperature) { temperatureerature = Math.round((temperature = (temperature - 32) * (5/9))); return temperature; } function toCelsius(temperature) { temperature = Math.round((temperature = (temperature - 32) * (5 / 9))); return temperature; } function kelvinToFahrenheit(temperature) { temperature = Math.round((1.8 * (temperature - 273)) + 32); return temperature; } <file_sep># Weather-App A basic weather app built with html, css, and javascript.
0911902395cac3ec73cd809f68b12811a47cd09a
[ "JavaScript", "Markdown" ]
2
JavaScript
sumaan49/Weather-App
24db7827de45325ea312593688c6231194c8271d
2a311517faf01b39b7f269499a93fce03a59bcd8
refs/heads/master
<repo_name>MQ9Realper/ur254<file_sep>/app/src/main/java/com/patriot/ur254/adapters/ProjectsAdapter.java package com.patriot.ur254.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.patriot.ur254.R; import java.util.List; import models.Project; /** * Created by dennismwebia on 7/21/17. */ public class ProjectsAdapter extends RecyclerView.Adapter<ProjectsAdapter.ProjectsViewHolder> { private Context mContext; private List<Project> projectList; private View itemView; public class ProjectsViewHolder extends RecyclerView.ViewHolder { private ImageView thumb; private TextView title, description; public ProjectsViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.textView_title); description = (TextView) view.findViewById(R.id.textViewProjectDescription); thumb = (ImageView) view.findViewById(R.id.imageView_thumbnail); } } public ProjectsAdapter(Context context, List<Project> projectList) { this.mContext = context; this.projectList = projectList; } @Override public ProjectsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_project_item, parent, false); return new ProjectsViewHolder(itemView); } @Override public void onBindViewHolder(final ProjectsViewHolder holder, final int position) { if (holder != null) { holder.title.setText(projectList.get(position).getProject_name()); holder.description.setText(projectList.get(position).getProject_description()); Glide.with(mContext).load(projectList.get(position).getProject_banner()).into(holder.thumb); } } @Override public int getItemCount() { return projectList.size(); } } <file_sep>/app/src/main/java/com/patriot/ur254/utils/SharedPreference.java package com.patriot.ur254.utils; import android.content.Context; import android.content.SharedPreferences; /** * Created by dennismwebia on 04/03/17. */ public class SharedPreference { private Context context = null; private SharedPreferences app_prefs; public SharedPreference(Context context) { app_prefs = context.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE); context = context; } public void SaveFirstName(String first_name) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("first_name", first_name); edit.apply(); } public String GetFirstName() { return app_prefs.getString("first_name", ""); } public void SaveLastName(String last_name) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("last_name", last_name); edit.apply(); } public String GetLastName() { return app_prefs.getString("last_name", ""); } public void SaveEmail(String email) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("email", email); edit.apply(); } public String GetEmail() { return app_prefs.getString("email", ""); } public void SaveConstituency(String constituency) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("constituency", constituency); edit.apply(); } public String GetConstituency() { return app_prefs.getString("constituency", ""); } public void SaveCounty(String county) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("county", county); edit.apply(); } public String GetCounty() { return app_prefs.getString("county", ""); } public void SaveWard(String ward) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("ward", ward); edit.apply(); } public String GetWard() { return app_prefs.getString("ward", ""); } public void SavePhoneNumber(String phone_number) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("phone_number", phone_number); edit.apply(); } public String GetPhoneNumber() { return app_prefs.getString("phone_number", ""); } public void SaveUserName(String username){ SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("username", username); edit.apply(); } public String GetUsername(){ return app_prefs.getString("username", ""); } public boolean getIsLoggedIn() { return app_prefs.getBoolean("logged_in", false); } public void putIsLoggedIn(boolean logged_in) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putBoolean("logged_in", logged_in); edit.apply(); } public void SaveSupporterType(String supporter_type){ SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("supporter_type", supporter_type); edit.apply(); } public String GetSupporterType() { return app_prefs.getString("supporter_type", "S"); } public String GetPhotoUrl() { return app_prefs.getString("photo_url", ""); } public void SavePhotoUrl(String photo_url){ SharedPreferences.Editor edit = app_prefs.edit(); edit.putString("photo_url", photo_url); edit.apply(); } public boolean getcontactSaved() { return app_prefs.getBoolean("contactssaved", false); } public void putcontactSaved(boolean contactssaved) { SharedPreferences.Editor edit = app_prefs.edit(); edit.putBoolean("contactssaved", contactssaved); edit.apply(); } } <file_sep>/app/src/main/java/com/patriot/ur254/activities/PrivacyPolicyActivity.java package com.patriot.ur254.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.joanzapata.pdfview.PDFView; import com.joanzapata.pdfview.listener.OnLoadCompleteListener; import com.patriot.ur254.R; import com.patriot.ur254.utils.UniversalUtils; public class PrivacyPolicyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_privacy_policy); PDFView pdfView = (PDFView) findViewById(R.id.pdfview); initToolBar(); LoadPdfFile(pdfView); } private void initToolBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_privacy_policy); toolbar.setTitle("Privacy Policy"); toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_keyboard_arrow_left_white_24dp)); toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(PrivacyPolicyActivity.this, TimelineActivity.class); startActivity(intent); finish(); } }); setSupportActionBar(toolbar); } private void LoadPdfFile(PDFView pdfView) { final UniversalUtils universalUtils = new UniversalUtils(this); universalUtils.ShowProgressDialog("Loading..."); pdfView.fromAsset("privacy_policy.pdf") .defaultPage(1) .showMinimap(false) .enableSwipe(true) .onLoad(new OnLoadCompleteListener() { @Override public void loadComplete(int nbPages) { universalUtils.DismissProgressDialog(); } }) .load(); } } <file_sep>/app/src/main/java/com/patriot/ur254/services/Contacts.java package com.patriot.ur254.services; import android.app.IntentService; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.net.Uri; import android.provider.ContactsContract; import android.provider.MediaStore; import com.patriot.ur254.database.D2; import com.patriot.ur254.utils.G4; import com.patriot.ur254.utils.SharedPreference; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * Created by dennis on 18/06/17. */ public class Contacts extends IntentService { public SharedPreferences loggedinuser; public static String filename = "UserName"; private static final String DATABASE_TABLE_OkoaTime = "contacts"; public int dbtotal = 0, phonetotal = 0, a, counter, phonecount = 0; Boolean internetavailable = false; String url, encodedurl, mynumber = ""; String userphonenumber, key, IMEInumber, ccode; String phoneNumber = null; String negatephoneNumber = null; String serverphoneNumber = null; String slashedphoneNumber = null; String countrycode = "254"; SQLiteDatabase DB = null; public static String contactname, image_uri; String[] names; String line; String returnedcode; Boolean update = true; Boolean display = false; public Contacts() { super("SCnts"); } @SuppressWarnings("deprecation") @Override protected void onHandleIntent(Intent intent) { loggedinuser = getSharedPreferences(filename, 0); SharedPreference preferences = new SharedPreference(getApplicationContext()); preferences.putcontactSaved(true); DB = this.openOrCreateDatabase(com.patriot.ur254.database.DB.DATABASE_NAME, MODE_PRIVATE, null); Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String _ID = ContactsContract.Contacts._ID; String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME; String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER; Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID; String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER; ContentResolver contentResolver = getContentResolver(); Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null); // Loop for every contact in the phone if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String contact_id = cursor.getString(cursor.getColumnIndex(_ID)); // final String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)); int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))); if (hasPhoneNumber > 0) { // Query and loop for every phone number of the contact Cursor phoneCursor = contentResolver.query( PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null); //int phonecount2=phoneCursor.getCount(); while (phoneCursor.moveToNext()) { phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER)); //////////////////////////////////////////// phoneNumber = phoneNumber.replaceAll("[^\\d]", ""); if (phoneNumber.length() < 8) { phoneNumber = "usiweke kwa db"; } else if (phoneNumber.length() > 14) { phoneNumber = "usiweke kwa db"; } else { if (phoneNumber.length() > 7) { contactname = phoneCursor.getString(phoneCursor.getColumnIndex(DISPLAY_NAME)); image_uri = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); String firstLetter = String.valueOf(phoneNumber .charAt(0)); // 1. if +254 -> remove + if (firstLetter.equals("+")) { negatephoneNumber = phoneNumber.substring(1); slashedphoneNumber = negatephoneNumber; } // 2. if 0722 -> remove 0 add 254 else if (firstLetter.equals("0")) { negatephoneNumber = phoneNumber.substring(1); if (countrycode.equals(null) || countrycode.length() < 1) { countrycode = "254"; } slashedphoneNumber = countrycode + negatephoneNumber; } // 3. If is starts with countrycode do nothing else if (phoneNumber.startsWith(countrycode)) { slashedphoneNumber = phoneNumber; } else {//Ab phone starts with 861 dont add country code of mycountry slashedphoneNumber = phoneNumber; } serverphoneNumber = slashedphoneNumber; if (serverphoneNumber.equals(mynumber)) { //dont add user number } else { ++phonetotal; Cursor autocs = null; Cursor autocstotal = null; autocs = DB.rawQuery("SELECT * FROM " + DATABASE_TABLE_OkoaTime + " WHERE number=" + serverphoneNumber + "", null); autocstotal = DB.rawQuery("SELECT * FROM " + DATABASE_TABLE_OkoaTime + "", null); autocs.moveToFirst(); dbtotal = autocstotal.getCount(); if (autocs.getCount() > 0) { Bitmap userphoto = null; if (image_uri != null) { try { userphoto = MediaStore.Images.Media.getBitmap(Contacts.this.getContentResolver(), Uri.parse(image_uri)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); userphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); image_uri = G4.encodeToString(b, G4.DEFAULT); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } isNameNew(contactname, serverphoneNumber, image_uri); D2 updatename = new D2(this); updatename.NewImage(serverphoneNumber, image_uri); } } else { D2 contactinfo = new D2(this); contactinfo.checkforallContacts(contactname, serverphoneNumber, "0", "", "0", "0"); if (image_uri != null) { try { Bitmap userphoto = null; userphoto = MediaStore.Images.Media.getBitmap(Contacts.this.getContentResolver(), Uri.parse(image_uri)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); userphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); image_uri = G4.encodeToString(b, G4.DEFAULT); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } D2 updatename = new D2(this); updatename.NewImage(serverphoneNumber, image_uri); } } autocs.close(); autocstotal.close(); } }//end if phonenumber > 5 }//end if has nonnumeric } phoneCursor.close(); } } } } public void isNameNew(String name, String number, String image) { Cursor autocs5 = DB.rawQuery("SELECT * FROM " + DATABASE_TABLE_OkoaTime + " WHERE number=" + number + "", null); autocs5.moveToFirst(); if (autocs5.getCount() > 0) { String dbname = autocs5.getString(1); String dbnumber = autocs5.getString(2); if (name.equals(dbname)) { } else { String updatedname = dbname + ", " + name; a = 0; String dbname2 = dbname; while (dbname2.contains(",")) { a = dbname2.split(",").length - 1; dbname2 = dbname2.replace(",", ""); //dbname = dbname.replace(" ",""); } if (a > 0) { names = dbname.split(","); for (int i = 0; i <= a; i++) { String splitname1 = names[i]; String frstlettter = String.valueOf(splitname1.charAt(0)); // 1. if space -> remove if (frstlettter.equals(" ")) { splitname1 = splitname1.substring(1); } if (name.equalsIgnoreCase(splitname1) || name.equals("found1stname=dbname")) { name = "found1stname=dbname"; } else { //if checking last name and not similar add.. if (i == a) { String newdbname = dbname + ", " + name; //DB already contained more than one name //so needed to update after checkin all names separated by comma D2 updatename = new D2(this); updatename.NewName(dbnumber, newdbname); } } } } else { //DB doesnt contain more than one name update normally D2 updatename = new D2(this); updatename.NewName(dbnumber, updatedname); } } } autocs5.close(); } } <file_sep>/app/src/main/java/com/patriot/ur254/utils/UniversalUtils.java package com.patriot.ur254.utils; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.patriot.ur254.R; import com.patriot.ur254.activities.MainActivity; import com.patriot.ur254.activities.SplashActivity; import com.patriot.ur254.views.Btn; import com.patriot.ur254.views.Txt; import net.bohush.geometricprogressview.GeometricProgressView; import net.bohush.geometricprogressview.TYPE; import java.util.ArrayList; /** * Created by dennis on 15/07/17. */ public class UniversalUtils { private Activity activity; private AlertDialog dialogBuilder, dialogError, dialogLogout; private FirebaseAuth firebaseAuth; private SharedPreference sharedPreference; public UniversalUtils(Activity activity) { this.activity = activity; this.firebaseAuth = FirebaseAuth.getInstance(); this.sharedPreference = new SharedPreference(activity); } public void centerToolbarTitle(@NonNull final Toolbar toolbar) { final CharSequence title = toolbar.getTitle(); final ArrayList<View> outViews = new ArrayList<>(1); toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT); if (!outViews.isEmpty()) { final TextView titleView = (TextView) outViews.get(0); titleView.setGravity(Gravity.CENTER); titleView.setTypeface(Typeface.createFromAsset(activity.getAssets(), "fonts/SourceSansPro-Regular.ttf")); final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams(); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; toolbar.requestLayout(); } } public void ShowProgressDialog(String message) { dialogBuilder = new AlertDialog.Builder(activity).create(); final View dialogView = LayoutInflater.from(activity).inflate(R.layout.layout_progress_view, null); dialogBuilder.setView(dialogView); dialogBuilder.setCancelable(false); Txt txtMessage = (Txt) dialogView.findViewById(R.id.textViewProgressText); txtMessage.setText(message); GeometricProgressView progressView = (GeometricProgressView) dialogView.findViewById(R.id.progressView); progressView.setType(TYPE.KITE); progressView.setNumberOfAngles(6); progressView.setColor(activity.getResources().getColor(R.color.colorPrimary)); progressView.setDuration(1000); progressView.setFigurePadding(16); dialogBuilder.show(); } public void DismissProgressDialog() { if (dialogBuilder.isShowing()) { dialogBuilder.dismiss(); } } public void ShowErrorDialog(String message) { dialogError = new AlertDialog.Builder(activity).create(); final View dialogView = LayoutInflater.from(activity).inflate(R.layout.layout_error_dialog, null); dialogError.setView(dialogView); dialogError.setCancelable(false); Txt txtMessage = (Txt) dialogView.findViewById(R.id.textViewErrorMessage); txtMessage.setText(message); Btn btnTryAgain = (Btn) dialogView.findViewById(R.id.buttonErrorTryAgain); btnTryAgain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialogError.isShowing()) { dialogError.dismiss(); } } }); dialogError.show(); } public void ShowLogoutConfirmation(String message) { dialogLogout = new AlertDialog.Builder(activity).create(); final View dialogView = LayoutInflater.from(activity).inflate(R.layout.layout_logout_confirmation, null); dialogLogout.setView(dialogView); dialogLogout.setCancelable(false); Txt txtMessage = (Txt) dialogView.findViewById(R.id.textViewErrorMessage); txtMessage.setText(message); Btn btnNo = (Btn) dialogView.findViewById(R.id.buttonLogoutNo); btnNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialogLogout.isShowing()) { dialogLogout.dismiss(); } } }); Btn btnYes = (Btn) dialogView.findViewById(R.id.buttonLogoutYes); btnYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { firebaseAuth.signOut(); sharedPreference.putIsLoggedIn(false); Intent intent = new Intent(activity, SplashActivity.class); activity.startActivity(intent); activity.finish(); } }); dialogLogout.show(); } } <file_sep>/app/src/main/java/com/patriot/ur254/adapters/VideosAdapter.java package com.patriot.ur254.adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubeThumbnailLoader; import com.google.android.youtube.player.YouTubeThumbnailView; import com.patriot.ur254.R; import com.patriot.ur254.activities.CustomLightboxActivity; import com.patriot.ur254.utils.DeveloperKey; import java.util.HashMap; import java.util.Map; import youtubecontent.YouTubeContent; /** * Created by dennismwebia on 09/11/16. */ public class VideosAdapter extends RecyclerView.Adapter<VideosAdapter.VideosViewHolder> { private Context mContext; private Map<View, YouTubeThumbnailLoader> mLoaders; private View itemView; public class VideosViewHolder extends RecyclerView.ViewHolder { private YouTubeThumbnailView thumb; private TextView title; public VideosViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.textView_title); thumb = (YouTubeThumbnailView) view.findViewById(R.id.imageView_thumbnail); } } public VideosAdapter(Context context) { this.mContext = context; this.mLoaders = new HashMap<>(); } @Override public VideosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_videos, parent, false); return new VideosViewHolder(itemView); } @Override public void onBindViewHolder(final VideosViewHolder holder, final int position) { //The item at the current position final YouTubeContent.YouTubeVideo item = YouTubeContent.ITEMS.get(position); final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb); if (item != null) { //Set the title holder.title.setText(item.title); holder.thumb.initialize(DeveloperKey.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) { youTubeThumbnailLoader.setVideo(item.id); youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() { @Override public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) { youTubeThumbnailLoader.release(); } @Override public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) { final String errorMessage = errorReason.toString(); Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show(); } }); } @Override public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) { final String errorMessage = youTubeInitializationResult.toString(); Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show(); } }); } itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String DEVELOPER_KEY = DeveloperKey.DEVELOPER_KEY; final YouTubeContent.YouTubeVideo video = YouTubeContent.ITEMS.get(holder.getAdapterPosition()); //Opens in the the custom Lightbox activity final Intent lightboxIntent = new Intent(mContext, CustomLightboxActivity.class); lightboxIntent.putExtra(CustomLightboxActivity.KEY_VIDEO_ID, video.id); mContext.startActivity(lightboxIntent); } }); } @Override public int getItemCount() { return YouTubeContent.ITEMS.size(); } } <file_sep>/app/src/main/java/com/patriot/ur254/activities/TermsOfUseActivity.java package com.patriot.ur254.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.joanzapata.pdfview.PDFView; import com.joanzapata.pdfview.listener.OnLoadCompleteListener; import com.patriot.ur254.R; import com.patriot.ur254.utils.UniversalUtils; public class TermsOfUseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_terms_of_use); PDFView pdfView = (PDFView) findViewById(R.id.pdfview); initToolBar(); LoadPdfFile(pdfView); } private void initToolBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_terms_use); toolbar.setTitle("Terms Of Use"); toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_keyboard_arrow_left_white_24dp)); toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(TermsOfUseActivity.this, TimelineActivity.class); startActivity(intent); finish(); } }); setSupportActionBar(toolbar); } private void LoadPdfFile(PDFView pdfView) { final UniversalUtils universalUtils = new UniversalUtils(this); universalUtils.ShowProgressDialog("Loading..."); pdfView.fromAsset("terms_of_use.pdf") .defaultPage(1) .showMinimap(false) .enableSwipe(true) .onLoad(new OnLoadCompleteListener() { @Override public void loadComplete(int nbPages) { universalUtils.DismissProgressDialog(); } }) .load(); } } <file_sep>/app/src/main/java/com/patriot/ur254/fragments/VideosFragment.java package com.patriot.ur254.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.patriot.ur254.R; import com.patriot.ur254.adapters.VideosAdapter; /** * A simple {@link Fragment} subclass. */ public class VideosFragment extends Fragment { private View viewVideos; public VideosFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment viewVideos = inflater.inflate(R.layout.fragment_videos, container, false); //setVideoList(); setUpRecyclerView(); return viewVideos; } private void setUpRecyclerView() { RecyclerView recyclerView = (RecyclerView) viewVideos.findViewById(R.id.listView); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(new VideosAdapter(getActivity())); } }
a1e125432826682bb1c83a65684b2560a0a51870
[ "Java" ]
8
Java
MQ9Realper/ur254
458a0e21137058ad84c5e836e5af532949c83dea
11e6d6bcf2c052598076ae5889855fd551d01f46
refs/heads/master
<repo_name>Formakingshit/task<file_sep>/app/Models/Actor.js /** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */ const Model = use('Model'); class Actor extends Model { actorFilms() { return this.hasMany('App/Models/ActorFilm', 'id', 'actor_id').orderBy('id'); } } module.exports = Actor; <file_sep>/README.md # Task application ## Setup 1. git clone //клонируем данных репозиторий 2. npm install //устанавливаем нод-модули 3. setting .env file //переименовываем файл .env.example в .env или же создаем копию, заполняем HOST=127.0.0.1 // адрес хоста PORT=3333 // адрес порта NODE_ENV=development APP_URL=http://${HOST}:${PORT} CACHE_VIEWS=false APP_KEY= // установится после 5 шага DB_CONNECTION=sqlite // ваш нпм-пакет отвечающий за соединение с базой данных DB_HOST=127.0.0.1 DB_PORT=3306 // адрес порта вашей базы данных DB_USER=root // ваш логин(имя) в учетной записе субд DB_PASSWORD= // ваш пароль в учетной записе субд DB_DATABASE=adonis // название вашей базы данных (CREATE DATABASE adonis) SESSION_DRIVER=cookie HASH_DRIVER=bcrypt Я использовал PgSql из-за этого в package.json присутстует строка "pg": "^7.10.0" которая зависит от вашего окружения. 4. create db // создаем базу данных (CREATE DATABASE adonis) прописываем в DB_DATABASE 5. adonis migration:run // создаем таблицы в базе данных 6. adonis key:generate // создание APP_KEY 7. adonis serve --dev // запуск сервера ## Without user interface Example of queries in postman collection (Task.postman_collection.json) <file_sep>/database/migrations/1556075580326_actor_film_schema.js /** @type {import('@adonisjs/lucid/src/Schema')} */ const Schema = use('Schema'); class ActorFilmSchema extends Schema { up() { this.create('actor_films', (table) => { table.increments(); table.integer('film_id').unsigned().references('id').inTable('films') .onDelete('cascade'); table.integer('actor_id').unsigned().references('id').inTable('actors') .onDelete('cascade'); table.timestamps(); }); } down() { this.drop('actor_films'); } } module.exports = ActorFilmSchema; <file_sep>/app/Controllers/Http/Film/FilmController.js const Film = use('App/Models/Film'); const ActorFilm = use('App/Models/ActorFilm'); const Actor = use('App/Models/Actor'); class AdminController { async index({ request, response }) { const data = request.only([ 'search', 'order_by', 'sorted_by', 'page', ]); const query = Film.query().with('actorFilms.actors'); if (data.order_by) { query.orderBy(data.order_by, data.sorted_by); } if (data.search) { query.where('title', 'ilike', `%${data.search}%`); } const films = await query.paginate(request.input('page', 1), request.input('per_page')); return response.send(films, 'Users list'); } async show({ response, params }) { const film = await Film.findByOrFail('id', params.id); await film.load('actorFilms.actors'); return response.send({ film }, 'User successfully registered in system'); } async create({ request, response }) { const data = request.only([ 'title', 'year', 'format', ]); const film = await Film.create(data); const dataActors = request.only('actors'); // TODO (I made it at 5 a.m) for (let i = 0; i < dataActors.actors.length; i += 1) { dataActors.actors[i] = dataActors.actors[i].split(' '); const actor = ( await Actor.findOrCreate( { name: dataActors.actors[i][0], surname: dataActors.actors[i][1] }, { name: dataActors.actors[i][0], surname: dataActors.actors[i][1] }, ) ).toJSON(); const actorFilm = {}; actorFilm.film_id = film.id; actorFilm.actor_id = actor.id; await ActorFilm.create(actorFilm); } await film.load('actorFilms.actors'); return response.send({ film }, 'Fild successfully added to system'); } async delete({ response, params }) { const film = await Film.findByOrFail('id', params.id); film.delete(); return response.send('Film successfully deleted'); } } module.exports = AdminController; <file_sep>/app/Models/ActorFilm.js /** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */ const Model = use('Model'); class ActorFilm extends Model { actors() { return this.hasOne('App/Models/Actor', 'actor_id', 'id').orderBy('id'); } films() { return this.hasOne('App/Models/Film', 'film_id', 'id').orderBy('id'); } } module.exports = ActorFilm;
7e269adb5a0a6347d57ba7c47924ae2285bacbad
[ "JavaScript", "Markdown" ]
5
JavaScript
Formakingshit/task
9f3e7e2985847105fe59fc3ff38870b8c1f6b331
950986be77ac00146dba5188d8cbbd5f13407fd9
refs/heads/master
<repo_name>jiyangzhu/Pack-it<file_sep>/Pack-it_seeker/Pack-it_seeker/Config.h // // Config.h // Pack-it_seeker // // Created by Jiyang on 2/24/15. // Copyright (c) 2015 Jiyang. All rights reserved. // #ifndef Pack_it_seeker_Config_h #define Pack_it_seeker_Config_h #pragma mark - Network Request #define BASE_URL @"http://172.16.31.10:8000" //[NSString stringWithFormat:@"%@%@%@", BASE_URL, xxx, xxx]; // xxx == @"/abc"; #define CLIENT_ID @"d92e1ba0d9e5b8dbb15cb9ce329294c8e777ea5131f5f7aa9cd92d3188845217" #define SECRET @"<KEY>" #define ON_RESOURCE_BASE64_CODE_FOR_CLIENTID_AND_SECRET @"Basic ZDkyZTFiYTBkOWU1YjhkYmIxNWNiOWNlMzI5Mjk0YzhlNzc3ZWE1MTMxZjVmN2FhOWNkOTJkMzE4ODg0NTIxNzphYmE4MTFmOTNjNzJmNTgyODgyYjlmM2M3ZjAzYjAzYjdmZGUzNDc5NTY4ZjQzN2U0NTUyYTExZTVlNzVhNzQ3" #define REDIRECT_URL @"urn:ietf:wg:oauth:2.0:oob" #define FOR_ACCOUNT_TYPE @"" #define SCOPE @"public write admin" #define KEY_CHAIN_GROUP @"" #define AUTH_URL BASE_URL@"/oauth/authorize" #define TOKEN_URL BASE_URL@"/oauth/token" //用户注册 #define ON_RESOURCE_URL_FOR_TOKEN_WITHOUT_USER BASE_URL@"/oauth/token" #define ON_RESOURCE_URL_TO_POST_USER_TELPHONE_OR_EMAIL BASE_URL@"/me" #define ON_RESOURCE_URL_TO_PUT_NEW_PASSWORD BASE_URL@"/me" #define ON_RESOURCE_URL_TO_GET_PROBLEMS BASE_URL@"/problems" #define ON_RESOURCE_URL_TO_GET_PROBLEM_BY_ID BASE_URL@"/problems/%@" #define ON_RESOURCE_URL_TO_PUT_TAG_FOR_PROBLEM BASE_URL@"/problems/%@" #define ON_RESOURCE_URL_TO_POST_PROBLEM BASE_URL@"/problems" #define ON_RESOURCE_URL_TO_GET_TAGS BASE_URL@"/tags" #define ON_RESOURCE_URL_TO_PUT_TOKEN BASE_URL@"/profiles/notification_profile" #pragma mark - BaiduMap #define BaiduMap_Key @"Zq1APR1rIS7k94yOFNh5Nt57" #endif
bc6f7ff7d5093ddd31f5c83fcc58526924db1d6b
[ "C" ]
1
C
jiyangzhu/Pack-it
3b515b4f6dd2adcac32e6adfae2825fcccfec8a2
a45904c1fd1a4d604263b3c020df88e786163bf3
refs/heads/master
<file_sep>def create_an_empty_array my_array = [] end def create_an_array my_array = ["1","2","3","4"] end def add_element_to_end_of_array(array,element) array = ["array","element"] array << "arrays!" return array end def add_element_to_start_of_array(array, element) array = ["array","element"] array.unshift element end def remove_element_from_end_of_array(array) array = ["arrays!"] array.pop end def remove_element_from_start_of_array(array) array = ["wow"] array.shift end def retrieve_element_from_index(array, index_number) my_array = ["cat""cat_2"] my_array = [0] return "am" end def retrieve_first_element_from_array(array) array = ["array"] array = [0] return "wow" end def retrieve_last_element_from_array(array) array = "arrays!" end
d80dabc1b6410bf8326b01122f791ba9a812496a
[ "Ruby" ]
1
Ruby
sarisgar28/array-CRUD-lab-onl01-seng-pt-030220
d920d400e2d5c3ef85b8d24a66b8822f644fa434
7bcd3b112bfe9363091658041a840eb40f5c8c56
refs/heads/master
<file_sep>import React from "react"; import IconLink from "../components/IconLink"; import SkillsList from "../components/SkillsList"; import Projects from "../components/Projects"; export default function HomePage() { return ( <div> <section> <div className="pageTop image" style={{ textAlign: "center" }}> <div className="text"> <h1 className="myName" style={{ fontSize: "50px" }}> <NAME> </h1> <p>Energetic Software Developer</p> <IconLink IconName="LinkedIn" /> <IconLink IconName="GitHub" /> </div> </div> </section> <section> <div className="contentTitle"> <h1>About Me</h1> </div> <div className="skill-content"> <SkillsList SkillName="Languages" /> <SkillsList SkillName="Frameworks" /> <SkillsList SkillName="Databases" /> <SkillsList SkillName="Technologies" /> </div> </section> <section> <div className="contentTitle"> <h1>Contributed Projects</h1> </div> <div className="project-content"> <div data-aos="fade-right"> <Projects ProjectName="Project 1" /> </div> <div data-aos="fade-left"> <Projects ProjectName="Project 2" /> </div> <div data-aos="fade-right"> <Projects ProjectName="Project 3" /> </div> <div data-aos="fade-left"> <Projects ProjectName="Project 4" /> </div> <div data-aos="fade-right"> <Projects ProjectName="Project 5" /> </div> </div> </section> </div> ); } <file_sep>import React from "react"; import { HashRouter, Route } from "react-router-dom"; import HomePage from "./pages/Home"; import ContactPage from "./pages/Contact"; import Header from "./components/Header"; import Footer from "./components/Footer"; export default function App() { return ( <HashRouter> <Header /> <Route exact path="/" component={HomePage} /> <Route path="/contact" component={ContactPage} /> <Footer /> </HashRouter> ); } <file_sep>import React from "react"; import IconLink from "../components/IconLink"; export default function ContactPage() { return ( <div> <div className="parallax"> <div className="text text-contact"> <h1>Thank you for visiting!</h1> </div> </div> <div className="coverImage"> <div className="coverText"> <h1>Contact</h1> <p>I would love to hear from you!</p> <p>BC, Canada</p> <IconLink IconName="LinkedIn" /> <IconLink IconName="GitHub" /> </div> </div> <div className="parallax"></div> </div> ); } <file_sep>import React from "react"; function IconLink({ IconName }) { const IconData = [ { name: "LinkedIn", url: "https://www.linkedin.com/in/yurie-koga-977700188/", icon: "fab fa-linkedin icons" }, { name: "GitHub", url: "https://github.com/Yurie-Koga", icon: "fab fa-github icons" } ]; const data = IconData.find(v => v.name === String(IconName)); return ( <a href={data.url} target="_blank" rel="noopener noreferrer"> <i className={data.icon}></i> </a> ); } export default IconLink; <file_sep>import React from "react"; function SkillsList({ SkillName }) { const Skills = [ { category: "Languages", name: ["C#", "JavaScript", "Java", "Python", "VB.NET", "VBScript"] }, { category: "Frameworks", name: [".NET", "React", "Node.js", "Express.js", "Jest", "ASP.NET"] }, { category: "Databases", name: ["Oracle", "SQL Server", "SQLite3"] }, { category: "Technologies", name: [ "Visual Studio", "AWS (S3, Route 53)", "Cypress", "Oracle Enterprise Manager", "SQL Server Management Studio" ] } ]; const skill = Skills.find(v => v.category === String(SkillName)); let list = []; for (let i in skill.name) list.push(<p>{skill.name[i]}</p>); let randomNum = Math.floor(Math.random() * 9999); let imageUrl = "url(https://picsum.photos/300?random=" + randomNum + ")"; return ( <div className="flexBox-skillList" style={{ "--imageUrl": imageUrl }}> <div style={{ paddingTop: "10px" }}> <h1>{skill.category}</h1> {list} </div> </div> ); } export default SkillsList;
b1c7babef776ec7fdeed8241d45eb44ec8252ba9
[ "JavaScript" ]
5
JavaScript
Yurie-Koga/My-Website
e1d7fa4904626b4cde22b72a97879264aedea3cf
ed63df78a4d85e4425bc2767e1daa8c8b2d6753e
refs/heads/master
<file_sep>const scissors = document.querySelector('#scissors'); const rock = document.querySelector('#rock'); const paper = document.querySelector('#paper'); const reset = document.querySelector('#reset'); let cScore = document.querySelector('#cScore'); let pScore = document.querySelector('#pScore'); let textBoard = document.querySelector('#text'); let playerSelection; let compTally = 0; let playerTally = 0; let compChoice = new Array('Rock', 'Paper', 'Scissors'); let round = 0; function computerPlay(lst){ let randomitem = lst[Math.floor(Math.random()*lst.length)]; return randomitem; } rock.addEventListener('click', function(){ playerSelection = rock.value = 'rock'; let computerSelection = computerPlay(compChoice); cScore.innerHTML = compTally; pScore.innerHTML = playerTally; if (playerSelection == 'rock' && computerSelection == 'Paper'){ textBoard.textContent = 'You lose! Paper wraps up rock!'; compTally += 1; winner(); } else if(playerSelection == 'rock' && computerSelection == 'Scissors'){ textBoard.textContent = 'You win! Rock smashes scissors!'; playerTally += 1; winner(); } else { textBoard.textContent = 'It\'s a tie! '; winner(); } return playerTally, compTally; }); scissors.addEventListener('click', function(){ playerSelection = scissors.value = 'scissors'; let computerSelection = computerPlay(compChoice); cScore.innerHTML = compTally; pScore.innerHTML = playerTally; if (playerSelection == 'scissors' && computerSelection == 'Rock'){ compTally += 1; round += 1; console.log(round); textBoard.textContent = 'You lose! Rock smashes scissors! '; winner() } else if (playerSelection == 'scissors' && computerSelection == 'Paper'){ playerTally += 1; round += 1; console.log(round); textBoard.textContent = 'You win! Scissors cuts up paper! '; winner() } else { textBoard.textContent = 'It\'s a tie'; round += 1; console.log(round); winner(); } return playerTally, compTally; }); paper.addEventListener('click', function(){ playerSelection = paper.value = 'paper'; let computerSelection = computerPlay(compChoice); cScore.innerHTML = compTally; pScore.innerHTML = playerTally; if (playerSelection == 'paper' && computerSelection == 'Scissors'){ textBoard.textContent = 'You lose! Scissors cuts up paper! '; compTally += 1; winner(); } else if (playerSelection == 'paper' && computerSelection == 'Rock'){ textBoard.textContent = 'You win! Paper wraps up rock! '; playerTally += 1; winner(); } else { textBoard.textContent = 'It\'s a tie!'; winner(); } return playerTally, compTally; }); function winner(){ if (playerTally === 5){ textBoard.textContent = 'GAME OVER YOU WON!'; } else if (compTally === 5){ textBoard.textContent = 'GAME OVER YOU LOSE!'; } else{ return false; } } reset.addEventListener('click', function(){ cScore.textContent = '0'; pScore.textContent = '0'; compTally = 0; playerTally = 0; round = 0; textBoard.textContent = '...'; });
68fcd71e4354b9bcd22d0b1780e6c7adb0ab0187
[ "JavaScript" ]
1
JavaScript
irtiza-S/RPS
2d90bf63c82fe4b1f0eedac94d32222ef53aaa26
06c9fe67c80ab29d75c9df7690455d60748c7a71
refs/heads/master
<repo_name>aaramirez5/CP1<file_sep>/README.md # CP1 CP1 files <file_sep>/DrawingPicture.java /** * Write a description of class LoopDrawing here. * * @author <NAME> * @version 1/29 */ import javax.swing.*; import java.awt.*; import java.awt.geom.*; public class DrawingPicture extends JComponent { public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D)g; /******** Put your code here *********/ Ellipse2D.Double circle = new Ellipse2D.Double(200,200,200,200); g2.setColor(Color.black); g2.fill(circle); //--------------------------------------- Ellipse2D.Double circle2 = new Ellipse2D.Double(100,100,100,100); g2.setColor(Color.blue); g2.fill(circle2); //--------------------------------------- Ellipse2D.Double circle3 = new Ellipse2D.Double(100,100,100,100); g2.setColor(Color.white); g2.fill(circle); //--------------------------------------- // comment this out once you have finished drawGrid(g2); } public void drawGrid(Graphics g2){ g2.setColor(new Color(211, 211, 211)); // Draw vertical lines for(int x = 0; x < 1000; x += 50){ g2.drawLine(x, 0, x, 1000); g2.drawString("" + x, x, 10); } // Draw horizontal lines for(int y = 50; y < 1000; y += 50){ g2.drawLine(0, y, 1000, y); g2.drawString("" + y, 0, y); } } }<file_sep>/ArrayGamejava.java //<NAME> //<NAME> import java.util.Scanner; import java.lang.Math; import java.util.Random; public class ArrayGamejava { public static void main(String[] args) { String[][] game = { {"O", "O", "O", "O"}, {"O", "O", "O", "O"}, {"O", "O", "O", "O"}, {"O", "O", "O", "O"}, }; String O = "O"; String direction = ""; game[0][0] = ("x"); int winx = (int) (Math.random() * 3 + 1); int winy = (int) (Math.random() * 3 + 1); game[winx][winy] = ("*"); System.out.println("Welcome to the Array Game! Move your sprite \"x\" to the \"*\" to win."); for(int row = 0; row < game.length; row++){ for(int col = 0; col < game[0].length; col++){ System.out.print(game[row][col] + " "); } System.out.println(); } gamePlay(winx, winy, game); } ------------------------------------------------ public void KeyTyped (KeyEvent e) { int c = e.getKeyCode (); if (c==KeyEvent.VK_UP) { b.y--; } else if(c==KeyEvent.VK_DOWN) { b.y++; } else if(c==KeyEvent.VK_LEFT) { b.x--; } else if(c==KeyEvent.VK_RIGHT) { b.x++; } System.out.println (b.x); b.repaint (); } --------------------------------------------------- public static void gamePlay(int winx, int winy, String game[][]) { int x = 0; int y = 0; for ( ;(winx!=x||winy!=y); ) { Scanner kin = new Scanner(System.in); System.out.print("\nWhich direction would you like to move? "); String direction = kin.nextLine(); if (direction.equals("up")) { game[x][y] = "O"; x = x - 1; if (x < 0) { System.out.println("Invalid Input"); } else { game[x][y] = "x"; for(int row = 0; row < game.length; row++){ for(int col = 0; col < game[0].length; col++){ System.out.print(game[row][col] + " "); } System.out.println(); } } } if (direction.equals("down")) { game[x][y] = "O"; x = x + 1; if (x > 3) { System.out.println("Invalid Input"); } else { game[x][y] = "x"; for(int row = 0; row < game.length; row++){ for(int col = 0; col < game[0].length; col++){ System.out.print(game[row][col] + " "); } System.out.println(); } } } if (direction.equals("left")) { game[x][y] = "O"; y = y - 1; if (y < 0) { System.out.println("Invalid Input"); } else { game[x][y] = "x"; for(int row = 0; row < game.length; row++){ for(int col = 0; col < game[0].length; col++){ System.out.print(game[row][col] + " "); } System.out.println(); } } } if (direction.equals("right")) { game[x][y] = "O"; y = y + 1; if (y > 3) { System.out.println("Invalid Input"); } else { game[x][y] = "x"; for(int row = 0; row < game.length; row++){ for(int col = 0; col < game[0].length; col++){ System.out.print(game[row][col] + " "); } System.out.println(); } } } } System.out.println("\nCongrats, you have won!"); } }
03931d80c6b637528b3abc799df97f8a4bca8dba
[ "Markdown", "Java" ]
3
Markdown
aaramirez5/CP1
21e567853d500be732083c00adcacbd638141a6a
02f66bc544852b375444187dd0d885ad78b51136
refs/heads/master
<repo_name>shinyafro/Slash-Rules<file_sep>/gradle.properties pluginGroup=net.dirtcraft pluginId=slashrules pluginVersion=1.0-SNAPSHOT <file_sep>/src/main/java/net/dirtcraft/slashrules/Commands/ReloadExecutor.java package net.dirtcraft.slashrules.Commands; import net.dirtcraft.slashrules.Slashrules; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import java.util.Set; public class ReloadExecutor implements CommandExecutor { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { Set<CommandMapping> commands = Sponge.getCommandManager().getOwnedBy(Slashrules.getInstance()); for (CommandMapping command : commands){ Sponge.getCommandManager().removeMapping(command); } CommandRegistrar.registerCommands(); Slashrules.setRulesData(); return CommandResult.success(); } } <file_sep>/src/main/java/net/dirtcraft/slashrules/Commands/AddLineExecutor.java package net.dirtcraft.slashrules.Commands; import net.dirtcraft.slashrules.Data.RulesData; import net.dirtcraft.slashrules.Slashrules; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; public class AddLineExecutor implements CommandExecutor { @Override public CommandResult execute(CommandSource src, CommandContext args) { @SuppressWarnings("OptionalGetWithoutIsPresent") String text = args.<String>getOne("text").get(); RulesData rulesData = Slashrules.getRulesData(); rulesData.addLine(text); return CommandResult.success(); } } <file_sep>/src/main/java/net/dirtcraft/slashrules/Slashrules.java package net.dirtcraft.slashrules; import com.google.inject.Inject; import net.dirtcraft.slashrules.Commands.CommandRegistrar; import net.dirtcraft.slashrules.Data.RulesData; import org.slf4j.Logger; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.Listener; import org.spongepowered.api.plugin.Plugin; import java.io.File; @Plugin( id = "slashrules", name = "Slashrules", description = "a better rules plugin", url = "https://github.com/Dirt-Craft", authors = { "ShinyAfro" } ) public class Slashrules { @Inject @DefaultConfig(sharedRoot = false) private File configDir; @Inject private Logger logger; private static Slashrules instance; private static RulesData rulesData; @Listener public void onServerStart(GameStartedServerEvent event) { instance = this; setRulesData(); CommandRegistrar.registerCommands(); } public static void setRulesData(){ rulesData = new RulesData(); } public static Slashrules getInstance() { return instance; } public static RulesData getRulesData() { return rulesData; } public File getConfigDir(){ return configDir; } public Logger getLogger(){ return logger; } } <file_sep>/src/main/java/net/dirtcraft/slashrules/Config/Lang.java package net.dirtcraft.slashrules.Config; public class Lang { public static final String EXCEPTION_LINE_VALUE_PROTECTED = "This rule is protected."; public static final String EXCEPTION_LINE_VALUE_SMALL = "Value needs to be greater then 0."; public static final String EXCEPTION_LINE_VALUE_BIG = "There are not this many rules."; public static final String MAIN_DESCRIPTION = "Display the server rules."; public static final String OTHER_DESCRIPTION = "Show the server to someone."; public static final String HELP_DESCRIPTION = "Edit the server rules."; public static final String REM_LINE_DESCRIPTION = "Removes a rule from the rules."; public static final String ADD_LINE_DESCRIPTION = "Adds a rule to the rules."; public static final String SET_LINE_DESCRIPTION = "Updates the specified rule to the supplied text."; public static final String RELOAD_DESCRIPTION = "reloads the plugin."; } <file_sep>/src/main/java/net/dirtcraft/slashrules/Commands/CommandRegistrar.java package net.dirtcraft.slashrules.Commands; import net.dirtcraft.slashrules.Config.Lang; import net.dirtcraft.slashrules.Config.Perms; import net.dirtcraft.slashrules.Slashrules; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.text.Text; public class CommandRegistrar { public static void registerCommands(){ CommandSpec reload = CommandSpec.builder() .description(Text.of(Lang.RELOAD_DESCRIPTION)) .permission(Perms.RELOAD) .executor(new ReloadExecutor()) .build(); CommandSpec removeLine = CommandSpec.builder() .description(Text.of(Lang.REM_LINE_DESCRIPTION)) .permission(Perms.REM_LINE) .arguments(GenericArguments.integer(Text.of("line"))) .executor(new RemoveLineExecutor()) .build(); CommandSpec addLine = CommandSpec.builder() .description(Text.of(Lang.ADD_LINE_DESCRIPTION)) .permission(Perms.ADD_LINE) .arguments(GenericArguments.remainingJoinedStrings(Text.of("text"))) .executor(new AddLineExecutor()) .build(); CommandSpec setLine = CommandSpec.builder() .description(Text.of(Lang.SET_LINE_DESCRIPTION)) .permission(Perms.SET_LINE) .arguments( GenericArguments.integer(Text.of("line")), (GenericArguments.remainingJoinedStrings(Text.of("text")))) .executor(new SetLineExecutor()) .build(); CommandSpec help = CommandSpec.builder() .description(Text.of(Lang.HELP_DESCRIPTION)) .permission(Perms.HELP) .executor(new HelpExecutor()) .build(); CommandSpec other = CommandSpec.builder() .description(Text.of(Lang.OTHER_DESCRIPTION)) .permission(Perms.OTHER) .arguments( GenericArguments.player(Text.of("player")), GenericArguments.optional(GenericArguments.integer(Text.of("line")))) .executor(new OtherExecutor()) .build(); CommandSpec rules = CommandSpec.builder() .description(Text.of(Lang.MAIN_DESCRIPTION)) .executor(new RulesExecutor()) .permission(Perms.MAIN) .arguments(GenericArguments.optional(GenericArguments.integer(Text.of("line")))) .child(help, "help", "?") .child(setLine, "editline", "edit", "setline", "set") .child(addLine, "addline", "add") .child(removeLine, "removeline", "deleteline", "remove", "delete", "del", "rem") .child(other, "other") .child(reload, "reload") .build(); Sponge.getCommandManager().register(Slashrules.getInstance(), rules, "rules"); } }
820cf96a133ab15d0e499bea57d15ea7d9ffff23
[ "Java", "INI" ]
6
INI
shinyafro/Slash-Rules
928bcf9deebb54d510ec6b9edbc89009d7e522cf
de8bc704d357a63764db415c088fbb239225f5c9
refs/heads/master
<file_sep>// // GlobalUI.h // Moluren // // Created by tcl-macpro on 14-10-12. // Copyright (c) 2014年 com.teamdongqin. All rights reserved. // #ifndef Moluren_GlobalUI_h #define Moluren_GlobalUI_h //主窗口的宽、高 #define MainScreenWidth [UIScreen mainScreen].bounds.size.width #define MainScreenHeight [UIScreen mainScreen].bounds.size.height #define baseUrl @"http://android.client.moluren.net" #define statisticsUrl @"/json/statistics" #define tokenUrl @"/json/token" #define connectUrl @"/json/connect" #define disconnectUrl @"/json/disconnect" #define receiveUrl @"/json/hb" #define sendUrl @"/json/say" #define typingUrl @"/json/typing" #endif
9336dac38d51d289e6f9c3d2cdaf4b91775cc2be
[ "C" ]
1
C
TeamDongqin/Moluren
cfb2eb2ec83433a5c15a8227907835047432ae1c
314ce12609744128d99191bd2943f379acd73d37
refs/heads/master
<repo_name>EttoreHector/CarND-BehaviouralCloning__Assignment<file_sep>/model.py # -*- coding: utf-8 -*- """ Created on Sun Mar 19 09:33:55 2017 @author: ettore """ #import os import csv import cv2 import numpy as np import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout from keras.layers.convolutional import Convolution2D lines = [] # Read the file log containing references to the images and stearing angles with open('./recovery/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: lines.append(line) # Split the images into training (80%) and test set (20%) train_samples, validation_samples = train_test_split(lines, test_size=0.2) # Correction for steering angle for left and right camera images correction = 0.2 # This function provides the model with training examples in a way # that does not consume too much memory resources. def generator(lines, batch_size=32): num_train_samples = len(lines) while 1: # Loop forever so the generator never terminates for offset in range(0, num_train_samples, batch_size): batch_lines = lines[offset:offset+batch_size] # These lists will contain train samples and corresponding labels images = [] angles = [] for line in batch_lines: # I read all three images, Centre (0), Left (1) and Right (2) for i in range(0,3): # Read the steering angle and the image angle = float(line[3]) image_path = './recovery/IMG/' + line[i].split('\\')[-1] image = cv2.imread(image_path) # Flip the steering angle and the image angle_flipped = -angle image_flipped = np.fliplr(image) # Append the original image and its mirrored version # to the corresponding list images.append(image) images.append(image_flipped) # Adjust the steering angle depending whether the image # was captured by the left or right camera if i == 1: angle += correction angle_flipped -= correction if i == 2: angle -= correction angle_flipped += correction # Append the steering angle of the original and mirrored # images to the corresponding list angles.append(angle) angles.append(angle_flipped) # Transform the lists of images and angles to numpy array # and feed them to the model. X_train = np.array(images) y_train = np.array(angles) yield sklearn.utils.shuffle(X_train, y_train) # compile and train the model using the generator function train_generator = generator(train_samples, batch_size=32) validation_generator = generator(validation_samples, batch_size=32) # This function creates the model and load (if so specified) previously # fitted parameters from a similar trained model def create_model(weights_path=None): # This is the architecture of the model model = Sequential() model.add(Cropping2D(cropping=((60,20), (0,0)), input_shape=(160,320,3))) model.add(Lambda(lambda x: x/255.0 - 0.5)) model.add(Convolution2D(24, 9, 9, subsample=(2, 2), border_mode='valid')) model.add(Convolution2D(36, 7, 7, subsample=(2, 2), border_mode='valid', activation='relu')) model.add(Convolution2D(48, 5, 5, subsample=(2, 2), border_mode='valid')) model.add(Convolution2D(64, 3, 3, subsample=(1, 1), border_mode='valid', activation='relu')) model.add(Convolution2D(64, 3, 3, subsample=(1, 1), border_mode='valid')) model.add(Flatten()) model.add(Dense(1164)) model.add(Dropout(0.5)) model.add(Dense(100)) model.add(Dense(50)) model.add(Dense(1)) # Load the fitted parameters of a trained model with the same architecture if weights_path: model.load_weights(weights_path) # You can opt to freeze the weights of convolutional layers and # retrain only those of the fully connected layers. for i in range(len(model.layers)-6): model.layers[i].trainable = False return model # Create, compile and train the model model = create_model('./model.h5b') model.compile(loss = 'mse', optimizer = 'adam') history_object = model.fit_generator(train_generator, samples_per_epoch = len(train_samples)*6, validation_data= validation_generator, nb_val_samples= len(validation_samples)*6, nb_epoch=4) print(history_object.history.keys()) # S1ave the trained model model.save('model.h5r') ### plot the training and validation loss for each epoch plt.plot(history_object.history['loss']) plt.plot(history_object.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'], loc='upper right') plt.show()
53afa940959f1328dc524005f54284621528cd0d
[ "Python" ]
1
Python
EttoreHector/CarND-BehaviouralCloning__Assignment
825899eb7cc5d7c54e1b94e405ac1f945a4c361d
db134130030cbae8d88add88852603270d464f45
refs/heads/master
<repo_name>sceptre12/Cesium-React-Wrapper<file_sep>/src/cesiumShapes/circle.js import React, { memo, useEffect, useState } from "react"; import { Cartesian3, Color, HeightReference } from "cesium"; const Circle = memo(({ circle, viewer, isParentSelected }) => { const { positions, radius, color, outlineColor, outlineWidth, id, isVisible } = circle; const [isFirstRun, setIsFirstRun] = useState(true); // Runs on the first mount useEffect(() => { viewer.entities.add({ id, position: Cartesian3.fromDegrees(positions.longitude, positions.latitude), show: !!isParentSelected ? true : isVisible, ellipse: { heightReference: HeightReference.CLAMP_TO_GROUND, semiMinorAxis: radius, semiMajorAxis: radius, material: Color.fromCssColorString(color), outlineColor: Color.fromCssColorString(outlineColor), outlineWidth } }); setIsFirstRun(false); }, []); /** * Updates the cesium entity when any of the properties passed to the * dependency array is updated */ useEffect(() => { if (!!viewer && !isFirstRun) { let pointObj = viewer.entities.getById(id); pointObj.show = isVisible; pointObj.position = Cartesian3.fromDegrees( positions.longitude, positions.latitude ); pointObj.polygon.semiMinorAxis = radius; pointObj.polygon.semiMajorAxis = radius; pointObj.polygon.material = Color.fromCssColorString(color); pointObj.polygon.outlineWidth = outlineWidth; pointObj.polygon.outlineColor = Color.fromCssColorString(outlineColor); pointObj.polygon.hierarchy = Cartesian3.fromDegreesArray(positions); } }, [ positions, isVisible, radius, color, outlineWidth, outlineColor, id, viewer ]); // Clean up viewer on unmount useEffect( () => () => { viewer.entities.removeById(id); }, [] ); return null; }); export default Circle; <file_sep>/src/cesiumShapes/point.js import React, { memo, useEffect, useState, Fragment } from "react"; import { Cartesian3, HeightReference, Color } from "cesium"; import Polyline from "./polyline"; import Circle from "./circle"; const Point = memo( ({ point, polylines, circles, viewer, isParentSelected }) => { const { position, color, pixelSize, outlineColor, outlineWidth, id, isVisible } = point; const [isFirstRun, setIsFirstRun] = useState(true); // Runs on the first mount useEffect(() => { viewer.entities.add({ id, position: Cartesian3.fromDegrees(position.longitude, position.latitude), show: !!isParentSelected ? true : isVisible, point: { heightReference: HeightReference.RELATIVE_TO_GROUND, color: Color.fromCssColorString(color), pixelSize, outlineColor: Color.fromCssColorString(outlineColor), outlineWidth } }); setIsFirstRun(false); }, []); /** * Updates the cesium entity when any of the properties passed to the * dependency array is updated */ useEffect(() => { if (!!viewer && !isFirstRun) { let pointObj = viewer.entities.getById(id); pointObj.show = isVisible; pointObj.point.color = Color.fromCssColorString(color); pointObj.point.pixelSize = pixelSize; pointObj.point.outlineColor = Color.fromCssColorString(outlineColor); pointObj.point.outlineWidth = outlineWidth; pointObj.position = Cartesian3.fromDegrees( position.longitude, position.latitude ); } }, [ position, isVisible, color, pixelSize, outlineColor, outlineWidth, id, viewer ]); // Clean up viewer on unmount useEffect( () => () => { viewer.entities.removeById(id); }, [] ); return ( <Fragment> {!!polylines ? Object.keys(polylines).map((polylineUUID, index) => ( <Polyline key={index} polyline={polylines[polylineUUID]} viewer={viewer} isParentSelected={isParentSelected} /> )) : null} {!!circles ? Object.keys(circles).map((circleUUID, index) => ( <Circle key={index} circle={circles[circleUUID]} viewer={viewer} isParentSelected={isParentSelected} /> )) : null} </Fragment> ); } ); export default Point; <file_sep>/src/App.js import React, { Component, Fragment } from "react"; import { Viewer } from "cesium"; import CesiumManager from "./cesiumShapes/CesiumManager"; import { createRandomUUID, randomNumberFromInterval } from "./util/helper"; import "./App.css"; class App extends Component { constructor(props) { super(props); this.state = { systemState: { isInEditMode: false, editedEntity: {} }, viewer: undefined, data: { points: { uuid1: { id: "uuid1", name: "point1", isVisible: false, position: { latitude: 40.03883, longitude: -75.59777 }, color: "#A35A00", pixelSize: 10, outlineColor: "#eeeeee", outlineWidth: 4 } }, rectangles: { uuid7: { id: "uuid7", name: "rect1", isVisible: false, coordinates: [-110.0, 20.0, -80.0, 25.0], color: "#A35A00", outlineColor: "#eeeeee", outlineWidth: 4 } }, circles: { uuid9: { id: "uuid9", name: "circ1", isVisible: false, positions: { longitude: -103.0, latitude: 40.0 }, radius: 300000, color: "#A35A00", outlineColor: "#eeeeee", outlineWidth: 4 } }, polygons: { uuid8: { id: "uuid8", name: "polyg1", isVisible: false, positions: [ -115.0, 37.0, -115.0, 32.0, -107.0, 33.0, -102.0, 31.0, -102.0, 35.0 ], color: "#A35A00", outlineColor: "#eeeeee", outlineWidth: 4 } }, polylines: { uuid2: { id: "uuid2", name: "polyl1", isVisible: false, positions: [-75, 35, -125, 35], color: "#282c35", width: 5, points: { uuid3: { id: "uuid3", name: "point3", isVisible: false, position: { latitude: 35, longitude: -75 }, color: "#A35A00", pixelSize: 10, outlineColor: "#eeeeee", outlineWidth: 4 }, uuid4: { id: "uuid4", name: "point4", isVisible: false, position: { latitude: 35, longitude: -125 }, color: "#A35A00", pixelSize: 10, outlineColor: "#eeeeee", outlineWidth: 4 } } } } } }; } componentDidMount() { this.setState({ viewer: new Viewer("cesiumContainer") }); } componentWillUnmount() { const { viewer } = this.state; viewer.destroy(); } addPoint = () => { const uuid = createRandomUUID(); this.setState(state => ({ ...state, data: { ...state.data, points: { ...state.data.points, [uuid]: { id: uuid, position: { latitude: randomNumberFromInterval(20, 50), longitude: randomNumberFromInterval(-100, -50) }, color: "#A35A00", pixelSize: 10, outlineColor: "#eeeeee", outlineWidth: 4 } } } })); }; onColorChange = e => { const color = e.target.value; this.setState(state => ({ ...state, data: { ...state.data, points: { ...state.data.points, uuid1: { ...state.data.points.uuid1, color } } } })); }; onPixelSizeChange = e => { const pixelSize = parseInt(e.target.value); this.setState(state => ({ ...state, data: { ...state.data, points: { ...state.data.points, uuid1: { ...state.data.points.uuid1, pixelSize } } } })); }; onOutlineColorChange = e => { const outlineColor = e.target.value; this.setState(state => ({ ...state, data: { ...state.data, points: { ...state.data.points, uuid1: { ...state.data.points.uuid1, outlineColor } } } })); }; onOutlineWidthChange = e => { const outlineWidth = parseInt(e.target.value); this.setState(state => ({ ...state, data: { ...state.data, points: { ...state.data.points, uuid1: { ...state.data.points.uuid1, outlineWidth } } } })); }; /** * Creates an unordered list of the data * For each new data */ dataList = data => { return ( <ul> {Object.keys(data).map((dataObj, index) => { let component = null; switch (dataObj) { case "points": component = Object.keys(data[dataObj]).map((pointUUID, key) => { const pointComponent = data[dataObj][pointUUID]; let childComponent = []; if (pointComponent.circles) { childComponent.push(this.dataList(pointComponent.circles)); } else if (pointComponent.polylines) { childComponent.push(this.dataList(pointComponent.polylines)); } return ( <li> {pointComponent.name} {!!component ? component.map((Child, index) => <Child key={index} />) : null} </li> ); }); break; case "polygons": break; case "polylines": case "rectangles": case "circles": default: component = <li>{data[dataObj].name}</li>; break; } return <Fragment>{component}</Fragment>; })} </ul> ); }; render() { const { data, viewer } = this.state; return ( <div className="App"> <div id="cesiumContainer"> {!!viewer ? ( <CesiumManager viewer={viewer} points={data.points} polylines={data.polylines} rectangles={data.rectangles} polygons={data.polygons} circles={data.circles} /> ) : ( undefined )} </div> <div id="itemMenu"> <div id="dataList"></div> <div> <h3>Point Update</h3> <input type="color" placeholder="Color" value={data.points.uuid1.color} onChange={this.onColorChange} /> <input type="color" placeholder="Outline Color" value={data.points.uuid1.outlineColor} onChange={this.onOutlineColorChange} /> <input type="number" placeholder="Outline Width" value={data.points.uuid1.outlineWidth} onChange={this.onOutlineWidthChange} /> <input type="number" placeholder="Pixel Size" value={data.points.uuid1.pixelSize} onChange={this.onPixelSizeChange} /> </div> <button onClick={this.addPoint}>Add Point</button> </div> </div> ); } } export default App; <file_sep>/src/cesiumShapes/CesiumManager.js import React, { Component, Fragment } from "react"; import Point from "./point"; import Polyline from "./polyline"; import Polygon from "./polygon"; import RectangleContainer from "./rectangle"; import Circle from "./circle"; class CesiumManager extends Component { static getDerivedStateFromError(error) { console.error("derrived error state", error); } componentDidCatch(error, errorInfo) { console.log("Error", error); console.log("Error info", errorInfo); } render() { const { points, viewer, polylines, rectangles, polygons, circles } = this.props; return ( <Fragment> {!!points ? Object.keys(points).map((pointUUID, index) => ( <Point key={index} point={points[pointUUID]} viewer={viewer} /> )) : null} {!!polylines ? Object.keys(polylines).map((polylineUUID, index) => ( <Polyline key={index} points={polylines[polylineUUID].points} polyline={polylines[polylineUUID]} viewer={viewer} /> )) : null} {!!rectangles ? Object.keys(rectangles).map((rectangleUUID, index) => ( <RectangleContainer key={index} rectangle={rectangles[rectangleUUID]} viewer={viewer} /> )) : null} {!!polygons ? Object.keys(polygons).map((polygonUUID, index) => ( <Polygon key={index} polygon={polygons[polygonUUID]} viewer={viewer} /> )) : null} {!!circles ? Object.keys(circles).map((circleUUID, index) => ( <Circle key={index} circle={circles[circleUUID]} viewer={viewer} /> )) : null} </Fragment> ); } } export default CesiumManager; <file_sep>/craco.config.js const webpack = require("webpack"); const path = require("path"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const HtmlWebpackTagsPlugin = require("html-webpack-tags-plugin"); const cesiumSource = "node_modules/cesium/Source"; module.exports = { plugins: [ { plugin: { overrideCracoConfig: ({ cracoConfig }) => { // Always return the config object. return cracoConfig; }, overrideWebpackConfig: ({ webpackConfig, context: { env } }) => { const cesiumPath = "cesium"; webpackConfig.plugins.push( new CopyWebpackPlugin([ { from: path.join(cesiumSource, `../Build/CesiumUnminified`), to: cesiumPath } ]), new HtmlWebpackTagsPlugin({ append: false, tags: [ ...["cesium/Widgets/widgets.css"], path.join(cesiumPath, "Cesium.js") ] }), new webpack.DefinePlugin({ CESIUM_BASE_URL: JSON.stringify(cesiumPath) }) ); webpackConfig.externals = { ...webpackConfig.externals, Cesium: "Cesium" }; webpackConfig.amd = { ...webpackConfig.amd, toUrlUndefined: true // Enable webpack-friendly use of require in Cesium }; webpackConfig.node = { ...webpackConfig.node, fs: "empty" // resolve node module use of fs }; webpackConfig.output = { ...webpackConfig.output, sourcePrefix: "" // needed to compile multiline strings in cesium }; webpackConfig.resolve = { ...webpackConfig.resolve, alias: { ...webpackConfig.resolve.alias, Cesium: path.resolve(__dirname, cesiumSource) } }; webpackConfig.module = { ...webpackConfig.module, unknownContextCritical: false }; return webpackConfig; } } } ] }; <file_sep>/src/util/helper.js import { v4 as uuidv4 } from "uuid"; export const randomNumberFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); export const createRandomUUID = () => uuidv4();
c3396673316f5f3fe9a71ef04aefa5bd276480e7
[ "JavaScript" ]
6
JavaScript
sceptre12/Cesium-React-Wrapper
6cc60c58f982d20ad9a5bfd5b7d63fde1bd6f76d
c7a7ab53b800c81fc2bc0a32dc3a50230f6c6666
refs/heads/master
<file_sep><?php Route::get('/buku','PerpustakaanController@index'); Route::get('/buku/tambah','PerpustakaanController@tambah'); Route::post('/buku/action','PerpustakaanController@action'); Route::get('/buku/edit/{id}','PerpustakaanController@edit'); Route::post('/buku/update','PerpustakaanController@update'); Route::get('/buku/hapus/{id}','PerpustakaanController@hapus');
53c9dbd6fac9e5c62401106e87beb31651ed35fd
[ "PHP" ]
1
PHP
Rafiaqnanpebrian/learnlaravel2
0104007e005ebaa68ff75cbe30ccc123c52bbeb2
ee61618973064f9321ec053354741723e6152213
refs/heads/master
<repo_name>HoussemDjeghri/UAVs-for-Traffic-Monitoring-A-Sequential-Game-based-Computation-Offloading-Sharing-Approach<file_sep>/Visual Studio Simulation/DroneSimulation/ServeurEdge.h #pragma once class ServeurEdge { private: int id; long double frequence_cpu; public: ServeurEdge(int id, long double frequence_cpu); int getId(); long double getFrequenceCpu(); void setId(int id); void setFrequenceCpu(long double frequence_cpu); long double TCalculCPU(long double cycles_tache); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Utilite.h #pragma once class Utilite { private: long double u1; long double u2; long double u3; long double u4; long double u5; long double u6; long double u7; long double u8; long double gt; public: Utilite(); long double getU1(); long double getU2(); long double getU3(); long double getU4(); long double getU5(); long double getU6(); long double getU7(); long double getGt(); void setU1(long double u1); void setU2(long double u2); void setU3(long double u3); void setU4(long double u4); void setU5(long double u5); void setU6(long double u6); void setU7(long double u7); void setGt(long double gt); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Tache.cpp #include "Tache.h" int Tache::getId() { return id; } long double Tache::getCi() { return ci; } long double Tache::getDi() { return di; } long double Tache::getRsi() { return rsi; } int Tache::getSi() { return si; } void Tache::setCi(long double ci) { this->ci = ci; } void Tache::setDi(long double di) { this->di = di; } void Tache::setRsi(long double rsi) { this->rsi = rsi; } void Tache::setSi(int si) { this->si = si; } void Tache::setId(int id) { this->id = id; } Tache::Tache(int id, long double ci, long double di, long double rsi, int si) { this->id = id; this->ci = ci; this->di = di; this->rsi = rsi; this->si = si; }<file_sep>/Visual Studio Simulation/DroneSimulation/Drone.cpp #include "Drone.h" Drone::Drone(int id, long double energie, long double frequence_cpu) { this->id = id; this->energie = energie; this->frequence_cpu = frequence_cpu; } int Drone::getId() { return id; } long double Drone::getEngerie() { return energie; } long double Drone::getFrequenceCpu() { return frequence_cpu; } void Drone::setId(int id) { this->id = id; } void Drone::setEnergie(long double energie) { this->energie = energie; } void Drone::setFrequenceCpu(long double frequence_cpu) { this->frequence_cpu = frequence_cpu; } long double Drone::TCalculCPU(long double cycles_tache) { return cycles_tache / frequence_cpu; } long double Drone::ECalculCPU(long double cycles_tache) { return cycles_tache * 2; } void Drone::majEnergie(long double taux) { energie = energie - taux; }<file_sep>/Visual Studio Simulation/DroneSimulation/CoutEnvoie.h #pragma once class CoutEnvoie { private: long double ce1; long double ce2; long double ce3; long double ce4; long double ce5; long double ce6; long double ce7; long double gt; public: CoutEnvoie(); long double getCE1(); long double getCE2(); long double getCE3(); long double getCE4(); long double getCE5(); long double getCE6(); long double getCE7(); long double getGt(); void setCE1(long double ce1); void setCE2(long double ce2); void setCE3(long double ce3); void setCE4(long double ce4); void setCE5(long double ce5); void setCE6(long double ce6); void setCE7(long double ce7); void setGt(long double gt); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Vehicule.cpp #include "Vehicule.h" int Vehicule::getId() { return id; } long double Vehicule::getEngerie() { return energie; } long double Vehicule::getFrequenceCpu() { return frequence_cpu; } bool Vehicule::estElectrique() { return est_electrique; } void Vehicule::setId(int id) { this->id = id; } void Vehicule::setEnergie(long double energie) { this->energie = energie; } void Vehicule::setFrequenceCpu(long double frequence_cpu) { this->frequence_cpu = frequence_cpu; } void Vehicule::estElectrique(bool est_electrique) { this->est_electrique = est_electrique; } Vehicule::Vehicule(int id, long double frequence_cpu, bool est_electrique, long double energie) { this->id = id; this->energie = energie; this->frequence_cpu = frequence_cpu; this->est_electrique = est_electrique; } Vehicule::Vehicule(int id, long double frequence_cpu, bool est_electrique) { this->id = id; this->frequence_cpu = frequence_cpu; this->est_electrique = est_electrique; } long double Vehicule::TCalculCPU(long double cycles_tache) { return cycles_tache / frequence_cpu; } long double Vehicule::ECalculCPU(long double cycles_tache) { return cycles_tache * 6; } void Vehicule::majEnergie(long double taux) { energie = energie - taux; }<file_sep>/Visual Studio Simulation/DroneSimulation/MyForm.h #pragma once #include <fstream> #include <iostream> #include "Tache.h" #include "Drone.h" #include "Vehicule.h" #include "ServeurEdge.h" #include "Temps.h" #include "Energie.h" #include "CoutCalcul.h" #include "CoutEnvoie.h" #include "Utilite.h" #include <map> #include <string> #include <map> #include <iterator> #include <stdlib.h> #include <stdio.h> #include <vector> #include <iomanip> #include <cmath> #include <limits> #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace DroneSimulation { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: int E_PC5 = 800; // Energy units consumed by the PC5 interface int E_LTEA = 800; // Energy units consumed by the LTE-A / 5G interface int Debit_PC5 = 50.4; // transmission rate via PC5 interface in MB/s int Debit_LTEA = 50.4; // transmission rate via the LTE-A/5G interface in MB/s long double C_LTEA = 0.00000000001; // communication cost of 1 KB via the LTE / 5G interface long double C_Calcul_SE = 0.000000000001; // computation cost of 1 KB of data by the Edge server long double C_Calcul_VV = 0.0000000000005; // computation cost of 1 KB of data by the neighboring vehicle int QoL = 1; // quality of link [0,1] //Weighting factors long double α = 0.2; // Delay long double β = 0.2; // Energy long double δ = 0.2; // QoL long double γ = 0.2; //CommunicationCost long double λ = 0.2; //ComputationCost // Quality of link between nodes long double QoL_DP_DS = 1; long double QoL_DP_SE = 1; long double QoL_DP_VP = 1; long double QoL_VP_SE = 1; long double QoL_VP_VV = 1; // Range of size and cycles of data to be processed long double cycle_cpu_var = 100000; long double max_cycle_cpu_var = 1000000000; long double taille_resultat_var = 5; long double max_taille_resultat_var = 15; long double tailleDonnee_var = 1000; long double maxTaille_var = 200000; long double PD_cpu_frequency = 12000000000; long double NV_cpu_frequency = 36000000000; long double AV_cpu_frequency = 60000000000; long double ES_cpu_frequency = 600000000000; //Maximum and minimum value of the 5 decision-making factors, its values ​​are used for the normalization of these 5 disjoint factors, its values ​​are recalculated at the start of the simulation long double maxT = 0; long double minT = 20000000000000; long double maxE = 0; long double minE = 20000000000000; long double maxCE = 0; long double minCE = 20000000000000; long double maxCC = 0; long double minCC = 20000000000000; bool calculer_limites = true; // variable to indicate to the program if it has to recalculate the limits of the parameters (max-min), if the limits are to be set manually. private: System::Windows::Forms::Label^ label26; private: System::Windows::Forms::TextBox^ textBox23; bool envoi_et_calcul_gratuit = false; // variable to indicate that the sending and calculation of the data is free, it is used to avoid an arethmustic exception when the currency is set to 0 in case the cost is set to 0 public: MyForm(void) { InitializeComponent(); this->textBox1->Text = E_PC5.ToString(); this->textBox2->Text = C_LTEA.ToString(); this->textBox3->Text = C_Calcul_SE.ToString(); this->textBox4->Text = E_LTEA.ToString(); this->textBox5->Text = C_Calcul_VV.ToString(); this->textBox6->Text = Debit_PC5.ToString(); this->textBox7->Text = QoL.ToString(); this->textBox8->Text = Debit_LTEA.ToString(); this->textBox9->Text = α.ToString(); this->textBox10->Text = β.ToString(); this->textBox11->Text = γ.ToString(); this->textBox12->Text = cycle_cpu_var.ToString(); this->textBox13->Text = λ.ToString(); this->textBox14->Text = tailleDonnee_var.ToString(); this->textBox15->Text = max_cycle_cpu_var.ToString(); this->textBox16->Text = maxTaille_var.ToString(); this->textBox17->Text = taille_resultat_var.ToString(); this->textBox18->Text = max_taille_resultat_var.ToString(); this->textBox19->Text = PD_cpu_frequency.ToString(); this->textBox20->Text = AV_cpu_frequency.ToString(); this->textBox21->Text = NV_cpu_frequency.ToString(); this->textBox22->Text = ES_cpu_frequency.ToString(); this->textBox23->Text = δ.ToString(); } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::Panel^ panel1; protected: private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::TextBox^ textBox8; private: System::Windows::Forms::TextBox^ textBox7; private: System::Windows::Forms::TextBox^ textBox6; private: System::Windows::Forms::TextBox^ textBox5; private: System::Windows::Forms::TextBox^ textBox4; private: System::Windows::Forms::TextBox^ textBox3; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Label^ label9; private: System::Windows::Forms::Label^ label8; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Label^ label14; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::TextBox^ textBox13; private: System::Windows::Forms::Label^ label13; private: System::Windows::Forms::Label^ label12; private: System::Windows::Forms::Label^ label11; private: System::Windows::Forms::Label^ label10; private: System::Windows::Forms::TextBox^ textBox11; private: System::Windows::Forms::TextBox^ textBox10; private: System::Windows::Forms::TextBox^ textBox9; private: System::Windows::Forms::Panel^ panel3; private: System::Windows::Forms::Label^ label20; private: System::Windows::Forms::Label^ label19; private: System::Windows::Forms::TextBox^ textBox18; private: System::Windows::Forms::TextBox^ textBox17; private: System::Windows::Forms::Label^ label18; private: System::Windows::Forms::Label^ label17; private: System::Windows::Forms::Label^ label16; private: System::Windows::Forms::Label^ label15; private: System::Windows::Forms::TextBox^ textBox16; private: System::Windows::Forms::TextBox^ textBox15; private: System::Windows::Forms::TextBox^ textBox14; private: System::Windows::Forms::TextBox^ textBox12; private: System::Windows::Forms::Label^ label21; private: System::Windows::Forms::Panel^ panel4; private: System::Windows::Forms::Label^ label25; private: System::Windows::Forms::Label^ label24; private: System::Windows::Forms::Label^ label23; private: System::Windows::Forms::Label^ label22; private: System::Windows::Forms::TextBox^ textBox22; private: System::Windows::Forms::TextBox^ textBox21; private: System::Windows::Forms::TextBox^ textBox20; private: System::Windows::Forms::TextBox^ textBox19; private: System::Windows::Forms::Button^ button1; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->panel1 = (gcnew System::Windows::Forms::Panel()); this->label9 = (gcnew System::Windows::Forms::Label()); this->label8 = (gcnew System::Windows::Forms::Label()); this->label7 = (gcnew System::Windows::Forms::Label()); this->label6 = (gcnew System::Windows::Forms::Label()); this->label5 = (gcnew System::Windows::Forms::Label()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->textBox8 = (gcnew System::Windows::Forms::TextBox()); this->textBox7 = (gcnew System::Windows::Forms::TextBox()); this->textBox6 = (gcnew System::Windows::Forms::TextBox()); this->textBox5 = (gcnew System::Windows::Forms::TextBox()); this->textBox4 = (gcnew System::Windows::Forms::TextBox()); this->textBox3 = (gcnew System::Windows::Forms::TextBox()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->label14 = (gcnew System::Windows::Forms::Label()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->label26 = (gcnew System::Windows::Forms::Label()); this->textBox23 = (gcnew System::Windows::Forms::TextBox()); this->textBox13 = (gcnew System::Windows::Forms::TextBox()); this->label13 = (gcnew System::Windows::Forms::Label()); this->label12 = (gcnew System::Windows::Forms::Label()); this->label11 = (gcnew System::Windows::Forms::Label()); this->label10 = (gcnew System::Windows::Forms::Label()); this->textBox11 = (gcnew System::Windows::Forms::TextBox()); this->textBox10 = (gcnew System::Windows::Forms::TextBox()); this->textBox9 = (gcnew System::Windows::Forms::TextBox()); this->panel3 = (gcnew System::Windows::Forms::Panel()); this->label20 = (gcnew System::Windows::Forms::Label()); this->label19 = (gcnew System::Windows::Forms::Label()); this->textBox18 = (gcnew System::Windows::Forms::TextBox()); this->textBox17 = (gcnew System::Windows::Forms::TextBox()); this->label18 = (gcnew System::Windows::Forms::Label()); this->label17 = (gcnew System::Windows::Forms::Label()); this->label16 = (gcnew System::Windows::Forms::Label()); this->label15 = (gcnew System::Windows::Forms::Label()); this->textBox16 = (gcnew System::Windows::Forms::TextBox()); this->textBox15 = (gcnew System::Windows::Forms::TextBox()); this->textBox14 = (gcnew System::Windows::Forms::TextBox()); this->textBox12 = (gcnew System::Windows::Forms::TextBox()); this->label21 = (gcnew System::Windows::Forms::Label()); this->panel4 = (gcnew System::Windows::Forms::Panel()); this->label25 = (gcnew System::Windows::Forms::Label()); this->label24 = (gcnew System::Windows::Forms::Label()); this->label23 = (gcnew System::Windows::Forms::Label()); this->label22 = (gcnew System::Windows::Forms::Label()); this->textBox22 = (gcnew System::Windows::Forms::TextBox()); this->textBox21 = (gcnew System::Windows::Forms::TextBox()); this->textBox20 = (gcnew System::Windows::Forms::TextBox()); this->textBox19 = (gcnew System::Windows::Forms::TextBox()); this->button1 = (gcnew System::Windows::Forms::Button()); this->panel1->SuspendLayout(); this->panel2->SuspendLayout(); this->panel3->SuspendLayout(); this->panel4->SuspendLayout(); this->SuspendLayout(); // // panel1 // this->panel1->BackColor = System::Drawing::SystemColors::ControlLight; this->panel1->Controls->Add(this->label9); this->panel1->Controls->Add(this->label8); this->panel1->Controls->Add(this->label7); this->panel1->Controls->Add(this->label6); this->panel1->Controls->Add(this->label5); this->panel1->Controls->Add(this->label4); this->panel1->Controls->Add(this->label3); this->panel1->Controls->Add(this->label2); this->panel1->Controls->Add(this->textBox8); this->panel1->Controls->Add(this->textBox7); this->panel1->Controls->Add(this->textBox6); this->panel1->Controls->Add(this->textBox5); this->panel1->Controls->Add(this->textBox4); this->panel1->Controls->Add(this->textBox3); this->panel1->Controls->Add(this->textBox2); this->panel1->Controls->Add(this->textBox1); this->panel1->Location = System::Drawing::Point(12, 549); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(728, 159); this->panel1->TabIndex = 0; // // label9 // this->label9->AutoSize = true; this->label9->BackColor = System::Drawing::Color::Transparent; this->label9->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label9->Location = System::Drawing::Point(462, 125); this->label9->Name = L"label9"; this->label9->Size = System::Drawing::Size(121, 16); this->label9->TabIndex = 16; this->label9->Text = L"Quality Of Link [0,1]*:"; // // label8 // this->label8->AutoSize = true; this->label8->BackColor = System::Drawing::Color::Transparent; this->label8->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label8->Location = System::Drawing::Point(372, 90); this->label8->Name = L"label8"; this->label8->Size = System::Drawing::Size(211, 16); this->label8->TabIndex = 15; this->label8->Text = L"Computation Cost Nearby Vehicule*:"; // // label7 // this->label7->AutoSize = true; this->label7->BackColor = System::Drawing::Color::Transparent; this->label7->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label7->Location = System::Drawing::Point(392, 53); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(191, 16); this->label7->TabIndex = 14; this->label7->Text = L"Computation Cost Edge Server*:"; // // label6 // this->label6->AutoSize = true; this->label6->BackColor = System::Drawing::Color::Transparent; this->label6->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label6->Location = System::Drawing::Point(413, 16); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(170, 16); this->label6->TabIndex = 13; this->label6->Text = L"Communication Cost LTE-A*:"; // // label5 // this->label5->AutoSize = true; this->label5->BackColor = System::Drawing::Color::Transparent; this->label5->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label5->Location = System::Drawing::Point(83, 124); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(119, 16); this->label5->TabIndex = 12; this->label5->Text = L"LTE-A Throughput*:"; // // label4 // this->label4->AutoSize = true; this->label4->BackColor = System::Drawing::Color::Transparent; this->label4->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label4->Location = System::Drawing::Point(94, 89); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(107, 16); this->label4->TabIndex = 11; this->label4->Text = L"PC5 Throughput*:"; // // label3 // this->label3->AutoSize = true; this->label3->BackColor = System::Drawing::Color::Transparent; this->label3->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label3->Location = System::Drawing::Point(30, 51); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(172, 16); this->label3->TabIndex = 10; this->label3->Text = L"LTE-A Energy Consumption*:"; // // label2 // this->label2->AutoSize = true; this->label2->BackColor = System::Drawing::Color::Transparent; this->label2->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label2->Location = System::Drawing::Point(42, 16); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(160, 16); this->label2->TabIndex = 9; this->label2->Text = L"PC5 Energy Consumption*:"; // // textBox8 // this->textBox8->Location = System::Drawing::Point(202, 123); this->textBox8->Name = L"textBox8"; this->textBox8->Size = System::Drawing::Size(126, 20); this->textBox8->TabIndex = 8; // // textBox7 // this->textBox7->Location = System::Drawing::Point(583, 124); this->textBox7->Name = L"textBox7"; this->textBox7->Size = System::Drawing::Size(126, 20); this->textBox7->TabIndex = 7; // // textBox6 // this->textBox6->Location = System::Drawing::Point(202, 88); this->textBox6->Name = L"textBox6"; this->textBox6->Size = System::Drawing::Size(126, 20); this->textBox6->TabIndex = 6; // // textBox5 // this->textBox5->Location = System::Drawing::Point(583, 88); this->textBox5->Name = L"textBox5"; this->textBox5->Size = System::Drawing::Size(126, 20); this->textBox5->TabIndex = 5; // // textBox4 // this->textBox4->Location = System::Drawing::Point(202, 50); this->textBox4->Name = L"textBox4"; this->textBox4->Size = System::Drawing::Size(126, 20); this->textBox4->TabIndex = 4; // // textBox3 // this->textBox3->Location = System::Drawing::Point(583, 52); this->textBox3->Name = L"textBox3"; this->textBox3->Size = System::Drawing::Size(126, 20); this->textBox3->TabIndex = 3; // // textBox2 // this->textBox2->Location = System::Drawing::Point(583, 15); this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(126, 20); this->textBox2->TabIndex = 2; // // textBox1 // this->textBox1->Location = System::Drawing::Point(202, 16); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(126, 20); this->textBox1->TabIndex = 1; // // label1 // this->label1->AutoSize = true; this->label1->BackColor = System::Drawing::Color::Transparent; this->label1->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label1->Location = System::Drawing::Point(15, 171); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(226, 25); this->label1->TabIndex = 0; this->label1->Text = L"Simulation Parameters"; this->label1->TextAlign = System::Drawing::ContentAlignment::TopCenter; // // label14 // this->label14->AutoSize = true; this->label14->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label14->Location = System::Drawing::Point(18, 197); this->label14->Name = L"label14"; this->label14->Size = System::Drawing::Size(328, 16); this->label14->TabIndex = 27; this->label14->Text = L"Simulation parameters can be kept by default or modified"; // // panel2 // this->panel2->BackColor = System::Drawing::SystemColors::ControlLight; this->panel2->Controls->Add(this->label26); this->panel2->Controls->Add(this->textBox23); this->panel2->Controls->Add(this->textBox13); this->panel2->Controls->Add(this->label13); this->panel2->Controls->Add(this->label12); this->panel2->Controls->Add(this->label11); this->panel2->Controls->Add(this->label10); this->panel2->Controls->Add(this->textBox11); this->panel2->Controls->Add(this->textBox10); this->panel2->Controls->Add(this->textBox9); this->panel2->Location = System::Drawing::Point(12, 426); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(728, 117); this->panel2->TabIndex = 28; // // label26 // this->label26->AutoSize = true; this->label26->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label26->Location = System::Drawing::Point(3, 76); this->label26->Name = L"label26"; this->label26->Size = System::Drawing::Size(199, 16); this->label26->TabIndex = 36; this->label26->Text = L"Qualtiy Of Link Weighting factor(δ):"; // // textBox23 // this->textBox23->Location = System::Drawing::Point(202, 75); this->textBox23->Name = L"textBox23"; this->textBox23->Size = System::Drawing::Size(126, 20); this->textBox23->TabIndex = 35; // // textBox13 // this->textBox13->Location = System::Drawing::Point(583, 45); this->textBox13->Name = L"textBox13"; this->textBox13->Size = System::Drawing::Size(126, 20); this->textBox13->TabIndex = 34; // // label13 // this->label13->AutoSize = true; this->label13->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label13->Location = System::Drawing::Point(339, 46); this->label13->Name = L"label13"; this->label13->Size = System::Drawing::Size(243, 16); this->label13->TabIndex = 33; this->label13->Text = L"Communication Cost weighting factor (λ)*:"; // // label12 // this->label12->AutoSize = true; this->label12->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label12->Location = System::Drawing::Point(339, 16); this->label12->Name = L"label12"; this->label12->Size = System::Drawing::Size(243, 16); this->label12->TabIndex = 32; this->label12->Text = L"Communication Cost weighting factor (γ)*:"; // // label11 // this->label11->AutoSize = true; this->label11->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label11->Location = System::Drawing::Point(32, 45); this->label11->Name = L"label11"; this->label11->Size = System::Drawing::Size(168, 16); this->label11->TabIndex = 31; this->label11->Text = L"Energy weighting factor (β)*:"; // // label10 // this->label10->AutoSize = true; this->label10->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label10->Location = System::Drawing::Point(40, 15); this->label10->Name = L"label10"; this->label10->Size = System::Drawing::Size(160, 16); this->label10->TabIndex = 30; this->label10->Text = L"Delay weighting factor (α)*:"; // // textBox11 // this->textBox11->Location = System::Drawing::Point(583, 14); this->textBox11->Name = L"textBox11"; this->textBox11->Size = System::Drawing::Size(126, 20); this->textBox11->TabIndex = 29; // // textBox10 // this->textBox10->Location = System::Drawing::Point(202, 44); this->textBox10->Name = L"textBox10"; this->textBox10->Size = System::Drawing::Size(126, 20); this->textBox10->TabIndex = 28; // // textBox9 // this->textBox9->Location = System::Drawing::Point(202, 15); this->textBox9->Name = L"textBox9"; this->textBox9->Size = System::Drawing::Size(126, 20); this->textBox9->TabIndex = 27; // // panel3 // this->panel3->BackColor = System::Drawing::SystemColors::ControlLight; this->panel3->Controls->Add(this->label20); this->panel3->Controls->Add(this->label19); this->panel3->Controls->Add(this->textBox18); this->panel3->Controls->Add(this->textBox17); this->panel3->Controls->Add(this->label18); this->panel3->Controls->Add(this->label17); this->panel3->Controls->Add(this->label16); this->panel3->Controls->Add(this->label15); this->panel3->Controls->Add(this->textBox16); this->panel3->Controls->Add(this->textBox15); this->panel3->Controls->Add(this->textBox14); this->panel3->Controls->Add(this->textBox12); this->panel3->Location = System::Drawing::Point(12, 311); this->panel3->Name = L"panel3"; this->panel3->Size = System::Drawing::Size(728, 109); this->panel3->TabIndex = 29; // // label20 // this->label20->AutoSize = true; this->label20->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label20->Location = System::Drawing::Point(529, 76); this->label20->Name = L"label20"; this->label20->Size = System::Drawing::Size(55, 16); this->label20->TabIndex = 11; this->label20->Text = L"max Ri*:"; // // label19 // this->label19->AutoSize = true; this->label19->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label19->Location = System::Drawing::Point(151, 75); this->label19->Name = L"label19"; this->label19->Size = System::Drawing::Size(51, 16); this->label19->TabIndex = 10; this->label19->Text = L"min Ri*:"; // // textBox18 // this->textBox18->Location = System::Drawing::Point(584, 76); this->textBox18->Name = L"textBox18"; this->textBox18->Size = System::Drawing::Size(126, 20); this->textBox18->TabIndex = 9; // // textBox17 // this->textBox17->Location = System::Drawing::Point(203, 74); this->textBox17->Name = L"textBox17"; this->textBox17->Size = System::Drawing::Size(126, 20); this->textBox17->TabIndex = 8; // // label18 // this->label18->AutoSize = true; this->label18->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label18->Location = System::Drawing::Point(527, 47); this->label18->Name = L"label18"; this->label18->Size = System::Drawing::Size(56, 16); this->label18->TabIndex = 7; this->label18->Text = L"max Di*:"; // // label17 // this->label17->AutoSize = true; this->label17->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label17->Location = System::Drawing::Point(529, 16); this->label17->Name = L"label17"; this->label17->Size = System::Drawing::Size(55, 16); this->label17->TabIndex = 6; this->label17->Text = L"max Ci*:"; // // label16 // this->label16->AutoSize = true; this->label16->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label16->Location = System::Drawing::Point(151, 45); this->label16->Name = L"label16"; this->label16->Size = System::Drawing::Size(52, 16); this->label16->TabIndex = 5; this->label16->Text = L"min Di*:"; // // label15 // this->label15->AutoSize = true; this->label15->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label15->Location = System::Drawing::Point(152, 14); this->label15->Name = L"label15"; this->label15->Size = System::Drawing::Size(51, 16); this->label15->TabIndex = 4; this->label15->Text = L"min Ci*:"; // // textBox16 // this->textBox16->Location = System::Drawing::Point(584, 46); this->textBox16->Name = L"textBox16"; this->textBox16->Size = System::Drawing::Size(126, 20); this->textBox16->TabIndex = 3; // // textBox15 // this->textBox15->Location = System::Drawing::Point(584, 16); this->textBox15->Name = L"textBox15"; this->textBox15->Size = System::Drawing::Size(126, 20); this->textBox15->TabIndex = 2; // // textBox14 // this->textBox14->Location = System::Drawing::Point(203, 45); this->textBox14->Name = L"textBox14"; this->textBox14->Size = System::Drawing::Size(126, 20); this->textBox14->TabIndex = 1; // // textBox12 // this->textBox12->Location = System::Drawing::Point(203, 14); this->textBox12->Name = L"textBox12"; this->textBox12->Size = System::Drawing::Size(126, 20); this->textBox12->TabIndex = 0; // // label21 // this->label21->AutoSize = true; this->label21->Font = (gcnew System::Drawing::Font(L"Century Gothic", 20.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label21->Location = System::Drawing::Point(56, 9); this->label21->Name = L"label21"; this->label21->Size = System::Drawing::Size(644, 99); this->label21->TabIndex = 30; this->label21->Text = L"UAVs for Traffic Monitoring : A Sequential \r\nGame based Computation Offloading/ S" L"haring \r\nApproach - Algorithm Simulation\r\n"; this->label21->TextAlign = System::Drawing::ContentAlignment::TopCenter; // // panel4 // this->panel4->BackColor = System::Drawing::SystemColors::ControlLight; this->panel4->Controls->Add(this->label25); this->panel4->Controls->Add(this->label24); this->panel4->Controls->Add(this->label23); this->panel4->Controls->Add(this->label22); this->panel4->Controls->Add(this->textBox22); this->panel4->Controls->Add(this->textBox21); this->panel4->Controls->Add(this->textBox20); this->panel4->Controls->Add(this->textBox19); this->panel4->ForeColor = System::Drawing::SystemColors::ControlText; this->panel4->Location = System::Drawing::Point(12, 220); this->panel4->Name = L"panel4"; this->panel4->Size = System::Drawing::Size(728, 85); this->panel4->TabIndex = 31; // // label25 // this->label25->AutoSize = true; this->label25->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label25->Location = System::Drawing::Point(403, 55); this->label25->Name = L"label25"; this->label25->Size = System::Drawing::Size(178, 16); this->label25->TabIndex = 7; this->label25->Text = L"Edge Server CPU Frequency*:"; // // label24 // this->label24->AutoSize = true; this->label24->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label24->Location = System::Drawing::Point(382, 20); this->label24->Name = L"label24"; this->label24->Size = System::Drawing::Size(198, 16); this->label24->TabIndex = 6; this->label24->Text = L"Nearby Vehicule CPU Frequency*:"; // // label23 // this->label23->AutoSize = true; this->label23->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label23->Location = System::Drawing::Point(11, 53); this->label23->Name = L"label23"; this->label23->Size = System::Drawing::Size(189, 16); this->label23->TabIndex = 5; this->label23->Text = L"Authority CPU Frequency (Ghz)*:"; // // label22 // this->label22->AutoSize = true; this->label22->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label22->Location = System::Drawing::Point(40, 15); this->label22->Name = L"label22"; this->label22->Size = System::Drawing::Size(161, 16); this->label22->TabIndex = 4; this->label22->Text = L"UAV CPU Frequency (Ghz)*:"; // // textBox22 // this->textBox22->Location = System::Drawing::Point(581, 53); this->textBox22->Name = L"textBox22"; this->textBox22->Size = System::Drawing::Size(126, 20); this->textBox22->TabIndex = 3; // // textBox21 // this->textBox21->Location = System::Drawing::Point(581, 19); this->textBox21->Name = L"textBox21"; this->textBox21->Size = System::Drawing::Size(126, 20); this->textBox21->TabIndex = 2; // // textBox20 // this->textBox20->Location = System::Drawing::Point(201, 53); this->textBox20->Name = L"textBox20"; this->textBox20->Size = System::Drawing::Size(125, 20); this->textBox20->TabIndex = 1; // // textBox19 // this->textBox19->Location = System::Drawing::Point(201, 15); this->textBox19->Name = L"textBox19"; this->textBox19->Size = System::Drawing::Size(126, 20); this->textBox19->TabIndex = 0; // // button1 // this->button1->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button1->Location = System::Drawing::Point(305, 727); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(141, 39); this->button1->TabIndex = 32; this->button1->Text = L"Launch Simulation"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click); // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(753, 787); this->Controls->Add(this->button1); this->Controls->Add(this->panel4); this->Controls->Add(this->label21); this->Controls->Add(this->panel3); this->Controls->Add(this->panel2); this->Controls->Add(this->label14); this->Controls->Add(this->panel1); this->Controls->Add(this->label1); this->MaximizeBox = false; this->MaximumSize = System::Drawing::Size(769, 826); this->MinimizeBox = false; this->MinimumSize = System::Drawing::Size(769, 826); this->Name = L"MyForm"; this->ShowIcon = false; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen; this->Text = L"UAVs for Traffic Monitoring : Algorithm Simulation"; this->panel1->ResumeLayout(false); this->panel1->PerformLayout(); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); this->panel3->ResumeLayout(false); this->panel3->PerformLayout(); this->panel4->ResumeLayout(false); this->panel4->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { E_PC5 = Double::Parse(this->textBox1->Text); C_LTEA= Double::Parse(this->textBox2->Text ); C_Calcul_SE =Double::Parse(this->textBox3->Text); E_LTEA =Double::Parse(this->textBox4->Text); C_Calcul_VV =Double::Parse(this->textBox5->Text); Debit_PC5 =Double::Parse(this->textBox6->Text); QoL =Double::Parse(this->textBox7->Text); Debit_LTEA =Double::Parse(this->textBox8->Text); α =Double::Parse(this->textBox9->Text); β =Double::Parse(this->textBox10->Text); γ =Double::Parse(this->textBox11->Text); cycle_cpu_var =Double::Parse(this->textBox12->Text); λ =Double::Parse(this->textBox13->Text); tailleDonnee_var =Double::Parse(this->textBox14->Text); max_cycle_cpu_var =Double::Parse(this->textBox15->Text); maxTaille_var =Double::Parse(this->textBox16->Text); taille_resultat_var =Double::Parse(this->textBox17->Text); max_taille_resultat_var =Double::Parse(this->textBox18->Text); PD_cpu_frequency =Double::Parse(this->textBox19->Text); AV_cpu_frequency =Double::Parse(this->textBox20->Text); NV_cpu_frequency =Double::Parse(this->textBox21->Text); ES_cpu_frequency =Double::Parse(this->textBox22->Text); δ =Double::Parse(this->textBox23->Text); std::vector <Tache> taches; // matrix containing the tasks to be calculated with the decision to be taken for each task std::vector <Drone> drones_secondaires; Drone drone_pricipal(1, 100, PD_cpu_frequency); Vehicule vehicule_police(1, AV_cpu_frequency, 0); Vehicule vehicule_voisin(2, NV_cpu_frequency, 0); ServeurEdge serveur_edge(1, ES_cpu_frequency); std::map < int, long double > utilites_Local; // matrix for storing the local computation utility in the main UAV for each task std::map < int, long double > utilites_Delestage_SE;// matrix to store the utility of the load shedding of the computation to the ES for each task std::map < int, long double > utilites_Partage_DS;// matrix to store the utility of sharing with SD for each task std::map < int, long double > utilites_Local_VP;// Matrix for storing the usefulness of local calculation in the authority vehicle for each task std::map < int, long double > utilites_VP_Delestage_SE;// matrice pour stocker l'utilité du délestage vers SE par le VP pour chaque tache std::map < int, long double > utilites_VP_Partage_VV_accpt;// matrix to store the utility of load shedding to ES by the AV for each task std::map < int, long double > utilites_VP_Partage_VV_refu;// Matrix for storing the usefulness of the refusal of the calculation by the nearby vehicles for each task for (int j = 2; j < 4; j++) { Drone drone_secondaire(j, 100, PD_cpu_frequency); drones_secondaires.push_back(drone_secondaire); } if (calculer_limites) { calibrer_limites(drone_pricipal, serveur_edge, vehicule_police, vehicule_voisin, drones_secondaires,taches, utilites_Local, utilites_Delestage_SE, utilites_Partage_DS, utilites_Local_VP, utilites_VP_Delestage_SE, utilites_VP_Partage_VV_accpt, utilites_VP_Partage_VV_refu); calculer_limites = false; } std::cout << "///////////////////////////////////////////////SIMULATION START/////////////////////////////////////////////////////"; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SIMULATION n°1 = calculation of the global utility, the energy, and the delay for each strategy in relation to the change of the CPU Cycles of the tasks ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Assignment of intervals of data size and complexity long double cycle_cpu = cycle_cpu_var; long double max_cycle_cpu = max_cycle_cpu_var; long double taille_resultat = taille_resultat_var; long double tailleDonnee = tailleDonnee_var; long double maxTaille = maxTaille_var; int iter = 1; // matrix to store the usefulness of each strategy+GT according to the CPU cycle change [CPU_Cycle, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Utilite> utilites_CPU; // matrix to store the energy of each strategy+GT according to the CPU cycle change [CPU_Cycle, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Energie> energies_CPU; // matrix to store the time of each strategy+GT according to the CPU cycle change [CPU_Cycle, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Temps> temps_CPU; // matrix to store the dispatch cost of each strategy+GT according to the CPU cycle change [CPU_Cycle, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, CoutEnvoie> coutEnvoi_CPU; // matrix to store the calculation cost of each strategy+GT according to the CPU cycle change [CPU_Cycle, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, CoutCalcul> coutCalcul_CPU; while (tailleDonnee <= maxTaille) { int i = 0; taches.clear(); while (cycle_cpu <= max_cycle_cpu) { Tache tachei(i, cycle_cpu, tailleDonnee, taille_resultat, 1); taches.push_back(tachei); cycle_cpu = cycle_cpu * 2; i++; } std::multimap < int, Tache> ::iterator itr; int meilleurStrategie; long double meilleurUtilite; long double meilleurEnergie; long double meilleurTemps; long double meilleurCoutEnvoi; long double meilleurCoutCalcul; long double temp_util = 0; long double temp_energ = 0; long double temp_temps = 0; long double temp_ce = 0; long double temp_cc = 0; for (int c = 0; c < taches.size(); c++) { Utilite temp_util_obj; Energie temp_ener_obj; Temps temp_temps_obj; CoutEnvoie temp_ce_obj; CoutCalcul temp_cc_obj; Tache ti = taches[c]; meilleurStrategie = 1; meilleurUtilite = 0; meilleurEnergie = 0; meilleurTemps = 0; meilleurCoutEnvoi = 0; meilleurCoutCalcul = 0; ///////////////////// S1 : local computation ////////////////////////////////////// temp_util = calcul_local_DP(ti, drone_pricipal); temp_energ = getEnergieS1(ti, drone_pricipal); temp_temps = getTempsS1(ti, drone_pricipal); temp_ce = getCES1(ti); temp_cc = getCCS1(ti); if (iter == 1) { temp_util_obj.setU1(temp_util); temp_ener_obj.setE1(temp_energ); temp_temps_obj.setT1(temp_temps); temp_ce_obj.setCE1(temp_ce); temp_cc_obj.setCC1(temp_cc); } else { utilites_CPU[ti.getCi()].setU1(utilites_CPU[ti.getCi()].getU1() + temp_util); energies_CPU[ti.getCi()].setE1(energies_CPU[ti.getCi()].getE1() + temp_energ); temps_CPU[ti.getCi()].setT1(temps_CPU[ti.getCi()].getT1() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE1(coutEnvoi_CPU[ti.getCi()].getCE1() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC1(coutCalcul_CPU[ti.getCi()].getCC1() + temp_cc); } utilites_Local.insert(std::pair<int, long double>(ti.getId(), temp_util)); meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; //////////////////////// S2 : offloading to Edge server////////////////////////// temp_util = calcul_delestage_SE(ti, serveur_edge); temp_energ = getEnergieS2(ti); temp_temps = getTempsS2(ti, serveur_edge); temp_ce = getCES2(ti); temp_cc = getCCS2(ti); if (iter == 1) { temp_util_obj.setU2(temp_util); temp_ener_obj.setE2(temp_energ); temp_temps_obj.setT2(temp_temps); temp_ce_obj.setCE2(temp_ce); temp_cc_obj.setCC2(temp_cc); } else { utilites_CPU[ti.getCi()].setU2(utilites_CPU[ti.getCi()].getU2() + temp_util); energies_CPU[ti.getCi()].setE2(energies_CPU[ti.getCi()].getE2() + temp_energ); temps_CPU[ti.getCi()].setT2(temps_CPU[ti.getCi()].getT2() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE2(coutEnvoi_CPU[ti.getCi()].getCE2() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC2(coutCalcul_CPU[ti.getCi()].getCC2() + temp_cc); } utilites_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 2; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ///////////////////////////////////// S3 : sharing with secondary drones/////////////////////////////////////////// temp_util = calcul_partage_DS(ti, drone_pricipal, drones_secondaires); temp_energ = getEnergieS3(ti, drone_pricipal, drones_secondaires); temp_temps = getTempsS3(ti, drone_pricipal, drones_secondaires); temp_ce = getCES3(ti); temp_cc = getCCS3(ti); if (iter == 1) { temp_util_obj.setU3(temp_util); temp_ener_obj.setE3(temp_energ); temp_temps_obj.setT3(temp_temps); temp_ce_obj.setCE3(temp_ce); temp_cc_obj.setCC3(temp_cc); } else { utilites_CPU[ti.getCi()].setU3(utilites_CPU[ti.getCi()].getU3() + temp_util); energies_CPU[ti.getCi()].setE3(energies_CPU[ti.getCi()].getE3() + temp_energ); temps_CPU[ti.getCi()].setT3(temps_CPU[ti.getCi()].getT3() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE3(coutEnvoi_CPU[ti.getCi()].getCE3() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC3(coutCalcul_CPU[ti.getCi()].getCC3() + temp_cc); } utilites_Partage_DS.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 3; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ////////////////////////////////////////////S4 : offloading to authority vehicle + local computation in authority vehicle////////////////////////////////////////////// temp_util = calcul_local_VP(ti, vehicule_police); temp_energ = getEnergieS4(ti, vehicule_police); temp_temps = getTempsS4(ti, vehicule_police); temp_ce = getCES4(ti); temp_cc = getCCS4(ti); if (iter == 1) { temp_util_obj.setU4(temp_util); temp_ener_obj.setE4(temp_energ); temp_temps_obj.setT4(temp_temps); temp_ce_obj.setCE4(temp_ce); temp_cc_obj.setCC4(temp_cc); } else { utilites_CPU[ti.getCi()].setU4(utilites_CPU[ti.getCi()].getU4() + temp_util); energies_CPU[ti.getCi()].setE4(energies_CPU[ti.getCi()].getE4() + temp_energ); temps_CPU[ti.getCi()].setT4(temps_CPU[ti.getCi()].getT4() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE4(coutEnvoi_CPU[ti.getCi()].getCE4() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC4(coutCalcul_CPU[ti.getCi()].getCC4() + temp_cc); } utilites_Local_VP.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 4; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } /////////////////////////////////////// S5 : offloading to authority vehicle + offloading to Edge server by the authority vehicle//////////////////////////////////////////////// temp_util = calcul_delestage_VP_SE(ti, serveur_edge); temp_energ = getEnergieS5(ti); temp_temps = getTempsS5(ti, serveur_edge); temp_ce = getCES5(ti); temp_cc = getCCS5(ti); if (iter == 1) { temp_util_obj.setU5(temp_util); temp_ener_obj.setE5(temp_energ); temp_temps_obj.setT5(temp_temps); temp_ce_obj.setCE5(temp_ce); temp_cc_obj.setCC5(temp_cc); } else { utilites_CPU[ti.getCi()].setU5(utilites_CPU[ti.getCi()].getU5() + temp_util); energies_CPU[ti.getCi()].setE5(energies_CPU[ti.getCi()].getE5() + temp_energ); temps_CPU[ti.getCi()].setT5(temps_CPU[ti.getCi()].getT5() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE5(coutEnvoi_CPU[ti.getCi()].getCE5() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC5(coutCalcul_CPU[ti.getCi()].getCC5() + temp_cc); } utilites_VP_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 5; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ////////////////////////////////////// S6 : offloading to authority vehicle + sharing with nearby vehicle + accpet computation by nearby vehicle////////////////////////////////////////// temp_util = calcul_partage_VV_accpt(ti, vehicule_police, vehicule_voisin); temp_energ = getEnergieS6(ti, vehicule_police, vehicule_voisin); temp_temps = getTempsS6(ti, vehicule_voisin); temp_ce = getCES6(ti); temp_cc = getCCS6(ti); if (iter == 1) { temp_util_obj.setU6(temp_util); temp_ener_obj.setE6(temp_energ); temp_temps_obj.setT6(temp_temps); temp_ce_obj.setCE6(temp_ce); temp_cc_obj.setCC6(temp_cc); } else { utilites_CPU[ti.getCi()].setU6(utilites_CPU[ti.getCi()].getU6() + temp_util); energies_CPU[ti.getCi()].setE6(energies_CPU[ti.getCi()].getE6() + temp_energ); temps_CPU[ti.getCi()].setT6(temps_CPU[ti.getCi()].getT6() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE6(coutEnvoi_CPU[ti.getCi()].getCE6() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC6(coutCalcul_CPU[ti.getCi()].getCC6() + temp_cc); } utilites_VP_Partage_VV_accpt.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 6; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ////////////////////////////////////////////S7 : offloading to authority vehicle + sharing with nearby vehicle + refuse computation by nearby vehicle////////////////////////////////////////// temp_util = calcul_partage_VV_refu(ti, vehicule_police); temp_energ = getEnergieS7(ti, vehicule_police); temp_temps = getTempsS7(ti, vehicule_police); temp_ce = getCES7(ti); temp_cc = getCCS7(ti); if (iter == 1) { temp_util_obj.setU7(temp_util); temp_ener_obj.setE7(temp_energ); temp_temps_obj.setT7(temp_temps); temp_ce_obj.setCE7(temp_ce); temp_cc_obj.setCC7(temp_cc); } else { utilites_CPU[ti.getCi()].setU7(utilites_CPU[ti.getCi()].getU7() + temp_util); energies_CPU[ti.getCi()].setE7(energies_CPU[ti.getCi()].getE7() + temp_energ); temps_CPU[ti.getCi()].setT7(temps_CPU[ti.getCi()].getT7() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE7(coutEnvoi_CPU[ti.getCi()].getCE7() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC7(coutCalcul_CPU[ti.getCi()].getCC7() + temp_cc); } utilites_VP_Partage_VV_refu.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 7; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } if (iter == 1) { temp_util_obj.setGt(meilleurUtilite); temp_ener_obj.setGt(meilleurEnergie); temp_temps_obj.setGt(meilleurTemps); temp_ce_obj.setGt(meilleurCoutEnvoi); temp_cc_obj.setGt(meilleurCoutCalcul); } else { utilites_CPU[ti.getCi()].setGt(utilites_CPU[ti.getCi()].getGt() + meilleurUtilite); energies_CPU[ti.getCi()].setGt(energies_CPU[ti.getCi()].getGt() + meilleurEnergie); temps_CPU[ti.getCi()].setGt(temps_CPU[ti.getCi()].getGt() + meilleurTemps); coutEnvoi_CPU[ti.getCi()].setGt(coutEnvoi_CPU[ti.getCi()].getGt() + meilleurCoutEnvoi); coutCalcul_CPU[ti.getCi()].setGt(coutCalcul_CPU[ti.getCi()].getGt() + meilleurCoutCalcul); } if (iter == 1) { utilites_CPU.insert(std::pair<long double, Utilite>(ti.getCi(), temp_util_obj)); energies_CPU.insert(std::pair<long double, Energie>(ti.getCi(), temp_ener_obj)); temps_CPU.insert(std::pair<long double, Temps>(ti.getCi(), temp_temps_obj)); coutEnvoi_CPU.insert(std::pair<long double, CoutEnvoie>(ti.getCi(), temp_ce_obj)); coutCalcul_CPU.insert(std::pair<long double, CoutCalcul>(ti.getCi(), temp_cc_obj)); } tailleDonnee = tailleDonnee * 2; std::cout << "Tache num " << ti.getId() << "Ci" << ti.getCi() << " U1 " << utilites_CPU[ti.getCi()].getU1() << " U2 " << utilites_CPU[ti.getCi()].getU2() << " U3 " << utilites_CPU[ti.getCi()].getU3() << " U4 " << utilites_CPU[ti.getCi()].getU4() << " U5 " << utilites_CPU[ti.getCi()].getU5() << " U6 " << utilites_CPU[ti.getCi()].getU6() << "U7 " << utilites_CPU[ti.getCi()].getU7() << "Meuilleur S" << utilites_CPU[ti.getCi()].getGt() << '\n'; //cout << "Tache num " << ti.getId() << " Ci: " << ti.getCi() << " Di: " << ti.getDi() << " CE1 " << coutEnvoi_CPU[ti.getCi()].getCE1() << " CE2 " << coutEnvoi_CPU[ti.getCi()].getCE2() << " CE3 " << coutEnvoi_CPU[ti.getCi()].getCE3() << " CE4 " << coutEnvoi_CPU[ti.getCi()].getCE4() << " U5 " << utilites_Donnees[ti.getDi()].getU5() << " U6 " << utilites_Donnees[ti.getDi()].getU6() << "U7 " << utilites_Donnees[ti.getDi()].getU7() << "Meuilleur S" << meilleurStrategie << '\n'; } iter++; cycle_cpu = cycle_cpu_var; tailleDonnee = tailleDonnee * 2; } /////////Calculation of the average utility of each strategy long double total_U1 = 0; long double total_U2 = 0; long double total_U3 = 0; long double total_U4 = 0; long double total_U5 = 0; long double total_U6 = 0; long double total_U7 = 0; long double total_Gt = 0; std::map<long double, Utilite>::iterator it1; int nb_util_cpu = 0; for (it1 = utilites_CPU.begin(); it1 != utilites_CPU.end(); it1++) { total_U1 = total_U1 + it1->second.getU1() / iter; total_U2 = total_U2 + it1->second.getU2() / iter; total_U3 = total_U3 + it1->second.getU3() / iter; total_U4 = total_U4 + it1->second.getU4() / iter; total_U5 = total_U5 + it1->second.getU5() / iter; total_U6 = total_U6 + it1->second.getU6() / iter; total_U7 = total_U7 + it1->second.getU7() / iter; total_Gt = total_Gt + it1->second.getGt() / iter; it1->second.setU1(it1->second.getU1() / iter); it1->second.setU2(it1->second.getU2() / iter); it1->second.setU3(it1->second.getU3() / iter); it1->second.setU4(it1->second.getU4() / iter); it1->second.setU5(it1->second.getU5() / iter); it1->second.setU6(it1->second.getU6() / iter); it1->second.setU7(it1->second.getU7() / iter); it1->second.setGt(it1->second.getGt() / iter); nb_util_cpu++; } ////// Storage of the average utility of each strategy in a CSV file std::map<long double, Utilite>::iterator it2; std::fstream fout; fout.open("Impact of task’s complexity on the average system utility.csv", std::ios::out); fout << "Cycles CPU,U1,U2,U3,U4,U5,U6,U7,GT \n"; for (it2 = utilites_CPU.begin(); it2 != utilites_CPU.end(); it2++) { fout << std::setprecision(std::numeric_limits< long double>::digits10) << it2->first / 100000 << ", " << it2->second.getU1() << ", " << it2->second.getU2() << ", " << it2->second.getU3() << ", " << it2->second.getU4() << ", " << it2->second.getU5() << ", " << it2->second.getU6() << ", " << it2->second.getU7() << ", " << it2->second.getGt() << ", " << "\n"; } /////////Calculation of the average energy of each strategy std::map<long double, Energie>::iterator it3; long double moy_en_cpu1 = 0; long double moy_en_cpu2 = 0; long double moy_en_cpu3 = 0; long double moy_en_cpu4 = 0; long double moy_en_cpu5 = 0; long double moy_en_cpu6 = 0; long double moy_en_cpu7 = 0; long double moy_en_cpugt = 0; for (it3 = energies_CPU.begin(); it3 != energies_CPU.end(); it3++) { moy_en_cpu1 = moy_en_cpu1 + (it3->second.getE1() / iter); moy_en_cpu2 = moy_en_cpu2 + (it3->second.getE2() / iter); moy_en_cpu3 = moy_en_cpu3 + (it3->second.getE3() / iter); moy_en_cpu4 = moy_en_cpu4 + (it3->second.getE4() / iter); moy_en_cpu5 = moy_en_cpu5 + (it3->second.getE5() / iter); moy_en_cpu6 = moy_en_cpu6 + (it3->second.getE6() / iter); moy_en_cpu7 = moy_en_cpu7 + (it3->second.getE7() / iter); moy_en_cpugt = moy_en_cpugt + (it3->second.getGt() / iter); it3->second.setE1(it3->second.getE1() / iter); it3->second.setE2(it3->second.getE2() / iter); it3->second.setE3(it3->second.getE3() / iter); it3->second.setE4(it3->second.getE4() / iter); it3->second.setE5(it3->second.getE5() / iter); it3->second.setE6(it3->second.getE6() / iter); it3->second.setE7(it3->second.getE7() / iter); it3->second.setGt(it3->second.getGt() / iter); } moy_en_cpu1 = moy_en_cpu1 / energies_CPU.size(); moy_en_cpu2 = moy_en_cpu2 / energies_CPU.size(); moy_en_cpu3 = moy_en_cpu3 / energies_CPU.size(); moy_en_cpu4 = moy_en_cpu4 / energies_CPU.size(); moy_en_cpu5 = moy_en_cpu5 / energies_CPU.size(); moy_en_cpu6 = moy_en_cpu6 / energies_CPU.size(); moy_en_cpu7 = moy_en_cpu7 / energies_CPU.size(); moy_en_cpugt = moy_en_cpugt / energies_CPU.size(); /////////Calculation of the average delay for each strategy std::map<long double, Temps>::iterator it10; long double moy_temps_cpu1 = 0; long double moy_temps_cpu2 = 0; long double moy_temps_cpu3 = 0; long double moy_temps_cpu4 = 0; long double moy_temps_cpu5 = 0; long double moy_temps_cpu6 = 0; long double moy_temps_cpu7 = 0; long double moy_temps_cpugt = 0; for (it10 = temps_CPU.begin(); it10 != temps_CPU.end(); it10++) { moy_temps_cpu1 = moy_temps_cpu1 + (it10->second.getT1() / iter); moy_temps_cpu2 = moy_temps_cpu2 + (it10->second.getT2() / iter); moy_temps_cpu3 = moy_temps_cpu3 + (it10->second.getT3() / iter); moy_temps_cpu4 = moy_temps_cpu4 + (it10->second.getT4() / iter); moy_temps_cpu5 = moy_temps_cpu5 + (it10->second.getT5() / iter); moy_temps_cpu6 = moy_temps_cpu6 + (it10->second.getT6() / iter); moy_temps_cpu7 = moy_temps_cpu7 + (it10->second.getT7() / iter); moy_temps_cpugt = moy_temps_cpugt + (it10->second.getGt() / iter); it10->second.setT1(it10->second.getT1() / iter); it10->second.setT2(it10->second.getT2() / iter); it10->second.setT3(it10->second.getT3() / iter); it10->second.setT4(it10->second.getT4() / iter); it10->second.setT5(it10->second.getT5() / iter); it10->second.setT6(it10->second.getT6() / iter); it10->second.setT7(it10->second.getT7() / iter); it10->second.setGt(it10->second.getGt() / iter); } moy_temps_cpu1 = moy_temps_cpu1 / temps_CPU.size(); moy_temps_cpu2 = moy_temps_cpu2 / temps_CPU.size(); moy_temps_cpu3 = moy_temps_cpu3 / temps_CPU.size(); moy_temps_cpu4 = moy_temps_cpu4 / temps_CPU.size(); moy_temps_cpu5 = moy_temps_cpu5 / temps_CPU.size(); moy_temps_cpu6 = moy_temps_cpu6 / temps_CPU.size(); moy_temps_cpu7 = moy_temps_cpu7 / temps_CPU.size(); moy_temps_cpugt = moy_temps_cpugt / temps_CPU.size(); std::map<long double, CoutEnvoie >::iterator it20; long double moy_ce_cpu1 = 0; long double moy_ce_cpu2 = 0; long double moy_ce_cpu3 = 0; long double moy_ce_cpu4 = 0; long double moy_ce_cpu5 = 0; long double moy_ce_cpu6 = 0; long double moy_ce_cpu7 = 0; long double moy_ce_cpugt = 0; for (it20 = coutEnvoi_CPU.begin(); it20 != coutEnvoi_CPU.end(); it20++) { moy_ce_cpu1 = moy_ce_cpu1 + (it20->second.getCE1() / iter); moy_ce_cpu2 = moy_ce_cpu2 + (it20->second.getCE2() / iter); moy_ce_cpu3 = moy_ce_cpu3 + (it20->second.getCE3() / iter); moy_ce_cpu4 = moy_ce_cpu4 + (it20->second.getCE4() / iter); moy_ce_cpu5 = moy_ce_cpu5 + (it20->second.getCE5() / iter); moy_ce_cpu6 = moy_ce_cpu6 + (it20->second.getCE6() / iter); moy_ce_cpu7 = moy_ce_cpu7 + (it20->second.getCE7() / iter); moy_ce_cpugt = moy_ce_cpugt + (it20->second.getGt() / iter); it20->second.setCE1(it20->second.getCE1() / iter); it20->second.setCE2(it20->second.getCE2() / iter); it20->second.setCE3(it20->second.getCE3() / iter); it20->second.setCE4(it20->second.getCE4() / iter); it20->second.setCE5(it20->second.getCE5() / iter); it20->second.setCE6(it20->second.getCE6() / iter); it20->second.setCE7(it20->second.getCE7() / iter); it20->second.setGt(it20->second.getGt() / iter); } moy_ce_cpu1 = moy_ce_cpu1 / coutEnvoi_CPU.size(); moy_ce_cpu2 = moy_ce_cpu2 / coutEnvoi_CPU.size(); moy_ce_cpu3 = moy_ce_cpu3 / coutEnvoi_CPU.size(); moy_ce_cpu4 = moy_ce_cpu4 / coutEnvoi_CPU.size(); moy_ce_cpu5 = moy_ce_cpu5 / coutEnvoi_CPU.size(); moy_ce_cpu6 = moy_ce_cpu6 / coutEnvoi_CPU.size(); moy_ce_cpu7 = moy_ce_cpu7 / coutEnvoi_CPU.size(); moy_ce_cpugt = moy_ce_cpugt / coutEnvoi_CPU.size(); std::map<long double, CoutCalcul >::iterator it21; long double moy_cc_cpu1 = 0; long double moy_cc_cpu2 = 0; long double moy_cc_cpu3 = 0; long double moy_cc_cpu4 = 0; long double moy_cc_cpu5 = 0; long double moy_cc_cpu6 = 0; long double moy_cc_cpu7 = 0; long double moy_cc_cpugt = 0; for (it21 = coutCalcul_CPU.begin(); it21 != coutCalcul_CPU.end(); it21++) { moy_cc_cpu1 = moy_cc_cpu1 + (it21->second.getCC1() / iter); moy_cc_cpu2 = moy_cc_cpu2 + (it21->second.getCC2() / iter); moy_cc_cpu3 = moy_cc_cpu3 + (it21->second.getCC3() / iter); moy_cc_cpu4 = moy_cc_cpu4 + (it21->second.getCC4() / iter); moy_cc_cpu5 = moy_cc_cpu5 + (it21->second.getCC5() / iter); moy_cc_cpu6 = moy_cc_cpu6 + (it21->second.getCC6() / iter); moy_cc_cpu7 = moy_cc_cpu7 + (it21->second.getCC7() / iter); moy_cc_cpugt = moy_cc_cpugt + (it21->second.getGt() / iter); it21->second.setCC1(it21->second.getCC1() / iter); it21->second.setCC2(it21->second.getCC2() / iter); it21->second.setCC3(it21->second.getCC3() / iter); it21->second.setCC4(it21->second.getCC4() / iter); it21->second.setCC5(it21->second.getCC5() / iter); it21->second.setCC6(it21->second.getCC6() / iter); it21->second.setCC7(it21->second.getCC7() / iter); it21->second.setGt(it21->second.getGt() / iter); } moy_cc_cpu1 = moy_cc_cpu1 / coutCalcul_CPU.size(); moy_cc_cpu2 = moy_cc_cpu2 / coutCalcul_CPU.size(); moy_cc_cpu3 = moy_cc_cpu3 / coutCalcul_CPU.size(); moy_cc_cpu4 = moy_cc_cpu4 / coutCalcul_CPU.size(); moy_cc_cpu5 = moy_cc_cpu5 / coutCalcul_CPU.size(); moy_cc_cpu6 = moy_cc_cpu6 / coutCalcul_CPU.size(); moy_cc_cpu7 = moy_cc_cpu7 / coutCalcul_CPU.size(); moy_cc_cpugt = moy_cc_cpugt / coutCalcul_CPU.size(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SIMULATION n°2 = Calculation of the overall utility, energy, and timeframe for each strategy in relation to the change in Task Data Size //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// cycle_cpu = cycle_cpu_var; max_cycle_cpu = max_cycle_cpu_var; taille_resultat = taille_resultat_var; tailleDonnee = tailleDonnee_var; maxTaille = maxTaille_var; iter = 1; // matrix to store the usefulness of each strategy+GT according to the change in data size [Data_Size, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Utilite> utilites_Donnees; // matrix to store the energy of each strategy+GT according to the change in data size [Data_Size, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Energie> energie_Donnees; // matrix to store the delay of each strategy+GT according to the change in data size [Data_Size, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Temps> temps_Donnees; // matrix to store the cost of communication for each strategy+GT according to the change in data size [Data_Size, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, CoutEnvoie> coutEnvoi_Donnees; // matrix to store the computation cost of each strategy+GT according to the change in data size [Data_Size, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, CoutCalcul> coutCalcul_Donnees; while (cycle_cpu <= max_cycle_cpu) { int i = 0; taches.clear(); while (tailleDonnee <= maxTaille) { Tache tachei(i, cycle_cpu, tailleDonnee, taille_resultat, 1); taches.push_back(tachei); tailleDonnee = tailleDonnee * 2; i++; } std::multimap < int, Tache> ::iterator itr; int meilleurStrategie; long double meilleurUtilite; long double meilleurEnergie; long double meilleurTemps; long double meilleurCoutEnvoi; long double meilleurCoutCalcul; long double temp_util = 0; long double temp_energ = 0; long double temp_temps = 0; long double temp_ce = 0; long double temp_cc = 0; for (int c = 0; c < taches.size(); c++) { Utilite temp_util_obj; Energie temp_energ_obj; Temps temp_temps_obj; CoutEnvoie temp_ce_obj; CoutCalcul temp_cc_obj; Tache ti = taches[c]; meilleurStrategie = 1; meilleurUtilite = 0; meilleurEnergie = 0; meilleurTemps = 0; meilleurCoutEnvoi = 0; meilleurCoutCalcul = 0; //////////////////////////////////////////////// S1 : local computation ///////////////////////////////////////////// temp_util = calcul_local_DP(ti, drone_pricipal); temp_energ = getEnergieS1(ti, drone_pricipal); temp_temps = getTempsS1(ti, drone_pricipal); temp_ce = getCES1(ti); temp_cc = getCCS1(ti); if (iter == 1) { temp_util_obj.setU1(temp_util); temp_energ_obj.setE1(temp_energ); temp_temps_obj.setT1(temp_temps); temp_ce_obj.setCE1(temp_ce); temp_cc_obj.setCC1(temp_cc); } else { utilites_Donnees[ti.getDi()].setU1(utilites_Donnees[ti.getDi()].getU1() + temp_util); energie_Donnees[ti.getDi()].setE1(energie_Donnees[ti.getDi()].getE1() + temp_energ); temps_Donnees[ti.getDi()].setT1(temps_Donnees[ti.getDi()].getT1() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE1(coutEnvoi_Donnees[ti.getDi()].getCE1() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC1(coutCalcul_Donnees[ti.getDi()].getCC1() + temp_cc); } utilites_Local.insert(std::pair<int, long double>(ti.getId(), temp_util)); meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; /////////////////////////////////////////////// S2 : offloading to Edge server///////////////////////////////// temp_util = calcul_delestage_SE(ti, serveur_edge); temp_energ = getEnergieS2(ti); temp_temps = getTempsS2(ti, serveur_edge); temp_ce = getCES2(ti); temp_cc = getCCS2(ti); if (iter == 1) { temp_util_obj.setU2(temp_util); temp_energ_obj.setE2(temp_energ); temp_temps_obj.setT2(temp_temps); temp_ce_obj.setCE2(temp_ce); temp_cc_obj.setCC2(temp_cc); } else { utilites_Donnees[ti.getDi()].setU2(utilites_Donnees[ti.getDi()].getU2() + temp_util); energie_Donnees[ti.getDi()].setE2(energie_Donnees[ti.getDi()].getE2() + temp_energ); temps_Donnees[ti.getDi()].setT2(temps_Donnees[ti.getDi()].getT2() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE2(coutEnvoi_Donnees[ti.getDi()].getCE2() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC2(coutCalcul_Donnees[ti.getDi()].getCC2() + temp_cc); } utilites_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 2; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ///////////////////////////////////////////////////// S3 :sharing with secondary drones///////////////////////////////////////////////////////////// temp_util = calcul_partage_DS(ti, drone_pricipal, drones_secondaires); temp_energ = getEnergieS3(ti, drone_pricipal, drones_secondaires); temp_temps = getTempsS3(ti, drone_pricipal, drones_secondaires); temp_ce = getCES3(ti); temp_cc = getCCS3(ti); if (iter == 1) { temp_util_obj.setU3(temp_util); temp_energ_obj.setE3(temp_energ); temp_temps_obj.setT3(temp_temps); temp_ce_obj.setCE3(temp_ce); temp_cc_obj.setCC3(temp_cc); } else { utilites_Donnees[ti.getDi()].setU3(utilites_Donnees[ti.getDi()].getU3() + temp_util); energie_Donnees[ti.getDi()].setE3(energie_Donnees[ti.getDi()].getE3() + temp_energ); temps_Donnees[ti.getDi()].setT3(temps_Donnees[ti.getDi()].getT3() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE3(coutEnvoi_Donnees[ti.getDi()].getCE3() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC3(coutCalcul_Donnees[ti.getDi()].getCC3() + temp_cc); } utilites_Partage_DS.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 3; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ///////////////////////////////////////////////////// S4 : offloading to authority vehicle + local computation in authority vehicle/////////////////////////////////// temp_util = calcul_local_VP(ti, vehicule_police); temp_energ = getEnergieS4(ti, vehicule_police); temp_temps = getTempsS4(ti, vehicule_police); temp_ce = getCES4(ti); temp_cc = getCCS4(ti); if (iter == 1) { temp_util_obj.setU4(temp_util); temp_energ_obj.setE4(temp_energ); temp_temps_obj.setT4(temp_temps); temp_ce_obj.setCE4(temp_ce); temp_cc_obj.setCC4(temp_cc); } else { utilites_Donnees[ti.getDi()].setU4(utilites_Donnees[ti.getDi()].getU4() + temp_util); energie_Donnees[ti.getDi()].setE4(energie_Donnees[ti.getDi()].getE4() + temp_energ); temps_Donnees[ti.getDi()].setT4(temps_Donnees[ti.getDi()].getT4() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE4(coutEnvoi_Donnees[ti.getDi()].getCE4() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC4(coutCalcul_Donnees[ti.getDi()].getCC4() + temp_cc); } utilites_Local_VP.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 4; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } /////////////////////////////////////////////////// S5 : offloading to authority vehicle + offloading to Edge server by the authority vehicle/////////////////////////////////////// temp_util = calcul_delestage_VP_SE(ti, serveur_edge); temp_energ = getEnergieS5(ti); temp_temps = getTempsS5(ti, serveur_edge); temp_ce = getCES5(ti); temp_cc = getCCS5(ti); if (iter == 1) { temp_util_obj.setU5(temp_util); temp_energ_obj.setE5(temp_energ); temp_temps_obj.setT5(temp_temps); temp_ce_obj.setCE5(temp_ce); temp_cc_obj.setCC5(temp_cc); } else { utilites_Donnees[ti.getDi()].setU5(utilites_Donnees[ti.getDi()].getU5() + temp_util); energie_Donnees[ti.getDi()].setE5(energie_Donnees[ti.getDi()].getE5() + temp_energ); temps_Donnees[ti.getDi()].setT5(temps_Donnees[ti.getDi()].getT5() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE5(coutEnvoi_Donnees[ti.getDi()].getCE5() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC5(coutCalcul_Donnees[ti.getDi()].getCC5() + temp_cc); } utilites_VP_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 5; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } ///////////////////////////////////////////// S6 : offloading to authority vehicle + sharing with nearby vehicle + accpet computation by nearby vehicle/////////////////////////////////// temp_util = calcul_partage_VV_accpt(ti, vehicule_police, vehicule_voisin); temp_energ = getEnergieS6(ti, vehicule_police, vehicule_voisin); temp_temps = getTempsS6(ti, vehicule_voisin); temp_ce = getCES6(ti); temp_cc = getCCS6(ti); if (iter == 1) { temp_util_obj.setU6(temp_util); temp_energ_obj.setE6(temp_energ); temp_temps_obj.setT6(temp_temps); temp_ce_obj.setCE6(temp_ce); temp_cc_obj.setCC6(temp_cc); } else { utilites_Donnees[ti.getDi()].setU6(utilites_Donnees[ti.getDi()].getU6() + temp_util); energie_Donnees[ti.getDi()].setE6(energie_Donnees[ti.getDi()].getE6() + temp_energ); temps_Donnees[ti.getDi()].setT6(temps_Donnees[ti.getDi()].getT6() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE6(coutEnvoi_Donnees[ti.getDi()].getCE6() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC6(coutCalcul_Donnees[ti.getDi()].getCC6() + temp_cc); } utilites_VP_Partage_VV_accpt.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 6; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } /////////////////////////////////////// S7 : offloading to authority vehicle + sharing with nearby vehicle + refuse computation by nearby vehicle///////////////////////////////////// temp_util = calcul_partage_VV_refu(ti, vehicule_police); temp_energ = getEnergieS7(ti, vehicule_police); temp_temps = getTempsS7(ti, vehicule_police); temp_ce = getCES7(ti); temp_cc = getCCS7(ti); if (iter == 1) { temp_util_obj.setU7(temp_util); temp_energ_obj.setE7(temp_energ); temp_temps_obj.setT7(temp_temps); temp_ce_obj.setCE7(temp_ce); temp_cc_obj.setCC7(temp_cc); } else { utilites_Donnees[ti.getDi()].setU7(utilites_Donnees[ti.getDi()].getU7() + temp_util); energie_Donnees[ti.getDi()].setE7(energie_Donnees[ti.getDi()].getE7() + temp_energ); temps_Donnees[ti.getDi()].setT7(temps_Donnees[ti.getDi()].getT7() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE7(coutEnvoi_Donnees[ti.getDi()].getCE7() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC7(coutCalcul_Donnees[ti.getDi()].getCC7() + temp_cc); } utilites_VP_Partage_VV_refu.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 7; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } if (iter == 1) { temp_util_obj.setGt(meilleurUtilite); temp_energ_obj.setGt(meilleurEnergie); temp_temps_obj.setGt(meilleurTemps); temp_ce_obj.setGt(meilleurCoutEnvoi); temp_cc_obj.setGt(meilleurCoutCalcul); } else { utilites_Donnees[ti.getDi()].setGt(utilites_Donnees[ti.getDi()].getGt() + meilleurUtilite); energie_Donnees[ti.getDi()].setGt(energie_Donnees[ti.getDi()].getGt() + meilleurEnergie); temps_Donnees[ti.getDi()].setGt(temps_Donnees[ti.getDi()].getGt() + meilleurTemps); coutEnvoi_Donnees[ti.getDi()].setGt(coutEnvoi_Donnees[ti.getDi()].getGt() + meilleurCoutEnvoi); coutCalcul_Donnees[ti.getDi()].setGt(coutCalcul_Donnees[ti.getDi()].getGt() + meilleurCoutCalcul); } if (iter == 1) { utilites_Donnees.insert(std::pair<long double, Utilite>(ti.getDi(), temp_util_obj)); energie_Donnees.insert(std::pair<long double, Energie>(ti.getDi(), temp_energ_obj)); temps_Donnees.insert(std::pair<long double, Temps>(ti.getDi(), temp_temps_obj)); coutEnvoi_Donnees.insert(std::pair<long double, CoutEnvoie>(ti.getDi(), temp_ce_obj)); coutCalcul_Donnees.insert(std::pair<long double, CoutCalcul>(ti.getDi(), temp_cc_obj)); } std::cout << "Tache num " << ti.getId() << " Ci: " << ti.getCi() << " Di: " << ti.getDi() << " U1 " << utilites_Donnees[ti.getDi()].getU1() << " U2 " << utilites_Donnees[ti.getDi()].getU2() << " U3 " << utilites_Donnees[ti.getDi()].getU3() << " U4 " << utilites_Donnees[ti.getDi()].getU4() << " U5 " << utilites_Donnees[ti.getDi()].getU5() << " U6 " << utilites_Donnees[ti.getDi()].getU6() << "U7 " << utilites_Donnees[ti.getDi()].getU7() << "Meuilleur S" << meilleurStrategie << '\n'; } iter++; cycle_cpu = cycle_cpu * 2; tailleDonnee = tailleDonnee_var; } iter--; /////////Calculation of the average utility of each strategy std::map<long double, Utilite>::iterator it5; int nb_util_donnes = 0; for (it5 = utilites_Donnees.begin(); it5 != utilites_Donnees.end(); it5++) { total_U1 = total_U1 + it5->second.getU1() / iter; total_U2 = total_U2 + it5->second.getU2() / iter; total_U3 = total_U3 + it5->second.getU3() / iter; total_U4 = total_U4 + it5->second.getU4() / iter; total_U5 = total_U5 + it5->second.getU5() / iter; total_U6 = total_U6 + it5->second.getU6() / iter; total_U7 = total_U7 + it5->second.getU7() / iter; total_Gt = total_Gt + it5->second.getGt() / iter; it5->second.setU1(it5->second.getU1() / iter); it5->second.setU2(it5->second.getU2() / iter); it5->second.setU3(it5->second.getU3() / iter); it5->second.setU4(it5->second.getU4() / iter); it5->second.setU5(it5->second.getU5() / iter); it5->second.setU6(it5->second.getU6() / iter); it5->second.setU7(it5->second.getU7() / iter); it5->second.setGt(it5->second.getGt() / iter); nb_util_donnes++; } std::map<long double, Utilite>::iterator it6; std::fstream fout3; fout3.open("Impact of different data sizes on the average system utility.csv", std::ios::out); fout3 << "Taille Données (Ko),U1,U2,U3,U4,U5,U6,U7,GT \n"; for (it6 = utilites_Donnees.begin(); it6 != utilites_Donnees.end(); it6++) { fout3 << std::setprecision(std::numeric_limits< long double>::digits10) << it6->first / 100 << ", " << it6->second.getU1() << ", " << it6->second.getU2() << ", " << it6->second.getU3() << ", " << it6->second.getU4() << ", " << it6->second.getU5() << ", " << it6->second.getU6() << ", " << it6->second.getU7() << ", " << it6->second.getGt() << ", " << "\n"; } /////////Calculation of the average energy of each strategy std::map<long double, Energie>::iterator it23; std::fstream fout23; fout23.open("Impact of different data sizes on the average system energy.csv", std::ios::out); fout23 << "Taille Données (Ko),E1,E2,E3,E4,E5,E6,E7,GT \n"; for (it23 = energie_Donnees.begin(); it23 != energie_Donnees.end(); it23++) { fout23 << std::setprecision(std::numeric_limits< long double>::digits10) << it23->first / 100 << ", " << it23->second.getE1() / iter << ", " << it23->second.getE2() / iter << ", " << it23->second.getE3() / iter << ", " << it23->second.getE4() / iter << ", " << it23->second.getE5() / iter << ", " << it23->second.getE6() / iter << ", " << it23->second.getE7() / iter << ", " << it23->second.getGt() / iter << ", " << "\n"; } /////////Calculation of the average delay for each strategy std::map<long double, Temps>::iterator it24; std::fstream fout24; fout24.open("Impact of different data sizes on the average system delay.csv", std::ios::out); fout24 << "Taille Données (Ko),T1,T2,T3,T4,T5,T6,T7,GT \n"; for (it24 = temps_Donnees.begin(); it24 != temps_Donnees.end(); it24++) { fout24 << std::setprecision(std::numeric_limits< long double>::digits10) << it24->first / 1000 << ", " << it24->second.getT1() / iter << ", " << it24->second.getT2() / iter << ", " << it24->second.getT3() / iter << ", " << it24->second.getT4() / iter << ", " << it24->second.getT5() / iter << ", " << it24->second.getT6() / iter << ", " << it24->second.getT7() / iter << ", " << it24->second.getGt() / iter << ", " << "\n"; } std::map<long double, Energie>::iterator it7; long double moy_en_data1 = 0; long double moy_en_data2 = 0; long double moy_en_data3 = 0; long double moy_en_data4 = 0; long double moy_en_data5 = 0; long double moy_en_data6 = 0; long double moy_en_data7 = 0; long double moy_en_datagt = 0; for (it7 = energie_Donnees.begin(); it7 != energie_Donnees.end(); it7++) { moy_en_data1 = moy_en_data1 + (it7->second.getE1() / iter); moy_en_data2 = moy_en_data2 + (it7->second.getE2() / iter); moy_en_data3 = moy_en_data3 + (it7->second.getE3() / iter); moy_en_data4 = moy_en_data4 + (it7->second.getE4() / iter); moy_en_data5 = moy_en_data5 + (it7->second.getE5() / iter); moy_en_data6 = moy_en_data6 + (it7->second.getE6() / iter); moy_en_data7 = moy_en_data7 + (it7->second.getE7() / iter); moy_en_datagt = moy_en_datagt + (it7->second.getGt() / iter); it7->second.setE1(it7->second.getE1() / iter); it7->second.setE2(it7->second.getE2() / iter); it7->second.setE3(it7->second.getE3() / iter); it7->second.setE4(it7->second.getE4() / iter); it7->second.setE5(it7->second.getE5() / iter); it7->second.setE6(it7->second.getE6() / iter); it7->second.setE7(it7->second.getE7() / iter); it7->second.setGt(it7->second.getGt() / iter); } moy_en_data1 = moy_en_data1 / energie_Donnees.size(); moy_en_data2 = moy_en_data2 / energie_Donnees.size(); moy_en_data3 = moy_en_data3 / energie_Donnees.size(); moy_en_data4 = moy_en_data4 / energie_Donnees.size(); moy_en_data5 = moy_en_data5 / energie_Donnees.size(); moy_en_data6 = moy_en_data6 / energie_Donnees.size(); moy_en_data7 = moy_en_data7 / energie_Donnees.size(); moy_en_datagt = moy_en_datagt / energie_Donnees.size(); long double moy_en_total1 = (moy_en_data1 + moy_en_cpu1) / 2; long double moy_en_total2 = (moy_en_data2 + moy_en_cpu2) / 2; long double moy_en_total3 = (moy_en_data3 + moy_en_cpu3) / 2; long double moy_en_total4 = (moy_en_data4 + moy_en_cpu4) / 2; long double moy_en_total5 = (moy_en_data5 + moy_en_cpu5) / 2; long double moy_en_total6 = (moy_en_data6 + moy_en_cpu6) / 2; long double moy_en_total7 = (moy_en_data7 + moy_en_cpu7) / 2; long double moy_en_totalgt = (moy_en_datagt + moy_en_cpugt) / 2; std::map<long double, Temps>::iterator it11; long double moy_temps_data1 = 0; long double moy_temps_data2 = 0; long double moy_temps_data3 = 0; long double moy_temps_data4 = 0; long double moy_temps_data5 = 0; long double moy_temps_data6 = 0; long double moy_temps_data7 = 0; long double moy_temps_datagt = 0; for (it11 = temps_Donnees.begin(); it11 != temps_Donnees.end(); it11++) { moy_temps_data1 = moy_temps_data1 + (it11->second.getT1() / iter); moy_temps_data2 = moy_temps_data2 + (it11->second.getT2() / iter); moy_temps_data3 = moy_temps_data3 + (it11->second.getT3() / iter); moy_temps_data4 = moy_temps_data4 + (it11->second.getT4() / iter); moy_temps_data5 = moy_temps_data5 + (it11->second.getT5() / iter); moy_temps_data6 = moy_temps_data6 + (it11->second.getT6() / iter); moy_temps_data7 = moy_temps_data7 + (it11->second.getT7() / iter); moy_temps_datagt = moy_temps_datagt + (it11->second.getGt() / iter); it11->second.setT1(it11->second.getT1() / iter); it11->second.setT2(it11->second.getT2() / iter); it11->second.setT3(it11->second.getT3() / iter); it11->second.setT4(it11->second.getT4() / iter); it11->second.setT5(it11->second.getT5() / iter); it11->second.setT6(it11->second.getT6() / iter); it11->second.setT7(it11->second.getT7() / iter); it11->second.setGt(it11->second.getGt() / iter); } moy_temps_data1 = moy_temps_data1 / temps_Donnees.size(); moy_temps_data2 = moy_temps_data2 / temps_Donnees.size(); moy_temps_data3 = moy_temps_data3 / temps_Donnees.size(); moy_temps_data4 = moy_temps_data4 / temps_Donnees.size(); moy_temps_data5 = moy_temps_data5 / temps_Donnees.size(); moy_temps_data6 = moy_temps_data6 / temps_Donnees.size(); moy_temps_data7 = moy_temps_data7 / temps_Donnees.size(); moy_temps_datagt = moy_temps_datagt / temps_Donnees.size(); long double moy_cpu_total1 = (moy_temps_data1 + moy_temps_cpu1) / 2; long double moy_cpu_total2 = (moy_temps_data2 + moy_temps_cpu2) / 2; long double moy_cpu_total3 = (moy_temps_data3 + moy_temps_cpu3) / 2; long double moy_cpu_total4 = (moy_temps_data4 + moy_temps_cpu4) / 2; long double moy_cpu_total5 = (moy_temps_data5 + moy_temps_cpu5) / 2; long double moy_cpu_total6 = (moy_temps_data6 + moy_temps_cpu6) / 2; long double moy_cpu_total7 = (moy_temps_data7 + moy_temps_cpu7) / 2; long double moy_cpu_totalgt = (moy_temps_datagt + moy_temps_cpugt) / 2; std::map<long double, CoutEnvoie >::iterator it30; long double moy_ce_data1 = 0; long double moy_ce_data2 = 0; long double moy_ce_data3 = 0; long double moy_ce_data4 = 0; long double moy_ce_data5 = 0; long double moy_ce_data6 = 0; long double moy_ce_data7 = 0; long double moy_ce_datagt = 0; for (it30 = coutEnvoi_Donnees.begin(); it30 != coutEnvoi_Donnees.end(); it30++) { moy_ce_data1 = moy_ce_data1 + (it30->second.getCE1() / iter); moy_ce_data2 = moy_ce_data2 + (it30->second.getCE2() / iter); moy_ce_data3 = moy_ce_data3 + (it30->second.getCE3() / iter); moy_ce_data4 = moy_ce_data4 + (it30->second.getCE4() / iter); moy_ce_data5 = moy_ce_data5 + (it30->second.getCE5() / iter); moy_ce_data6 = moy_ce_data6 + (it30->second.getCE6() / iter); moy_ce_data7 = moy_ce_data7 + (it30->second.getCE7() / iter); moy_ce_datagt = moy_ce_datagt + (it30->second.getGt() / iter); it30->second.setCE1(it30->second.getCE1() / iter); it30->second.setCE2(it30->second.getCE2() / iter); it30->second.setCE3(it30->second.getCE3() / iter); it30->second.setCE4(it30->second.getCE4() / iter); it30->second.setCE5(it30->second.getCE5() / iter); it30->second.setCE6(it30->second.getCE6() / iter); it30->second.setCE7(it30->second.getCE7() / iter); it30->second.setGt(it30->second.getGt() / iter); } moy_ce_data1 = moy_ce_data1 / coutEnvoi_Donnees.size(); moy_ce_data2 = moy_ce_data2 / coutEnvoi_Donnees.size(); moy_ce_data3 = moy_ce_data3 / coutEnvoi_Donnees.size(); moy_ce_data4 = moy_ce_data4 / coutEnvoi_Donnees.size(); moy_ce_data5 = moy_ce_data5 / coutEnvoi_Donnees.size(); moy_ce_data6 = moy_ce_data6 / coutEnvoi_Donnees.size(); moy_ce_data7 = moy_ce_data7 / coutEnvoi_Donnees.size(); moy_ce_datagt = moy_ce_datagt / coutEnvoi_Donnees.size(); long double moy_ce_total1 = (moy_ce_data1 + moy_ce_cpu1) / 2; long double moy_ce_total2 = (moy_ce_data2 + moy_ce_cpu2) / 2; long double moy_ce_total3 = (moy_ce_data3 + moy_ce_cpu3) / 2; long double moy_ce_total4 = (moy_ce_data4 + moy_ce_cpu4) / 2; long double moy_ce_total5 = (moy_ce_data5 + moy_ce_cpu5) / 2; long double moy_ce_total6 = (moy_ce_data6 + moy_ce_cpu6) / 2; long double moy_ce_total7 = (moy_ce_data7 + moy_ce_cpu7) / 2; long double moy_ce_totalgt = (moy_ce_datagt + moy_ce_cpugt) / 2; std::map<long double, CoutCalcul >::iterator it31; long double moy_cc_data1 = 0; long double moy_cc_data2 = 0; long double moy_cc_data3 = 0; long double moy_cc_data4 = 0; long double moy_cc_data5 = 0; long double moy_cc_data6 = 0; long double moy_cc_data7 = 0; long double moy_cc_datagt = 0; for (it31 = coutCalcul_Donnees.begin(); it31 != coutCalcul_Donnees.end(); it31++) { moy_cc_data1 = moy_cc_data1 + (it31->second.getCC1() / iter); moy_cc_data2 = moy_cc_data2 + (it31->second.getCC2() / iter); moy_cc_data3 = moy_cc_data3 + (it31->second.getCC3() / iter); moy_cc_data4 = moy_cc_data4 + (it31->second.getCC4() / iter); moy_cc_data5 = moy_cc_data5 + (it31->second.getCC5() / iter); moy_cc_data6 = moy_cc_data6 + (it31->second.getCC6() / iter); moy_cc_data7 = moy_cc_data7 + (it31->second.getCC7() / iter); moy_cc_datagt = moy_cc_datagt + (it31->second.getGt() / iter); it31->second.setCC1(it31->second.getCC1() / iter); it31->second.setCC2(it31->second.getCC2() / iter); it31->second.setCC3(it31->second.getCC3() / iter); it31->second.setCC4(it31->second.getCC4() / iter); it31->second.setCC5(it31->second.getCC5() / iter); it31->second.setCC6(it31->second.getCC6() / iter); it31->second.setCC7(it31->second.getCC7() / iter); it31->second.setGt(it31->second.getGt() / iter); } moy_cc_data1 = moy_cc_data1 / coutEnvoi_Donnees.size(); moy_cc_data2 = moy_cc_data2 / coutEnvoi_Donnees.size(); moy_cc_data3 = moy_cc_data3 / coutEnvoi_Donnees.size(); moy_cc_data4 = moy_cc_data4 / coutEnvoi_Donnees.size(); moy_cc_data5 = moy_cc_data5 / coutEnvoi_Donnees.size(); moy_cc_data6 = moy_cc_data6 / coutEnvoi_Donnees.size(); moy_cc_data7 = moy_cc_data7 / coutEnvoi_Donnees.size(); moy_cc_datagt = moy_cc_datagt / coutEnvoi_Donnees.size(); long double moy_cc_total1 = (moy_cc_data1 + moy_cc_cpu1) / 2; long double moy_cc_total2 = (moy_cc_data2 + moy_cc_cpu2) / 2; long double moy_cc_total3 = (moy_cc_data3 + moy_cc_cpu3) / 2; long double moy_cc_total4 = (moy_cc_data4 + moy_cc_cpu4) / 2; long double moy_cc_total5 = (moy_cc_data5 + moy_cc_cpu5) / 2; long double moy_cc_total6 = (moy_cc_data6 + moy_cc_cpu6) / 2; long double moy_cc_total7 = (moy_cc_data7 + moy_cc_cpu7) / 2; long double moy_cc_totalgt = (moy_cc_datagt + moy_cc_cpugt) / 2; /////////Storage of the global average energy of each strategy std::fstream fout10; fout10.open("Average energy of each strategy.csv", std::ios::out); fout10 << "Strategie,Moyenne Energie \n"; fout10 << std::setprecision(std::numeric_limits< long double>::digits10) << "S1" << ", " << moy_en_total1 << "\n" << "S2" << ", " << moy_en_total2 << "\n" << "S3" << ", " << moy_en_total3 << "\n" << "S4" << ", " << moy_en_total4 << "\n" << "S5" << ", " << moy_en_total5 << "\n" << "S6" << ", " << moy_en_total6 << "\n" << "S7" << ", " << moy_en_total7 << "\n" << "GT" << ", " << moy_en_totalgt << "\n"; std::fstream fout4; /////////Storage of the average overall delay for each strategy fout4.open("Average delay of each strategy.csv", std::ios::out); fout4 << "Strategie,Moyenne Temps \n"; fout4 << std::setprecision(std::numeric_limits< long double>::digits10) << "S1" << ", " << moy_cpu_total1 << "\n" << "S2" << ", " << moy_cpu_total2 << "\n" << "S3" << ", " << moy_cpu_total3 << "\n" << "S4" << ", " << moy_cpu_total4 << "\n" << "S5" << ", " << moy_cpu_total5 << "\n" << "S6" << ", " << moy_cpu_total6 << "\n" << "S7" << ", " << moy_cpu_total7 << "\n" << "GT" << ", " << moy_cpu_totalgt << "\n"; //Calculation of the overall utility of the system ---> (average CPU_Utility + average Data_Utility_Size)/2 std::fstream fout5; fout5.open("Average System Utility.csv", std::ios::out); fout5 << "Strategy,Globale Utility\n"; fout5 << std::setprecision(std::numeric_limits< long double>::digits10) << "S1" << ", " << total_U1 / (nb_util_cpu + nb_util_donnes) << "\n" << "S2" << ", " << total_U2 / (nb_util_cpu + nb_util_donnes) << "\n" << "S3" << ", " << total_U3 / (nb_util_cpu + nb_util_donnes) << "\n" << "S4" << ", " << total_U4 / (nb_util_cpu + nb_util_donnes) << "\n" << "S5" << ", " << total_U5 / (nb_util_cpu + nb_util_donnes) << "\n" << "S6" << ", " << total_U6 / (nb_util_cpu + nb_util_donnes) << "\n" << "S7" << ", " << total_U7 / (nb_util_cpu + nb_util_donnes) << "\n" << "GT" << ", " << total_Gt / (nb_util_cpu + nb_util_donnes) << "\n"; MessageBox::Show("Results are exported successfully in the project folder ", "Simulation Done", MessageBoxButtons::OK, MessageBoxIcon::Information); } long double getEnergieS1(Tache ti,Drone drone_pricipal) { long double E_resultat = ti.getRsi()*E_PC5; long double E_total = drone_pricipal.ECalculCPU(ti.getCi()) + E_resultat; return (E_total - minE) / (maxE - minE); } long double getEnergieS2(Tache ti) { long double E_envoi_SE = ti.getDi()*E_LTEA; long double E_resultat = ti.getRsi()*E_PC5; long double E_total = E_envoi_SE + E_resultat; return (E_total - minE) / (maxE - minE); } long double getEnergieS3(Tache ti, Drone drone_pricipal, std::vector <Drone> drones_secondaires) { long double nb_drones = drones_secondaires.size() + 1; std::vector<long double> taux_de_partage; taux_de_partage.push_back(0.4); taux_de_partage.push_back(0.4); long double taux_total = 0; for (int i = 0; i < taux_de_partage.size(); i++) { taux_total = taux_total + taux_de_partage[i]; } //Energie long double E_local_DP = drone_pricipal.ECalculCPU((1 - taux_total) *ti.getCi()); long double E_envoi = taux_total * ti.getDi()*E_PC5; long double E_calcul_DS = 0; for (int i = 0; i < drones_secondaires.size(); i++) { E_calcul_DS = E_calcul_DS + drones_secondaires[i].ECalculCPU(taux_de_partage[i] * ti.getCi()); } long double E_resultat_DS = taux_total * ti.getRsi() * E_PC5; long double E_resultat = E_resultat_DS + ti.getRsi() * E_PC5; long double E_total = E_local_DP + E_envoi + E_calcul_DS + E_resultat; return (E_total - minE) / (maxE - minE); } long double getEnergieS4(Tache ti,Vehicule vehicule_police) { long double E_envoi = ti.getDi()*E_PC5; long double E_local_VP = 0; if (vehicule_police.estElectrique()) { E_local_VP = vehicule_police.ECalculCPU(ti.getCi()); } long double E_total = E_envoi + E_local_VP; return (E_total - minE) / (maxE - minE); } long double getEnergieS5(Tache ti) { long double E_total = (ti.getDi() * E_PC5) + (ti.getDi() * E_LTEA); return (E_total - minE) / (maxE - minE); } long double getEnergieS6(Tache ti, Vehicule vehicule_police, Vehicule vehicule_voisin) { long double taux_de_partage = 0.5; //Energie long double E_envoi = (ti.getDi()*E_PC5); if (vehicule_police.estElectrique()) { E_envoi = (ti.getDi()*E_PC5) + (taux_de_partage * E_PC5); } long double E_local_VV = 0; long double E_resultat = 0; if (vehicule_voisin.estElectrique()) { E_local_VV = vehicule_voisin.ECalculCPU(taux_de_partage *ti.getCi()); E_resultat = taux_de_partage * ti.getRsi(); } long double E_total = E_envoi + E_local_VV + E_resultat; return (E_total - minE) / (maxE - minE); } long double getEnergieS7(Tache ti, Vehicule vehicule_police) { long double taux_de_partage = 0.5; long double E_envoi = (ti.getDi()*E_PC5); long double E_local_VP = 0; if (vehicule_police.estElectrique()) { E_envoi = E_envoi + (taux_de_partage*ti.getDi()* E_PC5); E_local_VP = vehicule_police.ECalculCPU(ti.getCi()); } long double E_total = E_envoi + E_local_VP; return (E_total - minE) / (maxE - minE); } //////////////////////////////////////// Functions for retrieving the delay for each strategy ///////////////////////////////////////////// long double getTempsS1(Tache ti, Drone drone_pricipal) { long double T_resultat = ti.getRsi() / (Debit_PC5 * 1000); long double T_total = drone_pricipal.TCalculCPU(ti.getCi()) + T_resultat; return (T_total - minT) / (maxT - minT); } long double getTempsS2(Tache ti,ServeurEdge serveur_edge) { //Temps long double T_envoi_SE = ti.getDi() / (Debit_LTEA * 1000); long double T_calcul_SE = serveur_edge.TCalculCPU(ti.getCi()); long double T_resultat = (ti.getRsi() / (Debit_LTEA * 1000)) + (ti.getRsi() / (Debit_PC5 * 1000)); long double T_total = T_envoi_SE + T_calcul_SE + T_resultat; return (T_total - minT) / (maxT - minT); } long double getTempsS3(Tache ti, Drone drone_pricipal, std::vector <Drone> drones_secondaires) { long double nb_drones = drones_secondaires.size() + 1; std::vector<long double> taux_de_partage; taux_de_partage.push_back(0.4); taux_de_partage.push_back(0.4); long double taux_total = 0; for (int i = 0; i < taux_de_partage.size(); i++) { taux_total = taux_total + taux_de_partage[i]; } //Temps long double T_local_DP = drone_pricipal.TCalculCPU((1 - taux_total) *ti.getCi()); long double T_envoi = (taux_total*ti.getDi()) / (Debit_PC5 * 1000); /*long double T_calcul_DS=0; for (int i = 0; i < drones_secondaires.size(); i++) { long double temp_t = drones_secondaires[i].TCalculCPU(taux_de_partage*ti.getCi()); if (temp_t > T_calcul_DS) T_calcul_DS = temp_t; } */ long double T_calcul_DS = 0; for (int i = 0; i < drones_secondaires.size(); i++) { T_calcul_DS = T_calcul_DS + drones_secondaires[i].TCalculCPU(taux_de_partage[i] * ti.getCi()); } T_calcul_DS = T_calcul_DS / nb_drones; long double T_resultat_DS = (taux_total*ti.getRsi()) / (Debit_PC5 * 1000); long double T_resultat = T_resultat_DS + (ti.getRsi() / (Debit_PC5 * 1000)); long double T_total = T_local_DP + T_envoi + T_calcul_DS + T_resultat; return (T_total - minT) / (maxT - minT); } long double getTempsS4(Tache ti,Vehicule vehicule_police) { //Temps long double T_envoi = ti.getDi() / (Debit_PC5 * 1000); long double T_local_VP = vehicule_police.TCalculCPU(ti.getCi()); long double T_total = T_envoi + T_local_VP; return (T_total - minT) / (maxT - minT); } long double getTempsS5(Tache ti, ServeurEdge serveur_edge) { //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + (ti.getDi() / (Debit_LTEA * 1000)); long double T_local_SE = serveur_edge.TCalculCPU(ti.getCi()); long double T_resultat = ti.getRsi() / (Debit_LTEA * 1000); long double T_total = T_envoi + T_local_SE + T_resultat; return (T_total - minT) / (maxT - minT); } long double getTempsS6(Tache ti, Vehicule vehicule_voisin) { long double taux_de_partage = 0.5; //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + ((taux_de_partage*ti.getDi()) / (Debit_PC5 * 1000)); long double T_local_VV = vehicule_voisin.TCalculCPU(taux_de_partage*ti.getCi()); long double T_resultat = (taux_de_partage * ti.getRsi()) / (Debit_PC5 * 1000); long double T_total = T_envoi + T_local_VV + T_resultat; return (T_total - minT) / (maxT - minT); } long double getTempsS7(Tache ti,Vehicule vehicule_police ) { long double taux_de_partage = 0.5; //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + ((taux_de_partage*ti.getDi()) / (Debit_PC5 * 1000)); long double T_local_VP = vehicule_police.TCalculCPU(ti.getCi()); long double T_total = T_envoi + T_local_VP; return (T_total - minT) / (maxT - minT); } //////////////////////////////////////// Functions to retrieve the communication cost of each strategy ///////////////////////////////////////////// long double getCES1(Tache ti) { return 0; } long double getCES2(Tache ti) { long double C_envoi_SE = (ti.getDi()*C_LTEA); return (C_envoi_SE - minCE) / (maxCE - minCE); } long double getCES3(Tache ti) { return 0; } long double getCES4(Tache ti) { return 0; } long double getCES5(Tache ti) { long double C_envoi_SE = ti.getDi()*C_LTEA; return (C_envoi_SE - minCE) / (maxCE - minCE); } long double getCES6(Tache ti) { return 0; } long double getCES7(Tache ti) { return 0; } //////////////////////////////////////// Functions for retrieving the computation cost of each strategy ///////////////////////////////////////////// long double getCCS1(Tache ti) { return 0; } long double getCCS2(Tache ti) { long double C_calcul_SE2 = (ti.getCi()*C_Calcul_SE); return (C_calcul_SE2 - minCC) / (maxCC - minCC); } long double getCCS3(Tache ti) { return 0; } long double getCCS4(Tache ti) { return 0; } long double getCCS5(Tache ti) { long double C_calcul_SE3 = ti.getCi()*C_Calcul_SE; return (C_calcul_SE3 - minCC) / (maxCC - minCC); } long double getCCS6(Tache ti) { long double C_calcul_VV2 = ti.getCi()*C_Calcul_VV; return (C_calcul_VV2 - minCC) / (maxCC - minCC); } long double getCCS7(Tache ti) { return 0; } ///////////////////////////////////////////// Function to calculate the utility of each strategy ////////////////////////////////////////////////////// // function to determine the utility of local computation in the main drone long double calcul_local_DP(Tache ti, Drone drone_pricipal) { //Temps long double T_resultat = ti.getRsi() / (Debit_PC5 * 1000); long double T_total = drone_pricipal.TCalculCPU(ti.getCi()) + T_resultat; //Energie long double E_resultat = ti.getRsi()*E_PC5; long double E_total = drone_pricipal.ECalculCPU(ti.getCi()) + E_resultat; //drone_pricipal.majEnergie(E_total*0.001); if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; } T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); //cout << "T_total: " << T_total << " E_total:" << E_total << " U1: " << ((α*T_total + β * E_total) / δ * (QoL_DP_VP + 1))<<"\n"; return ((α*T_total + β * E_total) / (δ * QoL_DP_VP + 1)); } // function to calculate the utility of the load shedding of the calculation to the ES long double calcul_delestage_SE(Tache ti,ServeurEdge serveur_edge) { //Temps long double T_envoi_SE = ti.getDi() / (Debit_LTEA * 1000); long double T_calcul_SE = serveur_edge.TCalculCPU(ti.getCi()); long double T_resultat = (ti.getRsi() / (Debit_LTEA * 1000)) + (ti.getRsi() / (Debit_PC5 * 1000)); long double T_total = T_envoi_SE + T_calcul_SE + T_resultat; //Energie long double E_envoi_SE = ti.getDi()*E_LTEA; long double E_resultat = ti.getRsi()*E_PC5; long double E_total = E_envoi_SE + E_resultat; //Coût envoi/calcul long double C_envoi_SE = (ti.getDi()*C_LTEA); long double C_calcul_SE2 = (ti.getCi()*C_Calcul_SE); std::cout << "---------------------------------------------------------------------- \n"; //drone_pricipal.majEnergie(E_total*0.001); //cout << " T envoi au SE " << T_envoi_SE << " T calcul local SE " << T_calcul_SE << " envoi du resulat au VP " << T_resultat << " CoutEn " << C_envoi_SE << " CoutCC " << C_calcul_SE2 << " (λ*C_calcul_SE2) " << (λ*C_calcul_SE2) << "\n"; //cout << "C_calcul_SE2 " << C_calcul_SE2 << " maxCC: " << maxCC << " minCC: " << minCC << "\n"; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; if (C_envoi_SE > maxCE) maxCE = C_envoi_SE; if (C_envoi_SE < minCE) minCE = C_envoi_SE; if (C_calcul_SE2 > maxCC) maxCC = C_calcul_SE2; if (C_calcul_SE2 < minCC) minCC = C_calcul_SE2; } //cout <<"C_calcul_SE2 " << C_calcul_SE2 << " maxCC: " << maxCC << " minCC: " << minCC << "\n"; T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); if (!envoi_et_calcul_gratuit) { C_envoi_SE = (C_envoi_SE - minCE) / (maxCE - minCE); C_calcul_SE2 = (C_calcul_SE2 - minCC) / (maxCC - minCC); } long double QoL = (QoL_DP_SE + QoL_DP_VP) / 2; //cout << " T envoi au SE " << T_envoi_SE << " T calcul local SE " << T_calcul_SE << " envoi du resulat au VP " << T_resultat << " CoutEn " << C_envoi_SE << " CoutCC " << C_calcul_SE2 << " (λ*C_calcul_SE2) " << (λ*C_calcul_SE2) << "\n"; return ((α * T_total + β * E_total) / (δ * QoL + 1)) + (γ*C_envoi_SE) + (λ*C_calcul_SE2); } // function for caclulating the utility of sharing the computation with secondary drones long double calcul_partage_DS(Tache ti, Drone drone_pricipal, std::vector <Drone> drones_secondaires) { long double nb_drones = drones_secondaires.size() + 1; std::vector<long double> taux_de_partage; taux_de_partage.push_back(0.4); taux_de_partage.push_back(0.4); long double taux_total = 0; for (int i = 0; i < taux_de_partage.size(); i++) { taux_total = taux_total + taux_de_partage[i]; } //Temps long double T_local_DP = drone_pricipal.TCalculCPU((1 - taux_total) *ti.getCi()); long double T_envoi = (taux_total*ti.getDi()) / (Debit_PC5 * 1000); /*long double T_calcul_DS=0; for (int i = 0; i < drones_secondaires.size(); i++) { long double temp_t = drones_secondaires[i].TCalculCPU(taux_de_partage*ti.getCi()); if (temp_t > T_calcul_DS) T_calcul_DS = temp_t; } */ long double T_calcul_DS = 0; for (int i = 0; i < drones_secondaires.size(); i++) { T_calcul_DS = T_calcul_DS + drones_secondaires[i].TCalculCPU(taux_de_partage[i] * ti.getCi()); } T_calcul_DS = T_calcul_DS / nb_drones; long double T_resultat_DS = (taux_total*ti.getRsi()) / (Debit_PC5 * 1000); long double T_resultat = T_resultat_DS + (ti.getRsi() / (Debit_PC5 * 1000)); long double T_total = T_local_DP + T_envoi + T_calcul_DS + T_resultat; //Energie long double E_local_DP = drone_pricipal.ECalculCPU((1 - taux_total) *ti.getCi()); long double E_envoi = taux_total * ti.getDi()*E_PC5; long double E_calcul_DS = 0; for (int i = 0; i < drones_secondaires.size(); i++) { E_calcul_DS = E_calcul_DS + drones_secondaires[i].ECalculCPU(taux_de_partage[i] * ti.getCi()); //drones_secondaires[i].majEnergie(drones_secondaires[i].ECalculCPU(taux_de_partage*ti.getCi() + taux_de_partage * ti.getRsi()*E_PC5*0.001)); } long double E_resultat_DS = taux_total * ti.getRsi() * E_PC5; long double E_resultat = E_resultat_DS + ti.getRsi() * E_PC5; long double E_total = E_local_DP + E_envoi + E_calcul_DS + E_resultat; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; } T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); long double QoL = (QoL_DP_DS + QoL_DP_VP) / 2; return ((α*T_total + β * E_total) / (δ * QoL + 1)); } // function to calculate the utility of offloading the calculation to AV + Local computation in AV long double calcul_local_VP(Tache ti,Vehicule vehicule_police) { //Temps long double T_envoi = ti.getDi() / (Debit_PC5 * 1000); long double T_local_VP = vehicule_police.TCalculCPU(ti.getCi()); long double T_total = T_envoi + T_local_VP; // cout << "T envoi au vp" << T_envoi << "T calcul local VP" << T_local_VP <<"\n"; //Energie long double E_envoi = ti.getDi()*E_PC5; long double E_local_VP = 0; if (vehicule_police.estElectrique()) { E_local_VP = vehicule_police.ECalculCPU(ti.getCi()); } long double E_total = E_envoi + E_local_VP; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; } T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); return ((α*T_total + β * E_total) / (δ * QoL_DP_VP + 1)); } // function to calculate the usefulness of offloading the calculation to the AV + offloading the calculation to the ES by the AV long double calcul_delestage_VP_SE(Tache ti, ServeurEdge serveur_edge) { //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + (ti.getDi() / (Debit_LTEA * 1000)); long double T_local_SE = serveur_edge.TCalculCPU(ti.getCi()); long double T_resultat = ti.getRsi() / (Debit_LTEA * 1000); long double T_total = T_envoi + T_local_SE + T_resultat; //Energie long double E_envoi = (ti.getDi() * E_PC5) + (ti.getDi() * E_LTEA); long double E_total = E_envoi; //Coût envoi/calcul long double C_envoi_SE = ti.getDi()*C_LTEA; long double C_calcul_SE3 = ti.getCi()*C_Calcul_SE; std::cout << "C_calcul_SEVP " << C_calcul_SE3 << " maxCC: " << maxCC << " minCC: " << minCC << "\n"; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; if (C_envoi_SE > maxCE) maxCE = C_envoi_SE; if (C_envoi_SE < minCE) minCE = C_envoi_SE; if (C_calcul_SE3 > maxCC) maxCC = C_calcul_SE3; if (C_calcul_SE3 < minCC) minCC = C_calcul_SE3; } std::cout << "C_calcul_SEVP " << C_calcul_SE3 << " maxCC: " << maxCC << " minCC: " << minCC << "\n"; T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); if (!envoi_et_calcul_gratuit) { C_envoi_SE = (C_envoi_SE - minCE) / (maxCE - minCE); C_calcul_SE3 = (C_calcul_SE3 - minCC) / (maxCC - minCC); } long double QoL = (QoL_DP_VP + QoL_VP_SE) / 2; //cout << "T_total: " << T_total << " E_total:" << E_total << "C_envoi_SE: " << C_envoi_SE << " C_calcul_SE:" << C_calcul_SE << " U5: " << ((α * T_total + β * E_total) / (δ * (QoL + 1))) + (γ*C_envoi_SE) + (λ*C_calcul_SE) << "\n"; return ((α * T_total + β * E_total) / (δ * QoL + 1)) + (γ*C_envoi_SE) + (λ*C_calcul_SE3); } // function to calculate the utility of offloading the calculation to AV + sharing of the computation with NV + acceptance of the computation by NV long double calcul_partage_VV_accpt(Tache ti,Vehicule vehicule_police,Vehicule vehicule_voisin) { long double taux_de_partage = 0.6; //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + ((taux_de_partage*ti.getDi()) / (Debit_PC5 * 1000)); long double T_local_VV = vehicule_voisin.TCalculCPU(taux_de_partage*ti.getCi()); long double T_resultat = (taux_de_partage * ti.getRsi()) / (Debit_PC5 * 1000); long double T_total = T_envoi + T_local_VV + T_resultat; //Energie long double E_envoi = (ti.getDi()*E_PC5); if (vehicule_police.estElectrique()) { E_envoi = (ti.getDi()*E_PC5) + (taux_de_partage * E_PC5); } long double E_local_VV = 0; long double E_resultat = 0; if (vehicule_voisin.estElectrique()) { E_local_VV = vehicule_voisin.ECalculCPU(taux_de_partage *ti.getCi()); E_resultat = taux_de_partage * ti.getRsi(); } long double E_total = E_envoi + E_local_VV + E_resultat; //Coût calcul long double C_calcul_VV2 = ti.getCi()*C_Calcul_VV; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; if (C_calcul_VV2 > maxCC) maxCC = C_calcul_VV2; if (C_calcul_VV2 < minCC) minCC = C_calcul_VV2; } T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); if (!envoi_et_calcul_gratuit) { C_calcul_VV2 = (C_calcul_VV2 - minCC) / (maxCC - minCC); } long double QoL = (QoL_DP_VP + QoL_VP_VV) / 2; return ((α * T_total + β * E_total) / (δ * QoL + 1)) + (λ*C_calcul_VV2); } // function to calculate the utility of offloading the calculation to AV + sharing of the computation with NV + refusing of the computation by NV long double calcul_partage_VV_refu(Tache ti,Vehicule vehicule_police) { long double taux_de_partage = 0.5; //Temps long double T_envoi = (ti.getDi() / (Debit_PC5 * 1000)) + ((taux_de_partage*ti.getDi()) / (Debit_PC5 * 1000)); long double T_local_VP = vehicule_police.TCalculCPU(ti.getCi()); long double T_total = T_envoi + T_local_VP; //Energie long double E_envoi = (ti.getDi()*E_PC5); long double E_local_VP = 0; if (vehicule_police.estElectrique()) { E_envoi = E_envoi + (taux_de_partage*ti.getDi()* E_PC5); E_local_VP = vehicule_police.ECalculCPU(ti.getCi()); } long double E_total = E_envoi + E_local_VP; if (calculer_limites) { if (T_total > maxT) maxT = T_total; if (T_total < minT) minT = T_total; if (E_total > maxE) maxE = E_total; if (E_total < minE) minE = E_total; } T_total = (T_total - minT) / (maxT - minT); E_total = (E_total - minE) / (maxE - minE); long double QoL = (QoL_DP_VP + QoL_VP_VV) / 2; return ((α * T_total + β * E_total) / (δ * QoL + 1)); } void calibrer_limites(Drone drone_pricipal,ServeurEdge serveur_edge, Vehicule vehicule_police, Vehicule vehicule_voisin, std::vector <Drone> drones_secondaires, std::vector <Tache> taches, std::map < int, long double > utilites_Local, std::map < int, long double > utilites_Delestage_SE, std::map < int, long double > utilites_Partage_DS, std::map < int, long double > utilites_Local_VP, std::map < int, long double > utilites_VP_Delestage_SE, std::map < int, long double > utilites_VP_Partage_VV_accpt, std::map < int, long double > utilites_VP_Partage_VV_refu) { long double cycle_cpu = cycle_cpu_var; long double max_cycle_cpu = max_cycle_cpu_var; long double taille_resultat = taille_resultat_var; long double tailleDonnee = tailleDonnee_var; long double maxTaille = maxTaille_var; // Loop for initializing the values of the tasks to be calculated as such Ci =[500000,...,10000000], Di=5Mo, Rsi=5ko int iter = 1; std::map<long double, Utilite> utilites_CPU; std::map<long double, Energie> energies_CPU; std::map<long double, Temps> temps_CPU; std::map<long double, CoutEnvoie> coutEnvoi_CPU; std::map<long double, CoutCalcul> coutCalcul_CPU; while (tailleDonnee <= maxTaille) { int i = 0; taches.clear(); while (cycle_cpu <= max_cycle_cpu) { Tache tachei(i, cycle_cpu, tailleDonnee, taille_resultat, 1); taches.push_back(tachei); cycle_cpu = cycle_cpu * 2; i++; } std::multimap < int, Tache> ::iterator itr; int meilleurStrategie;// variable used to store the strategy having the best utility for each task long double meilleurUtilite; long double meilleurEnergie; long double meilleurTemps; long double meilleurCoutEnvoi; long double meilleurCoutCalcul; long double temp_util = 0; long double temp_energ = 0; long double temp_temps = 0; long double temp_ce = 0; long double temp_cc = 0; for (int c = 0; c < taches.size(); c++) { Utilite temp_util_obj; Energie temp_ener_obj; Temps temp_temps_obj; CoutEnvoie temp_ce_obj; CoutCalcul temp_cc_obj; Tache ti = taches[c]; meilleurStrategie = 1; meilleurUtilite = 0; meilleurEnergie = 0; meilleurTemps = 0; meilleurCoutEnvoi = 0; meilleurCoutCalcul = 0; // S1 : local computation temp_util = calcul_local_DP(ti,drone_pricipal); temp_energ = getEnergieS1(ti, drone_pricipal); temp_temps = getTempsS1(ti, drone_pricipal); temp_ce = getCES1(ti); temp_cc = getCCS1(ti); if (iter == 1) { temp_util_obj.setU1(temp_util); temp_ener_obj.setE1(temp_energ); temp_temps_obj.setT1(temp_temps); temp_ce_obj.setCE1(temp_ce); temp_cc_obj.setCC1(temp_cc); } else { utilites_CPU[ti.getCi()].setU1(utilites_CPU[ti.getCi()].getU1() + temp_util); energies_CPU[ti.getCi()].setE1(energies_CPU[ti.getCi()].getE1() + temp_energ); temps_CPU[ti.getCi()].setT1(temps_CPU[ti.getCi()].getT1() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE1(coutEnvoi_CPU[ti.getCi()].getCE1() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC1(coutCalcul_CPU[ti.getCi()].getCC1() + temp_cc); } utilites_Local.insert(std::pair<int, long double>(ti.getId(), temp_util)); meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; // S2 : offloading to Edge server temp_util = calcul_delestage_SE(ti, serveur_edge); temp_energ = getEnergieS2(ti); temp_temps = getTempsS2(ti, serveur_edge); temp_ce = getCES2(ti); temp_cc = getCCS2(ti); if (iter == 1) { temp_util_obj.setU2(temp_util); temp_ener_obj.setE2(temp_energ); temp_temps_obj.setT2(temp_temps); temp_ce_obj.setCE2(temp_ce); temp_cc_obj.setCC2(temp_cc); } else { utilites_CPU[ti.getCi()].setU2(utilites_CPU[ti.getCi()].getU2() + temp_util); energies_CPU[ti.getCi()].setE2(energies_CPU[ti.getCi()].getE2() + temp_energ); temps_CPU[ti.getCi()].setT2(temps_CPU[ti.getCi()].getT2() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE2(coutEnvoi_CPU[ti.getCi()].getCE2() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC2(coutCalcul_CPU[ti.getCi()].getCC2() + temp_cc); } utilites_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 2; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S3 : sharing with secondary drones temp_util = calcul_partage_DS(ti,drone_pricipal, drones_secondaires); temp_energ = getEnergieS3(ti,drone_pricipal, drones_secondaires); temp_temps = getTempsS3(ti,drone_pricipal, drones_secondaires); temp_ce = getCES3(ti); temp_cc = getCCS3(ti); if (iter == 1) { temp_util_obj.setU3(temp_util); temp_ener_obj.setE3(temp_energ); temp_temps_obj.setT3(temp_temps); temp_ce_obj.setCE3(temp_ce); temp_cc_obj.setCC3(temp_cc); } else { utilites_CPU[ti.getCi()].setU3(utilites_CPU[ti.getCi()].getU3() + temp_util); energies_CPU[ti.getCi()].setE3(energies_CPU[ti.getCi()].getE3() + temp_energ); temps_CPU[ti.getCi()].setT3(temps_CPU[ti.getCi()].getT3() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE3(coutEnvoi_CPU[ti.getCi()].getCE3() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC3(coutCalcul_CPU[ti.getCi()].getCC3() + temp_cc); } utilites_Partage_DS.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 3; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S4 : offloading to authority vehicle + local computation in authority vehicle temp_util = calcul_local_VP(ti, vehicule_police); temp_energ = getEnergieS4(ti, vehicule_police); temp_temps = getTempsS4(ti, vehicule_police); temp_ce = getCES4(ti); temp_cc = getCCS4(ti); if (iter == 1) { temp_util_obj.setU4(temp_util); temp_ener_obj.setE4(temp_energ); temp_temps_obj.setT4(temp_temps); temp_ce_obj.setCE4(temp_ce); temp_cc_obj.setCC4(temp_cc); } else { utilites_CPU[ti.getCi()].setU4(utilites_CPU[ti.getCi()].getU4() + temp_util); energies_CPU[ti.getCi()].setE4(energies_CPU[ti.getCi()].getE4() + temp_energ); temps_CPU[ti.getCi()].setT4(temps_CPU[ti.getCi()].getT4() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE4(coutEnvoi_CPU[ti.getCi()].getCE4() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC4(coutCalcul_CPU[ti.getCi()].getCC4() + temp_cc); } utilites_Local_VP.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 4; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S5 : offloading to authority vehicle + offloading to Edge server by the authority vehicle temp_util = calcul_delestage_VP_SE(ti, serveur_edge); temp_energ = getEnergieS5(ti); temp_temps = getTempsS5(ti, serveur_edge); temp_ce = getCES5(ti); temp_cc = getCCS5(ti); if (iter == 1) { temp_util_obj.setU5(temp_util); temp_ener_obj.setE5(temp_energ); temp_temps_obj.setT5(temp_temps); temp_ce_obj.setCE5(temp_ce); temp_cc_obj.setCC5(temp_cc); } else { utilites_CPU[ti.getCi()].setU5(utilites_CPU[ti.getCi()].getU5() + temp_util); energies_CPU[ti.getCi()].setE5(energies_CPU[ti.getCi()].getE5() + temp_energ); temps_CPU[ti.getCi()].setT5(temps_CPU[ti.getCi()].getT5() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE5(coutEnvoi_CPU[ti.getCi()].getCE5() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC5(coutCalcul_CPU[ti.getCi()].getCC5() + temp_cc); } utilites_VP_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 5; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S6 : offloading to authority vehicle + sharing with nearby vehicle + accpet computation by nearby vehicle temp_util = calcul_partage_VV_accpt(ti, vehicule_police, vehicule_voisin); temp_energ = getEnergieS6(ti, vehicule_police, vehicule_voisin); temp_temps = getTempsS6(ti, vehicule_voisin); temp_ce = getCES6(ti); temp_cc = getCCS6(ti); if (iter == 1) { temp_util_obj.setU6(temp_util); temp_ener_obj.setE6(temp_energ); temp_temps_obj.setT6(temp_temps); temp_ce_obj.setCE6(temp_ce); temp_cc_obj.setCC6(temp_cc); } else { utilites_CPU[ti.getCi()].setU6(utilites_CPU[ti.getCi()].getU6() + temp_util); energies_CPU[ti.getCi()].setE6(energies_CPU[ti.getCi()].getE6() + temp_energ); temps_CPU[ti.getCi()].setT6(temps_CPU[ti.getCi()].getT6() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE6(coutEnvoi_CPU[ti.getCi()].getCE6() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC6(coutCalcul_CPU[ti.getCi()].getCC6() + temp_cc); } utilites_VP_Partage_VV_accpt.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 6; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S7 : offloading to authority vehicle + sharing with nearby vehicle + refuse computation by nearby vehicle temp_util = calcul_partage_VV_refu(ti, vehicule_police); temp_energ = getEnergieS7(ti,vehicule_police); temp_temps = getTempsS7(ti, vehicule_police); temp_ce = getCES7(ti); temp_cc = getCCS7(ti); if (iter == 1) { temp_util_obj.setU7(temp_util); temp_ener_obj.setE7(temp_energ); temp_temps_obj.setT7(temp_temps); temp_ce_obj.setCE7(temp_ce); temp_cc_obj.setCC7(temp_cc); } else { utilites_CPU[ti.getCi()].setU7(utilites_CPU[ti.getCi()].getU7() + temp_util); energies_CPU[ti.getCi()].setE7(energies_CPU[ti.getCi()].getE7() + temp_energ); temps_CPU[ti.getCi()].setT7(temps_CPU[ti.getCi()].getT7() + temp_temps); coutEnvoi_CPU[ti.getCi()].setCE7(coutEnvoi_CPU[ti.getCi()].getCE7() + temp_ce); coutCalcul_CPU[ti.getCi()].setCC7(coutCalcul_CPU[ti.getCi()].getCC7() + temp_cc); } utilites_VP_Partage_VV_refu.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 7; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } if (iter == 1) { temp_util_obj.setGt(meilleurUtilite); temp_ener_obj.setGt(meilleurEnergie); temp_temps_obj.setGt(meilleurTemps); temp_ce_obj.setGt(meilleurCoutEnvoi); temp_cc_obj.setGt(meilleurCoutCalcul); } else { utilites_CPU[ti.getCi()].setGt(utilites_CPU[ti.getCi()].getGt() + meilleurUtilite); energies_CPU[ti.getCi()].setGt(energies_CPU[ti.getCi()].getGt() + meilleurEnergie); temps_CPU[ti.getCi()].setGt(temps_CPU[ti.getCi()].getGt() + meilleurTemps); coutEnvoi_CPU[ti.getCi()].setGt(coutEnvoi_CPU[ti.getCi()].getGt() + meilleurCoutEnvoi); coutCalcul_CPU[ti.getCi()].setGt(coutCalcul_CPU[ti.getCi()].getGt() + meilleurCoutCalcul); } if (iter == 1) { utilites_CPU.insert(std::pair<long double, Utilite>(ti.getCi(), temp_util_obj)); energies_CPU.insert(std::pair<long double, Energie>(ti.getCi(), temp_ener_obj)); temps_CPU.insert(std::pair<long double, Temps>(ti.getCi(), temp_temps_obj)); coutEnvoi_CPU.insert(std::pair<long double, CoutEnvoie>(ti.getCi(), temp_ce_obj)); coutCalcul_CPU.insert(std::pair<long double, CoutCalcul>(ti.getCi(), temp_cc_obj)); } std::cout << "Ci " << ti.getCi() << " Di " << ti.getDi() << " Rsi " << ti.getRsi() << " Meuilleur Decision:" << meilleurStrategie << '\n'; std::cout << "Tache num " << ti.getId() << "Ci" << ti.getCi() << " U1 " << utilites_CPU[ti.getCi()].getU1() << " U2 " << utilites_CPU[ti.getCi()].getU2() << " U3 " << utilites_CPU[ti.getCi()].getU3() << " U4 " << utilites_CPU[ti.getCi()].getU4() << " U5 " << utilites_CPU[ti.getCi()].getU5() << " U6 " << utilites_CPU[ti.getCi()].getU6() << "U7 " << utilites_CPU[ti.getCi()].getU7() << "Meuilleur S" << utilites_CPU[ti.getCi()].getGt() << '\n'; } iter++; cycle_cpu = cycle_cpu_var; tailleDonnee = tailleDonnee * 2; } cycle_cpu = cycle_cpu_var; max_cycle_cpu = max_cycle_cpu_var; taille_resultat = taille_resultat_var; tailleDonnee = tailleDonnee_var; maxTaille = maxTaille_var; // Loop for initializing the values of the tasks to be calculated as such Ci =[500000,...,10000000], Di=5Mo, Rsi=5ko iter = 1; // matrice pour stocker l'utilité de chaque strategie+GT selon le changement de cycle CPU [Cycle_CPU, [U1,U2,U3,U4,U5,U6,U7,GT]] std::map<long double, Utilite> utilites_Donnees; std::map<long double, Energie> energie_Donnees; std::map<long double, Temps> temps_Donnees; std::map<long double, CoutEnvoie> coutEnvoi_Donnees; std::map<long double, CoutCalcul> coutCalcul_Donnees; while (cycle_cpu <= max_cycle_cpu) { int i = 0; taches.clear(); while (tailleDonnee <= maxTaille) { Tache tachei(i, cycle_cpu, tailleDonnee, taille_resultat, 1); taches.push_back(tachei); tailleDonnee = tailleDonnee * 2; i++; } std::multimap < int, Tache> ::iterator itr; int meilleurStrategie;// variable used to store the strategy having the best utility for each task long double meilleurUtilite; long double meilleurEnergie; long double meilleurTemps; long double meilleurCoutEnvoi; long double meilleurCoutCalcul; long double temp_util = 0; long double temp_energ = 0; long double temp_temps = 0; long double temp_ce = 0; long double temp_cc = 0; for (int c = 0; c < taches.size(); c++) { Utilite temp_util_obj; Energie temp_energ_obj; Temps temp_temps_obj; CoutEnvoie temp_ce_obj; CoutCalcul temp_cc_obj; Tache ti = taches[c]; meilleurStrategie = 1; meilleurUtilite = 0; meilleurEnergie = 0; meilleurTemps = 0; meilleurCoutEnvoi = 0; meilleurCoutCalcul = 0; // S1 : local computation temp_util = calcul_local_DP(ti, drone_pricipal); temp_energ = getEnergieS1(ti, drone_pricipal); temp_temps = getTempsS1(ti,drone_pricipal); temp_ce = getCES1(ti); temp_cc = getCCS1(ti); if (iter == 1) { temp_util_obj.setU1(temp_util); temp_energ_obj.setE1(temp_energ); temp_temps_obj.setT1(temp_temps); temp_ce_obj.setCE1(temp_ce); temp_cc_obj.setCC1(temp_cc); } else { utilites_Donnees[ti.getDi()].setU1(utilites_Donnees[ti.getDi()].getU1() + temp_util); energie_Donnees[ti.getDi()].setE1(energie_Donnees[ti.getDi()].getE1() + temp_energ); temps_Donnees[ti.getDi()].setT1(temps_Donnees[ti.getDi()].getT1() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE1(coutEnvoi_Donnees[ti.getDi()].getCE1() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC1(coutCalcul_Donnees[ti.getDi()].getCC1() + temp_cc); } utilites_Local.insert(std::pair<int, long double>(ti.getId(), temp_util)); meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; // S2 : offloading to Edge server temp_util = calcul_delestage_SE(ti, serveur_edge); temp_energ = getEnergieS2(ti); temp_temps = getTempsS2(ti, serveur_edge); temp_ce = getCES2(ti); temp_cc = getCCS2(ti); if (iter == 1) { temp_util_obj.setU2(temp_util); temp_energ_obj.setE2(temp_energ); temp_temps_obj.setT2(temp_temps); temp_ce_obj.setCE2(temp_ce); temp_cc_obj.setCC2(temp_cc); } else { utilites_Donnees[ti.getDi()].setU2(utilites_Donnees[ti.getDi()].getU2() + temp_util); energie_Donnees[ti.getDi()].setE2(energie_Donnees[ti.getDi()].getE2() + temp_energ); temps_Donnees[ti.getDi()].setT2(temps_Donnees[ti.getDi()].getT2() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE2(coutEnvoi_Donnees[ti.getDi()].getCE2() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC2(coutCalcul_Donnees[ti.getDi()].getCC2() + temp_cc); } utilites_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 2; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S3 : sharing with secondary drones temp_util = calcul_partage_DS(ti, drone_pricipal, drones_secondaires); temp_energ = getEnergieS3(ti, drone_pricipal, drones_secondaires); temp_temps = getTempsS3(ti, drone_pricipal, drones_secondaires); temp_ce = getCES3(ti); temp_cc = getCCS3(ti); if (iter == 1) { temp_util_obj.setU3(temp_util); temp_energ_obj.setE3(temp_energ); temp_temps_obj.setT3(temp_temps); temp_ce_obj.setCE3(temp_ce); temp_cc_obj.setCC3(temp_cc); } else { utilites_Donnees[ti.getDi()].setU3(utilites_Donnees[ti.getDi()].getU3() + temp_util); energie_Donnees[ti.getDi()].setE3(energie_Donnees[ti.getDi()].getE3() + temp_energ); temps_Donnees[ti.getDi()].setT3(temps_Donnees[ti.getDi()].getT3() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE3(coutEnvoi_Donnees[ti.getDi()].getCE3() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC3(coutCalcul_Donnees[ti.getDi()].getCC3() + temp_cc); } utilites_Partage_DS.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 3; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S4 : offloading to authority vehicle + local computation in authority vehicle temp_util = calcul_local_VP(ti, vehicule_police); temp_energ = getEnergieS4(ti,vehicule_police); temp_temps = getTempsS4(ti, vehicule_police); temp_ce = getCES4(ti); temp_cc = getCCS4(ti); if (iter == 1) { temp_util_obj.setU4(temp_util); temp_energ_obj.setE4(temp_energ); temp_temps_obj.setT4(temp_temps); temp_ce_obj.setCE4(temp_ce); temp_cc_obj.setCC4(temp_cc); } else { utilites_Donnees[ti.getDi()].setU4(utilites_Donnees[ti.getDi()].getU4() + temp_util); energie_Donnees[ti.getDi()].setE4(energie_Donnees[ti.getDi()].getE4() + temp_energ); temps_Donnees[ti.getDi()].setT4(temps_Donnees[ti.getDi()].getT4() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE4(coutEnvoi_Donnees[ti.getDi()].getCE4() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC4(coutCalcul_Donnees[ti.getDi()].getCC4() + temp_cc); } utilites_Local_VP.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 4; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S5 : offloading to authority vehicle + offloading to Edge server by the authority vehicle temp_util = calcul_delestage_VP_SE(ti, serveur_edge); temp_energ = getEnergieS5(ti); temp_temps = getTempsS5(ti, serveur_edge); temp_ce = getCES5(ti); temp_cc = getCCS5(ti); if (iter == 1) { temp_util_obj.setU5(temp_util); temp_energ_obj.setE5(temp_energ); temp_temps_obj.setT5(temp_temps); temp_ce_obj.setCE5(temp_ce); temp_cc_obj.setCC5(temp_cc); } else { utilites_Donnees[ti.getDi()].setU5(utilites_Donnees[ti.getDi()].getU5() + temp_util); energie_Donnees[ti.getDi()].setE5(energie_Donnees[ti.getDi()].getE5() + temp_energ); temps_Donnees[ti.getDi()].setT5(temps_Donnees[ti.getDi()].getT5() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE5(coutEnvoi_Donnees[ti.getDi()].getCE5() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC5(coutCalcul_Donnees[ti.getDi()].getCC5() + temp_cc); } utilites_VP_Delestage_SE.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 5; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S6 : offloading to authority vehicle + sharing with nearby vehicle + accpet computation by nearby vehicle temp_util = calcul_partage_VV_accpt(ti, vehicule_police, vehicule_voisin); temp_energ = getEnergieS6(ti, vehicule_police, vehicule_voisin); temp_temps = getTempsS6(ti, vehicule_voisin); temp_ce = getCES6(ti); temp_cc = getCCS6(ti); if (iter == 1) { temp_util_obj.setU6(temp_util); temp_energ_obj.setE6(temp_energ); temp_temps_obj.setT6(temp_temps); temp_ce_obj.setCE6(temp_ce); temp_cc_obj.setCC6(temp_cc); } else { utilites_Donnees[ti.getDi()].setU6(utilites_Donnees[ti.getDi()].getU6() + temp_util); energie_Donnees[ti.getDi()].setE6(energie_Donnees[ti.getDi()].getE6() + temp_energ); temps_Donnees[ti.getDi()].setT6(temps_Donnees[ti.getDi()].getT6() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE6(coutEnvoi_Donnees[ti.getDi()].getCE6() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC6(coutCalcul_Donnees[ti.getDi()].getCC6() + temp_cc); } utilites_VP_Partage_VV_accpt.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 6; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } //S7 : offloading to authority vehicle + sharing with nearby vehicle + refuse computation by nearby vehicle temp_util = calcul_partage_VV_refu(ti, vehicule_police); temp_energ = getEnergieS7(ti, vehicule_police); temp_temps = getTempsS7(ti, vehicule_police); temp_ce = getCES7(ti); temp_cc = getCCS7(ti); if (iter == 1) { temp_util_obj.setU7(temp_util); temp_energ_obj.setE7(temp_energ); temp_temps_obj.setT7(temp_temps); temp_ce_obj.setCE7(temp_ce); temp_cc_obj.setCC7(temp_cc); } else { utilites_Donnees[ti.getDi()].setU7(utilites_Donnees[ti.getDi()].getU7() + temp_util); energie_Donnees[ti.getDi()].setE7(energie_Donnees[ti.getDi()].getE7() + temp_energ); temps_Donnees[ti.getDi()].setT7(temps_Donnees[ti.getDi()].getT7() + temp_temps); coutEnvoi_Donnees[ti.getDi()].setCE7(coutEnvoi_Donnees[ti.getDi()].getCE7() + temp_ce); coutCalcul_Donnees[ti.getDi()].setCC7(coutCalcul_Donnees[ti.getDi()].getCC7() + temp_cc); } utilites_VP_Partage_VV_refu.insert(std::pair<int, long double>(ti.getId(), temp_util)); if (temp_util < meilleurUtilite) { meilleurStrategie = 7; meilleurUtilite = temp_util; meilleurEnergie = temp_energ; meilleurTemps = temp_temps; meilleurCoutEnvoi = temp_ce; meilleurCoutCalcul = temp_cc; } if (iter == 1) { temp_util_obj.setGt(meilleurUtilite); temp_energ_obj.setGt(meilleurEnergie); temp_temps_obj.setGt(meilleurTemps); temp_ce_obj.setGt(meilleurCoutEnvoi); temp_cc_obj.setGt(meilleurCoutCalcul); } else { utilites_Donnees[ti.getDi()].setGt(utilites_Donnees[ti.getDi()].getGt() + meilleurUtilite); energie_Donnees[ti.getDi()].setGt(energie_Donnees[ti.getDi()].getGt() + meilleurEnergie); temps_Donnees[ti.getDi()].setGt(temps_Donnees[ti.getDi()].getGt() + meilleurTemps); coutEnvoi_Donnees[ti.getDi()].setGt(coutEnvoi_Donnees[ti.getDi()].getGt() + meilleurCoutEnvoi); coutCalcul_Donnees[ti.getDi()].setGt(coutCalcul_Donnees[ti.getDi()].getGt() + meilleurCoutCalcul); } if (iter == 1) { utilites_Donnees.insert(std::pair<long double, Utilite>(ti.getDi(), temp_util_obj)); energie_Donnees.insert(std::pair<long double, Energie>(ti.getDi(), temp_energ_obj)); temps_Donnees.insert(std::pair<long double, Temps>(ti.getDi(), temp_temps_obj)); coutEnvoi_Donnees.insert(std::pair<long double, CoutEnvoie>(ti.getDi(), temp_ce_obj)); coutCalcul_Donnees.insert(std::pair<long double, CoutCalcul>(ti.getDi(), temp_cc_obj)); } std::cout << "Tache num " << ti.getId() << " Ci: " << ti.getCi() << " Di: " << ti.getDi() << " U1 " << utilites_Donnees[ti.getDi()].getU1() << " U2 " << utilites_Donnees[ti.getDi()].getU2() << " U3 " << utilites_Donnees[ti.getDi()].getU3() << " U4 " << utilites_Donnees[ti.getDi()].getU4() << " U5 " << utilites_Donnees[ti.getDi()].getU5() << " U6 " << utilites_Donnees[ti.getDi()].getU6() << "U7 " << utilites_Donnees[ti.getDi()].getU7() << "Meuilleur S" << meilleurStrategie << '\n'; } iter++; cycle_cpu = cycle_cpu * 2; tailleDonnee = tailleDonnee_var; } taches.clear(); std::cout << "MaxT: " << maxT << " minT: " << minT << " maxE: " << maxE << " minE: " << minE << " maxCE: " << maxCE << " minCE: " << minCE << " maxCC: " << maxCC << " minCC: " << minCC << "\n"; } }; } <file_sep>/Visual Studio Simulation/DroneSimulation/CoutCalcul.cpp #include "CoutCalcul.h" CoutCalcul::CoutCalcul() { } long double CoutCalcul::getCC1() { return cc1; } long double CoutCalcul::getCC2() { return cc2; } long double CoutCalcul::getCC3() { return cc3; } long double CoutCalcul::getCC4() { return cc4; } long double CoutCalcul::getCC5() { return cc5; } long double CoutCalcul::getCC6() { return cc6; } long double CoutCalcul::getCC7() { return cc7; } long double CoutCalcul::getGt() { return gt; } void CoutCalcul::setCC1(long double cc1) { this->cc1 = cc1; } void CoutCalcul::setCC2(long double cc2) { this->cc2 = cc2; } void CoutCalcul::setCC3(long double cc3) { this->cc3 = cc3; } void CoutCalcul::setCC4(long double cc4) { this->cc4 = cc4; } void CoutCalcul::setCC5(long double cc5) { this->cc5 = cc5; } void CoutCalcul::setCC6(long double cc6) { this->cc6 = cc6; } void CoutCalcul::setCC7(long double cc7) { this->cc7 = cc7; } void CoutCalcul::setGt(long double gt) { this->gt = gt; }<file_sep>/Visual Studio Simulation/DroneSimulation/Temps.h #pragma once class Temps { private: long double t1; long double t2; long double t3; long double t4; long double t5; long double t6; long double t7; long double t8; long double gt; public: Temps(); long double getT1(); long double getT2(); long double getT3(); long double getT4(); long double getT5(); long double getT6(); long double getT7(); long double getGt(); void setT1(long double t1); void setT2(long double t2); void setT3(long double t3); void setT4(long double t4); void setT5(long double t5); void setT6(long double t6); void setT7(long double t7); void setGt(long double gt); }; <file_sep>/Visual Studio Simulation/DroneSimulation/CoutCalcul.h #pragma once class CoutCalcul { private: long double cc1; long double cc2; long double cc3; long double cc4; long double cc5; long double cc6; long double cc7; long double gt; public: CoutCalcul(); long double getCC1(); long double getCC2(); long double getCC3(); long double getCC4(); long double getCC5(); long double getCC6(); long double getCC7(); long double getGt(); void setCC1(long double cc1); void setCC2(long double cc2); void setCC3(long double cc3); void setCC4(long double cc4); void setCC5(long double cc5); void setCC6(long double cc6); void setCC7(long double cc7); void setGt(long double gt); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Tache.h #pragma once class Tache { private: int id; long double ci; long double di; long double rsi; int si; public: Tache(); int getId(); long double getCi(); long double getDi(); long double getRsi(); int getSi(); void setCi(long double ci); void setDi(long double di); void setRsi(long double rsi); void setSi(int si); void setId(int id); Tache(int id, long double ci, long double di, long double rsi, int si); }; <file_sep>/Visual Studio Simulation/DroneSimulation/CoutEnvoie.cpp #include "CoutEnvoie.h" CoutEnvoie::CoutEnvoie(){} long double CoutEnvoie::getCE1() { return ce1; } long double CoutEnvoie::getCE2() { return ce2; } long double CoutEnvoie::getCE3() { return ce3; } long double CoutEnvoie::getCE4() { return ce4; } long double CoutEnvoie::getCE5() { return ce5; } long double CoutEnvoie::getCE6() { return ce6; } long double CoutEnvoie::getCE7() { return ce7; } long double CoutEnvoie::getGt() { return gt; } void CoutEnvoie::setCE1(long double ce1) { this->ce1 = ce1; } void CoutEnvoie::setCE2(long double ce2) { this->ce2 = ce2; } void CoutEnvoie::setCE3(long double ce3) { this->ce3 = ce3; } void CoutEnvoie::setCE4(long double ce4) { this->ce4 = ce4; } void CoutEnvoie::setCE5(long double ce5) { this->ce5 = ce5; } void CoutEnvoie::setCE6(long double ce6) { this->ce6 = ce6; } void CoutEnvoie::setCE7(long double ce7) { this->ce7 = ce7; } void CoutEnvoie::setGt(long double gt) { this->gt = gt; }<file_sep>/README.md # UAVs-for-Traffic-Monitoring-A-Sequential-Game-based-Computation-Offloading-Sharing-Approach Authors: <NAME>(<EMAIL>), <NAME>(<EMAIL>), <NAME>(<EMAIL>), <NAME>(<EMAIL>) and <NAME>(<EMAIL>) -Department of Computer Science, University of Jijel -<NAME>, Jijel, Algeria -NTIC Faculty, University of Abdelhamid Mehri - Constantine 2, Constantine, Algeria -DRIVE EA1859, University Bourgogne Franche-Comté, France -Orange Labs, Châtillon, France <file_sep>/Visual Studio Simulation/DroneSimulation/ServeurEdge.cpp #include "ServeurEdge.h" int ServeurEdge::getId() { return id; } long double ServeurEdge::getFrequenceCpu() { return frequence_cpu; } void ServeurEdge::setId(int id) { this->id = id; } void ServeurEdge::setFrequenceCpu(long double frequence_cpu) { this->frequence_cpu = frequence_cpu; } ServeurEdge::ServeurEdge(int id, long double frequence_cpu) { this->id = id; this->frequence_cpu = frequence_cpu; } long double ServeurEdge::TCalculCPU(long double cycles_tache) { return cycles_tache / frequence_cpu; }<file_sep>/Visual Studio Simulation/DroneSimulation/Energie.cpp #include "Energie.h" Energie::Energie(){} long double Energie::getE1() { return e1; } long double Energie::getE2() { return e2; } long double Energie::getE3() { return e3; } long double Energie::getE4() { return e4; } long double Energie::getE5() { return e5; } long double Energie::getE6() { return e6; } long double Energie::getE7() { return e7; } long double Energie::getGt() { return gt; } void Energie::setE1(long double e1) { this->e1 = e1; } void Energie::setE2(long double e2) { this->e2 = e2; } void Energie::setE3(long double e3) { this->e3 = e3; } void Energie::setE4(long double e4) { this->e4 = e4; } void Energie::setE5(long double e5) { this->e5 = e5; } void Energie::setE6(long double e6) { this->e6 = e6; } void Energie::setE7(long double e7) { this->e7 = e7; } void Energie::setGt(long double gt) { this->gt = gt; }<file_sep>/Visual Studio Simulation/DroneSimulation/Utilite.cpp #include "Utilite.h" Utilite::Utilite() {} long double Utilite::getU1() { return u1; } long double Utilite::getU2() { return u2; } long double Utilite::getU3() { return u3; } long double Utilite::getU4() { return u4; } long double Utilite::getU5() { return u5; } long double Utilite::getU6() { return u6; } long double Utilite::getU7() { return u7; } long double Utilite::getGt() { return gt; } void Utilite::setU1(long double u1) { this->u1 = u1; } void Utilite::setU2(long double u2) { this->u2 = u2; } void Utilite::setU3(long double u3) { this->u3 = u3; } void Utilite::setU4(long double u4) { this->u4 = u4; } void Utilite::setU5(long double u5) { this->u5 = u5; } void Utilite::setU6(long double u6) { this->u6 = u6; } void Utilite::setU7(long double u7) { this->u7 = u7; } void Utilite::setGt(long double gt) { this->gt = gt; }<file_sep>/Visual Studio Simulation/DroneSimulation/Vehicule.h #pragma once class Vehicule { private: int id; bool est_electrique; long double energie; long double frequence_cpu; public: int getId(); long double getEngerie(); long double getFrequenceCpu(); bool estElectrique(); void setId(int id); void setEnergie(long double energie); void setFrequenceCpu(long double frequence_cpu); void estElectrique(bool est_electrique); Vehicule(int id, long double frequence_cpu, bool est_electrique, long double energie); Vehicule(int id, long double frequence_cpu, bool est_electrique); long double TCalculCPU(long double cycles_tache); long double ECalculCPU(long double cycles_tache); void majEnergie(long double taux); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Energie.h #pragma once class Energie { private: long double e1; long double e2; long double e3; long double e4; long double e5; long double e6; long double e7; long double e8; long double gt; public: Energie(); long double getE1(); long double getE2(); long double getE3(); long double getE4(); long double getE5(); long double getE6(); long double getE7(); long double getGt(); void setE1(long double e1); void setE2(long double e2); void setE3(long double e3); void setE4(long double e4); void setE5(long double e5); void setE6(long double e6); void setE7(long double e7); void setGt(long double gt); }; <file_sep>/Visual Studio Simulation/DroneSimulation/Temps.cpp #include "Temps.h" Temps::Temps() { } long double Temps::getT1() { return t1; } long double Temps::getT2() { return t2; } long double Temps::getT3() { return t3; } long double Temps::getT4() { return t4; } long double Temps::getT5() { return t5; } long double Temps::getT6() { return t6; } long double Temps::getT7() { return t7; } long double Temps::getGt() { return gt; } void Temps::setT1(long double t1) { this->t1 = t1; } void Temps::setT2(long double t2) { this->t2 = t2; } void Temps::setT3(long double t3) { this->t3 = t3; } void Temps::setT4(long double t4) { this->t4 = t4; } void Temps::setT5(long double t5) { this->t5 = t5; } void Temps::setT6(long double t6) { this->t6 = t6; } void Temps::setT7(long double t7) { this->t7 = t7; } void Temps::setGt(long double gt) { this->gt = gt; }
029ff83a32a07442eda93b1c3171f43d4cf13f44
[ "Markdown", "C++" ]
19
C++
HoussemDjeghri/UAVs-for-Traffic-Monitoring-A-Sequential-Game-based-Computation-Offloading-Sharing-Approach
ff851c5f3cdb637d7eee318b6e0ad940a8d9683d
67d39128d80a65d6bb269d2a38123b5cb7734f04
refs/heads/master
<repo_name>Zaelix/STEMKit<file_sep>/src/Main/ModRegistry.java package Main; import java.io.IOException; public class ModRegistry { public static void main (String[] args) throws IOException { //ForgeMod.addSword("Testing"); ForgeMod.addBlock("Science Block"); //ForgeMod.addBow("Testing"); //ForgeMod.addMaterial("BANANA", 3, 3000, 15F, 150F, 200); //ForgeMod.addSword("MatSword","BANANA"); } } <file_sep>/src/Objects/Deprecated.java package Objects; public class Deprecated { /* public static void addBlockDEP(String name) throws IOException{ Path myPath = findFiles(); // Block Strings String blockDecSearchString = "Block Declaration Space"; String blockDecInsertString = " public static Block " + name + "_Block;"; String blockInitSearchString = "Block Initialization Space"; String blockInitInsertString = " "+name+"_Block = new " + name + "Block(Material.rock);"; String blockRegSearchString = "Block Registration Space"; String blockRegInsertString = " GameRegistry.registerBlock(" + name + "_Block, " + name + "Block.getUnlocalizedName());"; Object[] temp = findInsertingSpace(blockRegistry, name, blockDecSearchString, blockDecInsertString, 0, ""); String fileContent = (String)temp[0]; int num = (int)temp[1]; //System.out.println("Finding " + blockInitSearchString + "..."); temp = findInsertingSpace(blockRegistry, name, blockInitSearchString, blockInitInsertString, num, fileContent); fileContent = (String)temp[0]; num = (int)temp[1]; //System.out.println("Finding " + blockRegSearchString + "..."); temp = findInsertingSpace(blockRegistry, name, blockRegSearchString, blockRegInsertString, num, fileContent); fileContent = (String)temp[0]; num = (int)temp[1]; fileContent = finishRead(blockRegistry, num, fileContent); //System.out.println("Writing to File \"" + blockRegistry + "\""); if(isRedundant(blockRegistry, blockDecInsertString) && isRedundant(blockRegistry, blockInitInsertString) && isRedundant(blockRegistry, blockRegInsertString)){ System.out.println("Block Registration already exists, skipping BlockRegistry rewrite"); } else{ System.out.println("Updating BlockRegistry..."); writeFile(blockRegistry, fileContent); } System.out.println("Creating Block Class file..."); writeFile(Paths.get(campPath + "/block/" + name + "Block.java"), createNewBlockContent(name)); } public static void addSwordDEP(String name) throws IOException{ Path myPath = findFiles(); // Sword Strings String swordDecSearchString = "Sword Declaration Space"; String swordDecInsertString = " public static Item " + name + "_Sword;"; String swordInitSearchString = "Sword Initialization Space"; String swordInitInsertString = " "+name+"_Sword = new " + name + "Sword(MainRegistry.WAFFLETOOL);"; String swordRegSearchString = "Sword Registration Space"; String swordRegInsertString = " GameRegistry.registerItem(" + name + "_Sword, " + name + "Sword.getUnlocalizedName());"; //System.out.println("Finding " + swordDecSearchString + "..."); Object[] temp = findInsertingSpace(itemRegistry, name, swordDecSearchString, swordDecInsertString, 0, ""); String fileContent = (String)temp[0]; int num = (int)temp[1]; //System.out.println("Finding " + swordInitSearchString + "..."); temp = findInsertingSpace(itemRegistry, name, swordInitSearchString, swordInitInsertString, num, fileContent); fileContent = (String)temp[0]; num = (int)temp[1]; //System.out.println("Finding " + swordRegSearchString + "..."); temp = findInsertingSpace(itemRegistry, name, swordRegSearchString, swordRegInsertString, num, fileContent); fileContent = (String)temp[0]; num = (int)temp[1]; fileContent = finishRead(itemRegistry, num, fileContent); //System.out.println("Writing to File \"" + itemRegistry + "\""); if(isRedundant(itemRegistry, swordDecInsertString) && isRedundant(itemRegistry, swordInitInsertString) && isRedundant(itemRegistry, swordRegInsertString)){ System.out.println("Item Registration already exists, skipping ItemRegistry rewrite"); } else{ System.out.println("Updating ItemRegistry..."); writeFile(itemRegistry, fileContent); } System.out.println("Creating Sword Class file..."); writeFile(Paths.get(campPath + "/item/" + name + "Sword.java"), createNewSwordContent(name)); } */ }
16e1432012e4fc5fedeacd690a4ad8f28d431883
[ "Java" ]
2
Java
Zaelix/STEMKit
a16154681130588d54f3175169eb564e9712e17d
9e5eb0c1e3b1f4775b75c3c387a162ac10b31258
refs/heads/main
<repo_name>Gonior/android-latihan1-biodataDiri<file_sep>/app/src/main/java/com/example/biodatadiri/Bio.kt package com.example.biodatadiri class Bio { public val nama = "<NAME>" public val nim = "10118901" public val kelas = "IF-11K" public val jk = "Laki - Laki" public val ttl = "Bandung, 14 Desember 1997" public val gol_darah = "A" public val addrs = "Lembang - Punclut" public val food = "Batagor" public val drink = "Air Putih" public val hobi = "<NAME>" public val song = "Kaikai kitan - Eve" public val film = "Anime" public val wish_job = "Pengangguran sukses" }<file_sep>/app/src/main/java/com/example/biodatadiri/MainActivity.kt package com.example.biodatadiri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val b = Bio() tvNama.text = b.nama tvNim.text = b.nim tvAddrs.text = b.addrs tvJK.text = b.jk tvTTL.text = b.ttl tvKelas.text = b.kelas tvGolDar.text = b.gol_darah tvFood.text = b.food tvDrink.text = b.drink tvHobi.text = b.hobi tvSong.text = b.song tvFilm.text = b.film tvJob.text = b.wish_job } }<file_sep>/settings.gradle include ':app' rootProject.name = "Biodata Diri"
b5126605ce8ce4d4c15763519829764c8ec01600
[ "Kotlin", "Gradle" ]
3
Kotlin
Gonior/android-latihan1-biodataDiri
6b7ebb945174800ade7535eea346b5f00e2b2c4c
a398cf71dd983ce2aac4d26f021007f43289177d
refs/heads/master
<repo_name>laughingg/Socket<file_sep>/CocoaAsyncSocketDemo/CocoaAsyncSocketDemo/ServiceViewController.swift // // ServiceViewController.swift // CocoaAsyncSocketClient // // Created by Laughing on 2017/3/14. // Copyright © 2017年 Laughing. All rights reserved. // import UIKit import CocoaAsyncSocket class ServiceViewController: UIViewController { @IBOutlet weak var portField: UITextField! var serviceSocket: GCDAsyncSocket? var newServiceSocket: GCDAsyncSocket? var msgs : [String] = [] { didSet { DispatchQueue.main.async { self.tableView.reloadData() } } } @IBOutlet weak var msgField: UITextField! @IBAction func sendBtnClick(_ sender: Any) { if msgField.text?.characters.count == 0 { print(#function, "\n--: desc: ", "请输入你要发送的内容!") } else { let msgData = ("Client(\(tag)):" + msgField.text!).data(using: .utf8) newServiceSocket!.write(msgData!, withTimeout: -1, tag: tag) } } @IBAction func clearBtnClick(_ sender: Any) { msgs.removeAll() } @IBAction func startListenPort(_ sender: Any) { do { let port = UInt16((portField.text! as NSString).intValue) // 监听本机的 12345 端口 try serviceSocket?.accept(onPort: port) msgs.append("开始监听本机8080 端口") print(#function, "\n--: desc: ", "开始监听本机\(portField.text) 端口", "\n--: port:", port) } catch { print(#function, "\n--: desc: ", "监听本机\(portField.text) 端口失败!", "\n--: error: ", error) } } @IBOutlet weak var tableView: UITableView! let tag = 101; override func viewDidLoad() { super.viewDidLoad() serviceSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.global()) portField.text = "8080"; tableView.dataSource = self tableView.delegate = self } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { tableView.endEditing(true) } } extension ServiceViewController: UITableViewDelegate { } extension ServiceViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return msgs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = msgs[indexPath.row] return cell! } } // MARK: 服务 extension ServiceViewController : GCDAsyncSocketDelegate { // 已经接受新的 socket 连接 func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) { print(#function, "\n--: socket: ", sock, "\n--: desc: ", "有新的 sock 连接!", "\n--: newSocket: ", newSocket) newServiceSocket = newSocket newSocket.write("1234567890".data(using: .utf8)!, withTimeout: -1, tag: tag) // 准备开始接收数据 newSocket.readData(withTimeout: -1, tag: tag) } // 数据接收完成 func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { let receiverStr = String(data: data, encoding: .utf8) msgs.append(receiverStr!) sock.readData(withTimeout: -1, tag: tag) print(#function, "\n--: socket: ", sock, "\n--: desc: ", "数据接收完成", "\n--: dataStr: ", receiverStr!, "\n--: tag: ", tag ) } // 数据发送成功 func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { // sock.readData(withTimeout: -1, tag: tag) } func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { print("sock 连接已经断开!") msgs.append("sock 连接已经断开!") } } <file_sep>/CocoaAsyncSocketDemo/CocoaAsyncSocketDemo/ClientViewController.swift // // ClientViewController.swift // CocoaAsyncSocketClient // // Created by Laughing on 2017/3/14. // Copyright © 2017年 Laughing. All rights reserved. // import UIKit import CocoaAsyncSocket class ClientViewController: UIViewController { @IBOutlet weak var hostField: UITextField! @IBOutlet weak var portField: UITextField! @IBOutlet weak var messageTableView: UITableView! @IBOutlet weak var messageField: UITextField! var messages:[String] = [] { didSet { DispatchQueue.main.async { self.messageTableView.reloadData() } } } let tag = 100 var socket: GCDAsyncSocket? override func viewDidLoad() { super.viewDidLoad() hostField.text = "192.168.16.72" portField.text = "8080" messageTableView.delegate = self messageTableView.dataSource = self // 创建 socket socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.global()) } } // MARK: - 事件处理 extension ClientViewController { @IBAction func clean(_ sender: Any) { messages.removeAll() } @IBAction func send(_ sender: Any) { if messageField.text == nil || messageField.text == ""{ print(#function,"\n --: desc: ", "发送的信息不能为空") return } let msgData = ("Client(\(tag)):" + messageField.text!).data(using: .utf8) socket?.write(msgData!, withTimeout: -1, tag: tag) messages.append( String(data: msgData!, encoding: .utf8)! ) } @IBAction func connect(_ sender: Any) { if socket!.isConnected { print(#function,"\n --: desc: ", "socket 已经连接!") return } do { let port = UInt16((portField.text! as NSString).intValue) try socket?.connect(toHost: hostField.text!, onPort:port) let mes = "连接:" + hostField.text! + ": \(port)" messages.append(mes) } catch { print(error) } } } // MARK: GCDAsyncSocketDelegate extension ClientViewController : GCDAsyncSocketDelegate { func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { print(#function,"\n --: sock: ", sock, "\n --: desc: ", "sock 断开连接", "\n --: Error:", err ?? "错误为 nil") sock.readData(withTimeout: -1, tag: tag) } // 和服务器创建连接完成 func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { print(#function,"\n --: sock: ", sock, "\n --: desc: ", "sock 连接成功!", "\n --: host: ", host, "\n --: port: ", port) sock.readData(withTimeout: -1, tag: tag) self.messages.append("连接主机成功!") } // 数据接收完成 func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { let receiverStr = String(data: data, encoding: .utf8) // 通知对方接受数据完成,可以进行下次的数据的接收 sock.readData(withTimeout: -1, tag: tag) self.messages.append(receiverStr!) } // 数据发送成功 func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { // 数据发送完成后一定要调用下读数据的方法 // 通知对方接收数据 sock.readData(withTimeout: -1, tag: tag) print(#function,"\n --: sock: ", sock, "\n --: desc: ", "sock 数据发送成功!", "\n --: tag: ", tag) DispatchQueue.main.async { self.messageField.text = nil } } } extension ClientViewController : UITableViewDelegate { } extension ClientViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") cell?.textLabel?.text = messages[indexPath.row] return cell! } }
f2287e8b71d10ec8e9e55256f1671d03eac05f28
[ "Swift" ]
2
Swift
laughingg/Socket
6d19b469a3025da7db76b1848cfe395344f41436
26725f4b4f7be3d667a041f66dbe61ad21c09940
refs/heads/master
<repo_name>hrifai/iconic-video-variant-backend<file_sep>/controller.js const model = require('./model'); class Controller { constructor(){} async getSearchResults(req,res){ //getting search results by proxying // query params to existing api let results = await model.getSearchResults(req.query); //if we are in the variant where we want video links if(req.query.video){ //getting the skus of the products that have videos const skus = results._embedded.product .filter(product => !!product.video_count) .map(product => product.sku); //get the video data ie.links const videos = await model.getVideoData(skus); //add the video data to the existing search results //matched by sku model.enrichData(results,videos); //prioritise the results by sorting based on video count results._embedded.product.sort((a,b) => { return b.video_count - a.video_count; }) } return res .status(200) .send(results); } } module.exports = new Controller();<file_sep>/test.js const supertest = require("supertest"); const assert = require('assert'); const app = require("./app"); describe("For the endpoint without video", function() { const default_url = "/variant-search?gender=female&page=9&page_size=100"; describe("GET default search results", function () { it("should give back some results", function (done) { supertest(app) .get(default_url) .expect(200) .then(response => { const data = JSON.parse(response.text); if(data._embedded.product.length > 0) done() }) }); it("should give back results with no video_links property", function (done) { supertest(app) .get(default_url) .expect(200) .then(response => { const data = JSON.parse(response.text); if(!(data._embedded.product.every(product => product.video_links))) done(); }) }); }); }); describe("For the endpoint with video", function() { const video_varient_url = "/variant-search?gender=female&page=9&page_size=100&video=true"; describe("GET search results enriched with video", function () { it("should give back some results", function (done) { supertest(app) .get(video_varient_url) .expect(200) .then(response => { const data = JSON.parse(response.text); if(data._embedded.product.length > 0) done() }) }); it("should give back results with video_links property", function (done) { supertest(app) .get(video_varient_url) .expect(200) .then(response => { const data = JSON.parse(response.text); if(data._embedded.product.filter(p => p.video_links).length > 0) done(); }) }); it("should prioritise results with video_count", function (done) { supertest(app) .get(video_varient_url) .expect(200) .then(response => { const data = JSON.parse(response.text); const products = data._embedded.product; const expected_sort = products.sort((a,b) => { return b.video_count - a.video_count }); if(expected_sort[0].video_count <= products[0].video_count) done(); }) }); }); });<file_sep>/app.js const express = require('express'); const app = express(); const controller = require('./controller'); const dotenv = require('dotenv'); dotenv.config(); app.use(express.json()); app.get('/variant-search', (req,res) => controller.getSearchResults(req,res)); app.listen(process.env.PORT, () => { console.log(`SERVER LISTENING ON PORT ${process.env.PORT}`); }); module.exports = app;<file_sep>/README.md # iconic-video-variant-backend This project is a Backend Technical Challenge. The task was to create a lightweight API that could be used for an AB test. Using an existing endpoint to get back results and then, depending on the users variant, enrich the search results with video data. # Logic The new endpoint works by taking in all the same query params and filters as the existing endpoint as well as a new parameter `` ?video=true `` that signifies whether or not to enrich the search results with videos. # Running and testing In order to run this project you can simply install dependencies and run the app using ``` npm install && node app.js ``` This will start the localhost server on port 8080 In order to test the project you will need to install the dev dependencies and run the mocha test file using ``` npm install --dev && mocha test.js ``` _note: you may need to install mocha globally for this to work_<file_sep>/model.js const axios = require('axios'); class Model { constructor(){ this._baseUrl = 'https://eve.theiconic.com.au'; } async getSearchResults(options){ //getting all the query params from the incoming request //and turning them into a query string to filter existing //products endpoint const queryParams = new URLSearchParams(options); const product_path = '/catalog/products?' + queryParams; const {data} = await axios.get(this._baseUrl + product_path); return data; } async getVideoData(skus){ const mapped_data = []; const getUrl = (sku) => `${this._baseUrl}/catalog/products/${sku}/videos`; //using promise all to request all the video data at once //more time efficient as less halting then waiting for each one const promises = skus.map(sku => axios.get(getUrl(sku))); const results = (await Promise.all(promises)) .map(response => response.data); //creating a sku to video mapping to match the results to later for(let i=0;i<skus.length;i++){ mapped_data.push({ sku: skus[i], videos: results[i]._embedded.videos_url }) } return mapped_data; } enrichData(results,videos){ //matching the product with the video based on sku //if there is no video then video_links will be null for(const product of results._embedded.product){ product.video_links = product.video_count === 0 ? null : (videos.find(video => video.sku === product.sku)).videos } } } module.exports = new Model();
06180176d3d7207ef705166701d678472d404eb1
[ "JavaScript", "Markdown" ]
5
JavaScript
hrifai/iconic-video-variant-backend
2c0743e3556295cdb996300cfc695f3036713761
6d04231e27d790817c139c3abde6dbcb8ef5e902
refs/heads/master
<repo_name>WorryJack/replace<file_sep>/TalDataGroup/StructDerivation.py import cx_Oracle as oracle import configparser # cursor = oracle.connect('haxesbi' , 'IuT7FcLmQa1Z', '192.168.11.194').cursor() table_list = ['DN_CLASS_COUNT'] for i in table_list: sql = "SELECT * FROM col WHERE tname = " + "'" + i + "'" +" ORDER BY tname,colno " print(sql)<file_sep>/TalDataGroup/demo2.py from TalDataGroup.replace_by_folders import FilesReader import os ProjectPath = os.path.abspath('..') path_org = [ProjectPath + '/everyday_hr_document_directory_mysql2/'] # path = ProjectPath + '/test/' for path in path_org: file = os.listdir(path) print(file) if '.DS_Store' in file: file.remove('.DS_Store') #去除.DS_Store文件 else: pass reader1 = FilesReader(path) # # reader1.replace_in_path('jdbc:oracle:thin:@192.168.11.194:1521:linxesbi2', 'jdbc:mysql://192.168.13.42:3336/xesbi', False) # reader1.replace_in_path('--password-file hdfs://turinghdfs:8020/user/hdfs/password/SQOOP_HAXESBI/password.file', '--password-file hdfs://turinghdfs:8020/user/hdfs/password/SQOOP_MYSQL/password.file', False) reader1.replace_in_path('&#47;data&#47;downf&#47;', '&#47;data&#47;downf&#47;mysqlfile&#47;', False) # reader1.replace_in_path('--username xesbi', '--username xesbi_readonly', False) # reader1.replace_in_path('--password <PASSWORD>', '--password-file hdfs://turinghdfs:8020/user/hdfs/password/SQOOP_XESBI_MYSQL/password.file', False) # # # reader1.replace_in_path('Oracle', 'MySql', False) # reader1.replace_in_path('bi_income_others', 'bi_income_others', False) <file_sep>/TalDataGroup/demo.py import time date_time_now = time.strftime("%Y-%m-%d %H:%M", time.localtime()) import datetime today = datetime.date.today() # 今天 yesterday = datetime.date.strftime(today - datetime.timedelta(days=1), '%Y-%m-%d') temp_date_min = date_time_now[11:] temp_date_day = date_time_now[:10] print(type(yesterday)) print(yesterday) # temp_date_min >= "00:00" and temp_date_min <= "00:15" : <file_sep>/TalDataGroup/replacecpt.py from TalDataGroup.replace_by_folders import FilesReader import os import xml.etree.ElementTree as ET #获取父目录路径 ProjectPath = os.path.abspath('..') # path_org = [ProjectPath + '/cptfile/', ProjectPath + '/bi_detail/'] path_org = [ProjectPath + '/demo/'] for path in path_org: file = os.listdir(path) print(file) if '.DS_Store' in file: file.remove('.DS_Store') #去除.DS_Store文件 else: pass reader1 = FilesReader(path) reader1.replace_in_path('Key:data_time', 'Key:run_time', False) reader1.replace_in_path('Key:RUN_TIME', 'Key:run_time', False) reader1.replace_in_path('xesbidw', 'newbi_mysql', False) reader1.replace_in_path('haxesbi.', '', False) reader1.replace_in_path('--', '-- ', False) reader1.replace_in_path('NVL', 'ifnull', False) for i in file: tree = ET.parse(path + i)# 读取xml文件 print(i) root = tree.getroot() child = root.find('ReportParameterAttr') if child is None: pass else: child = child.find('ParameterUI') if child is None: pass else: child = child.find('Layout') if child is None: pass else: child = child.findall('Widget') if child is None: pass else: for child2 in child: child3 = child2.find('InnerWidget').find('Dictionary') if child3 is None: pass else: addr = child3.find('FormulaDictAttr') if addr is None: pass else: kiName = child3.find('FormulaDictAttr').get('kiName') viName = child3.find('FormulaDictAttr').get('viName') if kiName is None and viName is None: pass else: newkiName = kiName.lower() newviName = viName.lower() old_kistr = "kiName=\"" + kiName +"\"" old_vistr = "viName=\"" + viName +"\"" new_kistr = "kiName=\"" + newkiName +"\"" new_vistr = "viName=\"" + newviName +"\"" reader1.replace_in_path(old_kistr, new_kistr, False) reader1.replace_in_path(old_vistr, new_vistr, False) # 采用字符串替换,直接写xml文件会破坏cpt文件结构 <file_sep>/TalDataGroup/replace_by_folders.py # -*- coding: utf-8 -*- # @author: liangzhi, 2019/10/10 import re import os from pathlib import Path class FilesReader(object): ''' Read all files from path,every file end with end_type. this class can replace some str of all the files in a path. ''' def __init__(self, path="defult", end_type=[".cpt"]): self.end_type = end_type if path == "defult": self.path = os.getcwd() else: self.path = path self.fileList = [] self.fileNumber = 0 self._CreatFileList() def __repr__(self): return 'FilesReader(path={0.path!s})'.format(self) def _CreatFileList(self): p = Path(self.path) for e_t in self.end_type: self.fileList.extend(list(p.glob("**/*" + e_t))) self.fileNumber = len(self.fileList) @property def files(self): return [os.path.relpath(f) for f in self.fileList] def file_replace(self, file_name, old_str, new_str, is_right_link=True): """ 替换文件中的字符串 :param file:文件名 :param old_str:old字符串 :param new_str:新字符串 """ if is_right_link: r_str = '' else: r_str = '\s' file_data = "" with open(file_name, "r", encoding="utf-8") as f: lines = f.read() str_at = lines.find(old_str) reg = re.compile(re.escape(old_str) + r_str, re.IGNORECASE) if len(reg.findall(lines)) != 0: str_at = reg.findall(lines) new_lines = reg.sub(new_str, lines) file_data += new_lines with open(file_name, "w", encoding="utf-8") as f: f.write(file_data) else: str_at = None return_num = str_at return return_num def replace_in_path(self, old_str, new_str, is_right_link=True): for file in self.fileList: find_str = self.file_replace(file, old_str, new_str, is_right_link=True) if find_str != None: print("replace:%(file_name)s with: %(re_str)s" % {'file_name': os.path.relpath(file), 're_str': find_str}) class FoldersReader(object): ''' path: the path of the folders at sel: the list of folders' name you want to select end_type: the type of files you want to replace,input a list of them ''' def __init__(self, path, sel=[], end_type=[".cpt"]): self.path = path self.sel = sel self.end_type = end_type self.folders = [os.path.relpath(i) for i in os.listdir(self.path) if os.path.relpath(i) in sel] def replace_in_path(self, old_str, new_str): for folder in self.folders: _reaader = FilesReader(self.path + '/' + folder, self.end_type) _reaader.replace_in_path(old_str, new_str)
4fd5d36465f18a32dd597f6152f0c6a7adf08b54
[ "Python" ]
5
Python
WorryJack/replace
0a77b06015d8e75b77d076ea9cb93e561e3d973c
d24d678bb64896dd2c76d31a00ff7b9fea9f5315
refs/heads/master
<repo_name>YuraSmoliy/home_task<file_sep>/src/main/java/com/example/servingwebcontent/Servise.java package com.example.servingwebcontent; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class Servise { List<String> cities = new ArrayList<String>(); public void readFile() { FileReader fr = null; try { fr = new FileReader("C:\\Users\\Yura\\game_cities\\src\\main\\resources\\cities.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } Scanner scan = new Scanner(fr); while (scan.hasNextLine()) { String mycity = scan.nextLine(); System.out.println(mycity); cities.add(mycity); } try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } public String comperCityEnd(String customerCity) { Iterator iterator = cities.iterator(); while (iterator.hasNext()) { String newCiti = iterator.next().toString().toLowerCase(); if (customerCity.charAt(customerCity.length() - 1) == newCiti.charAt(0)) return newCiti; } return "I do not know any city"; } public boolean checkCustomerResponse(String customerCity, String lastCity) { customerCity.toLowerCase(); return lastCity.charAt(lastCity.length() - 1) == customerCity.charAt(0); } } <file_sep>/src/main/java/com/example/servingwebcontent/CityController.java package com.example.servingwebcontent; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.Map; @Controller public class CityController { Servise servise = new Servise(); String lastSystemCity = "lviv"; @RequestMapping(value = "/begin", method = RequestMethod.GET) public String begin(@RequestParam(name = "name", required = false, defaultValue = "Lviv") String name, Map<String, Object> model) { servise.readFile(); model.put("next", name); return "next"; } @RequestMapping(value = "/next", method = RequestMethod.GET) public String next(@RequestParam(name = "next", required = false, defaultValue = "Some word") String name, Map<String, Object> model) { String systemValue = servise.comperCityEnd(name); if (servise.checkCustomerResponse(name, lastSystemCity)) { lastSystemCity = systemValue; model.put("next", systemValue); } else { model.put("next", "Your city is wrong, try again, last my answer was " + lastSystemCity); } return "next"; } @RequestMapping(value = "/end", method = RequestMethod.POST) public String end( @RequestParam(name = "name", required = false, defaultValue = "") String name, Map<String, Object> model) { model.put("end", "Thanks for game"); return "end"; } }
ce8586e55fe01b339fbd78343b7bbc6e4e733797
[ "Java" ]
2
Java
YuraSmoliy/home_task
e248c1afb42a136e4d0cd77d4c587ab57d1ad651
c29ac5fed784832b935029cf6cf06eefc1c2a886
refs/heads/master
<repo_name>adriancostin6/2D-Platformer-Java<file_sep>/src/ImageLoader.java import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; public class ImageLoader { private BufferedImage bI ; public BufferedImage loadImage(String filePath) throws IOException { bI = ImageIO.read(getClass().getResource(filePath)); return bI; } }<file_sep>/README.md #2D Platformer Simple game I made when learning Java. 2 Players that can shoot each other until one of them runs out of health. No textures or animations, just rectangles and collision bounds are drawn. <file_sep>/src/ObjectHandler.java import java.awt.*; import java.util.LinkedList; public class ObjectHandler { //create linked list for our objects public LinkedList<GameObject> object = new LinkedList<>(); private GameObject temp ; public void tick(){ for (int i=0;i<object.size();i++) { GameObject o = object.get(i); temp = o; temp.tick(object); } } public void render(Graphics g){ for (int i=0;i<object.size();i++) { GameObject o = object.get(i); temp = o; temp.render(g); } } public void addObject(GameObject o){ object.add(o); } public void removeObject(GameObject o){ object.remove(o); } public void createLevel(){ for(int xx =0;xx<Game.WIDTH-10;xx+=20){ addObject(new Block(xx,Game.HEIGHT-20)); addObject(new Block(xx,0)); } for(int yy =0;yy<Game.HEIGHT;yy+=20){ addObject(new Block(0,yy)); addObject(new Block(Game.WIDTH-20,yy)); } int yy = Game.HEIGHT-200; for(int xx = 300;xx<900;xx+=20) addObject(new Block(xx,yy)); } }<file_sep>/src/Window.java import javax.swing.*; import java.awt.*; public class Window { Window(int w,int h,Game game){ //sets the canvas size Dimension windowSize = new Dimension(w,h); game.setPreferredSize(windowSize); game.setMaximumSize(windowSize); game.setMinimumSize(windowSize); //adds canvas to frame and sets frame parameters JFrame frame = new JFrame("Game"); frame.add(game); frame.setResizable(true); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setLocationRelativeTo(null); game.start(); } }<file_sep>/src/Player.java import java.awt.*; import java.util.LinkedList; public class Player extends GameObject{ ObjectHandler handler; public Player(float x, float y, ObjectHandler handler) { super(x, y); this.handler = handler; } //player object parameters private float gravity = 0.5f; private final int WIDTH= 60,HEIGHT=70; private int health = 300; @Override public void tick(LinkedList<GameObject> object) { x+=velX; y+=velY; if(isFalling || isJumping){ velY+=gravity; //limit falling speed if needed // if(velY > 10) // velY = 10; } //checks collision between player object and other game objects checkColision(object); } @Override public void render(Graphics g) { g.setColor(Color.cyan); g.fillRect((int)x,(int)y,WIDTH,HEIGHT); /* * Used to render colision bound on player object * Player object is a rectangle * We set: * top bound * bottom bound * left bound * right bound * All bounds are smaller rectangles inside our main player rectangle */ /////////////////////////////////// Graphics2D g2d = (Graphics2D) g ; g2d.setColor(Color.red); g2d.draw(getBounds()); g2d.draw(getLeftBounds()); g2d.draw(getRightBounds()); g2d.draw(getTopBounds()); //////////////////////////////////// /* * Health Bar for player */ //////////////////////////////////// // g.fillRect(40,40,health,20); g2d.fillRoundRect(20 ,20,health,10,10,10); /////////////////////////////////// } private void checkColision(LinkedList<GameObject> object){ for (int i=0;i<object.size();i++) { GameObject o = object.get(i); if(o instanceof Block){ if(getTopBounds().intersects(o.getBounds())){ velY = 0; y = o.getY() + 20; } if(getBounds().intersects(o.getBounds())){ y = o.getY()-HEIGHT; isFalling = false; velY = 0; isJumping = false; }else{ isFalling = true; } if(getLeftBounds().intersects(o.getBounds())){ velX = 0; x = o.getX() + 20; } if(getRightBounds().intersects(o.getBounds())){ velX = 0; x = o.getX() - WIDTH; } } //check collisions between players if(o instanceof Player2){ if(getBounds().intersects(((Player2) o).getTopBounds())){ velY = 0; isFalling = false; isJumping = false; y = o.getY() - HEIGHT; }else isFalling = true; if(getLeftBounds().intersects(((Player2) o).getRightBounds())){ x = o.getX()+WIDTH; velX = 0; } if(getRightBounds().intersects(((Player2) o).getLeftBounds())){ velX = 0; x = o.getX() - WIDTH; } } } } /* *First method gets bottom bounds x stays the same, y moves down by height/2 *Second method gets top bounds, x and y stay the same (note we have divided HEIGHT by 2 to split top and bottom) * Third method gets left bounds * Fourth method gets right bounds */ @Override public Rectangle getBounds() { return new Rectangle((int)x+10,(int)(y+HEIGHT/2),WIDTH-20,HEIGHT/2); } public Rectangle getTopBounds() { return new Rectangle((int)x+10,(int)y,WIDTH-20,HEIGHT/2); } public Rectangle getLeftBounds() { return new Rectangle((int)x,(int)y+10,WIDTH/2,HEIGHT-20); } public Rectangle getRightBounds() { return new Rectangle((int)(x+WIDTH/2),(int)y+10,WIDTH/2,HEIGHT-20); } public float getGravity() { return gravity; } public void setGravity(float gravity) { this.gravity = gravity; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } } <file_sep>/src/GameObject.java import java.awt.*; import java.util.LinkedList; public abstract class GameObject { protected float x,y; protected float velX = 0, velY = 0; protected boolean isFalling = true; protected boolean isJumping = false; protected int isFacing = 1; protected boolean shooting = false; //Default value for facing is 1 meaning all objects are by default facing to the right //if we change this to -1 they are facing to the left //we will use this in the player to shoot bullets in both directions public int getIsFacing() { return isFacing; } public void setIsFacing(int isFacing) { this.isFacing = isFacing; } public boolean isFalling() { return isFalling; } public void setFalling(boolean falling) { isFalling = falling; } public boolean isJumping() { return isJumping; } public void setJumping(boolean jumping) { isJumping = jumping; } //constructor public GameObject(float x, float y) { this.x = x; this.y = y; } //tick and render abstract methods public abstract void tick(LinkedList<GameObject> object); public abstract void render(Graphics g); public abstract Rectangle getBounds(); //getters and setters public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getVelX() { return velX; } public void setVelX(float velX) { this.velX = velX; } public float getVelY() { return velY; } public void setVelY(float velY) { this.velY = velY; } public boolean isShooting() { return shooting; } public void setShooting(boolean shooting) { this.shooting = shooting; } }
6a914cba1fd7247906cf2606db52e0bf23f80b1c
[ "Markdown", "Java" ]
6
Java
adriancostin6/2D-Platformer-Java
26331f764480d8309571b6678a8b88efe4512ca6
d102a04f257e70bb86130cf6aac24e94c8d2246d
refs/heads/master
<repo_name>Eneko-Eguiguren/GestorDeNotas<file_sep>/src/principales/AsignaturaECTS.java package principales; public class AsignaturaECTS extends Asignatura{ public int ects; public AsignaturaECTS(String nom, int ects) { super(nom); this.ects = ects; } public int getEcts() { return ects; } public void setEcts(int ects) { this.ects = ects; } public String toString() { return nombre + " (valor : " + ects+" ects)" ; } } <file_sep>/src/principales/Curso.java package principales; public class Curso { public String nombre; public Curso(String nomCurso){ this.nombre = nomCurso; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } } <file_sep>/src/principales/Asignatura.java package principales; public class Asignatura { public String nombre; public int nota; public Asignatura(String nom) { this.nombre = nom; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getNota() { return nota; } public void setNota(int nota) { this.nota = nota; } }
481229670bfeed47c24b130e5a0b5be2336b1e55
[ "Java" ]
3
Java
Eneko-Eguiguren/GestorDeNotas
715e0887c6c59f00734f53d847b54a0257f0c3d6
dc2ea5fb828c3f3f425f91f277b69ba4651ab876
refs/heads/master
<repo_name>SpacefulSpecies/CalendR<file_sep>/src/CalendR/Period/Second.php <?php namespace CalendR\Period; /** * Represents a second * * @author <NAME> <<EMAIL>> */ class Second extends PeriodAbstract { /** * @param \DateTime $begin * @param FactoryInterface $factory * * @throws Exception\NotASecond */ public function __construct(\DateTime $begin, $factory = null) { parent::__construct($factory); if ($this->getFactory()->getStrictDates() && !self::isValid($begin)) { throw new Exception\NotASecond; } // Not in strict mode, accept any timestamp and set the begin date back to the beginning of this period. $this->begin = clone $begin; // Still do this to make sure there aren't any microseconds. $this->begin->setTime($this->begin->format('G'), $this->begin->format('i'), $this->begin->format('s')); $this->end = clone $begin; $this->end->add($this->getDateInterval()); } /** * Returns the period as a DatePeriod * * @return \DatePeriod */ public function getDatePeriod() { return new \DatePeriod($this->begin, new \DateInterval('PT1S'), $this->end); } /** * @param \DateTime $start * * @return bool */ public static function isValid(\DateTime $start) { return $start->format('u') === '000000'; } /** * Returns the second * * @return string */ public function __toString() { return $this->format('s'); } /** * Returns a \DateInterval equivalent to the period * * @return \DateInterval */ public static function getDateInterval() { return new \DateInterval('PT1S'); } }
1ef7eceab3d0707977ff4dafdd98bb9e454c5d9a
[ "PHP" ]
1
PHP
SpacefulSpecies/CalendR
41907c2acb8e9967c7277f60877e750b34eef97f
75439cd2c18830fd1f119e353cb47ad6c9612b4b
refs/heads/master
<repo_name>t-ateya/Lecture-1-cmcs5373<file_sep>/public/app.js import * as Auth from '../controller/auth.js' import * as Home from './viewpage/home_page.js' import * as About from './viewpage/about_page.js' import * as Routes from './controller/routes.js' import * as Search from './viewpage/search_page.js' Auth.addEventListeners() Home.addEventListeners() About.addEventListeners() Search.addEventListeners() window.onload = () => { const pathname = window.location.pathname const href = window.location.href Routes.routing(pathname,href) } window.addEventListener('popstate', e => { e.preventDefault() const pathname = e.target.location.pathname const href = e.target.location.href Routes.routing(pathname,href) }) <file_sep>/public/model/constant.js // development phase export const DEV = true export const iDmodalSigninForm = 'modal-signin-form' export const iDmodalPopupInfo = 'modal-popupinfo' export const iDmodalCreateNewThread = 'modal-create-thread-form' export const iDmodalDeleteForm = 'modal-delete-form' export const collectionName = { THREADS: 'threads', MESSAGES: 'messages' }
6894ae0caed7db34dd3b770e8dd8ebf8df61ecce
[ "JavaScript" ]
2
JavaScript
t-ateya/Lecture-1-cmcs5373
dee01fefa879bb12582ed66df511894d6d2180c8
633919a8693516534d2b728dc0bdd3c5bea0bb16
refs/heads/master
<file_sep># Hands-on 4 ## Interaksi melalui Keyboard ## Interaksi melalui Mouse <file_sep>function main() { var canvas = document.getElementById("canvas_main"), gl = canvas.getContext("webgl"); var vertices = []; var cubePoints = [ [-0.5, 0.5, 0.5], // A, 0 [-0.5, -0.5, 0.5], // B, 1 [ 0.5, -0.5, 0.5], // C, 2 [ 0.5, 0.5, 0.5], // D, 3 [-0.5, 0.5, -0.5], // E, 4 [-0.5, -0.5, -0.5], // F, 5 [ 0.5, -0.5, -0.5], // G, 6 [ 0.5, 0.5, -0.5] // H, 7 ]; var cubeColors = [ [], [1.0, 0.0, 0.0], // merah [0.0, 1.0, 0.0], // hijau [0.0, 0.0, 1.0], // biru [1.0, 1.0, 1.0], // putih [1.0, 0.5, 0.0], // oranye [1.0, 1.0, 0.0], // kuning [] ]; function quad(a, b, c, d) { var indices = [a, b, c, c, d, a]; for (var i=0; i<indices.length; i++) { for (var j=0; j<3; j++) { vertices.push(cubePoints[indices[i]][j]); } for (var j=0; j<3; j++) { vertices.push(cubeColors[a][j]); } } } quad(1, 2, 3, 0); // Kubus depan quad(2, 6, 7, 3); // Kubus kanan quad(3, 7, 4, 0); // Kubus atas quad(4, 5, 1, 0); // Kubus kiri quad(5, 4, 7, 6); // Kubus belakang quad(6, 2, 1, 5); // Kubus bawah var vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); var vertexShaderCode = 'attribute vec3 aPosition;' + 'attribute vec3 aColor;' + 'varying vec3 vColor;' + 'void main(void) {' + 'vColor = aColor;' + 'gl_Position = vec4(aPosition.xy, aPosition.z - 1.0, 1.0);' + // digeser 1 satuan menjauh '}'; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertexShaderCode); gl.compileShader(vertexShader); var fragmentShaderCode = 'precision mediump float;' + 'varying vec3 vColor;' + 'void main(void) {' + 'gl_FragColor = vec4(vColor, 1.0);' + '}'; var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragmentShaderCode); gl.compileShader(fragmentShader); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var position = gl.getAttribLocation(shaderProgram, "aPosition"); gl.vertexAttribPointer(position, 3, gl.FLOAT, false, 6 * Float32Array.BYTES_PER_ELEMENT, 0); gl.enableVertexAttribArray(position); var color = gl.getAttribLocation(shaderProgram, "aColor"); gl.vertexAttribPointer(color, 3, gl.FLOAT, false, 6 * Float32Array.BYTES_PER_ELEMENT, 3 * Float32Array.BYTES_PER_ELEMENT); gl.enableVertexAttribArray(color); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.enable(gl.DEPTH_TEST); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.drawArrays(gl.TRIANGLES, 0, 36); }<file_sep># Hands-on WebGL Grafkom ## Table of Content - [Hands-on 1](https://github.com/grafkom-2020/hands-on-webgl/tree/master/hands_on-1) - Canvas - Context - Context Attributes - Viewport - Color Mask - [Hands-on 2](https://github.com/grafkom-2020/hands-on-webgl/tree/master/hands_on-2) - Shader (Fragment Shader & Vertex Shader) - Points and Triangles - [Hands-on 3](https://github.com/grafkom-2020/hands-on-webgl/tree/master/hands_on-3) - Proses di CPU (JavaScript) - Proses di GPU (Shader) - [Hands-on 4](https://github.com/grafkom-2020/hands-on-webgl/tree/master/hands_on-4) - Interaksi melalui Keyboard - Interaksi melalui Mouse<file_sep># Hands-on 1 ## Canvas Canvas (`<canvas>`) merupakan tag pada HTML5 yang digunakan untuk menggambar grafika via script (JavaScript), misalnya membuat garis, menggabungkan images, dan membuat animasi. Perlu diingat bahwa canvas hanya merupakan sebuah "container"nya saja, perlu script yang merefer ke canvas tersebut agar canvas dapat merender/draw sebuah grafika. Contoh implementasi canvas: ```HTML <canvas id="myCanvas" width="200" height="100"></canvas> ``` ## Context Canvas context merupakan object dengan method dan properties yang bisa digunakan untuk menggambar/merender grafika di dalam elemen canvas. Canvas context bisa berupa `2d` dan `webgl` namun tidak terbatas pada dua itu saja. Tiap canvas hanya bisa memiliki satu context, semisal method `getContext()` dipanggil berkali-kali, maka itu akan merefer ke object context yang sama. Syntax: ```JavaScript gl.getContext(contextType); gl.getContext(contextType, contextAttributes); //contextType merupakan DOMString berisi context identifier (2d, webgl, bitmaprenderer, etc) ``` Contoh implementasi context: ```HTML <canvas id="canvas_main" width="300" height="300"></canvas> ``` ```JavaScript var canvas = document.getElementById('canvas_main') var context = canvas.getContext('2d') console.log(context) ``` ## Context Attributes Context attributes merupakan sebuah dictionary berisi attribute pada canvas yang dipassing sebagai parameter kedua (optional) pada `getContext()` . Context attributes berbeda-beda tergantung context yang kita apply pada canvas. `WebGLContextAttributes` merupakan context attributes yang dibawa saat kita apply context `webgl` pada canvas kita. Perlu diingat jika kita tidak mem-passing context attributes saat `getContext()` maka default value akan diterapkan Berikut merupakan context attributes yang bisa kita gunakan saat menggunakan context `webgl` (value merupakan default value setiap context attributes): ```GLSL dictionary WebGLContextAttributes { boolean alpha = true; boolean depth = true; boolean stencil = false; boolean antialias = true; boolean premultipliedAlpha = true; boolean preserveDrawingBuffer = false; WebGLPowerPreference powerPreference = "default"; boolean failIfMajorPerformanceCaveat = false; boolean desynchronized = false; }; ``` Contoh implementasi context attributes: ```JavaScript var canvas = document.getElementById('canvas_main') var context = canvas.getContext('webgl', { antialias: false, stencil: true }) console.log(context.contextAttributes()) ``` Context attributes dan detailnya bisa dilihat [disini](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext). ## Implementasi Canvas dan WebGL - Buat canvas dan import file JavaScript yang berisi method untuk rendering pada canvas. ```HTML <body onload="main()"> <canvas id="canvas_main" width="800" height="600"> Browser tidak support HTML5 element. </canvas> <script type="text/javascript" src="scripts/main.js"></script> </body> ``` Pada tag `<body>` terdapat DOM event `onload`, yang memiliki method untuk mengexecute JavaScript langsung setelah page selesai diload. - Refer canvas pada file JavaScript dan get context sebagai `webgl` ```JavaScript function main() { var canvas = document.getElementById("canvas_main") var gl = canvas.getContext("webgl") } ``` - Clearing WebGL context dengan solid color ```JavaScript function handleCanvas() { ... gl.clearColor(0.0, 0.0, 0.0, 1.0) gl.clear(gl.COLOR_BUFFER_BIT) } ``` `clearColor()` merupakan method yang digunakan untuk mengatur color value yang digunakan saat clear color buffers. Untuk mengecek atau mendapatkan clear color yang terpakai sekarang, bisa dengan melihat value `COLOR_CLEAR_VALUE`. Warna yang diapply akan digunakan saat `clear()` method terpanggil, dengan kata lain method `clearColor()` tidak akan rendering apa-apa. Method ini memiliki param (R, G, B, A) dengan value clamped antara 0 dan 1. Syntax: ```JavaScript void gl.clearColor(red, green, blue, alpha); ``` `clear()` merupakan method yang "membersihkan" buffer dengan value yang sudah didefinisikan. Value bisa didefinisikan dari method `clearColor()`, `clearDepth()` atau `clearStensil()`. Pada contoh diatas, karena kita menggunakan `clearColor()`, maka kita harus "membersihkan" color buffer agar hasilnya muncul/dirender. Oleh karena itu kita memasukkan param mask yang digunakan adalah `COLOR_BUFFER_BIT`. Param mask merupakan sebuah bitwise yang mengindikasikan buffer mana yang akan "dibersihkan". Terdapat tiga bitwise yang bisa digunakan, sesuai dengan method apa yang kita gunakan untuk membersihkan buffer, yaitu `COLOR_BUFFER_BIT`, `DEPTH_BUFFER_BIT`, dan `STENCIL_BUFFER_BIT`. Syntax: ```JavaScript void gl.clear(mask); ``` ## Viewport `viewport()` merupakan method pada WebGL yang mengatur viewport, yang mengontrol transformasi posisi atau koordinat pada clip space. Clip space sendiri merupakan sebuah space yang digunakan vertex shader untuk menentukan posisi dimana sebuah vertex akan dirender. Syntax: ```JavaScript void gl.viewport(x, y, width, height); ``` Contoh implementasi viewport: ```JavaScript function handleCanvas() { ... gl.viewport(0, 0, canvas.width, canvas.height); } ``` ``` vertex attributes --[vertex shader]--> clip space --[viewport]--> canvas space --[CSS]--> HTML frame space --[browser, OS, hardware]--> physical pixel space ``` ## Color Mask Color mask (`colorMask()`) merupakan method yang mengatur color component mana yang enabled/disabled saat drawing atau rendering ke frame buffer. Untuk melihat color mask yang sedang aktif saat ini, bisa dengan melihat value `COLOR_WRITEMASK`. Syntax: ```JavaScript void gl.colorMask(red, green, blue, alpha); //Semua param adalah tipe boolean dengan default value true ``` Contoh implementasi Color Mask: ```JavaScript function handleCanvas() { ... gl.clearColor(1.0, 0.0, 0.0, 1.0) gl.colorMask(false, true, true, true) gl.clear(gl.COLOR_BUFFER_BIT) } ``` Pada method `clearColor()` kita mempassing warna merah, namun pada saat dirender, output pada canvas bukan warna merah namun warna hitam. Hal ini terjadi karena kita memanggil method `colorMask()` dengan parameter pertama `false`, dengan kata lain kita "mengabaikan" color component warna merah saat rendering. --- ### Referensi yang digunakan: - [WebGL Specification](https://www.khronos.org/registry/webgl/specs/latest/1.0/) - [WebGL: 2D and 3D graphics for the web](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) - [WebGLRenderingContext.clear()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/clear) - [WebGLRenderingContext.clearColor()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/clearColor) - [WebGLRenderingContext.viewport()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/viewport) - [WebGLRenderingContext.colorMask()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/colorMask)<file_sep># Hands-on 3 ## Proses di CPU (JavaScript) Kita sekarang berpindah dari pembuatan obyek 2D (segitiga di hands-on 2) ke pembuatan obyek 3D, dalam hal ini adalah obyek kubus. Untuk dapat membuat sebuah kubus, kita membutuhkan definisi posisi dari titik-titik sudut kubus berikut dengan warna masing-masing sisinya. Ada 8 titik sudut kubus yang perlu kita definisikan posisinya di aplikasi JavaScript. Kita akan buat kubus ini berukuran 1 unit baik dari segi lebar, tinggi, dan panjangnya. ```JavaScript var cubePoints = [ [-0.5, 0.5, 0.5], // A, 0 [-0.5, -0.5, 0.5], // B, 1 [ 0.5, -0.5, 0.5], // C, 2 [ 0.5, 0.5, 0.5], // D, 3 [-0.5, 0.5, -0.5], // E, 4 [-0.5, -0.5, -0.5], // F, 5 [ 0.5, -0.5, -0.5], // G, 6 [ 0.5, 0.5, -0.5] // H, 7 ]; ``` ![https://i.pinimg.com/originals/f9/51/cf/f951cfd3baaf74282dfb67ae5a810f8f.gif](https://i.pinimg.com/originals/f9/51/cf/f951cfd3baaf74282dfb67ae5a810f8f.gif) Warna-warna yang akan kita aplikasikan pada kubus kali ini akan kita sesuaikan dengan warna kubus yang sering kita lihat dari kubus rubik, yakni: merah, hijau, biru, putih, oranye, dan kuning. Definisi warna pada JavaScript cukup disematkan pada indeks 1-6 (indeks 0 dan 7 sengaja kita kosongkan). Alasannya akan dijelaskan pada paragraf berikutnya. ```JavaScript var cubeColors = [ [], [1.0, 0.0, 0.0], // merah [0.0, 1.0, 0.0], // hijau [0.0, 0.0, 1.0], // biru [1.0, 1.0, 1.0], // putih [1.0, 0.5, 0.0], // oranye [1.0, 1.0, 0.0], // kuning [] ]; ``` Agar keenam sisi kubus bisa mendapatkan warna yang berbeda-beda, maka satu titik sudut kubus tidak cukup hanya didefinisikan sebagai sebuah verteks. Alih-alih, kita membutuhkan 3 definisi verteks terpisah untuk satu buah titik sudut agar dari satu titik sudut ini bisa mengakomodasi tiga sisi dengan warna yang berbeda untuk masing-masingnya. Untuk membantu proses pendefinisian verteks ini kita akan membuat fungsi `quad`. Fungsi ini akan mengolah kedelapan titik sudut untuk didistribusikan sebagai 36 buah verteks (dalam array `vertices`) yang akan memuat atribut posisi `cubePoints` dan warna `cubeColors`. Fungsi ini akan dipanggil 6 kali, yakni sebanyak jumlah sisi kubus. ```JavaScript function quad(a, b, c, d) { var indices = [a, b, c, c, d, a]; for (var i=0; i<indices.length; i++) { for (var j=0; j<3; j++) { vertices.push(cubePoints[indices[i]][j]); } for (var j=0; j<3; j++) { vertices.push(cubeColors[a][j]); } } } quad(1, 2, 3, 0); // Kubus depan quad(2, 6, 7, 3); // Kubus kanan quad(3, 7, 4, 0); // Kubus atas quad(4, 5, 1, 0); // Kubus kiri quad(5, 4, 7, 6); // Kubus belakang quad(6, 2, 1, 5); // Kubus bawah ``` Jangan lupa sebagai langkah akhir (di bagian proses di CPU) untuk menyambungkan variabel warna di JavaScript dengan variabel warna di _shader_ agar _pointer_ terhadap _vertex buffer object_ tereksekusi dengan tepat. ```JavaScript var color = gl.getAttribLocation(shaderProgram, "aColor"); gl.vertexAttribPointer(color, 3, gl.FLOAT, false, 6 * Float32Array.BYTES_PER_ELEMENT, 3 * Float32Array.BYTES_PER_ELEMENT); gl.enableVertexAttribArray(color); ``` Untuk proses penggambaran verteks-nya, kita akan menggunakan `gl.TRIANGLES` dengan jumlah verteks total sebanyak 36. ```JavaScript gl.drawArrays(gl.TRIANGLES, 0, 36); ``` ## Proses di GPU (Shader) ### Vertex Shader Oleh karena kita perlu menambahkan atribut warna ke dalam verteks, maka kita perlu menambahkan variabel baru di _shader_ untuk mengakomodasi ini. Pada awalnya, variabel `aColor` dibuat dengan _qualifier `attribute`_ yang berarti akan menangkap nilai dari CPU (JavaScript) untuk kemudian ditransfer ke _fragment shader_ melalui variabel `vColor` yang dibuat dengan _qualifier `varying`_. Variabel **warna** ini bertipedatakan `vec3`sebagaimana variabel posisi. Hanya saja 3 elemen yang dicakup bukan ~xyz~ tapi **rgb**. ```GLSL attribute vec3 aPosition; attribute vec3 aColor; varying vec3 vColor; void main(void) { vColor = aColor; gl_Position = vec4(aPosition, 1.0); } ``` ### Fragment Shader Variabel `vColor` yang dideklarasikan di _vertex shader_ akan ditangkap oleh variabel `vColor` (juga `varying`) yang ada di _fragment shader_. Pada akhirnya, `vColor` akan menyusun 3 elemen awal dari `gl_FragColor`. ```GLSL precision mediump float; varying vec3 vColor; void main(void) { gl_FragColor = vec4(vColor, 1.0); } ``` <file_sep># Hands-on 2 ## Shader Shader merupakan program yang didesain untuk di-run pada graphics processor, secara paralel. Shader ditulis menggunakan OpenGL ES Shader Language (GLSL). Untuk bisa bekerja, WebGL membutuhkan 2 shader setiap kali kita draw sesuatu pada canvas, yaitu *fragment shader* dan *vertex shader.* Setiap shader ini merupakan sebuah function/method. Kedua shader ini akan saling berhubungan menjadi sebuah program/shader program. Pada sebuah project/aplikasi WebGL, shader program lebih dari satu terkadang dibutuhkan. ### Vertex Shader ![https://webglfundamentals.org/webgl/lessons/resources/vertex-shader-anim.gif](https://webglfundamentals.org/webgl/lessons/resources/vertex-shader-anim.gif) Vertex shader merupakan sebuah fungsi yang dipanggil pada setiap vertex. Vertex shader mengontrol data pada setiap vertex (per-vertex data) seperti koordinat, warna, dan texture pada koordinat tersebut. Selain itu vertex shader juga mengatur transformasi vertex, seperti merubah koordinat vertex, normalisasi, transformasi texture koordinat, lighting, dan color material. Sample code vertex shader: ```GLSL //attribute merupakan qualifier yang menghubungkan antara vertex shader dan per-vertex data //value ini selalu beruba setiap eksekusi vertex shader attribute vec2 coordinates; void main(void) { gl_Position = vec4(coordinates, 0.0, 1.0); }; ``` Pada sample di atas, kita mendeklarasikan sebuah attribute variable bernama `coordinates`. Variable ini akan diasosiakan (dihubungkan) dengan *Vertex Buffer Object* menggunakan method `getAttribLocation()`. `gl_Position` merupakan variable yang sudah predefined yang hanya ada di vertex shader. Variablee ini yang berisi posisi dari vertex. Pada sample diatas, attribute variable `coordinates` dipassing dalam bentuk vector. ### Fragment Shader ![https://gsculerlor.s-ul.eu/MRoljygw](https://gsculerlor.s-ul.eu/MRoljygw) Sebuah mesh terbuat dari beberapa triangles, dan permukaan dari tiap triangle ini yang disebut dengan fragment. Fragment shader sendiri merupakan sebuah fungsi yang dipanggil pada setiap fragment. Fragment shader akan mengatur dan mengkalkulasi warna pada setiap pixelnya. Fragment shader dapat melakukan operasi pada interpolated value, texture, fog, dan color summing. Sample code fragment shader: ```GLSL void main(void) { gl_FragColor = vec4(0, 0.8, 0, 1); } ``` Pada sample di atas, value dari color disimpan pada variable `gl_FragColor`. `gl_FragColor` merupakan variable predefined pada fragment shader yang membawa output data berupa color value dari pixel. ### Implementasi shader pada WebGL Implementasi shader pada WebGL membutuhkan beberapa step: - Membuat shader object Pada WebGL, terdapat method `createShader()` yang akan membuat shader object kosong. Syntax: ```GLSL Object createShader (enum type) //Enum type bisa berupa gl.VERTEX_SHADER atau gl.FRAGMENT_SHADER ``` - Attach source ke shader object Source code shader kita perlu diattach ke shader object yang sudah kita buat sebelumnya menggunakan method `shaderSource()` Syntax: ```GLSL void shaderSource(Object shader, string source) ``` - Compile shader Setelah shader object attached dengan sourcenya, shader perlu di compile sebelum kita passing ke program kita menggunakan method `compileShader()` Syntax: ```GLSL void compileShader(Object shader) ``` Contoh implementasi: ```Javascript var vertCode = 'attribute vec2 coordinates;' + 'void main(void) {' + ' gl_Position = vec4(coordinates, 0.0, 1.0);' + '}'; var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, vertCode); gl.compileShader(vertShader); var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(0.0, 1.0, 1.0, 0.5);' + '}'; var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, fragCode); gl.compileShader(fragShader); ``` Setelah selesai membuat vertex shader dan fragment shader, kita perlu menggabungkan keduanya ke dalam sebuah program: - Membuat program object Seperti biasa kita perlu membuat program object kosong, menggunakan method `createProgram()` Syntax: ```GLSL WebGLProgram gl.createProgram(); ``` - Attach shader ke program Setelah memiliki object program kosong, kita perlu attach shader yang sudah dicompile sebelumnya ke dalam program kita menggunakan method `attachShader()` Syntax: ```GLSL void gl.attachShader(program, shader); ``` - Link program Linking program merupakan tahap akhir untuk linking antar program (shader progam dan program) menggunakan method `linkProgram()` Syntax: ```GLSL void gl.linkProgram(program); ``` - Menggunakan program yang sudah dibuat Kita perlu menspesifikkan program mana yang akan digunakan sebagai bagian dari rendering state menggunakan method `useProgram()` Syntax: ```GLSL void gl.useProgram(program); ``` Contoh implementasi: ```JavaScript var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertShader); gl.attachShader(shaderProgram, fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); ``` ## Drawing Points dan Triangles Define vertices sebagai coordinates dan simpan ke dalam buffer ```JavaScript var vertices = [ -0.5, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0, ]; var vertex_buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); ``` Membuat dan compile shaders dan WebGL program ```JavaScript var vertCode = 'attribute vec3 coordinates;' + 'void main(void) {' + 'gl_Position = vec4(coordinates, 1.0);' + 'gl_PointSize = 10.0;'+ '}'; var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, vertCode); gl.compileShader(vertShader); var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}'; var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, fragCode); gl.compileShader(fragShader); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertShader); gl.attachShader(shaderProgram, fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); ``` Associate shader dengan buffer object ```JavaScript gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); var coord = gl.getAttribLocation(shaderProgram, "coordinates"); gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(coord); ``` Draw objects ```JavaScript gl.drawArrays(gl.POINTS, 0, 3); ``` Untuk menggambar sebuah Triangles, yang perlu diubah adalah parameter yang dipassing kedalam fungsi `gl.drawArrays` atau `gl.drawElements`. Ada 7 jenis, yaitu `POINTS`, `LINES`, `LINE_STRIP`, `LINE_LOOP`, `TRIANGLES`, `TRIANGLE_STRIP`, dan `TRIANGLE_FAN`. Jadi untuk menggambar sebuah triangle dengan vertex yang sudah dibuat sebelumnya cukup dengan merubah line berikut. ```JavaScript gl.drawArrays(gl.TRIANGLES, 0, 3); ``` Perlu diperhatikan juga bahwa kita juga bisa menghapus `gl_PointSize` yang kita gunakan sebelumnya karena yang dirender bukanlah points. --- ### Referensi yang digunakan: - [Shader](https://www.khronos.org/opengl/wiki/Shader) - [WebGLShader](https://developer.mozilla.org/en-US/docs/Web/API/WebGLShader) - [WebGL Specification](https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.8) - [WebGL Shaders and GLSL](https://webglfundamentals.org/webgl/lessons/webgl-shaders-and-glsl.html) - [Unbinding a WebGL buffer, worth it?](https://stackoverflow.com/questions/28259022/unbinding-a-webgl-buffer-worth-it) - [WebGLRenderingContext.drawArrays()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawArrays) - [WebGLRenderingContext.drawElements()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements)
5d6fa2bd8a0810f75ed0e213d46eb4696f21e7ad
[ "Markdown", "JavaScript" ]
6
Markdown
grafkom-2020/hands-on-webgl
fe772b904be12df11770fb36e73c9a2e365a349e
60a9526263eda850b482c27fd218509ebd74b201
refs/heads/master
<file_sep># ORMLiteKotlin ORMLite database implementaion in Kotlin > visit here to know about Room Database: <https://github.com/jbankz/RoomKotlin> > visit here to know about SQLite Database: <https://github.com/jbankz/SQLiteKotlin> <file_sep>package com.androidatc.myormliteexample import android.database.sqlite.SQLiteDatabase import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper import com.j256.ormlite.support.ConnectionSource import com.j256.ormlite.table.TableUtils object DatabaseHelper: OrmLiteSqliteOpenHelper(App.instance, "names.db", null, 1) { override fun onCreate(database: SQLiteDatabase?, connectionSource: ConnectionSource?) { TableUtils.createTableIfNotExists(connectionSource, Person::class.java) } override fun onUpgrade(database: SQLiteDatabase?, connectionSource: ConnectionSource?, oldVersion: Int, newVersion: Int) { TableUtils.dropTable<Person, Any>(connectionSource, Person::class.java, true) onCreate(database, connectionSource) } }
06a0053894bc264e2a8ac3656335bda2df216b0d
[ "Markdown", "Kotlin" ]
2
Markdown
jbankz/ORMLiteKotlin
86d31ad68c1f899969353734fea28e7f71c1e1c6
017c221255db8f1f21e327136c90e1ace542bf4b
refs/heads/master
<file_sep>class RemovePostIdFromTopics < ActiveRecord::Migration def change remove_column :topics, :post_id, :integer remove_column :posts, :commentable_id, :integer remove_column :posts, :commentable_type, :string end end <file_sep>class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @topic = Topic.find(params[:topic_id]) @post = @topic.posts.create(post_params) @post.user_id = current_user.id if current_user @post.save if @post.save flash[:notice] = "Your post was successfully saved" redirect_to topic_path(@topic) else flash.now[:error] = "Something went wrong" render :new end end def update @topic = Topic.find(params[:topic_id]) @post = @topic.posts.find(params[:id]) if @post.update(post_params) flash[:notice] = "Your post successfully updated" redirect_to posts_path(@post) else flash[:error] = "Something is wrong" render :edit end end def edit @topic = Topic.find(params[:topic_id]) @post = @topic.posts.find(params[:id]) end def destroy @post = Topic.posts.find(params[:id]) @post.destroy respond_to do |format| format.html { redirect_to posts_url, error: 'Post was successfully destroyed.' } format.json { head :no_content } end end private def set_post @post = Post.find(params[:id]) end def post_params params.require(:post).permit(:title, :text, :user_id, :topic_id) end end <file_sep>json.extract! @video, :id, :title, :video, :created_at, :updated_at <file_sep>class RenameAgeColuumnToDateOfBirthInUsers < ActiveRecord::Migration def change rename_column :users, :age, :date_of_birth end end <file_sep>class AddCommentableIdAndCommentableTypeToPosts < ActiveRecord::Migration def change add_column :posts, :commentable_id, :integer add_column :posts, :commentable_type, :string end end <file_sep>json.array!(@news_pages) do |news_page| json.extract! news_page, :id, :title, :content json.url news_page_url(news_page, format: :json) end <file_sep>json.extract! @user, :id, :first_name, :last_name, :age, :email, :created_at, :updated_at <file_sep>class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :topics has_many :posts validates :first_name, presence: true validates :last_name, presence: true validates :email, presence: true validates :date_of_birth, presence: true validates :gender, presence: true has_attached_file :photo, styles: {large: "600x600", medium: "300x300", thumb: "100x100", small: "50x50#" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/ end <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :configure_devise_params, if: :devise_controller? def configure_devise_params devise_parameter_sanitizer.for(:sign_up) do |u| u.permit(:first_name, :last_name, :gender, :email, :date_of_birth, :photo, :password, :password_confirmation, :bio) end end def authenticate_admin! unless current_user.admin redirect_to root_path end end # helper_method :current_user, :logged_in? # def current_user # @current_user ||= User.find(session[:user_id]) if session[:user_id] # end # def logged_in? # !!current_user # end # def require_user # if !logged_in? # flash[:danger] = "You must be logged in to perform this action" # redirect_to root_path # end # end end <file_sep>require 'test_helper' class NewsPagesControllerTest < ActionController::TestCase setup do @news_page = news_pages(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:news_pages) end test "should get new" do get :new assert_response :success end test "should create news_page" do assert_difference('NewsPage.count') do post :create, news_page: { content: @news_page.content, title: @news_page.title } end assert_redirected_to news_page_path(assigns(:news_page)) end test "should show news_page" do get :show, id: @news_page assert_response :success end test "should get edit" do get :edit, id: @news_page assert_response :success end test "should update news_page" do patch :update, id: @news_page, news_page: { content: @news_page.content, title: @news_page.title } assert_redirected_to news_page_path(assigns(:news_page)) end test "should destroy news_page" do assert_difference('NewsPage.count', -1) do delete :destroy, id: @news_page end assert_redirected_to news_pages_path end end <file_sep>class AddUserIdToPosts < ActiveRecord::Migration def change t.references :user, index: true add_foreign_key :posts, :users end end
69ae2ea1918bf55a4bd1578ecf8717c44fded049
[ "Ruby" ]
11
Ruby
Alisher778/BE-Final_Project
6f1300e4df121b11f74e845fdf05682cb344099a
2d2cd82bb913b4a7eb4e9bc605356066fe46a9fa