branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>Finabashi/Koby_Project<file_sep>/README.md # Koby_Project Exercice Git <file_sep>/fonction.js // exercise 1 function perimetre(number1, number2, number3, number4) { return (number1 + number2 + number3 + number4) } // exercise 2 function aire(number1, number2) { return (number1 * number2) } document.getElementById("button").onclick = function(){ var number1 = document.getElementById("calculer").value ; var number2 = document.getElementById("calcule").value ; alert(aire(number1,number2)); } // exercise 3 function seconde(jour, heure, minute) { return (jour * 3000) +(heure *1600) +(minute * 60); } document.getElementById("button3").onclick = function(){ var number1 = document.getElementById("trois").value ; var number2 = document.getElementById("trois3").value ; var number3 = document.getElementById("trois4").value ; alert(seconde(number1, number2, number3)); } // exercise 4
f3b87c7dc7154fea8073425bbbb32a1d9e8a3395
[ "Markdown", "JavaScript" ]
2
Markdown
Finabashi/Koby_Project
1566767f86b6dc9842069e522ad487f4aba4ad1d
7017fbca9b49a21380fb3f02f69ca69c1e150715
refs/heads/master
<file_sep>package ru.boiko.se; import lombok.SneakyThrows; import java.util.concurrent.*; /** * Домашнее задание к уроку 5 */ public class App { private static final int CARS_COUNT = 4; @SneakyThrows public static void main(String[] args) { final CyclicBarrier cyclicBarrier = new CyclicBarrier(CARS_COUNT); final CountDownLatch startCountDownLatch = new CountDownLatch(CARS_COUNT); final CountDownLatch raceCountDownLatch = new CountDownLatch(CARS_COUNT); final Semaphore tunnelTraffic = new Semaphore(CARS_COUNT / 2); final ExecutorService executorService = Executors.newCachedThreadPool(); System.out.println("ВАЖНОЕ ОБЪЯВЛЕНИЕ >>> Подготовка!!!"); Race race = new Race(new Road(60), new Tunnel(tunnelTraffic), new Road(40)); Car[] cars = new Car[CARS_COUNT]; for (int i = 0; i < cars.length; i++) { cars[i] = new Car(race, 20 + (int) (Math.random() * 10), startCountDownLatch, raceCountDownLatch, cyclicBarrier, CARS_COUNT); } for (Car car : cars) { executorService.submit(car); } startCountDownLatch.await(); System.out.println("ВАЖНОЕ ОБЪЯВЛЕНИЕ >>> Гонка началась!!!"); raceCountDownLatch.await(); System.out.println("ВАЖНОЕ ОБЪЯВЛЕНИЕ >>> Гонка закончилась!!!"); executorService.shutdown(); } }
6e1ed15fefd95007410b021539ff4f4a8d625268
[ "Java" ]
1
Java
NikiArt/lessonfive
31cc1b5a18e2e8cc8496a23f07abb5b15538c7d0
cf9f278841ad91b9156be01750cc0d4a231fa0f2
refs/heads/main
<repo_name>nandozz/ESP1-smart-lamp<file_sep>/IP_setting/IP_setting.ino #include <ESP8266WiFi.h> const char* ssid = "Thanks God"; // Isi dengan nama wifi anad const char* password = "<PASSWORD>@"; //wifi password nya WiFiServer server(80); #define pin_relay 0 // pin relaya pada GPIO0 IPAddress local_IP(192, 168, 100, 184); IPAddress gateway(192, 168, 100, 1); IPAddress subnet(255, 255, 255, 0); IPAddress primaryDNS(8, 8, 8, 8); //optional IPAddress secondaryDNS(8, 8, 4, 4); //optional void setup() { Serial.begin(115200); //baud komunikasi pinMode(pin_relay,OUTPUT); //didefinisikan sebagai output digitalWrite(pin_relay, LOW); //nilai awalnya low = tidak aktif //Memulai menghubungkan ke wifi Serial.println(); Serial.println(); if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) { Serial.println("STA Failed to configure"); } Serial.print("Menghubungkan dengan wifi..."); Serial.println(ssid); //prosedur koneksi ke wifi yang dijadikan target dan password WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); //.......... } Serial.println(""); Serial.println("terhubung ke WiFi Anda"); server.begin(); Serial.println("Siap digunakan"); //menampilkan alamat IP address Serial.print("Gunakan IP ini sebagai kendali Relay : "); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { //cek kondisi jika terhubung dengan module WiFiClient client = server.available(); if (!client) { return; } // menunggu sampai module relay programming kirim data Serial.println("Client Baru"); while(!client.available()) { delay(1); } String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Mencocokan permintaan awal int value = LOW; if (request.indexOf("/pin_relay=ON") != -1) { Serial.println("Kondisi_Relay=ON"); digitalWrite(pin_relay,LOW); value = LOW; } if (request.indexOf("/pin_relay=OFF") != -1) { Serial.println("Kondisi_Relay=OFF"); digitalWrite(pin_relay,HIGH); value = HIGH; } client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // this is a must client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<head><title>ESP-01 IOT Kendali module Relay Programming</title></head>"); client.print("Kondisi relay sekarang ; "); if(value == HIGH) { client.print("MATI"); } else { client.print("HIDUP"); } client.println("<br><br>"); client.println("Turn <a href=\"/pin_relay=OFF\">MATI</a> RELAY<br>"); client.println("Turn <a href=\"/pin_relay=ON\"HIDUP</a> RELAY<br>"); client.println("</html>"); delay(1); Serial.println("Client disonnected"); Serial.println(""); } <file_sep>/README.md # ESP1-smart-lamp use ESP1, thingspeak <file_sep>/Access_Point_Hotspot/Access_Point_Hotspot.ino #include <ESP8266WiFi.h> const char* ssid = "SMART IoT"; // Nama AP/Hotspot const char* password = "<PASSWORD>"; // Password AP/Hotspot // Mengatur IP Address ---------------------------------------------------- IPAddress IP(192,168,100,111); IPAddress NETWORK(192,168,100,1); IPAddress NETMASK(255,255,255,0); IPAddress DNS(8, 8, 8, 8); IPAddress secondaryDNS(8, 8, 4, 4); //optional int LED = 2; WiFiServer server(80); void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); delay(10); // Mengatur WiFi ---------------------------------------------------------- Serial.println(); Serial.print("Configuring access point..."); WiFi.mode(WIFI_AP); // Mode AP/Hotspot WiFi.softAP(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); //.......... } if (!WiFi.config(IP, NETWORK, NETMASK, DNS,secondaryDNS)) { Serial.println("STA Failed to configure"); } // Start the server ------------------------------------------------------- server.begin(); Serial.println("Server dijalankan"); // Print the IP address --------------------------------------------------- Serial.println(WiFi.localIP()); } void loop() { //cek kondisi jika terhubung dengan module WiFiClient client = server.available(); if (!client) { return; } // menunggu sampai module relay programming kirim data Serial.println("Client Baru"); while(!client.available()) { delay(1); } String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Mencocokan permintaan awal int value = LOW; if (request.indexOf("/pin_relay=ON") != -1) { Serial.println("Kondisi_Relay=ON"); digitalWrite(LED,LOW); value = LOW; } if (request.indexOf("/pin_relay=OFF") != -1) { Serial.println("Kondisi_Relay=OFF"); digitalWrite(LED,HIGH); value = HIGH; } client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // this is a must client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<head><title>ESP-01 IOT Kendali module Relay Programming</title></head>"); client.print("Kondisi relay sekarang ; "); if(value == HIGH) { client.print("MATI"); } else { client.print("HIDUP"); } client.println("<br><br>"); client.println("Turn <a href=\"/pin_relay=OFF\">MATI</a> RELAY<br>"); client.println("Turn <a href=\"/pin_relay=ON\"HIDUP</a> RELAY<br>"); client.println("</html>"); delay(1); Serial.println("Client disonnected"); Serial.println(""); } <file_sep>/Read_json_thingspeak_data/Read_json_thingspeak_data.ino /* Preference Ctrl + comma > http://arduino.esp8266.com/stable/package_esp8266com_index.json * Setting board to ESP8266 setting > board * add library arduinojson version 5.13 *  * ESP8266 JSON Decode of server response  * -<NAME> * https://circuits4you.com  */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266HTTPClient.h> #include <ArduinoJson.h> /////////////////////////////////////////////// EDIT PROFILE ////////////////////////////////////////// const char* wifiName = ""; const char* wifiPass = ""; //Web Server address to read/write from String API = "B9ABSKETD0062LXG"; String ID = "803833"; String Field = "2"; ////////////////////////////////////////////////////////////////////////////////////////////////////// //const char *host = "http://api.thingspeak.com/channels/803833/fields/2/last.json"; String host = "http://api.thingspeak.com/channels/"+ID+"/fields/"+Field+"/last.json"; String wri = "http://api.thingspeak.com/update?api_key="+API+"&field"+Field+"=0"; String feed = "https://api.thingspeak.com/channels/"+ID+"/feeds.json"; const int output2 = 0; void setup() { Serial.begin(115200); pinMode(output2, OUTPUT); digitalWrite(output2, HIGH); delay(100); Serial.println(); Serial.print("Connecting to "); Serial.println(wifiName); WiFi.begin(wifiName, wifiPass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); //You can get IP address assigned to ESP } void loop() { HTTPClient http; //Declare object of class HTTPClient Serial.print("\nRequest Link:"); Serial.println(host); Serial.println(wri); Serial.println(feed); http.begin(host); //Specify request destination int httpCode = http.GET(); //Send the request String payload = http.getString(); //Get the response payload from server Serial.print("\nResponse Code:"); //200 is OK Serial.println(httpCode); //Print HTTP return code Serial.print("Returned data from Server:"); Serial.println(payload); //Print request response payload if(httpCode == 200) { // Allocate JsonBuffer // Use arduinojson.org/assistant to compute the capacity. const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60; DynamicJsonBuffer jsonBuffer(capacity); // Parse JSON object JsonObject& root = jsonBuffer.parseObject(payload); if (!root.success()) { Serial.println(F("Parsing failed!")); return; } // Decode JSON/Extract values //////////////////////// Serial.println(F("Response:")); int field = root["field"+Field]; // 1 /*const char* Time = root["time"]; // "<NAME>" const char* username = root["data"][0]; // "Bret" const char* email = root["data"][1]; // "<EMAIL> */ Serial.println("Field "+Field+" : "+String(field)); if(field==1){ digitalWrite(output2, LOW); Serial.println("Lamp ON"); } else { digitalWrite(output2, HIGH); Serial.println("Lamp OFF"); } /*//////////////////// Serial.println(F("Response:")); Serial.println(root["sensor"].as<char*>()); Serial.println(root["time"].as<char*>()); Serial.println(root["data"][0].as<char*>()); Serial.println(root["data"][1].as<char*>()); */ } else { Serial.println("Error in response"); } http.end(); //Close connection Serial.println("Close connection"); delay(5000); //GET Data at every 5 seconds }
d24b5e5c7980bbd9b9c1a7fc812a76f7b22139ae
[ "Markdown", "C++" ]
4
C++
nandozz/ESP1-smart-lamp
090d223b9b46839ce1cfc60dbb3faba1a1efaf08
bf7fe3c90c20de0b03cea22af85444b0277a8c84
refs/heads/master
<repo_name>xlplbo/libevent<file_sep>/Client/main.cpp #include <stdio.h> #include <assert.h> #include <WinSock2.h> int main(int argc, char **argv) { #ifdef WIN32 WSADATA wsa_data; WSAStartup(0x0201, &wsa_data); #endif struct sockaddr_in server_address; memset( &server_address, 0, sizeof( server_address ) ); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); server_address.sin_port = htons( 9995 ); int sockfd = socket( PF_INET, SOCK_STREAM, 0 ); assert( sockfd >= 0 ); if ( connect( sockfd, ( struct sockaddr* )&server_address, sizeof( server_address ) ) < 0 ) { printf( "connection failed\n" ); } else { printf( "send oob data out\n" ); const char* oob_data = "abc"; const char* normal_data = "123"; send( sockfd, normal_data, strlen( normal_data ), 0 ); send( sockfd, oob_data, strlen( oob_data ), MSG_OOB ); send( sockfd, normal_data, strlen( normal_data ), 0 ); } return 0; }
912a97a82defe9fc9e0b174580d446b5c1bf818c
[ "C++" ]
1
C++
xlplbo/libevent
3c3c0c68fac7ed96c081a60bd16d0a8fd7c23996
bcd174b6eb191f336772d5fec75c3a5c6d725b90
refs/heads/master
<repo_name>bobbyangelov/mood-guesser<file_sep>/flask-backend/mood-guesser.py from datetime import datetime from flask import ( Flask, abort, flash, redirect, render_template, request, url_for, ) app = Flask(__name__) app.config['DEBUG'] == True @app.route('/') def show_index(): return render_template('home.html') if __name__ == "__main__": app.run() <file_sep>/explorer.py import dataloader import pandas as pd test_data_df = pd.read_csv(test_data_file_name, header = None, delimiter = '\t', quoting = 3) test_data_df.columns = ["Text"] train_data_df = pd.read_csv(train_data_file_name, header = None, delimiter = '\t', quoting = 3) train_data_df.columns = ["Sentiment", "Text"] train_data_df.shape train_data_df.head <file_sep>/whole-script.py import urllib import pandas as pd import numpy as np import re, nltk from sklearn.feature_extraction.text import CountVectorizer from nltk.stem.porter import PorterStemmer # define URLs test_data_url = "https://dl.dropboxusercontent.com/u/8082731/datasets/UMICH-SI650/testdata.txt" train_data_url = "https://dl.dropboxusercontent.com/u/8082731/datasets/UMICH-SI650/training.txt" # define local file names test_data_file_name = 'test_data.csv' train_data_file_name = 'train_data.csv' # download files using urlib test_data_f = urllib.urlretrieve(test_data_url, test_data_file_name) train_data_f = urllib.urlretrieve(train_data_url, train_data_file_name) # load files into dataframes test_data_df = pd.read_csv(test_data_file_name, header = None, delimiter = '\t', quoting = 3) test_data_df.columns = ["Text"] train_data_df = pd.read_csv(train_data_file_name, header = None, delimiter = '\t', quoting = 3) train_data_df.columns = ["Sentiment", "Text"] # sanity check of data train_data_df.shape test_data_df.shape train_data_df.head() test_data_df.head() # count labels for each sentiment class train_data_df.Sentiment.value_counts() # calculate average number of words per sentence np.mean([len(s.split(" ")) for s in train_data_df.Text]) # Building corpus stemmer = PorterStemmer() def stem_tokens(tokens, stemmer): stemmed = [] for item in tokens: stemmed.append(stemmer.stem(item)) return stemmed def tokenize(text): # remove non letters text = re.sub("[^a-zZ-Z]", " ", text) # tokenize tokens = nltk.word_tokenize(text) # stem stems = stem_tokens(tokens, stemmer) return stems vectorizer = CountVectorizer( analyzer = 'word', tokenizer = tokenize, lowercase = True, stop_words = 'english', max_features = 85 ) corpus_data_features = vectorizer.fit_transform(train_data_df.Text.tolist() + test_data_df.Text.tolist()) corpus_data_features_nd = corpus_data_features.toarray() corpus_data_features_nd.shape <file_sep>/dataloader.py import urllib test_data_url = "https://dl.dropboxusercontent.com/u/8082731/datasets/UMICH-SI650/testdata.txt" train_data_url = "https://dl.dropboxusercontent.com/u/8082731/datasets/UMICH-SI650/training.txt" test_data_file_name = "test_data.csv" train_data_file_name = "train_data.csv" test_data_f = urllib.urlretrieve(test_data_url, test_data_file_name) train_data_f = urllib.urlretrieve(train_data_url, train_data_file_name)
555efdcaa4b49660b776512c259b84f3d77500c2
[ "Python" ]
4
Python
bobbyangelov/mood-guesser
33f647a5f4008202980a29f634d46601ceac6e5a
effb34d1dafc03010e9eb6e66eb8ee6881f526d7
refs/heads/master
<file_sep>--- name: Question about: Describe this issue template's purpose here. --- <!-- 1. Please make sure that you have searched in the older issues before submitting a new one! 2. Please fill out all the required information! --> #### I am submitting a - [x] Question #### Description #### What is the use-case or motivation for changing an existing behavior? #### Which versions are you using for the following packages? Angular: ngx-sharebuttons: <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { NgProgressModule } from 'ngx-progressbar'; import { NgProgressRouterModule } from 'ngx-progressbar/router'; import { HIGHLIGHT_OPTIONS, HighlightModule } from 'ngx-highlightjs'; // import { SHARE_BUTTONS_CONFIG } from '../../../ngx-sharebuttons/src/public-api'; // import { ShareIconsModule } from '../../../ngx-sharebuttons/icons/src/public_api'; import { SHARE_BUTTONS_CONFIG } from 'ngx-sharebuttons'; import { ShareIconsModule } from 'ngx-sharebuttons/icons'; import { FaIconLibrary } from '@fortawesome/angular-fontawesome'; import { faLightbulb } from '@fortawesome/free-solid-svg-icons/faLightbulb'; import { faCoffee } from '@fortawesome/free-solid-svg-icons/faCoffee'; import { faInfo } from '@fortawesome/free-solid-svg-icons/faInfo'; import { faBook } from '@fortawesome/free-solid-svg-icons/faBook'; import { faTimesCircle } from '@fortawesome/free-solid-svg-icons/faTimesCircle'; import { faShare } from '@fortawesome/free-solid-svg-icons/faShare'; import { SharedModule } from './shared'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { DocsService } from './docs/docs.service'; export function getHighlightLanguages() { return { typescript: () => import('highlight.js/lib/languages/typescript'), css: () => import('highlight.js/lib/languages/css'), xml: () => import('highlight.js/lib/languages/xml') }; } @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule.withServerTransition({ appId: 'serverApp' }), BrowserAnimationsModule, AppRoutingModule, HttpClientModule, HighlightModule, NgProgressModule, NgProgressRouterModule, SharedModule, ShareIconsModule ], providers: [ DocsService, { provide: HIGHLIGHT_OPTIONS, useValue: { coreLibraryLoader: () => import('highlight.js/lib/core'), languages: getHighlightLanguages() } }, { provide: SHARE_BUTTONS_CONFIG, useValue: { twitterAccount: 'MurhafSousli', theme: 'material-dark', debug: true } } ], bootstrap: [AppComponent] }) export class AppModule { constructor(iconLibrary: FaIconLibrary) { iconLibrary.addIcons(faLightbulb, faBook, faCoffee, faInfo, faTimesCircle, faShare); } } <file_sep>import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { ApiDatabase, ApiDataSource } from '../../docs/docs.class'; import { DocsService } from '../../docs/docs.service'; import { Title } from '@angular/platform-browser'; @Component({ host: { class: 'page' }, selector: 'app-popup-buttons', templateUrl: './popup-buttons.component.html', styleUrls: ['./popup-buttons.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class PopupButtonsComponent implements OnInit { code = { name: '<share-popup-button>, <button shareButtonsPopup>', example: '<share-popup-button>Share</share-popup-button>', styles: `@import '~@angular/cdk/overlay-prebuilt.css'; /** Add this only for non-material project */ @import '~ngx-sharebuttons/themes/default/default-theme';`, npm: `npm i ngx-sharebuttons @angular/cdk npm i @fortawesome/fontawesome-svg-core @fortawesome/angular-fontawesome @fortawesome/free-solid-svg-icons @fortawesome/free-brands-svg-icons`, import: `import { ShareButtonsPopupModule } from 'ngx-sharebuttons/popup'; @NgModule({ imports: [ ShareButtonsPopupModule, ShareIconsModule // Optional if you want the default share icons ] })` }; displayedColumns = ['type', 'name', 'description']; dataSource: ApiDataSource | null; constructor(private docs: DocsService, private titleService: Title) { } ngOnInit() { this.titleService.setTitle('Share Buttons Component'); const apiDatabase = new ApiDatabase(this.docs.getContainerApi()); this.dataSource = new ApiDataSource(apiDatabase); } }
749c2f087595adda87df21f288453eb57460d96d
[ "Markdown", "TypeScript" ]
3
Markdown
mustafahakeem/ngx-sharebuttons
fe1b90afef5ec81a31e942a51449887ed2e7fbb1
24c0017ac5d07d5c11d2986f3314fd8aa02603f4
refs/heads/master
<file_sep>package ds.hdfs; import proto.ProtoHDFS; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; public class DataNode implements DataNodeInterface { // This data structure allows thread safe access to the blocks of this specific data node protected ConcurrentHashMap<String, Boolean> requestsFulfilled; protected ConcurrentHashMap<String, ProtoHDFS.BlockMeta> blockMetas; protected String dataId; protected String dataIp; protected int port; @Override public byte[] readBlock(byte[] inp) throws IOException { ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); // A request sent to readBlocks should only contain a block list consisting of a single block List<ProtoHDFS.Block> requestBlockList = request.getBlockList(); LinkedList<ProtoHDFS.Block> blockList = new LinkedList<>(requestBlockList); ProtoHDFS.Block block = blockList.pop(); ProtoHDFS.BlockMeta blockMeta = block.getBlockMeta(); String fileName = blockMeta.getFileName(); int blockNumber = blockMeta.getBlockNumber(); int repNumber = blockMeta.getRepNumber(); String blockName = fileName + "_" + blockNumber + "_" + repNumber; if(this.blockMetas.containsKey(blockName)){ byte[] blockBytes = Files.readAllBytes(Paths.get(blockName)); String blockContents = new String(blockBytes); ProtoHDFS.Block.Builder blockBuilder = ProtoHDFS.Block.newBuilder(); blockBuilder.setBlockMeta(this.blockMetas.get(blockName)); blockBuilder.setBlockContents(blockContents); ProtoHDFS.Block responseBlock = blockBuilder.build(); blockBuilder.clear(); ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.SUCCESS); responseBuilder.setBlock(responseBlock); responseBuilder.setErrorMessage(String.format("Block %1$d replication %2$d for %3$s read success", blockNumber, repNumber, fileName)); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); }else{ ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.FAILURE); responseBuilder.setErrorMessage(String.format("Block %1$d replication %2$d for %3$s does not exist", blockNumber, repNumber, fileName)); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } } @Override public byte[] writeBlock(byte[] inp) throws IOException { ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); // Make the replication factor configurable later int repFactor = 3; List<ProtoHDFS.Block> requestBlockList = request.getBlockList(); LinkedList<ProtoHDFS.Block> blockList = new LinkedList<>(requestBlockList); ProtoHDFS.Block block = blockList.pop(); ProtoHDFS.BlockMeta blockMeta = block.getBlockMeta(); String blockContents = block.getBlockContents(); String fileName = blockMeta.getFileName(); int blockNumber = blockMeta.getBlockNumber(); int repNumber = blockMeta.getRepNumber(); if(repNumber < repFactor){ // Send a 'request' object to the next data node to replicate block on another data node // Still need to figure out how to access other data nodes from a data node } String blockName = fileName + "_" + blockNumber + "_" + repNumber; File file = new File(blockName); FileOutputStream fileOutputStream; if(file.exists() || file.createNewFile()){ fileOutputStream = new FileOutputStream(file); fileOutputStream.write(blockContents.getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.SUCCESS); responseBuilder.setErrorMessage(String.format("Block %1$d replication %2$d for %3$s write success", blockNumber, repNumber, fileName)); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } // This method binds the Data Node to the server so the client can access it and use its services (methods) public void bindServer(String dataId, String dataIp, int dataPort){ try{ // This is the stub which will be used to remotely invoke methods on another Data Node // Initial value of the port is set to 0 DataNodeInterface dataNodeStub = (DataNodeInterface) UnicastRemoteObject.exportObject(this, 0); // This sets the IP address of this particular Data Node instance System.setProperty("java.rmi.server.hostname", dataIp); // This gets reference to remote object registry located at the specified port Registry registry = LocateRegistry.getRegistry(dataPort); // This rebinds the Data Node to the remote object registry at the specified port in the previous step // Uses the values of id (or 'name') of the Data Node and a Remote which is the stub for this Data node registry.rebind(dataId, dataNodeStub); System.out.println("\n Data Node connected to RMI registry \n"); }catch(Exception e){ System.err.println("Server Exception: " + e.toString()); e.printStackTrace(); } } public DataNodeInterface getDNStub(String dataId, String dataIp, int dataPort) { while(true){ try{ Registry registry = LocateRegistry.getRegistry(dataIp, dataPort); DataNodeInterface dataNodeStub = (DataNodeInterface)registry.lookup(dataId); System.out.println("\n Data Node Found! Replicating to Data Node \n"); return dataNodeStub; }catch(RemoteException | NotBoundException e){ System.out.println("\n Searching for Data Node ... \n"); }finally{ System.out.println("timed out?!?!??!"); } } } // This method finds the Name Node and returns a stub (Remote to the Name Node) with which the Data Node // could use to invoke functions on the Name Node public NameNodeInterface getNNStub(String id, String ip, int port){ while(true){ try{ // This gets the remote object registry at the specified port Registry registry = LocateRegistry.getRegistry(ip, port); // This gets the Remote to the Name Node using the ID of the Name Node NameNodeInterface nameNodeStub = (NameNodeInterface)registry.lookup(id); System.out.println("\n Name Node Found! \n"); return nameNodeStub; }catch(Exception e){ System.out.println("\n Searching for Name Node ... \n"); } } } public static void main(String[] args){ } } <file_sep>package ds.hdfs; import java.io.*; public class Test { public static void main(String[] args){ File file = new File("randomFile.txt"); File out = new File("outFile.txt"); int readBytes = 0; try { byte[] b = new byte[10]; if((file.exists() || file.createNewFile() && (out.exists() || out.createNewFile()))){ FileInputStream fileInputStream = new FileInputStream(file); FileOutputStream fileOutputStream = new FileOutputStream(out); while((readBytes = fileInputStream.read(b)) != -1){ fileOutputStream.write(b, 0, readBytes); fileOutputStream.write("cool beans".getBytes()); } fileInputStream.close(); fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package ds.hdfs; import com.google.protobuf.InvalidProtocolBufferException; import proto.ProtoHDFS; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; public class NameNode implements NameNodeInterface { protected Registry serverRegistry; protected ConcurrentHashMap<String, Boolean> requestsFulfilled; protected ConcurrentHashMap<String, ProtoHDFS.FileHandle> fileHandles; protected ConcurrentHashMap<String, ReentrantReadWriteLock> fileLocks; protected String nameId; protected String nameIp; protected int port; //Hashmap private HashMap<String, Boolean> map_heartbeat; private Namenode() { map_heartbeat = new HashMap<>(); } @Override public byte[] openFile(byte[] inp) throws RemoteException, InvalidProtocolBufferException { ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); ProtoHDFS.Request.RequestType operation = request.getRequestType(); ProtoHDFS.FileHandle fileHandle = request.getFileHandle(); String fileName = fileHandle.getFileName(); if(this.fileHandles.containsKey(fileName)){ // If file does exist, first check if it is a read or write request // If read request, return a file handle // If write request, return an error response if(operation == ProtoHDFS.Request.RequestType.READ){ return getBlockLocations(inp); }else if(operation == ProtoHDFS.Request.RequestType.WRITE){ ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.FAILURE); responseBuilder.setErrorMessage("File " + fileName + " already exists! Write failed!"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } }else{ // If file does not exist, assign the blocks of the file to different data nodes return assignBlock(inp); } ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.FAILURE); responseBuilder.setErrorMessage("Invalid Request Type!"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } @Override public byte[] closeFile(byte[] inp) throws RemoteException, InvalidProtocolBufferException { ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); ProtoHDFS.FileHandle requestFileHandle = request.getFileHandle(); String fileName = requestFileHandle.getFileName(); ReentrantReadWriteLock lock = this.fileLocks.get(fileName); if(lock.isWriteLockedByCurrentThread()){ ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); writeLock.unlock(); }else{ ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); readLock.unlock(); } ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.SUCCESS); responseBuilder.setErrorMessage("File handle for " + fileName + " successfully closed"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } @Override public byte[] getBlockLocations(byte[] inp) throws RemoteException, InvalidProtocolBufferException { // To assign blocks, we first get the number of blocks that will be needed // For each block we create a "pipeline" of Data Nodes where the blocks are written to and replicated ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); ProtoHDFS.FileHandle requestFileHandle = request.getFileHandle(); String fileName = requestFileHandle.getFileName(); ReentrantReadWriteLock lock = this.fileLocks.get(fileName); ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); readLock.lock(); ProtoHDFS.FileHandle responseFileHandle = this.fileHandles.get(fileName); List<ProtoHDFS.Pipeline> pipelines = responseFileHandle.getPipelinesList(); for(ProtoHDFS.Pipeline p : pipelines){ p.getBlocksList().sort(new RepSorter()); } pipelines.sort(new PipelineSorter()); ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.SUCCESS); responseBuilder.setFileHandle(responseFileHandle); responseBuilder.setErrorMessage("File handle for " + fileName + " successfully obtained"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } @Override public byte[] assignBlock(byte[] inp) throws RemoteException, InvalidProtocolBufferException { // To assign blocks, we first get the number of blocks that will be needed // For each block we create a "pipeline" of Data Nodes where the blocks are written to and replicated ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); // At this stage since the file hasn't been stored in the HDFS yet, the fileHandle really only contains the // filename as well as the file size which will be used to compute number of blocks needed. The pipeline // variable in fileHandle at this point should be empty ProtoHDFS.FileHandle fileHandle = request.getFileHandle(); String fileName = fileHandle.getFileName(); long fileSize = fileHandle.getFileSize(); synchronized (this){ // This part locks the file handle once it has been created if(!this.fileLocks.containsKey(fileName)){ // File has not yet been initialized by another thread so create file handle this.fileLocks.putIfAbsent(fileName, new ReentrantReadWriteLock()); }else{ // Another thread has already initialized the file so return error ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.FAILURE); responseBuilder.setErrorMessage("File " + fileName + " has been created by another thread"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } } ReentrantReadWriteLock lock = this.fileLocks.get(fileName); ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); writeLock.lock(); // Make block size and replication factor to be configurable later int blockSize = 64000000; int repFactor = 3; int numBlocks = (int) (fileSize / blockSize + 1); ProtoHDFS.FileHandle.Builder fileHandleBuilder = ProtoHDFS.FileHandle.newBuilder(); ArrayList<ProtoHDFS.Pipeline> pipelines = new ArrayList<>(); for(int i = 0; i < numBlocks; i++){ ProtoHDFS.Pipeline.Builder pipelineBuilder = ProtoHDFS.Pipeline.newBuilder(); ArrayList<ProtoHDFS.Block> blocks = new ArrayList<>(); // This part picks three random data nodes using the Data Node Ids String[] dataNodes = this.serverRegistry.list(); List<String> dataNodesList = Arrays.asList(dataNodes); Collections.shuffle(dataNodesList); List<String> selectedDataNodes = dataNodesList.subList(0, repFactor); for(int j = 0; j < repFactor; j++){ ProtoHDFS.BlockMeta.Builder blockMetaBuilder = ProtoHDFS.BlockMeta.newBuilder(); blockMetaBuilder.setFileName(fileName); blockMetaBuilder.setBlockNumber(i); blockMetaBuilder.setRepNumber(j); blockMetaBuilder.setDataId(selectedDataNodes.get(j)); ProtoHDFS.BlockMeta blockMeta = blockMetaBuilder.build(); blockMetaBuilder.clear(); ProtoHDFS.Block.Builder blockBuilder = ProtoHDFS.Block.newBuilder(); blockBuilder.setBlockMeta(blockMeta); ProtoHDFS.Block block = blockBuilder.buildPartial(); blockBuilder.clear(); blocks.add(block); } pipelineBuilder.setPipelineNumber(i); pipelineBuilder.addAllBlocks(blocks); ProtoHDFS.Pipeline pipeline = pipelineBuilder.build(); pipelineBuilder.clear(); pipelines.add(pipeline); } fileHandleBuilder.setFileName(fileName); fileHandleBuilder.setFileSize(fileSize); fileHandleBuilder.addAllPipelines(pipelines); ProtoHDFS.FileHandle newFileHandle = fileHandleBuilder.build(); fileHandleBuilder.clear(); ProtoHDFS.Response.Builder responseBuilder = ProtoHDFS.Response.newBuilder(); responseBuilder.setResponseId(requestId); responseBuilder.setResponseType(ProtoHDFS.Response.ResponseType.SUCCESS); responseBuilder.setFileHandle(newFileHandle); responseBuilder.setErrorMessage("File handle for " + fileName + " created successfully"); ProtoHDFS.Response response = responseBuilder.buildPartial(); responseBuilder.clear(); return response.toByteArray(); } @Override public byte[] list(byte[] inp) throws RemoteException, InvalidProtocolBufferException { ProtoHDFS.Request request = ProtoHDFS.Request.parseFrom(inp); String requestId = request.getRequestId(); Enumeration<String> fileKeys = this.fileHandles.keys(); List<String> fileKeysList = Collections.list(fileKeys); List<String> sortedFileKeys = fileKeysList.stream().sorted().collect(Collectors.toList()); ProtoHDFS.ListResponse.Builder listResponseBuilder = ProtoHDFS.ListResponse.newBuilder(); listResponseBuilder.setResponseId(requestId); listResponseBuilder.setResponseType(ProtoHDFS.ListResponse.ResponseType.SUCCESS); listResponseBuilder.setErrorMessage("Files on HDFS successfully retrieved"); listResponseBuilder.addAllFileNames(sortedFileKeys); ProtoHDFS.ListResponse listResponse = listResponseBuilder.build(); listResponseBuilder.clear(); return listResponse.toByteArray(); } @Override public byte[] blockReport(byte[] inp) throws RemoteException { while(true) { try{ ProtoHDFS.Blockreport blockreport = ProtoHDFS.Blockreport.parseFrom(inp); }catch (InvalidProtocolBufferException e) { e.printStackTrace(); //time interval for 5 seconds Thread.sleep(5000); //send heartbeat datastub.blockReport(); } return null; } } @Override public byte[] heartBeat(byte[] inp) throws RemoteException { while(true) { try{ ProtoHDFS.Heartbeat heartbeat = ProtoHDFS.Heartbeat.parseFrom(inp); }catch (InvalidProtocolBufferException e) { e.printStackTrace(); //time interval for 4 seconds Thread.sleep(4000); //send heartbeat datastub.heartbeat(); map_heartbeat.put("Heartbeat Recieved", true); } return null; } } public static void main(String[] args){ } } <file_sep>package ds.hdfs; import com.google.protobuf.InvalidProtocolBufferException; import proto.ProtoHDFS; import java.io.*; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; public class Client { public DataNodeInterface dataStub; public NameNodeInterface nameStub; public Client(){ // Put stuff here later } public DataNodeInterface getDataStub(String dataId, String dataIp, int port){ while(true){ try{ Registry registry = LocateRegistry.getRegistry(dataIp, port); return (DataNodeInterface)registry.lookup(dataId); }catch(Exception ignored){} } } public NameNodeInterface getNameStub(String nameId, String nameIp, int port){ while(true){ try{ Registry registry = LocateRegistry.getRegistry(nameId, port); return (NameNodeInterface)registry.lookup(nameIp); }catch(Exception ignored){} } } // This method stores the file in the HDFS public void putFile(String fileName) { System.out.println("Going to put file " + fileName); File file = new File(fileName); try{ // Make block size configurable later int blockSize = 64000000; int numBlocks = (int) (file.length() / blockSize + 1); ArrayList<byte[]> blocks = new ArrayList<>(); byte[] blockContents = new byte[blockSize]; FileInputStream fileInputStream = new FileInputStream(file); while(fileInputStream.read(blockContents) != -1){ blocks.add(blockContents); } fileInputStream.close(); // Just a sanity check assert blocks.size() == numBlocks : "Something went wrong! Did not properly read file into blocks!"; ProtoHDFS.FileHandle.Builder fileHandleBuilder = ProtoHDFS.FileHandle.newBuilder(); fileHandleBuilder.setFileName(fileName); fileHandleBuilder.setFileSize(file.length()); ProtoHDFS.FileHandle fileHandle = fileHandleBuilder.buildPartial(); ProtoHDFS.Request.Builder requestBuilder = ProtoHDFS.Request.newBuilder(); String requestId = UUID.randomUUID().toString(); requestBuilder.setRequestId(requestId); requestBuilder.setRequestType(ProtoHDFS.Request.RequestType.WRITE); requestBuilder.setFileHandle(fileHandle); ProtoHDFS.Request openRequest = requestBuilder.buildPartial(); requestBuilder.clear(); // Read these variables from the config file later String nameId = "namenode"; String nameIp = "192.168.12.75"; int port = 1099; NameNodeInterface nameStub = getNameStub(nameId, nameIp, port); byte[] openResponseBytes = nameStub.openFile(openRequest.toByteArray()); ProtoHDFS.Response openResponse = ProtoHDFS.Response.parseFrom(openResponseBytes); String responseId = openResponse.getResponseId(); ProtoHDFS.Response.ResponseType openResponseType = openResponse.getResponseType(); if(openResponseType == ProtoHDFS.Response.ResponseType.SUCCESS){ // If write file completed successfully send write requests to the data nodes // using the file handle obtained from the response System.out.println("File " + fileName + " successfully opened"); fileHandle = openResponse.getFileHandle(); List<ProtoHDFS.Pipeline> pipelineList = fileHandle.getPipelinesList(); ArrayList<ProtoHDFS.Pipeline> pipelineArrayList = new ArrayList<>(pipelineList); for(int i = 0; i < numBlocks; i++){ byte[] blockContent = blocks.get(i); ProtoHDFS.Pipeline pipeline = pipelineArrayList.get(i); List<ProtoHDFS.Block> blocksList = pipeline.getBlocksList(); ArrayList<ProtoHDFS.Block> requestBlocks = new ArrayList<>(); for(ProtoHDFS.Block block : blocksList){ ProtoHDFS.Block.Builder blockBuilder = ProtoHDFS.Block.newBuilder(); blockBuilder.setBlockMeta(block.getBlockMeta()); blockBuilder.setBlockContents(Arrays.toString(blockContent)); ProtoHDFS.Block requestBlock = blockBuilder.build(); blockBuilder.clear(); requestBlocks.add(requestBlock); } String writeRequestId = UUID.randomUUID().toString(); requestBuilder.setRequestId(writeRequestId); requestBuilder.setRequestType(ProtoHDFS.Request.RequestType.WRITE); requestBuilder.addAllBlock(requestBlocks); ProtoHDFS.Request writeBlockRequest = requestBuilder.buildPartial(); requestBuilder.clear(); // Configure these variables later String dataId = "data1"; String dataIp = "192.168.12.1"; int dataPort = 1099; DataNodeInterface dataStub = getDataStub(dataId, dataIp, dataPort); byte[] writeResponseBytes = dataStub.writeBlock(writeBlockRequest.toByteArray()); ProtoHDFS.Response writeResponse = ProtoHDFS.Response.parseFrom(writeResponseBytes); String writeResponseId = writeResponse.getResponseId(); ProtoHDFS.Response.ResponseType writeResponseType = writeResponse.getResponseType(); if(writeResponseType == ProtoHDFS.Response.ResponseType.SUCCESS){ System.out.println("File " + fileName + " successfully written"); }else{ System.out.println(writeResponse.getErrorMessage()); } } }else{ // If failed to open and get file handle System.out.println(openResponse.getErrorMessage()); } // Now send a close request to close (or unlock) the other file handle so other threads can use it String closeRequestId = UUID.randomUUID().toString(); requestBuilder.setRequestId(closeRequestId); requestBuilder.setRequestType(ProtoHDFS.Request.RequestType.CLOSE); ProtoHDFS.Request closeRequest = requestBuilder.buildPartial(); requestBuilder.clear(); byte[] closeResponseBytes = nameStub.closeFile(closeRequest.toByteArray()); ProtoHDFS.Response closeResponse = ProtoHDFS.Response.parseFrom(closeResponseBytes); String closeResponseId = closeResponse.getResponseId(); ProtoHDFS.Response.ResponseType closeResponseType = closeResponse.getResponseType(); // !!!!!!!!!!! We need to implement something that allows it to keep sending close requests until // file handle fails to unlock. Otherwise we'll run into deadlock !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if(closeResponseType == ProtoHDFS.Response.ResponseType.SUCCESS){ System.out.println("File handle for " + fileName + " successfully closed"); }else{ System.out.println(closeResponse.getErrorMessage()); } }catch(Exception e){ if(e instanceof RemoteException){ System.out.println("Something went wrong when working with name node stub or data node stub!"); }else if(e instanceof InvalidProtocolBufferException){ System.out.println("Tried to parse object in put() that is not defined in protocol buffer!"); }else if(e instanceof FileNotFoundException){ System.out.println("Trying to put() " + fileName + " does not exist locally!"); }else if(e instanceof IOException){ System.out.println("Something went wrong when performing file io in put()!"); }else{ // Some general unspecified error System.out.println("An unspecified error has occurred in put(): " + e.getMessage()); } e.printStackTrace(); } } public void getFile(String fileName) { System.out.println("Going to get " + fileName); File file = new File(fileName); try{ ProtoHDFS.Request.Builder requestBuilder = ProtoHDFS.Request.newBuilder(); if(file.exists() || file.createNewFile()){ FileOutputStream fileOutputStream = new FileOutputStream(file); ProtoHDFS.FileHandle.Builder fileHandleBuilder = ProtoHDFS.FileHandle.newBuilder(); fileHandleBuilder.setFileName(fileName); fileHandleBuilder.setFileSize(file.length()); ProtoHDFS.FileHandle fileHandle = fileHandleBuilder.buildPartial(); fileHandleBuilder.clear(); String openRequestId = UUID.randomUUID().toString(); requestBuilder.setRequestId(openRequestId); requestBuilder.setRequestType(ProtoHDFS.Request.RequestType.READ); requestBuilder.setFileHandle(fileHandle); ProtoHDFS.Request openRequest = requestBuilder.buildPartial(); requestBuilder.clear(); // Configure these values later String nameId = "namenode"; String nameIp = "192.168.12.75"; int port = 1099; NameNodeInterface nameStub = getNameStub(nameId, nameIp, port); byte[] openResponseBytes = nameStub.openFile(openRequest.toByteArray()); ProtoHDFS.Response openResponse = ProtoHDFS.Response.parseFrom(openResponseBytes); String openResponseId = openResponse.getResponseId(); ProtoHDFS.Response.ResponseType openResponseType = openResponse.getResponseType(); fileHandle = openResponse.getFileHandle(); List<ProtoHDFS.Pipeline> pipelines = fileHandle.getPipelinesList(); ArrayList<List<ProtoHDFS.Block>> blocksList = pipelines.stream() .map(ProtoHDFS.Pipeline::getBlocksList) .collect(Collectors.toCollection(ArrayList::new)); boolean hasMissingBlock = blocksList.parallelStream().anyMatch(List::isEmpty); if(hasMissingBlock){ // If the list of block replicas is empty for any of the blocks, immediately throw an error // Maybe toss out the file as well since it's corrupted? }else{ ArrayList<ProtoHDFS.Block> readBlocks = blocksList.stream() .map(p -> p.get(0)) .collect(Collectors.toCollection(ArrayList::new)); // Writes the contents from a copy of each block into the fileOutputStream for (ProtoHDFS.Block b : readBlocks) { byte[] bytes = b.getBlockContents().getBytes(); fileOutputStream.write(bytes); } } // Now send a close request to close (or unlock) the other file handle so other threads can use it String closeRequestId = UUID.randomUUID().toString(); requestBuilder.setRequestId(closeRequestId); requestBuilder.setRequestType(ProtoHDFS.Request.RequestType.CLOSE); ProtoHDFS.Request closeRequest = requestBuilder.buildPartial(); requestBuilder.clear(); byte[] closeResponseBytes = nameStub.closeFile(closeRequest.toByteArray()); ProtoHDFS.Response closeResponse = ProtoHDFS.Response.parseFrom(closeResponseBytes); String closeResponseId = closeResponse.getResponseId(); ProtoHDFS.Response.ResponseType closeResponseType = closeResponse.getResponseType(); // !!!!!!!!!!! We need to implement something that allows it to keep sending close requests until // file handle fails to unlock. Otherwise we'll run into deadlock !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if(closeResponseType == ProtoHDFS.Response.ResponseType.SUCCESS){ System.out.println("File handle for " + fileName + " successfully closed"); }else{ System.out.println(closeResponse.getErrorMessage()); } }else{ System.out.println("Failed to create " + fileName + " to read to"); } }catch(Exception e){ System.out.println("File " + fileName + " not found!"); } } public void list() { try{ ProtoHDFS.Request.Builder listRequestBuilder = ProtoHDFS.Request.newBuilder(); String listRequestId = UUID.randomUUID().toString(); listRequestBuilder.setRequestId(listRequestId); listRequestBuilder.setRequestType(ProtoHDFS.Request.RequestType.LIST); ProtoHDFS.Request listRequest = listRequestBuilder.buildPartial(); listRequestBuilder.clear(); // Read these variables from the config file later String nameId = "namenode"; String nameIp = "192.168.12.75"; int port = 1099; NameNodeInterface nameStub = getNameStub(nameId, nameIp, port); byte[] listResponseBytes = nameStub.list(listRequest.toByteArray()); ProtoHDFS.ListResponse listResponse = ProtoHDFS.ListResponse.parseFrom(listResponseBytes); String listResponseId = listResponse.getResponseId(); ProtoHDFS.ListResponse.ResponseType listResponseType = listResponse.getResponseType(); if(listResponseType == ProtoHDFS.ListResponse.ResponseType.SUCCESS){ // Gets the list of files and prints it out line by line List<String> filesList = listResponse.getFileNamesList(); //noinspection SimplifyStreamApiCallChains filesList.stream().forEach(System.out :: println); }else{ System.out.println(listResponse.getErrorMessage()); } }catch(Exception e){ if(e instanceof RemoteException){ System.out.println("Something went wrong in list() when communicating with the name node!"); }else if(e instanceof InvalidProtocolBufferException){ System.out.println("Tried to parse something in list() that is not defined in the protocol buffer!"); }else{ // general unspecified error System.out.println("An unspecified error has occurred in list(): " + e.getMessage()); } e.printStackTrace(); } } public static void main(String[] args){ } }
b62986c8c8c085eda701ebcd9c477d3cdc375468
[ "Java" ]
4
Java
KevinWu97/MapReduce
a0559e496f176bcfc40bda5c285e3db72ea08797
e852ac8ca8ee4d724e3c86a8b95736946ee28ce6
refs/heads/master
<repo_name>cyanpencil/LD30<file_sep>/LD30/public_html/Engine.js //Questo engine viene chiamato dentro Main, con setTimeout(engine_main_loop, 0), creando un altro thread var t = Date.now(); var t_tick = 20; var variazione = 0.05; var t_sleep, lastFrameTime = 0, framesTime = 0, startFrame = 0; function engine_main_loop() { //fps lastFrameTime = Date.now() - startFrame; framesTime = (framesTime *(1 - variazione) + lastFrameTime*variazione); startFrame = Date.now(); //motore tick(); //loop t += t_tick; t_sleep = t - Date.now(); if (t_sleep > 0) {setTimeout(engine_main_loop, t_sleep);} else {engine_main_loop();} } //Funzione chiamata da engine_main_loop. Chiamata 1/t_tick volte al secondo. function tick() { //fai attenzione a questa linea setTimeout(aggiornaPosizioni, 0); //potrebbe rallentare molto. Attenzione. Non fare stupidaggini } function aggiornaPosizioni() { obj.rotation.x += .1; for (var i = 0; i < robe.length; i++) {robe[i].rotation.y += .01;} for (var i = 0; i < meshes.length; i++) {meshes[i].rotation.y += .01;} for (var i = 0; i < personaggi.length; i++) {personaggi[i].update();} // protagonista.avanzaUno(); } function possoFareTurno() { if (Date.now() - whenTurnoStarted < turnoDuration) return false; else return true; } var whenTurnoStarted; var turnoDuration = 300; function turno() { //boh fai qualcosa whenTurnoStarted = Date.now(); } for (var i = 0; i < meshes.length; i++) {meshes[i].rotation.y += .01;} for (var i = 0; i < personaggi.length; i++) {personaggi[i].update();} // protagonista.avanzaUno(); } function possoFareTurno() { if (Date.now() - whenTurnoStarted < turnoDuration) return false; else return true; } var whenTurnoStarted; var turnoDuration = 300; function turno() { //boh fai qualcosa whenTurnoStarted = Date.now(); } <file_sep>/README.md LD30 ==== <NAME> 30, by the brogrammers <file_sep>/LD30/public_html/Controlli.js document.addEventListener('keydown', function(event) { if (!possoFareTurno()) return; if(event.keyCode == 37|| event.keyCode == 65) { // left_arrow_pressed = true; protagonista.girati(2); protagonista.avanzaUno(); } else if(event.keyCode == 39|| event.keyCode == 68) { // right_arrow_pressed = true; protagonista.girati(1); protagonista.avanzaUno(); } if (event.keyCode == 38 || event.keyCode == 87) { // up_arrow_pressed = true; protagonista.girati(3); protagonista.avanzaUno(); } else if(event.keyCode == 40|| event.keyCode == 83) { // down_arrow_pressed = true; protagonista.girati(0); protagonista.avanzaUno(); } else if (event.keyCode == 32) { protagonista.attacca(); } turno(); });<file_sep>/LD30/public_html/Main.js // ---- Loaders e Rendering -----// var scene, camera, renderer; var projector; var tga_loader, json_loader; // ---------- Mappa -------------// var map1 = new Array(1, 0, 0, 1, 1, 1, 0, 0, 1); var map1_lenght = Math.sqrt(map1.length); var map1_block_lenght = 5; var map1_position_x = 0, map1_position_y = 0, map1_position_z = 20; // -------- Modelli -------------// var meshes = []; var personaggi = []; var weapons = []; var protagonista; var cubetto1, obj; $(function () { initialize(); loadModels(); setTimeout(engine_main_loop, 0); }); function initialize() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.x = 0; camera.position.y = 60; camera.position.z = 400; camera.lookAt(scene.position); renderer = new THREE.WebGLRenderer({antialias : true}); renderer.setClearColor( 0x000000, 0); renderer.setSize(window.innerWidth - 30, window.innerHeight - 60); //renderer.setClearColor( scene.fog.color, 1 ); renderer.gammaInput = true; renderer.gammeOutput = true; renderer.physicallyBasedShading = true; // renderer.autoClear = false; //roba strana, meglio non toccare projector = new THREE.Projector(); // initialize object to perform world/screen calculations projector = new THREE.Projector(); // initialize object to perform world/screen calculations document.addEventListener( 'mousedown', onDocumentMouseDown, false ); // when the mouse moves, call the given function $("#WebGL-output").append(renderer.domElement); // makeGUI(); //------------------- SSAO, o qualcosa del genere :D --------------------// var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; composer = new THREE.EffectComposer( renderer ); composer.addPass( new THREE.RenderPass( scene, camera ) ); depthTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); var effect = new THREE.ShaderPass( THREE.SSAOShader ); effect.uniforms[ 'tDepth' ].value = depthTarget; effect.uniforms[ 'size' ].value.set( window.innerWidth, window.innerHeight ); effect.uniforms[ 'cameraNear' ].value = camera.near; effect.uniforms[ 'cameraFar' ].value = camera.far; effect.renderToScreen = true; composer.addPass( effect ); //------------------------------------------------------------------------// var update = function() { requestAnimationFrame(update); //in pratica passo come argomento tutta la funzione update(), dicendogli che deve animarla all'infinito //Inserire qui tutte le funzioni di animazione (esempio i pesci che ondeggiano) //E tutte le cose che si devono ridisegnare in un certo modo ogni frame scene.overrideMaterial = depthMaterial; renderer.render( scene, camera, depthTarget ); scene.overrideMaterial = null; composer.render(); }; update(); } function loadModels() { var planeGeometry = new THREE.PlaneGeometry(120,80); var planeMaterial = new THREE.MeshBasicMaterial({ color: 0x844d5e }); var plane = new THREE.Mesh(planeGeometry,planeMaterial); plane.position.set(0,0,-20); scene.add(plane); tga_loader = new THREE.TGALoader(); json_loader = new THREE.JSONLoader(); var textureProva = tga_loader.load("palette_default.tga"); Fprotagonista = function(geometry) {protagonista = creaPersonaggio(geometry, 0, 2, 15, 1, textureProva)}; json_loader.load("chr_fox.js", Fprotagonista); FFuretto = function(geometry) {createScene(geometry, 20, -10, 0, 2, textureProva)}; json_loader.load("furetto.js", FFuretto); FBusterSmall = function(geometry) {creaWeapon(geometry, 0, 0, 0, 1, textureProva)}; json_loader.load("buster_sword_small.js", FBusterSmall); FBusterBig = function(geometry) {creaWeapon(geometry, 0, 0, 0, 1, textureProva)}; json_loader.load("buster_sword_big.js", FBusterBig); // setTimeout(function() {protagonista.addWeapon(weapons[1]);}, 300); var pointLight = new THREE.PointLight(0xFFFFFF); pointLight.position.set(0, 0, 30); scene.add(pointLight); var OBJMTLLoader = new THREE.OBJMTLLoader(); OBJMTLLoader.load('castle.obj', 'castle.mtl', function (object) { obj = object; obj.position.set(-10, -10, 0); scene.add(obj); }); //--------GENERAZIONE DELLA MAPPA-------- var boxTerrainGeometry = new THREE.BoxGeometry(5, 5, 5); var boxTerrainMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); for (var i=0; i < map1_lenght; i++){ for(var j=0; j < map1_lenght; j++){ if (map1[i * map1_lenght + j] === 1){ var boxTerrain = new THREE.Mesh(boxTerrainGeometry,boxTerrainMaterial); boxTerrain.position.set(map1_position_x + j * map1_block_lenght, map1_position_y, map1_position_z + i * map1_block_lenght); scene.add(boxTerrain); } } } //--------------------------------------- } function createScene(geometry, x, y, z, scale, tmap) { tizia = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map: tmap})); tizia.position.set(x, y, z); tizia.scale.set(scale, scale, scale); tizia.rotation.y = 1; scene.add(tizia); robe.push(tizia); } function loadModels() { var planeGeometry = new THREE.PlaneGeometry(120,80); var planeMaterial = new THREE.MeshBasicMaterial({ color: 0x844d5e }); var plane = new THREE.Mesh(planeGeometry,planeMaterial); plane.position.set(0,0,-20); scene.add(plane); //--------------------TESTO var theText = "ciao!"; var text3d = new THREE.TextGeometry( theText, { size: 2, height: 0.1, curveSegments: 3, font: "helvetiker" }); var textMaterial = new THREE.MeshBasicMaterial( { color: Math.random() * 0x000000, overdraw: 0.5 } ); text = new THREE.Mesh( text3d, textMaterial ); text.position.z = 40; scene.add(text); //-----FINE TESTO tga_loader = new THREE.TGALoader(); json_loader = new THREE.JSONLoader(); var textureProva = tga_loader.load("palette_default.tga"); callbackKey = function(geometry) {createScene(geometry, 0, 0, 0, 2, textureProva)}; json_loader.load("chr_fox.js", callbackKey); callbackKey2 = function(geometry) {createScene(geometry, 20, -10, 0, 2, textureProva)}; json_loader.load("furetto.js", callbackKey2); var pointLight = new THREE.PointLight(0xFFFFFF); pointLight.position.set(0, 0, 30); scene.add(pointLight); var OBJMTLLoader = new THREE.OBJMTLLoader(); OBJMTLLoader.load('castle.obj', 'castle.mtl', function (object) { obj = object; obj.position.set(-10, -10, 0); scene.add(obj); }); //--------GENERAZIONE DELLA MAPPA-------- var boxTerrainGeometry = new THREE.BoxGeometry(5, 5, 5); var boxTerrainMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); map1[0] = new Array(); map1[1] = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); map1[2] = new Array(0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); map1[3] = new Array(0,0,0,0,0,0,0,1,2,2,2,2,1,1,1,1,1,1,1,2,3,2,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0); map1[4] = new Array(0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0); map1[5] = new Array(0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0); map1[6] = new Array(0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0); map1[7] = new Array(0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0); map1[8] = new Array(0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0); map1[9] = new Array(0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,1,0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0); map1[10] = new Array(0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); map1[11] = new Array(0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0); map1[12] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0); map1[13] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0); map1[14] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0); map1[15] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0); map1[16] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,0); map1[17] = new Array(0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0); map1[18] = new Array(0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0); map1[19] = new Array(0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0); map1[20] = new Array(0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0); map1[21] = new Array(0,0,0,1,0,1,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0); map1[22] = new Array(0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0); map1[23] = new Array(0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0); map1[24] = new Array(0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0); map1[25] = new Array(0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,0,0); map1[26] = new Array(0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0); map1[27] = new Array(0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,0,0,1,0,0,0,0); map1[28] = new Array(0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,1,0,0,0,0); map1[29] = new Array(0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0); map1[30] = new Array(0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0); map1[31] = new Array(0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,0,0); map1[32] = new Array(0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0); map1[33] = new Array(0,4,4,5,4,3,2,0,0,0,0,0,1,2,2,2,2,2,1,0,0,0,0,0,0,1,0,0,1,2,2,1,1,0,0,0,0,0,0,0); map1[34] = new Array(0,0,4,4,4,3,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0); map1[35] = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0); map1[36] = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0); map1[37] = new Array(); map1[38] = new Array(); map1[39] = new Array(); for (var i=0; i < map1_lenght; i++){ for(var j=0; j < map1[i].length; j++){ if (map1[i][j] !=0){ for (var k=0; k<map1[i][j]; k++){ var boxTerrain = new THREE.Mesh(boxTerrainGeometry,boxTerrainMaterial); boxTerrain.position.set(map1_position_x + j * map1_block_lenght, map1_position_y-k*map1_block_lenght, map1_position_z + i * map1_block_lenght); scene.add(boxTerrain); } } } } //--------------------------------------- tizia = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map: tmap})); tizia.position.set(x, y, z); tizia.scale.set(scale, scale, scale); tizia.rotation.y = 1; scene.add(tizia); meshes.push(tizia); return tizia; } function creaPersonaggio(geometry, x, y, z, scale, tmap) { //Si ricorda che il personaggio e' un Object3D che contiene la mesh var temp = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map: tmap})); var tamp = new Personaggio(temp,x,y,z); // tamp.position.set(x,50,z); tamp.scale.set(scale,scale,scale); personaggi.push(tamp); scene.add(tamp); return tamp; } function creaWeapon(geometry, x, y, z, scale, tmap) { var temp = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map:tmap})); temp.position.set(x,y,z); temp.scale.set(scale,scale,scale); weapons.push(temp); return temp; } function onDocumentMouseDown( event ) { } <file_sep>/LD30/public_html/personaggio.js //ATTENZIONE: //DIREZIONI: // 0 - SUD // 1 - EST // 2 - OVEST // 3 - NORD Personaggio.prototype = new THREE.Object3D(); Personaggio.prototype.constructor = Personaggio; var AZIONE_ATTACCA = 0; var AZIONE_MUOVI = 1; function Personaggio(mesh, x, y, z) { THREE.Object3D.call(this); this.mesh = mesh; this.add(mesh); this.direzione = 0; this.step_length = 5; this.durataAttacco = 0.3; this.position.x = x; this.position.y = y; this.position.z = z; this.target_x = this.position.x; this.target_y = this.position.y; this.target_z = this.position.z; this.old_x = this.position.x; this.old_y = this.position.x; this.old_z = this.position.x; this.hasWeapon = false; this.weapon = null; this.weapon_x = -6; this.weapon_y = 4; this.weapon_z = 0; this.prossimaAzione = 0; } Personaggio.prototype.update = function() { if (this.prossimaAzione == AZIONE_MUOVI) { var ratio = (Date.now() - whenTurnoStarted) / turnoDuration; if (ratio < 1) { this.position.x = this.old_x + (this.target_x - this.old_x) * ratio; this.position.y = this.old_y + (this.target_y - this.old_y) * ratio; this.position.z = this.old_z + (this.target_z - this.old_z) * ratio; } else { this.position.set(this.target_x, this.target_y, this.target_z); } } else if (this.prossimaAzione == AZIONE_ATTACCA) { var ratio = (Date.now() - whenTurnoStarted) / turnoDuration; if (this.hasWeapon) { if (ratio < this.durataAttacco) this.weapon.rotation.x += .3; else if (ratio > 1 - this.durataAttacco && ratio < 1) this.weapon.rotation.x -= .3; else if (ratio > 1) this.weapon.rotation.x = 0; } else { if (ratio < this.durataAttacco) this.mesh.position.z += .3; else if (ratio > 1 - this.durataAttacco && ratio < 1) this.mesh.position.z -= .3; else if (ratio > 1) this.mesh.position.z = 0; } } } Personaggio.prototype.girati = function(direzione) { switch(direzione) { case 0: this.rotation.y = 0; break; case 1: this.rotation.y = Math.PI/2; break; case 2: this.rotation.y = Math.PI * 3 / 2; break; case 3: this.rotation.y = Math.PI; break; } this.direzione = direzione; } Personaggio.prototype.avanzaUno = function () { this.old_x = this.position.x; this.old_y = this.position.y; this.old_z = this.position.z; switch(this.direzione) { case 0: this.target_z += this.step_length; break; case 1: this.target_x += this.step_length; break; case 2: this.target_x -= this.step_length; break; case 3: this.target_z -= this.step_length; break; } this.prossimaAzione = AZIONE_MUOVI; } Personaggio.prototype.attacca = function() { this.prossimaAzione = AZIONE_ATTACCA; } Personaggio.prototype.addWeapon = function (weapon) { this.hasWeapon = true; this.weapon = weapon; this.weapon.position.set(this.weapon_x, this.weapon_y, this.weapon_z); this.add(weapon); }<file_sep>/LD30/nbproject/project.properties auxiliary.org-netbeans-modules-web-clientproject-api.js_2e_libs_2e_folder=js/libs config.folder=${file.reference.LD30-config} file.reference.LD30-config=config file.reference.LD30-public_html=public_html file.reference.LD30-test=test files.encoding=UTF-8 site.root.folder=${file.reference.LD30-public_html} test.folder=${file.reference.LD30-test} <file_sep>/LD30/public_html/Main2.js var scene, camera, spotLight; var targetList = []; var projector, mouse = { x: 0, y: 0 }; var cubetto1, cubetto2, cubetto3; var icosaedro, icosaedro2; var tutorial; //var wave, wave2, wave3; var bottone1, bottone2, bottone3, bottone4, bottone5; var wave1, wave2, wave3, wave4, wave5, wave6, wave7; var cubetto_boost1, cubetto_boost2, cubetto_boost3; var cubetto_boost1_filler, cubetto_boost2_filler, cubetto_boost3_filler; $(function () { scene = new THREE.Scene(); var cameradelay = 40; camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.x = 0; camera.position.y = 0; camera.position.z = 80; camera.lookAt(scene.position); var renderer = new THREE.WebGLRenderer({antialias : false}); renderer.setClearColor( 0x000000, 0); renderer.setSize(window.innerWidth - 30, window.innerHeight - 60); //piano di prova var planeGeometry = new THREE.PlaneGeometry(200,120); var planeMaterial = new THREE.MeshPhongMaterial({ color: 0x044d5e }); var plane = new THREE.Mesh(planeGeometry,planeMaterial); plane.castShadow = false; plane.receiveShadow = false; //plane.rotation.x=-0.5*Math.PI; plane.position.x=-5; plane.position.y=40; plane.position.z=-15; scene.add(plane); var tutorialGeometry = new THREE.PlaneGeometry(110, 55); var tutorialTextureMap = THREE.ImageUtils.loadTexture("drawables/tutorial_1.png") var tutorialMaterial = new THREE.MeshPhongMaterial({ map: tutorialTextureMap, transparent: true, emissive: 0xffffff }); tutorial = new THREE.Mesh(tutorialGeometry, tutorialMaterial); tutorial.position.z = 15; tutorial.position.x = 0; tutorial.position.y = 9; scene.add(tutorial); //titolo var titleMap = THREE.ImageUtils.loadTexture("drawables/title.png"); var titleGeometry = new THREE.PlaneGeometry(100, 75); var titleMaterial = new THREE.MeshPhongMaterial({ emissive: 0x305b70, map: titleMap, transparent: true }); var title = new THREE.Mesh(titleGeometry,titleMaterial); title.position.z = -13; scene.add(title); /////////////////////HERE COMES THE SUNSHINE ///////////////////ONDE SPLINE var numPoints = 100; spline = new THREE.SplineCurve3([ new THREE.Vector3(0, -5, 0), new THREE.Vector3(15, 3, 0), new THREE.Vector3(30, -3, 0), new THREE.Vector3(45, 3, 0), new THREE.Vector3(60, -3, 0), new THREE.Vector3(75, 3, 0), new THREE.Vector3(90, -3, 0), new THREE.Vector3(105, 3, 0), new THREE.Vector3(120, -3, 0), ]); var material = new THREE.LineBasicMaterial({ color: 0xffffff, }); var geometry = new THREE.Geometry(); var splinePoints = spline.getPoints(numPoints); for(var i = 0; i < splinePoints.length; i++){ geometry.vertices.push(splinePoints[i]); } wave1 = new THREE.Line(geometry, material); wave1.position.x = camera.position.x - 60; wave1.position.z = 18; scene.add(wave1); wave2 = new THREE.Line(geometry, material); wave2.position.x = camera.position.x - 58; wave2.position.z = 18; scene.add(wave2); wave3 = new THREE.Line(geometry, material); wave3.position.x = camera.position.x - 56; wave3.position.z = 18; scene.add(wave3); wave4 = new THREE.Line(geometry, material); wave4.position.x = camera.position.x - 56; wave4.position.z = 18; scene.add(wave4); wave5 = new THREE.Line(geometry, material); wave5.position.x = camera.position.x - 56; wave5.position.z = 18; scene.add(wave5); wave6 = new THREE.Line(geometry, material); wave6.position.x = camera.position.x - 56; wave6.position.z = 18; scene.add(wave6); wave7 = new THREE.Line(geometry, material); wave7.position.x = camera.position.x - 56; wave7.position.z = 18; scene.add(wave7); ///////////////////////////////////////////////// EWW RAYCASTING PROVA ///////////////////////////////////////////////// PROFESSIONAL RAYCASTING var unAltroMaterial = new THREE.MeshBasicMaterial({color: 0xffffff, vertexColors: THREE.FaceColors}); var unAltroMaterial2 = new THREE.MeshBasicMaterial( { color: 0xaaaaaa, vertexColors: THREE.FaceColors, wireframe: true} ); var faceColorMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var cubettoGeometry = new THREE.BoxGeometry(10, 10, 10); var cubetto1Material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var cubetto2Material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var cubetto3Material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var cubetto4Material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var cubetto5Material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, wireframe: true} ); var bottoneGeometry = new THREE.PlaneGeometry(10, 10); var bottone1TextureMap = THREE.ImageUtils.loadTexture("drawables/bottonespeed.png"); var bottone2TextureMap = THREE.ImageUtils.loadTexture("drawables/bottonesteer.png"); var bottone3TextureMap = THREE.ImageUtils.loadTexture("drawables/bottonelight.png"); var bottone4TextureMap = THREE.ImageUtils.loadTexture("drawables/bottoneboost.png"); var bottone5TextureMap = THREE.ImageUtils.loadTexture("drawables/bottonesize.png"); var bottone1Material = new THREE.MeshPhongMaterial({ map: bottone1TextureMap, transparent: true, emissive: 0xffffff }); var bottone2Material = new THREE.MeshPhongMaterial({ map: bottone2TextureMap, transparent: true, emissive: 0xffffff }); var bottone3Material = new THREE.MeshPhongMaterial({ map: bottone3TextureMap, transparent: true, emissive: 0xffffff }); var bottone4Material = new THREE.MeshPhongMaterial({ map: bottone4TextureMap, transparent: true, emissive: 0xffffff }); var bottone5Material = new THREE.MeshPhongMaterial({ map: bottone5TextureMap, transparent: true, emissive: 0xffffff }); bottone1 = new THREE.Mesh(bottoneGeometry, bottone1Material); bottone2 = new THREE.Mesh(bottoneGeometry, bottone2Material); bottone3 = new THREE.Mesh(bottoneGeometry, bottone3Material); bottone4 = new THREE.Mesh(bottoneGeometry, bottone4Material); bottone5 = new THREE.Mesh(bottoneGeometry, bottone5Material); bottone1.position.y = 40; bottone2.position.y = 40; bottone3.position.y = 40; bottone4.position.y = 40; bottone5.position.y = 40; scene.add(bottone1); scene.add(bottone2); scene.add(bottone3); scene.add(bottone4); scene.add(bottone5); cubetto1 = new THREE.Mesh(cubettoGeometry, cubetto1Material); cubetto2 = new THREE.Mesh(cubettoGeometry, cubetto2Material); cubetto3 = new THREE.Mesh(cubettoGeometry, cubetto3Material); cubetto4 = new THREE.Mesh(cubettoGeometry, cubetto4Material); cubetto5 = new THREE.Mesh(cubettoGeometry, cubetto5Material); cubetto1.position.y = 40; cubetto2.position.y = 40; cubetto3.position.y = 40; cubetto4.position.y = 40; cubetto5.position.y = 40; scene.add(cubetto1); scene.add(cubetto2); scene.add(cubetto3); scene.add(cubetto4); scene.add(cubetto5); targetList.push(cubetto1); targetList.push(cubetto2); targetList.push(cubetto3); targetList.push(cubetto4); targetList.push(cubetto5); //cubetti del boost!!! cubetto_boost1 = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial2); cubetto_boost2 = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial2); cubetto_boost3 = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial2); cubetto_boost1_filler = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial); cubetto_boost2_filler = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial); cubetto_boost3_filler = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), unAltroMaterial); cubetto_boost1.position.z = 60; cubetto_boost2.position.z = 60; cubetto_boost3.position.z = 60; cubetto_boost1_filler.position.z = 60; cubetto_boost2_filler.position.z = 60; cubetto_boost3_filler.position.z = 60; cubetto_boost1_filler.scale.set(1, 0.01, 1); cubetto_boost2_filler.scale.set(1, 0.01, 1); cubetto_boost3_filler.scale.set(1, 0.01, 1); scene.add(cubetto_boost1); scene.add(cubetto_boost2); scene.add(cubetto_boost3); cubetto_boost2.visible = false; cubetto_boost3.visible = false; scene.add(cubetto_boost1_filler); scene.add(cubetto_boost2_filler); scene.add(cubetto_boost3_filler); // initialize object to perform world/screen calculations projector = new THREE.Projector(); // when the mouse moves, call the given function document.addEventListener( 'mousedown', onDocumentMouseDown, false ); var icosaedroGeometry = new THREE.IcosahedronGeometry(2); icosaedro = new THREE.Mesh(icosaedroGeometry, faceColorMaterial); scene.add(icosaedro); icosaedro.rotation.z = 2; icosaedro2 = icosaedro.clone(); scene.add(icosaedro2); $("#WebGL-output").append(renderer.domElement); loadSprites(); inizializzaModelli(); setTimeout(engine_main_loop, 0); makeGUI(); var update = function() { //in pratica passo come argomento tutta la funzione update(), dicendogli che deve animarla all'infinito requestAnimationFrame(update); //Inserire qui tutte le funzioni di animazione (esempio i pesci che ondeggiano) for (var i = 0; i < array_pesci.length; i++) { array_pesci[i].ondeggia(); rotateAroundWorldAxis(array_pesci[i].mesh, new THREE.Vector3(0,0,1), array_pesci[i].angolo_dove_dovrebbe_guardare - array_pesci[i].angolo_direzione); array_pesci[i].angolo_direzione = array_pesci[i].angolo_dove_dovrebbe_guardare; } updateGUI(); updateLuce(); updateBoost(); plane.position.x = camera.position.x; plane.position.y = camera.position.y; icosaedro.position.set(camera.position.x+18, camera.position.y-8, camera.position.z-30); icosaedro2.rotation.x += 1/64; icosaedro2.position.set(camera.position.x+18, camera.position.y-4, camera.position.z-30); icosaedro.rotation.x += 1/64; testo_profondita.mesh.position.set(camera.position.x+18, camera.position.y-8.3, camera.position.z-30); testo_monete.mesh.position.set(camera.position.x+18, camera.position.y-4.3, camera.position.z-30); testo_prezzo1.mesh.position.set(camera.position.x - 30, 30, 0); testo_prezzo2.mesh.position.set(camera.position.x - 15, 30, 0); testo_prezzo3.mesh.position.set(camera.position.x, 30, 0); testo_prezzo4.mesh.position.set(camera.position.x + 15, 30, 0); testo_prezzo5.mesh.position.set(camera.position.x + 30, 30, 0); renderer.render(scene, camera); }; update(); }); function onDocumentMouseDown( event ) { // the following line would stop any other event handler from firing // (such as the mouse's TrackballControls) // event.preventDefault(); tutorial.visible = false; //console.log("Click."); scene.remove(tutorial); // update the mouse variable mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; // find intersections // create a Ray with origin at the mouse position // and direction into the scene (camera direction) var vector = new THREE.Vector3( mouse.x, mouse.y, 1 ); projector.unprojectVector( vector, camera ); var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); // create an array containing all objects in the scene with which the ray intersects var intersects = ray.intersectObjects( targetList ); // if there is one (or more) intersections //if ( intersects.length > 0 ) //{ //console.log("Hit @ " + toString( intersects[0].point ) ); // change the color of the closest face. //intersects[ 0 ].face.color.setRGB( 0.8 * Math.random() + 0.2, 0, 0 ); if (intersects[0].object==cubetto1) { cubetto1.material.color.setRGB(1-(num_upgrade_velocita+1)*0.2, 1, 1 ); console.log("yeah1"); upgrade_velocita(); } if (intersects[0].object==cubetto2) { cubetto2.material.color.setRGB(1-(num_upgrade_manovrabilita+1)*0.2, 1, 1); console.log("yeah2"); upgrade_manovrabilita(); } if (intersects[0].object==cubetto3) { cubetto3.material.color.setRGB(1-(num_upgrade_luce+1)*0.2, 1, 1); console.log("yeah3"); upgrade_luce(); } if (intersects[0].object==cubetto4) { cubetto4.material.color.setRGB(1-(num_upgrade_boost+1)*0.3, 1, 1 ); console.log("yeah4"); upgrade_boost(); } if (intersects[0].object==cubetto5) { cubetto5.material.color.setRGB(1-(num_upgrade_size+1)*0.2, 1, 1 ); console.log("yeah5"); upgrade_size(); } intersects[ 0 ].object.geometry.colorsNeedUpdate = true; //} }
3d67ca50131a808e98c0d93a17c0ee223b3b4dc9
[ "JavaScript", "Markdown", "INI" ]
7
JavaScript
cyanpencil/LD30
4f4182cb4930a58adcca891bacc141e58a3eab5d
1d76187a761722bc6d4b3b00bd5d5d0f9f0b733e
refs/heads/master
<repo_name>vi109/Destinations<file_sep>/resources/js/main.js // Auto slide one var slideIndex = 0; carousel(); function carousel() { var i; var x = document.getElementsByClassName("slide"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slideIndex++; if (slideIndex > x.length) {slideIndex = 1} x[slideIndex-1].style.display = "block"; setTimeout(carousel, 5000); // Change image every 2 seconds } // Auto slide two - fade in via W3 link html var slideIndexB = 0; carouselB(); function carouselB() { var i; var x = document.getElementsByClassName("slide-two"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slideIndexB++; if (slideIndexB > x.length) {slideIndexB = 1} x[slideIndexB-1].style.display = "block"; setTimeout(carouselB, 5000); // Change image every 2 seconds } // Auto slide Three var slideIndexC = 0; carouselC(); function carouselC() { var i; var x = document.getElementsByClassName("slide-three"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slideIndexC++; if (slideIndexC > x.length) {slideIndexC = 1} x[slideIndexC-1].style.display = "block"; setTimeout(carouselC, 5000); // Change image every 2 seconds } // Mobile Navigation function myFunction() { var x = document.getElementById("Demo"); if (x.className.indexOf("w3-show") == -1) { x.className += " w3-show"; } else { x.className = x.className.replace(" w3-show", ""); } } /* MANUAL SLIDE var slideIndex = 1; showDivs(slideIndex); function plusDivs(n) { showDivs(slideIndex += n); } function showDivs(n) { var i; var x = document.getElementsByClassName("slide"); if (n > x.length) {slideIndex = 1} if (n < 1) {slideIndex = x.length} for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[slideIndex-1].style.display = "block"; } */
c58c0145d190497eac6df448ff97cdbe127be9ba
[ "JavaScript" ]
1
JavaScript
vi109/Destinations
3bc93e410f416b90fac822c8068c89cee3198f2c
a4114a882087de1cb36e42023c430af9172ed37e
refs/heads/master
<repo_name>kevin90045/Gravel<file_sep>/Assets/Scripts/DropRock.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using Dummiesman; using System.IO; using System; using System.Xml; public class DropRock : MonoBehaviour { public Transform Stone; public int GravelCount = 0; public int SceneCount = 0; public bool Finish = false; public int NumOfGravel = 100; public int NumOfScene = 1; public float CheckTimeInterval = 5; //unit: second public float DropTimeInterval = 0.1f; // unit: second public int StopGravelsNum = 0; public float TimeOutThreshold = 60; // unit: second public float Xmax = 3; public float Xmin = -3; public float Zmax = 3; public float Zmin = -3; public float Y = 3; public string FilePath; private string[] FileNames; private System.Random rnd; private bool FinishDisplayed = false; private List<Vector3> Positions, Rotations; private List<string> PickFileNames; private float TimeAccumulated = 0; // Awake call when object is create void Awake() { Debug.Log("Awake"); rnd = new System.Random(Guid.NewGuid().GetHashCode()); FileNames = Directory.GetFiles(@FilePath); Debug.Log("Totally " + FileNames.Length + " gravels"); Positions = new List<Vector3>(); Rotations = new List<Vector3>(); PickFileNames = new List<string>(); } // Start is called before the first frame update void Start() { Debug.Log("Start Scene " + SceneCount.ToString()); } // Update is called once per frame void Update() { if (!Finish) { if (GravelCount < NumOfGravel) { if (TimeAccumulated > DropTimeInterval) { string fileName = FileNames[rnd.Next() % FileNames.Length]; GameObject loadedObject = new OBJLoader().Load(fileName).transform.GetChild(0).gameObject; PickFileNames.Add(fileName); // add Rigidbody Rigidbody rb = loadedObject.AddComponent<Rigidbody>(); rb.useGravity = true; rb.isKinematic = false; // add MeshCollider MeshCollider mc = loadedObject.AddComponent<MeshCollider>(); mc.convex = true; // set parent loadedObject.transform.parent.parent = Stone; // set position float X = Convert.ToSingle(rnd.NextDouble() * Math.Abs(Xmax - Xmin) + Xmin); float Z = Convert.ToSingle(rnd.NextDouble() * Math.Abs(Zmax - Zmin) + Zmin); loadedObject.transform.position = new Vector3(X, Y, Z); // add position and rotation Positions.Add(Vector3.zero); Rotations.Add(Vector3.zero); GravelCount++; TimeAccumulated = 0; } } else if (TimeAccumulated > CheckTimeInterval) { if (TimeAccumulated > TimeOutThreshold) { Debug.Log("Time out! Just output results directly..."); Finish = true; } else { Debug.Log("Checking..."); Finish = true; for (int i = Positions.Count - 1; i >= 0; i--) { if (CompareVector(Positions[i], Stone.GetChild(i).GetChild(0).position) && CompareVector(Rotations[i], Stone.GetChild(i).GetChild(0).eulerAngles)) { Positions.RemoveAt(i); Rotations.RemoveAt(i); StopGravelsNum++; } else { Finish = false; var newPosition = Stone.GetChild(i).GetChild(0).position; Positions[i] = new Vector3(newPosition.x, newPosition.y, newPosition.z); var newRotation = Stone.GetChild(i).GetChild(0).eulerAngles; Rotations[i] = new Vector3(newRotation.x, newRotation.y, newRotation.z); } } } TimeAccumulated = 0; } TimeAccumulated += Time.deltaTime; } else { if (!FinishDisplayed) { WriteCSV("scene_" + SceneCount.ToString() + ".csv"); WriteXML("scene_" + SceneCount.ToString() + ".xml"); Debug.Log("Finish"); FinishDisplayed = true; SceneCount++; // reset if (SceneCount < NumOfScene) { Finish = false; Positions = new List<Vector3>(); Rotations = new List<Vector3>(); PickFileNames = new List<string>(); GravelCount = 0; TimeAccumulated = 0; FinishDisplayed = false; foreach (Transform child in Stone) { GameObject.Destroy(child.gameObject); } Debug.Log("Start Scene " + SceneCount.ToString()); } } } } private void WriteXML(string filename) { XmlDocument xmlDoc = new XmlDocument(); XmlElement root = xmlDoc.CreateElement("scene"); for (int i = 0; i < Stone.childCount; i++) { var position = Stone.GetChild(i).GetChild(0).position; var rotation = Stone.GetChild(i).GetChild(0).eulerAngles; XmlElement part = xmlDoc.CreateElement("part"); // objloader XmlElement objLoader = xmlDoc.CreateElement("filter"); objLoader.SetAttribute("type", "objloader"); XmlElement objLoaderParam1 = xmlDoc.CreateElement("param"); objLoaderParam1.SetAttribute("type", "string"); objLoaderParam1.SetAttribute("key", "filepath"); objLoaderParam1.SetAttribute("value", Path.Combine(Path.GetFileName(Path.GetDirectoryName(PickFileNames[i])), Path.GetFileName(PickFileNames[i]))); XmlElement objLoaderParam2 = xmlDoc.CreateElement("param"); objLoaderParam2.SetAttribute("type", "boolean"); objLoaderParam2.SetAttribute("key", "recomputeVertexNormals"); objLoaderParam2.SetAttribute("value", "true"); objLoader.AppendChild(objLoaderParam1); objLoader.AppendChild(objLoaderParam2); part.AppendChild(objLoader); // rotate XmlElement rotate = xmlDoc.CreateElement("filter"); rotate.SetAttribute("type", "rotate"); XmlElement rotateParam = xmlDoc.CreateElement("param"); rotateParam.SetAttribute("type", "rotation"); rotateParam.SetAttribute("key", "rotation"); XmlElement rotateParamRotRoll = xmlDoc.CreateElement("rot"); rotateParamRotRoll.SetAttribute("axis", "roll"); rotateParamRotRoll.SetAttribute("angle_deg", rotation.x.ToString()); XmlElement rotateParamRotPitch = xmlDoc.CreateElement("rot"); rotateParamRotPitch.SetAttribute("axis", "pitch"); rotateParamRotPitch.SetAttribute("angle_deg", rotation.z.ToString()); // change Y and Z order XmlElement rotateParamRotYaw = xmlDoc.CreateElement("rot"); rotateParamRotYaw.SetAttribute("axis", "yaw"); rotateParamRotYaw.SetAttribute("angle_deg", rotation.y.ToString()); // change Y and Z order rotateParam.AppendChild(rotateParamRotRoll); rotateParam.AppendChild(rotateParamRotPitch); rotateParam.AppendChild(rotateParamRotYaw); rotate.AppendChild(rotateParam); part.AppendChild(rotate); // translate XmlElement translate = xmlDoc.CreateElement("filter"); translate.SetAttribute("type", "translate"); XmlElement translateParam = xmlDoc.CreateElement("param"); translateParam.SetAttribute("type", "vec3"); translateParam.SetAttribute("key", "offset"); translateParam.SetAttribute("value", string.Format("{0};{1};{2}", position.x, position.z, position.y)); // change Y and Z order translate.AppendChild(translateParam); part.AppendChild(translate); // scale XmlElement scale = xmlDoc.CreateElement("filter"); scale.SetAttribute("type", "scale"); XmlElement scaleParam = xmlDoc.CreateElement("param"); scaleParam.SetAttribute("type", "double"); scaleParam.SetAttribute("key", "scale"); scaleParam.SetAttribute("value", "1"); scale.AppendChild(scaleParam); part.AppendChild(scale); // add part root.AppendChild(part); } xmlDoc.AppendChild(root); xmlDoc.Save(Path.Combine(Path.GetDirectoryName(FileNames[0]), filename)); } private void WriteCSV(string filename) { string outputFileName = Path.Combine(Path.GetDirectoryName(FileNames[0]), filename); using (StreamWriter file = new StreamWriter(outputFileName)) { for (int i = 0; i < Stone.childCount; i++) { var position = Stone.GetChild(i).GetChild(0).position; var rotation = Stone.GetChild(i).GetChild(0).eulerAngles; file.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6}", Path.Combine(Path.GetFileName(Path.GetDirectoryName(PickFileNames[i])), Path.GetFileName(PickFileNames[i])), position.x, position.y, position.z, rotation.x, rotation.y, rotation.z)); } } } private bool CompareVector(Vector3 v1, Vector3 v2) { var xdiff = Math.Abs(v1.x - v2.x); var ydiff = Math.Abs(v1.y - v2.y); var zdiff = Math.Abs(v1.z - v2.z); if (xdiff < 1e-3 && ydiff < 1e-3 && zdiff < 1e-3) return true; return false; } }
d6096c60d9f01b377ac6895f3d04b0a3c58e38d1
[ "C#" ]
1
C#
kevin90045/Gravel
e898ac11421c30fa61d56ed89456a5aefbaaba30
af8420efbb268d8db427ad42cd2ec76db2afe2f5
refs/heads/master
<repo_name>a2gs/Arduino_ethernetHTTPServer<file_sep>/README.md # Arduino_ethernetHTTPServer Arduino Set/Get/Status GPIO HTTP Server using Ethernet Shield W5100 <file_sep>/Arduino_ethernetHTTPServer/Arduino_ethernetHTTPServer.ino #include <SPI.h> #include <Ethernet.h> byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress ip(192, 168, 1, 177); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields //Ethernet.init(5); // MKR ETH shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); while(!Serial) delay(5); Serial.println("Ethernet WebServer Example"); // start the Ethernet connection and the server: Ethernet.begin(mac, ip); // Check for Ethernet hardware present if(Ethernet.hardwareStatus() == EthernetNoHardware){ Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); while(true) delay(5); // do nothing, no point running without Ethernet hardware } if(Ethernet.linkStatus() == LinkOFF) Serial.println("Ethernet cable is not connected."); // Arduino UNO // pinMode(0, OUTPUT); // Serial // pinMode(1, OUTPUT); // Serial pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); // SD Card pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); // pinMode(10, OUTPUT); // SPI // pinMode(11, OUTPUT); // SPI // pinMode(12, OUTPUT); // SPI // pinMode(13, OUTPUT); // SPI pinMode(A0, OUTPUT); pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); pinMode(A3, OUTPUT); pinMode(A4, OUTPUT); pinMode(A5, OUTPUT); // start the server server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } int pinNumber(char *pin) { if (strncasecmp(pin, "D0", 2) == 0) return(0); else if(strncasecmp(pin, "D1", 2) == 0) return(1); else if(strncasecmp(pin, "D2", 2) == 0) return(2); else if(strncasecmp(pin, "D3", 2) == 0) return(3); else if(strncasecmp(pin, "D4", 2) == 0) return(4); else if(strncasecmp(pin, "D5", 2) == 0) return(5); else if(strncasecmp(pin, "D6", 2) == 0) return(6); else if(strncasecmp(pin, "D7", 2) == 0) return(7); else if(strncasecmp(pin, "D8", 2) == 0) return(8); else if(strncasecmp(pin, "D9", 2) == 0) return(9); else if(strncasecmp(pin, "D10", 3) == 0) return(10); else if(strncasecmp(pin, "D11", 3) == 0) return(11); else if(strncasecmp(pin, "D12", 3) == 0) return(12); else if(strncasecmp(pin, "D13", 3) == 0) return(13); else if(strncasecmp(pin, "A0", 2) == 0) return(A0); else if(strncasecmp(pin, "A1", 2) == 0) return(A1); else if(strncasecmp(pin, "A2", 2) == 0) return(A2); else if(strncasecmp(pin, "A3", 2) == 0) return(A3); else if(strncasecmp(pin, "A4", 2) == 0) return(A4); else if(strncasecmp(pin, "A5", 2) == 0) return(A5); return(-1); } void loop() { #define URL_DELIMITER_CHAR ('?') #define REQBUFF_SZ (12) char reqBuff[REQBUFF_SZ] = {'\0'}; char c = 0; // listen for incoming clients EthernetClient client = server.available(); if(client){ // an http request ends with a blank line bool currentLineIsBlank = true; Serial.println("new client"); while(client.connected()){ if(client.available()){ #define RESBUFF_SZ (200) char response[RESBUFF_SZ] = {'\0'}; c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if(c == '\n' && currentLineIsBlank){ /* there is no strncasecmp() into arduino SDK */ if((reqBuff[0] == 'S' || reqBuff[0] == 's') && (reqBuff[1] == 'T' || reqBuff[1] == 't') && (reqBuff[2] == 'A' || reqBuff[2] == 'a') && (reqBuff[3] == 'T' || reqBuff[3] == 't') && (reqBuff[4] == 'U' || reqBuff[4] == 'u') && (reqBuff[5] == 'S' || reqBuff[5] == 's')){ /* pins 10, 11, 12 and 13 used to ethernet shield snprintf(response, RESBUFF_SZ, "D0=%c<br>D1=%c<br>D2=%c<br>D3=%c<br>D4=%c<br>D5=%c<br>D6=%c<br>D7=%c<br>D8=%c<br>D9=%c<br>" "D10=%c<br>D11=%c<br>D12=%c<br>D13=%c<br>A0=%c<br>A1=%c<br>A2=%c<br>A3=%c<br>A4=%c<br>A5=%c", (digitalRead(0) == LOW ? '0' : '1'), (digitalRead(1) == LOW ? '0' : '1'), (digitalRead(2) == LOW ? '0' : '1'), (digitalRead(3) == LOW ? '0' : '1'), (digitalRead(4) == LOW ? '0' : '1'), (digitalRead(5) == LOW ? '0' : '1'), (digitalRead(6) == LOW ? '0' : '1'), (digitalRead(7) == LOW ? '0' : '1'), (digitalRead(8) == LOW ? '0' : '1'), (digitalRead(9) == LOW ? '0' : '1'), (digitalRead(10) == LOW ? '0' : '1'), (digitalRead(11) == LOW ? '0' : '1'), (digitalRead(12) == LOW ? '0' : '1'), (digitalRead(13) == LOW ? '0' : '1'), (digitalRead(A0) == LOW ? '0' : '1'), (digitalRead(A1) == LOW ? '0' : '1'), (digitalRead(A2) == LOW ? '0' : '1'), (digitalRead(A3) == LOW ? '0' : '1'), (digitalRead(A4) == LOW ? '0' : '1'), (digitalRead(A5) == LOW ? '0' : '1')); */ snprintf(response, RESBUFF_SZ, "D0=%c<br>D1=%c<br>D2=%c<br>D3=%c<br>D4=%c<br>D5=%c<br>D6=%c<br>D7=%c<br>" "D8=%c<br>D9=%c<br>A0=%c<br>A1=%c<br>A2=%c<br>A3=%c<br>A4=%c<br>A5=%c", (digitalRead(0) == LOW ? '0' : '1'), (digitalRead(1) == LOW ? '0' : '1'), (digitalRead(2) == LOW ? '0' : '1'), (digitalRead(3) == LOW ? '0' : '1'), (digitalRead(4) == LOW ? '0' : '1'), (digitalRead(5) == LOW ? '0' : '1'), (digitalRead(6) == LOW ? '0' : '1'), (digitalRead(7) == LOW ? '0' : '1'), (digitalRead(8) == LOW ? '0' : '1'), (digitalRead(9) == LOW ? '0' : '1'), (digitalRead(A0) == LOW ? '0' : '1'), (digitalRead(A1) == LOW ? '0' : '1'), (digitalRead(A2) == LOW ? '0' : '1'), (digitalRead(A3) == LOW ? '0' : '1'), (digitalRead(A4) == LOW ? '0' : '1'), (digitalRead(A5) == LOW ? '0' : '1')); }else if((reqBuff[0] == 'S' || reqBuff[0] == 's') && (reqBuff[1] == 'E' || reqBuff[1] == 'e') && (reqBuff[2] == 'T' || reqBuff[2] == 't')){ int pinReq = 0; // 01234567 // SET/D1=0 pinReq = pinNumber(&reqBuff[4]); if(pinReq == -1){ // TODO: ERRO } if(reqBuff[strlen(reqBuff)-1] == '0') digitalWrite(pinReq, LOW ); else digitalWrite(pinReq, HIGH); /* Serial.println("*****************"); Serial.println(strlen(reqBuff)); Serial.println(reqBuff[strlen(reqBuff)-1]); Serial.println(pinReq); Serial.println("*****************"); */ snprintf(response, RESBUFF_SZ, "GPIO [%d] set to [%c]", pinReq, (digitalRead(pinReq) == LOW ? '0' : '1')); }else if((reqBuff[0] == 'G' || reqBuff[0] == 'g') && (reqBuff[1] == 'E' || reqBuff[1] == 'e') && (reqBuff[2] == 'T' || reqBuff[2] == 't')){ int pinReq = 0; // 012345 // GET/D1 pinReq = pinNumber(&reqBuff[4]); if(pinReq == -1){ // TODO: ERRO } snprintf(response, RESBUFF_SZ, "%c", (digitalRead(pinReq) == LOW ? '0' : '1')); } // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response // client.println("Refresh: 5"); refresh the page automatically every 5 sec client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println(response); client.println("</html>"); /* Serial.println(">>>>> ENVIANDO:"); Serial.println(response); */ break; } if(c == URL_DELIMITER_CHAR){ int i = 0; memset(reqBuff, 0, REQBUFF_SZ); // getting the request parameter for(i = 0; i < REQBUFF_SZ && c != '\n'; i++){ c = client.read(); reqBuff[i] = c; Serial.write(c); } reqBuff[i-2] = '\0'; // writes \0 over \r /* Serial.println(">>>>> RECEBIDO:"); Serial.println(reqBuff); Serial.println(">>>>> RECEBIDO BYTES:"); Serial.println(i); Serial.println(">>>>> RECEBIDO STRLEN():"); Serial.println(strlen(reqBuff)); */ } if(c == '\n'){ // you're starting a new line currentLineIsBlank = true; }else if (c != '\r'){ // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disconnected"); } }
d381ed79c6ca69d3e91d21f37e5cf56939f6a30b
[ "Markdown", "C++" ]
2
Markdown
a2gs/Arduino_ethernetHTTPServer
e06ec3cd36c19bb4e783c3e2eca9373298c0a835
3520434c8af0966178759183c016145e5b76c1a6
refs/heads/master
<file_sep>Flow.init = function(o) { o = (o || {}); var watch = (o.watch || true), fileList = []; var calledDir = (o.buildpath || Flow.path.called); var configPath = calledDir + '/flow.json'; var config = require(configPath); var project = (config.project || false); //Will recompile project when settings file is updated //fileList.push(calledDir + '/flow.json'); if(project) { var css = (project.css || false), html = (project.html || false), js = (project.js || false); if(css) { for(cssFile in css.files) { Flow.compile[css.engine]({ output: calledDir + css.files[cssFile], src: calledDir + cssFile, paths: [ calledDir + '/src/stylus/' ] }); //fileList.push(calledDir + cssFile.toString()) } } if(html && html.files) { Flow.compiler({ calledDir : calledDir, files : html.files, type : 'html' }); /*for(htmlFile in html.files) { fileList.push(calledDir + htmlFile.toString()) }*/ } if(js && js.files) { Flow.compiler({ calledDir : calledDir, files : js.files, type : 'js' }); js.files.forEach(function(file, key) { if(file.frameworks) { file.frameworks.forEach(function(file, key) { fileList.push(file.toString()); }); } /*file.src.forEach(function(file, key) { fileList.push(calledDir + file.toString()); });*/ }); } } /*if(watch) { fileList.forEach(function(val, key) { Flow.watch({ file: val }); }); }*/ }; <file_sep>var FILE_ENCODING = 'utf-8', EOL = '\n'; // setup var fs = require('fs'), exec = require('child_process').exec, //sass = require(__dirname + '/../node_modules/node-sass/sass'), stylus = require('stylus'), //StylusSprite = require("stylus-sprite"), util = require('util'), wrench = require('wrench'); var Flow = {}; <file_sep>Flow.compile.stylus = function(o) { o = (o || {}); var output = (o.output || false), paths = (o.paths || false), src = (o.src || false); /*sprite = new StylusSprite({ image_root: Flow.path.called + '/src/img', output_file: Flow.path.called + '/deploy/img/sprite.png' });*/ stylus(fs.readFileSync(src, 'utf8')) //Get contents of stylus file //.set('filename', 'app.css') .set('paths', paths) /*.define('sprite', function(filename, option_val){ // preparation phase return sprite.spritefunc(filename, option_val); })*/ .render(function(err, css) { //console.log(css); fs.writeFileSync(output, css, 'utf8'); //if (err) throw err; // rendering phase /*sprite.build(css, function(err, css){ //if (err) throw err; console.log(css); });*/ }); }; <file_sep>Flow.compile.html = function(o, callback) { var command = Flow.path.markx + ' ', md = (o.md || false), output = (o.output || false), jade = (o.jade || false), src = false; if(jade && md) { command += '--template ' + jade + ' '; src = md; } if(jade && !md) { src = jade; } if(!jade && md) { src = md; } if(output && src) { command += src + ' > '; command += output; fs.unlinkSync(output); exec(command, function(error, stdout, stderr) { if(error !== null) { console.log('exec error: ' + error); console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); } else { callback(); } }); } }; <file_sep>Flow.compiler = function(o) { o = (o || {}); var calledDir = (o.calledDir || false), files = (o.files || []), frameworks, list, minify, out, output, src, srcList, type = (o.type || false); if(calledDir && files && type) { switch(type) { case 'html': for(file in files) { output = (files[file].toString() || false); src = (file.toString() || false); if(output && src) { var command = Flow.path.markx + ' ' + calledDir + src + ' > ' + calledDir + output; //filetype = input.substr(input.lastIndexOf('.') + 1); exec(command, function(error, stdout, stderr) { //console.log('stdout: ' + stdout); //console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); } } break; case 'js': files.forEach(function(file, key) { frameworks = (file.frameworks || false); output = (file.output || false); src = (file.src || false); if(output && src) { srcList = src.map(function(srcItem) { return calledDir + srcItem; }); if(frameworks) { list = frameworks.concat(srcList); } else { list = srcList; } out = list.map(function(item) { return fs.readFileSync(item, FILE_ENCODING); }); fs.writeFileSync(calledDir + output, out.join(EOL), FILE_ENCODING); } }); break; } } };<file_sep>Flow.watch = function(o) { o = (o || {}); var file = (o.file || false); if(file) { console.log("Watching: ", file); fs.watch(file, { persistant: true, internal: 1000 }, function(ev, file) { console.log(' '); console.log('Compiling...'); console.log(' '); Flow.init({ watch: false }); }); } }; <file_sep>#Flow ##Compiling Jade and Markdown to HTML ###Markdown to HTML Supply the path to the .md file and the path to the output .html Flow.compile.html({ md : 'path/to/content.md', output : 'path/to/content.html' }); ###Jade to HTML Supply the path to the .jade file and the path to the output .html Flow.compile.html({ jade : 'path/to/template.jade', output : 'path/to/template.jade' }); ###Jade + Markdown to HTML Jade can be used as a template and markdown can be written as the content Flow.compile.html({ jade : 'path/to/template.jade', md : 'path/to/content.md', output : 'path/to/combined.html' });<file_sep>if(typeof exports !== "undefined") { exports = module.exports = function(path) { Flow.path = path; return Flow; }; } <file_sep>#!/usr/bin/env node var FILE_ENCODING = 'utf-8', EOL = '\n', DIST_FILE_PATH = './lib/flow.js'; // setup var _fs = require('fs'); function concat(fileList, distPath) { var out = fileList.map(function(filePath){ return _fs.readFileSync(filePath, FILE_ENCODING); }); _fs.writeFileSync(distPath, out.join(EOL), FILE_ENCODING); console.log(' '+ distPath +' built.'); } concat([ "./src/flow.js", "./src/exports.js", "./src/compile/compile.js", "./src/compile/html.js", "./src/compile/stylus.js", "./src/compile/compiler.js", "./src/init.js", "./src/watch.js" ], DIST_FILE_PATH); function uglify(srcPath, distPath) { var uglyfyJS = require('uglify-js'), jsp = uglyfyJS.parser, pro = uglyfyJS.uglify, ast = jsp.parse( _fs.readFileSync(srcPath, FILE_ENCODING) ); ast = pro.ast_mangle(ast); ast = pro.ast_squeeze(ast); _fs.writeFileSync(distPath, pro.gen_code(ast), FILE_ENCODING); console.log(' '+ distPath +' built.'); } uglify('./lib/flow.js', './lib/flow.min.js');<file_sep>var FILE_ENCODING = 'utf-8', EOL = '\n'; // setup var fs = require('fs'), exec = require('child_process').exec, //sass = require(__dirname + '/../node_modules/node-sass/sass'), stylus = require('stylus'), //StylusSprite = require("stylus-sprite"), util = require('util'), wrench = require('wrench'); var Flow = {}; if(typeof exports !== "undefined") { exports = module.exports = function(path) { Flow.path = path; return Flow; }; } Flow.compile = {}; Flow.compile.html = function(o, callback) { var command = Flow.path.markx + ' ', md = (o.md || false), output = (o.output || false), jade = (o.jade || false), src = false; if(jade && md) { command += '--template ' + jade + ' '; src = md; } if(jade && !md) { src = jade; } if(!jade && md) { src = md; } if(output && src) { command += src + ' > '; command += output; fs.unlinkSync(output); exec(command, function(error, stdout, stderr) { if(error !== null) { console.log('exec error: ' + error); console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); } else { callback(); } }); } }; Flow.compile.stylus = function(o) { o = (o || {}); var output = (o.output || false), paths = (o.paths || false), src = (o.src || false); /*sprite = new StylusSprite({ image_root: Flow.path.called + '/src/img', output_file: Flow.path.called + '/deploy/img/sprite.png' });*/ stylus(fs.readFileSync(src, 'utf8')) //Get contents of stylus file //.set('filename', 'app.css') .set('paths', paths) /*.define('sprite', function(filename, option_val){ // preparation phase return sprite.spritefunc(filename, option_val); })*/ .render(function(err, css) { //console.log(css); fs.writeFileSync(output, css, 'utf8'); //if (err) throw err; // rendering phase /*sprite.build(css, function(err, css){ //if (err) throw err; console.log(css); });*/ }); }; Flow.compiler = function(o) { o = (o || {}); var calledDir = (o.calledDir || false), files = (o.files || []), frameworks, list, minify, out, output, src, srcList, type = (o.type || false); if(calledDir && files && type) { switch(type) { case 'html': for(file in files) { output = (files[file].toString() || false); src = (file.toString() || false); if(output && src) { var command = Flow.path.markx + ' ' + calledDir + src + ' > ' + calledDir + output; //filetype = input.substr(input.lastIndexOf('.') + 1); exec(command, function(error, stdout, stderr) { //console.log('stdout: ' + stdout); //console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); } } break; case 'js': files.forEach(function(file, key) { frameworks = (file.frameworks || false); output = (file.output || false); src = (file.src || false); if(output && src) { srcList = src.map(function(srcItem) { return calledDir + srcItem; }); if(frameworks) { list = frameworks.concat(srcList); } else { list = srcList; } out = list.map(function(item) { return fs.readFileSync(item, FILE_ENCODING); }); fs.writeFileSync(calledDir + output, out.join(EOL), FILE_ENCODING); } }); break; } } }; Flow.init = function(o) { o = (o || {}); var watch = (o.watch || true), fileList = []; var calledDir = Flow.path.called; var configPath = calledDir + '/flow.json'; var config = require(configPath); var project = (config.project || false); //Will recompile project when settings file is updated fileList.push(calledDir + '/flow.json'); if(project) { var css = (project.css || false), html = (project.html || false), js = (project.js || false); if(css) { for(cssFile in css.files) { Flow.compile[css.engine]({ output: calledDir + css.files[cssFile], src: calledDir + cssFile, paths: [ calledDir + '/src/stylus/' ] }); fileList.push(calledDir + cssFile.toString()) } } if(html && html.files) { Flow.compiler({ calledDir : calledDir, files : html.files, type : 'html' }); for(htmlFile in html.files) { fileList.push(calledDir + htmlFile.toString()) } } if(js && js.files) { Flow.compiler({ calledDir : calledDir, files : js.files, type : 'js' }); js.files.forEach(function(file, key) { if(file.frameworks) { file.frameworks.forEach(function(file, key) { fileList.push(file.toString()); }); } file.src.forEach(function(file, key) { fileList.push(calledDir + file.toString()); }); }); } } /*if(watch) { fileList.forEach(function(val, key) { Flow.watch({ file: val }); }); }*/ }; Flow.watch = function(o) { o = (o || {}); var file = (o.file || false); if(file) { console.log("Watching: ", file); fs.watch(file, { persistant: true, internal: 1000 }, function(ev, file) { console.log(' '); console.log('Compiling...'); console.log(' '); Flow.init({ watch: false }); }); } };
48ba7a3fd7cd36e2d9e446c221d10b49f8bbbcd5
[ "JavaScript", "Markdown" ]
10
JavaScript
travis4all/flowin
0e8b57e80545af7191d71c5f33015bd66d8856fd
bee1afee65609b9e6e5314ceead9fb52da6970d4
refs/heads/master
<file_sep>pip3 install django-cors-headers <file_sep># Generated by Django 2.2 on 2019-04-13 23:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Restaurant', '0001_initial'), ] operations = [ migrations.CreateModel( name='TableType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=30, null=True)), ('supportedNum', models.IntegerField(default=1)), ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Restaurant.Restaurant')), ], ), migrations.CreateModel( name='TableData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('remainNum', models.IntegerField(default=0)), ('dateTime', models.DateTimeField()), ('restaurant', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='Restaurant.Restaurant')), ('tableType', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Table.TableType')), ], ), ] <file_sep>from .serializers import * from rest_framework import viewsets, status from .models import * from Restaurant.models import Restaurant from datetime import datetime,timedelta, date from rest_framework.response import Response from django.db import connection import pytz from Reservation.models import ReservationInfo class TableTypeViewSet(viewsets.ModelViewSet): serializer_class = TableTypeSerializer def get_queryset(self): queryset = TableType.objects.all() rest_id = self.request.query_params.get('restaurant', None) if rest_id is not None: queryset = queryset.filter(restaurant=rest_id) print(rest_id) return queryset def create(self, request): restaurant = request.data.get('restaurant') type = request.data.get('type') supportedNum = request.data.get('supportedNum') l = request.data.get('periods') totalNum = request.data.get('totalNum') instance = TableType(restaurant=Restaurant.objects.get(pk=restaurant), type=type, supportedNum=supportedNum) instance.save() iniGen(instance, l, totalNum) return Response({'restaurant': restaurant, 'type': type, 'supportedNum':supportedNum, 'totalNum':totalNum, 'periods':l}, status=status.HTTP_201_CREATED) def update(self, request, pk): old_ins = TableType.objects.get(pk=pk) type = request.data.get('type') restaurant = request.data.get('restaurant') supportedNum = request.data.get('supportedNum') l = request.data.get('periods') totalNum = request.data.get('totalNum') old_ins.type = type old_ins.supportedNum = supportedNum TableData.objects.filter(tableType=old_ins.id).delete() old_ins.save() iniGen(old_ins, l, totalNum) return Response({'id':old_ins.id,'restaurant': restaurant, 'type': type, 'supportedNum':supportedNum, 'totalNum':totalNum, 'periods':l}, status=status.HTTP_200_OK) def destroy(self, request, pk=None): if ReservationInfo.objects.filter(type=pk, dateTime__gte = datetime.now()).exists(): return Response({'error':'Cannot delete due to future reservation.'}, status=status.HTTP_400_BAD_REQUEST) else: TableType.objects.filter(id=pk).delete() return Response({'Message':'OK'}, status=status.HTTP_200_OK) class TableDataViewSet(viewsets.ModelViewSet): serializer_class = TableDataSerializer def get_queryset(self): queryset = TableData.objects.all() rest_id = self.request.query_params.get('restaurant', None) tabletype = self.request.query_params.get('tabletype', None) time = self.request.query_params.get('datetime', None) date = self.request.query_params.get('date', None) if time is not None: queryset = queryset.filter(dateTime=time) else: if date is not None: date = datetime.strptime(date, "%Y-%m-%d") st = datetime(date.year, date.month, date.day, 00, 00, 00, tzinfo=pytz.UTC) et = datetime(date.year, date.month, date.day, 23, 59, 59, tzinfo=pytz.UTC) queryset = queryset.filter(dateTime__lte=et,dateTime__gte=st) if rest_id is not None: queryset = queryset.filter(restaurant=rest_id) if tabletype is not None: queryset = queryset.filter(tableType=tabletype) return queryset def iniGen(TableType, l, total): for time in l: timeslot = datetime.strptime(time, "%H:%M:%S") today = datetime.today() st = datetime(today.year, today.month, today.day, timeslot.hour, timeslot.minute, timeslot.second, tzinfo=pytz.UTC) et = datetime(today.year, today.month+1, today.day, timeslot.hour, timeslot.minute, timeslot.second, tzinfo=pytz.UTC) timeslot = datetime.strptime(time, "%H:%M:%S") daySeq = [s for s in datetime_range(st, et, timedelta(days=1))] for d in daySeq: instance = TableData(tableType = TableType, type = TableType.type, restaurant= TableType.restaurant, remainNum=total, dateTime=d) instance.save() def datetime_range(start, end, delta): current = start while current < end: yield current current += delta <file_sep>from django.db import models from Table.models import TableType from Restaurant.models import Restaurant from django.contrib.auth.models import User from datetime import datetime, date from django.db.models import DateTimeField class ReservationInfo(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True) type = models.ForeignKey(TableType, on_delete=models.CASCADE) dateTime = DateTimeField(auto_now=False, null=True) guestNum = models.IntegerField(default=1) class PastOrderReview(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default=3) description = models.TextField(null=True) rated = models.BooleanField(default=False) <file_sep># Generated by Django 2.2 on 2019-04-13 23:45 import Restaurant.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Restaurant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('yelp_id', models.CharField(blank=True, default=Restaurant.utils.uuidToStr, max_length=100)), ('address', models.CharField(max_length=30, null=True)), ('city', models.CharField(max_length=20)), ('state', models.CharField(max_length=10)), ('name', models.CharField(max_length=100)), ('photo_url', models.CharField(max_length=200)), ('ratings_count', models.IntegerField(default=0)), ('rating', models.DecimalField(decimal_places=1, default=1, max_digits=2)), ('price', models.CharField(max_length=10, null=True)), ('phone_num', models.CharField(max_length=100, null=True)), ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='RestaurantCat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=50)), ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Restaurant.Restaurant')), ], ), ] <file_sep>from django.urls import path from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'table-type', TableTypeViewSet, basename='tabletype') router.register(r'table-data', TableDataViewSet, basename='tabledata') urlpatterns = router.urls <file_sep>from rest_framework import serializers from .models import TableType, TableData from datetime import datetime, date class TableTypeSerializer(serializers.ModelSerializer): class Meta: model = TableType fields = ('id', 'restaurant', 'type', 'supportedNum') class TableDataSerializer(serializers.ModelSerializer): class Meta: model = TableData fields = ('id', 'tableType', 'type', 'restaurant', 'remainNum', 'dateTime') <file_sep>from rest_framework import serializers from .models import * class WSNumberSerializer(serializers.ModelSerializer): class Meta: model = WSNumber fields = ('id', 'restaurant', 'waitingNumber', 'servedNumber') class WaitingUserSerializer(serializers.ModelSerializer): class Meta: model = WaitingUser fields = ('id', 'user', 'restaurant', 'myNumber', 'first_name') <file_sep># Generated by Django 2.2 on 2019-04-15 23:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TakeANumber', '0001_initial'), ] operations = [ migrations.AddField( model_name='waitinguser', name='first_name', field=models.CharField(max_length=100, null=True), ), ] <file_sep>from django.urls import path from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'reservation', ReservationInfoViewSet, basename='reservation') router.register(r'review', PastOrderReviewViewSet, basename='review') urlpatterns = router.urls <file_sep># Generated by Django 2.2 on 2019-04-13 23:45 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserVector', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('american', models.IntegerField(default=0)), ('seafood', models.IntegerField(default=0)), ('steak', models.IntegerField(default=0)), ('fast', models.IntegerField(default=0)), ('bar', models.IntegerField(default=0)), ('finedining', models.IntegerField(default=0)), ('chinese', models.IntegerField(default=0)), ('japanese', models.IntegerField(default=0)), ('korean', models.IntegerField(default=0)), ('mexican', models.IntegerField(default=0)), ('pizza', models.IntegerField(default=0)), ('breakfast', models.IntegerField(default=0)), ('noodle', models.IntegerField(default=0)), ('italian', models.IntegerField(default=0)), ('mediterranean', models.IntegerField(default=0)), ('french', models.IntegerField(default=0)), ('vegetarian', models.IntegerField(default=0)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='UserType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_superUser', models.BooleanField(default=False)), ('is_restaurant', models.BooleanField(default=False)), ('is_common', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Preference', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('preference', models.CharField(max_length=30, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] <file_sep>from django.urls import path from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'wsnumber', WSNumberViewSet, basename="wsnumber") router.register(r'waiting-user', WaitingUserViewSet, basename="waitinguser") urlpatterns = router.urls <file_sep># Generated by Django 2.2 on 2019-04-18 04:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Reservation', '0004_auto_20190418_0226'), ] operations = [ migrations.AlterField( model_name='pastorderreview', name='rating', field=models.DecimalField(decimal_places=1, default=1.0, max_digits=2), ), ] <file_sep>from User.models import UserVector import numpy as np from sklearn.neighbors import NearestNeighbors from .utils import columnNames import math def getSimilarUsers(user_id, num): querySet = UserVector.objects.all() params = querySet.values_list(*columnNames) UVs = np.array([arr for arr in params]) if len(UVs) == 1: return [] tmp = UVs[:,0].reshape((len(UVs))) targetIndex = (tmp == int(user_id)) nonTargetIndex = (tmp != int(user_id)) nn = NearestNeighbors(metric='cosine') target,nonTarget = UVs[targetIndex], UVs[nonTargetIndex] nn.fit(nonTarget[:,1:]) res = [] tmp = nn.kneighbors(target[:, 1:], num, return_distance=False) for index in tmp[0]: res += [nonTarget[index][0]] return res def getCategoryList(user_id, num): querySet = UserVector.objects.filter(user=user_id) params = querySet.values_list(*columnNames) UV = np.array([arr for arr in params]) UV = UV[0][1:] sum = np.sum(UV) distr = np.array([int(math.ceil(num*i/sum)) for i in UV]) return(distr) <file_sep>from rest_framework import serializers from .models import * class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id','user', 'address', 'city', 'state', 'photo_url','name', 'phone_num', 'price','ratings_count','rating') class RestaurantCatSerializer(serializers.ModelSerializer): class Meta: model = RestaurantCat fields = ('id','restaurant', 'title') # user is the User's id ''' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id','restaurant', 'user', 'description', 'ratings', 'date') ''' <file_sep>from rest_framework import serializers from .models import * class ReservationInfoSerializer(serializers.ModelSerializer): class Meta: model = ReservationInfo fields = ('id','restaurant','user','first_name', 'type', 'guestNum', 'dateTime') class PastOrderReviewSerializer(serializers.ModelSerializer): class Meta: model = PastOrderReview fields = ('id','restaurant', 'user', 'rating', 'description', 'rated') # user is the User's id <file_sep>import uuid def uuidToStr(): return str(uuid.uuid4()) initPreferenceWeight = 20 ratePreferenceTable = { 1:-2, 2:-1, 3:0, 4:1, 5:2 } columnNames = ["user", "american", "seafood", "steak", "fast", "bar", "finedining", "chinese", "japanese", "korean", "mexican", "pizza", "breakfast", "noodle", "italian", "mediterranean","french","vegetarian"] <file_sep>from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): User = get_user_model() if not User.objects.filter(username="yansky").exists(): User.objects.create_superuser("yansky", "<EMAIL>", "Yanyujia0709") <file_sep>Django==2.2 django-cors-headers==2.5.2 djangorestframework==3.9.2 djangorestframework-jwt==1.11.0 numpy==1.16.2 psycopg2-binary==2.8 PyJWT==1.7.1 pytz==2018.9 scikit-learn==0.20.3 scipy==1.2.1 sklearn==0.0 sqlparse==0.3.0 virtualenv==16.4.3<file_sep>from rest_framework import serializers from django.contrib.auth.models import User from .models import * from rest_framework.authtoken.models import Token from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'last_login', 'date_joined') class UserTypeSerializer(serializers.ModelSerializer): class Meta: model = UserType fields = ('id', 'user', 'is_restaurant', 'is_common') class UserVectorSerializer(serializers.ModelSerializer): class Meta: model = UserVector fields = ('id','user', "american", "seafood", "steak", "fast", "bar", "finedining", "chinese", "japanese", "korean", "mexican", "pizza", "breakfast", "noodle", "italian", "mediterranean","french","vegetarian") class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def create(self, validate_data): password = validate_data.pop('password', None) instance = self.Meta.model(**validate_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'id', 'token', 'password', 'username', 'email', 'first_name', 'last_name', 'last_login', 'date_joined') class PreferenceSerializer(serializers.ModelSerializer): class Meta: model = Preference fields = ('id','user', 'preference') # user is the User's id <file_sep># Generated by Django 2.2 on 2019-04-18 02:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Reservation', '0003_reservationinfo_first_name'), ] operations = [ migrations.AddField( model_name='pastorderreview', name='rated', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='pastorderreview', name='description', field=models.TextField(null=True), ), ] <file_sep>from django.db import models from django.contrib.auth.models import User class Preference(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) preference = models.CharField(max_length=30, null=True) class UserType(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_superUser = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) is_common = models.BooleanField(default=False) class UserVector(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) american = models.IntegerField(default=0) seafood = models.IntegerField(default=0) steak = models.IntegerField(default=0) fast = models.IntegerField(default=0) bar = models.IntegerField(default=0) finedining = models.IntegerField(default=0) chinese = models.IntegerField(default=0) japanese = models.IntegerField(default=0) korean = models.IntegerField(default=0) mexican = models.IntegerField(default=0) pizza = models.IntegerField(default=0) breakfast = models.IntegerField(default=0) noodle = models.IntegerField(default=0) italian = models.IntegerField(default=0) mediterranean = models.IntegerField(default=0) french = models.IntegerField(default=0) vegetarian = models.IntegerField(default=0) <file_sep>from .serializers import * from rest_framework import viewsets, status from rest_framework.response import Response from Restaurant.models import Restaurant from django.contrib.auth.models import User from .utils import * ## TODO: Need super user authentication class WSNumberViewSet(viewsets.ModelViewSet): serializer_class = WSNumberSerializer def get_queryset(self): queryset = WSNumber.objects.all() rest_id = self.request.query_params.get('restaurant', None) if rest_id is not None: queryset = queryset.filter(restaurant=rest_id) return queryset def update(self, request, pk=None): old_ins = WSNumber.objects.get(restaurant=pk) waitingNumber = request.data.get('waitingNumber', None) servedNumber = request.data.get('servedNumber', None) if waitingNumber is not None: old_ins.waitingNumber = waitingNumber if servedNumber is not None: old_ins.servedNumber = servedNumber old_ins.save() return Response({'id':old_ins.id, 'restaurant':pk, 'waitingNumber':old_ins.waitingNumber, 'servedNumber':old_ins.servedNumber}, status=status.HTTP_200_OK) class WaitingUserViewSet(viewsets.ModelViewSet): serializer_class = WaitingUserSerializer def get_queryset(self): queryset = WaitingUser.objects.all() rest_id = self.request.query_params.get('restaurant', None) myNumber = self.request.query_params.get('myNumber', None) if rest_id is not None: servedNumber = WSNumber.objects.get(restaurant=rest_id).servedNumber queryset = queryset.filter(restaurant=rest_id, myNumber__gte=servedNumber) if myNumber is not None: queryset = queryset.filter(myNumber=myNumber) return queryset def create(self, request): user = request.data.get("user") restaurant = request.data.get("restaurant") first_name = request.data.get("first_name","") ws_obj = WSNumber.objects.get(restaurant=restaurant) ws_obj.waitingNumber = ws_obj.waitingNumber + 1 ws_obj.save() myNumber = ws_obj.waitingNumber sql = "INSERT INTO \"TakeANumber_waitinguser\"(restaurant_id,user_id,\"first_name\", \"myNumber\") VALUES({},{},\'{}\',{});".format(restaurant, user, first_name, myNumber) executeSQL(sql) #instance = WaitingUser(first_name=first_name,restaurant = Restaurant.objects.get(id=restaurant), user = User.objects.get(id=user), myNumber=myNumber) #instance.save() return Response({'restaurant':restaurant, 'user':user, 'first_name':first_name, 'myNumber':myNumber},status=status.HTTP_201_CREATED) <file_sep>from django.apps import AppConfig class TakeanumberConfig(AppConfig): name = 'TakeANumber' <file_sep>from __future__ import unicode_literals from .models import * from .serializers import * from rest_framework import filters from User.models import * from django.contrib.auth.models import User from Restaurant.models import * from Restaurant.utils import * from rest_framework import viewsets,status from rest_framework.response import Response from datetime import datetime from .utils import * from Table.models import * class ReservationInfoViewSet(viewsets.ModelViewSet): serializer_class = ReservationInfoSerializer def get_queryset(self): queryset = ReservationInfo.objects.all() rest_id = self.request.query_params.get('restaurant', None) user_id = self.request.query_params.get('user', None) time = self.request.query_params.get('before', None) if time is not None: time = datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ") if rest_id is not None: queryset = queryset.filter(restaurant=rest_id) if user_id is not None: queryset = queryset.filter(user=user_id) if time is not None: queryset = queryset.filter(dateTime__lt=time) return queryset def create(self, request): # assume we have spare table left restaurant = request.data.get("restaurant") user = request.data.get("user") first_name = request.data.get("first_name", "") type = request.data.get("type") dateTime = request.data.get("dateTime") guestNum = request.data.get("guestNum") instance = ReservationInfo(restaurant=Restaurant.objects.get(id=restaurant), user=User.objects.get(id=user), first_name=first_name,type=TableType.objects.get(id=type), dateTime=dateTime,guestNum=guestNum) instance.save() sql = "UPDATE \"Table_tabledata\" SET \"remainNum\" = \"remainNum\" -1 WHERE \"tableType_id\"={} AND \"dateTime\" = \'{}\';".format(type,dateTime) executeSQL(sql) #table_data_obj = TableData.objects.get(tableType=type,dateTime=dateTime) #table_data_obj.remainNum = table_data_obj.remainNum -1 #table_data_obj.save() return Response({'id':instance.id,'restaurant':restaurant, 'user':user,'first_name':first_name, 'type':type,'dateTime':dateTime,'guestNum':guestNum}, status=status.HTTP_201_CREATED) def destroy(self, request, pk=None): if ReservationInfo.objects.filter(id=pk).exists(): # add table first instance = ReservationInfo.objects.get(id=pk) print(instance.type,instance.dateTime) #sql = "UPDATE \"Table_tabledata\" SET \"remainNum\" = \"remainNum\" +1 WHERE \"tableType_id\"={} AND \"dateTime\" = \'{}\';".format(instance.type,instance.dateTime) #executeSQL(sql) table_data_obj = TableData.objects.get(tableType=instance.type,dateTime=instance.dateTime) table_data_obj.remainNum = table_data_obj.remainNum + 1 table_data_obj.save() sql = "DELETE FROM \"Reservation_reservationinfo\" WHERE id = {};".format(pk) executeSQL(sql) return Response({'message':'Successful delete'}, status=status.HTTP_200_OK) else: return Response({'error':'The reservation does not exist'}, status=status.HTTP_400_BAD_REQUEST) class PastOrderReviewViewSet(viewsets.ModelViewSet): serializer_class = PastOrderReviewSerializer def get_queryset(self): queryset = PastOrderReview.objects.all() rest_id = self.request.query_params.get('restaurant', None) user_id = self.request.query_params.get('user', None) if rest_id is not None: queryset = queryset.filter(restaurant=rest_id) if user_id is not None: queryset = queryset.filter(user=user_id) return queryset def create(self, request): # create default value rest_id = request.data.get("restaurant") user_id = request.data.get("user") rating = request.data.get("rating", 4) description = request.data.get("description", "") rated = request.data.get("rated", False) instance = PastOrderReview(restaurant=Restaurant.objects.get(id=request.data.get("restaurant")), user = User.objects.get(id = request.data.get("user")), rating = request.data.get("rating"), description = request.data.get("description"), rated = request.data.get("rated")) instance.save() #sql = "INSERT INTO \"Reservation_pastorderreview\"(restaurant_id, user_id, rating, description, rated) VALUES({},{},{},\'{}\',{})".format(rest_id,user_id,rating,description,rated) #executeSQL(sql) return Response({'id':instance.id, 'restaurant':request.data.get("restaurant"), 'user':request.data.get("user"),'rating':request.data.get("rating"), 'description':request.data.get("description"), 'rated':rated}, status=status.HTTP_201_CREATED) def update(self, request, pk=None): rest_id = request.data.get("restaurant") user_id = request.data.get("user") rating = request.data.get("rating", 4) description = request.data.get("description", "") rated = request.data.get("rated", False) instance = PastOrderReview.objects.get(id=pk) instance.rating = rating instance.description = description instance.rated = rated instance.save() rest_obj = Restaurant.objects.get(id=rest_id) temp = rest_obj.ratings_count * rest_obj.rating + rating rest_obj.ratings_count = rest_obj.ratings_count + 1 rest_obj.rating = temp / rest_obj.ratings_count rest_obj.save() UVinstance = UserVector.objects.get(user=request.data.get("user")) cats = RestaurantCat.objects.raw("SELECT * FROM \"Restaurant_restaurantcat\" WHERE restaurant_id = {}".format(rest_id)) #cats = RestaurantCat.objects.filter(restaurant=request.data.get("restaurant")) for cat in cats: title = cat.title delta = ratePreferenceTable[request.data.get("rating")] setattr(UVinstance, title, getattr(UVinstance, title) + delta) UVinstance.save() return Response({'id':instance.id,'restaurant':rest_id, 'user':user_id,'rating':rating, 'description':description, 'rated':rated}, status=status.HTTP_200_OK) <file_sep>from __future__ import unicode_literals from .serializers import * from rest_framework import viewsets, status from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework.permissions import AllowAny, IsAuthenticated from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view, permission_classes from django.contrib.auth import authenticate from .models import * from Restaurant.models import Restaurant from django.core.exceptions import ObjectDoesNotExist from django.forms.models import model_to_dict from .permissions import UserPermission from Restaurant.utils import * class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): if self.action == 'create' or self.action == 'retrieve': return (AllowAny(),) else: #return (AllowAny(),) return (IsAuthenticated(),UserPermission()) def retrieve(self, request, pk=None): try: is_restaurant = UserType.objects.get(user=pk).is_restaurant user_obj = User.objects.get(id=pk) res = {} res["user"] = user_obj.id res["username"] = user_obj.username res["email"] = user_obj.email res["first_name"] = user_obj.first_name res["last_name"] = user_obj.last_name res["last_login"] = user_obj.last_login res["date_joined"] = user_obj.date_joined if is_restaurant: try: restaurant = Restaurant.objects.get(user=pk).id except ObjectDoesNotExist: restaurant = 0 res["restaurant"] = restaurant return Response(res, status=status.HTTP_200_OK) else: return Response(res, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({'error': 'User not found.'}, status=status.HTTP_404_NOT_FOUND) def create(self, request): serializers = UserSerializerWithToken(data=request.data) if serializers.is_valid(): serializers.save() try: usertype = request.data.get("usertype") instance = UserType(user = User.objects.get(username=request.data.get("username")), is_restaurant = True) if usertype == 'restaurant' else UserType(user = User.objects.get(username=request.data.get("username")), is_common = True) instance.save() if usertype == "common": preference_list = request.data.get("preference", None) if preference_list: PreferenceViewSet.setPreference(User.objects.get(username=request.data.get("username")), preference_list) return Response(serializers.data, status=status.HTTP_201_CREATED) except: instance = User.objects.get(username = request.data.get("username")).delete() return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) class PreferenceViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' and self.action == 'retrieve': return (AllowAny(),) else: #return (AllowAny(),) return (IsAuthenticated(),UserPermission()) def retrieve(self, request, pk=None): ps = Preference.objects.filter(user = pk) l = [] for p in ps: l += [p.preference] return Response({"user":pk, "perference":l}, status=status.HTTP_200_OK) def update(self, request, pk=None): if pk != request.user.id: return Response({"detail": "You do not have permission to perform this action."}, status=status.HTTP_403_FORBIDDEN) self.setPreference(User.objects.get(id=pk), request.data.get("preference")) return Response({"user":pk, "preference":request.data.get("preference")}, status=status.HTTP_200_OK) @classmethod def setPreference(self, user_obj, p_list): if not UserType.objects.get(user = user_obj).is_common: return ps = Preference.objects.filter(user = user_obj.id) if ps: for p in ps: instance = UserVector.get(user=user_obj.id) setattr(instance, p, getattr(instance, p) - initPreferenceWeight) instance.save() for p in p_list: instance = Preference(user=user_obj, preference=p) instance.save() try: instance = UserVector.objects.get(user=user_obj.id) except ObjectDoesNotExist: instance = UserVector(user=user_obj) setattr(instance, p, getattr(instance, p) + initPreferenceWeight) instance.save() class UserTypeViewSet(viewsets.ModelViewSet): queryset = UserType.objects.all() serializer_class = UserTypeSerializer def get_permissions(self): if self.action == 'create' and self.action == 'retrieve': return (AllowAny(),) else: return (IsAuthenticated(),UserPermission()) class UserVectorViewSet(viewsets.ModelViewSet): queryset = UserVector.objects.all() serializer_class = UserVectorSerializer @csrf_exempt @api_view(['POST',]) @permission_classes((AllowAny,)) def login(request): username = request.data.get("username") password = request.data.get("<PASSWORD>") is_restaurant = request.data.get("is_restaurant", False) if not is_restaurant: is_common = request.data.get("is_common", False) if username is None or password is None: return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST) try: user = User.objects.get(username=username) except User.DoesNotExist: return Response({'error': 'User not found.'}, status=status.HTTP_404_NOT_FOUND) else: if user.check_password(password): token, _ = Token.objects.get_or_create(user=user) userType = UserType.objects.get(user=user.id) if (userType.is_restaurant and is_restaurant) or (userType.is_common and is_common): return Response({'token': token.key, 'id': user.id}, status=status.HTTP_200_OK) else: return Response({'error': 'Incorrect user type.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'error': 'Invalid password.'}, status=status.HTTP_401_UNAUTHORIZED) <file_sep>from __future__ import unicode_literals from .models import * from .serializers import * from rest_framework import viewsets, status from rest_framework.response import Response from User.models import UserVector from .recommander import * from Reservation.models import PastOrderReview from .utils import columnNames import random from django.contrib.auth.models import User from User.serializers import * from TakeANumber.models import WSNumber id= 400 class RestaurantViewSet(viewsets.ModelViewSet): serializer_class = RestaurantSerializer def get_queryset(self): user_id = self.request.query_params.get('user', None) isCommon = self.request.query_params.get('is_common', False) city = self.request.query_params.get('city', None) if user_id is not None: if not isCommon: queryset = Restaurant.objects.all() queryset = queryset.filter(user=user_id) else: ids = set() SUs = getSimilarUsers(user_id, 1) rest_lists = [] rest_lists += PastOrderReview.objects.filter(user__in=SUs, rating__gt=3).order_by("-rating").only('restaurant') rest_lists += PastOrderReview.objects.filter(user=user_id, rating__gt=3).order_by("-rating").only('restaurant') i = 0 for rest in rest_lists: if i >= 4: break if city and rest.restaurant.city == city: ids.add(rest.restaurant.id) i += 1 distr = getCategoryList(user_id, 10-i) rest_lists = [] for index, count in enumerate(distr): type = columnNames[index+1] if not count: continue rest_lists += Restaurant.objects.raw("Select * from \"Restaurant_restaurant\" as T1 INNER JOIN \"Restaurant_restaurantcat\" as T2 ON T1.id = T2.restaurant_id WHERE title = \'{}\' Order By ratings_count*rating limit \'{}\';".format(type, count)) for rest in rest_lists: if city and rest.city == city: ids.add(rest.id) rest_lists = list(ids) random.shuffle(rest_lists) rest_lists = rest_lists[0:10] queryset = Restaurant.objects.filter(id__in=rest_lists).order_by("-rating") return queryset query = self.request.query_params.get('query', None) price = self.request.query_params.get('price', None) popular = self.request.query_params.get('popular', False) if popular: queryset = Restaurant.objects.order_by('-rating','-ratings_count') else: queryset = Restaurant.objects.all() if query is not None: #queryset = queryset.filter(name=name) rest_lists = Restaurant.objects.raw( "(SELECT * FROM \"Restaurant_restaurant\" WHERE name LIKE \'%%{}%%\') UNION (SELECT * FROM \"Restaurant_restaurant\" WHERE address LIKE \'%%{}%%\');".format(query,query)) queryset = Restaurant.objects.filter(id__in=map(lambda rest:rest.id, rest_lists)) if city is not None: queryset = queryset.filter(city=city) if price is not None: queryset = queryset.filter(price=price) return queryset def update(self, request, pk): old_ins = Restaurant.objects.get(pk=pk) user = request.data.get('user') old_ins.address = request.data.get('address') old_ins.city = request.data.get('city') old_ins.state = request.data.get('state') old_ins.name = request.data.get('name') old_ins.photo_url = request.data.get('photo_url') old_ins.ratings_count = request.data.get('ratings_count', 0) old_ins.rating = request.data.get('rating', 0.0) old_ins.price = request.data.get('price') old_ins.phone_num = request.data.get('phone_num') l = request.data.get('categories', None) RestaurantCat.objects.filter(restaurant=old_ins.id).delete() old_ins.save() if l is not None: iniGen(old_ins, l) return Response({'id': old_ins.id, 'user': user, 'address': old_ins.address,'city': old_ins.city,'state': old_ins.state,'photo_url': old_ins.photo_url,'name': old_ins.name,'phone_num': old_ins.phone_num,'price': old_ins.price,'ratings_count': old_ins.ratings_count, 'rating':old_ins.rating,'categories':l}, status=status.HTTP_200_OK) def create(self, request): #global id #id = id + 1 user = request.data.get('user') address = request.data.get('address') city = request.data.get('city') state = request.data.get('state') name = request.data.get('name') photo_url = request.data.get('photo_url') ratings_count = request.data.get('ratings_count',0) rating = request.data.get('rating',1.0) price = request.data.get('price','$$') phone_num = request.data.get('phone_num',0) l = request.data.get('categories', None) old_ins = Restaurant(user=User.objects.get(pk=user), address=address,city=city,state=state,name=name,photo_url=photo_url,ratings_count=ratings_count,rating=rating,price=price,phone_num=phone_num) old_ins.save() ws_ins = WSNumber(restaurant=old_ins) ws_ins.save() if l is not None: iniGen(old_ins, l) return Response({'id': old_ins.id, 'user': user, 'address': old_ins.address,'city': old_ins.city,'state': old_ins.state,'photo_url': old_ins.photo_url,'name': old_ins.name,'phone_num': old_ins.phone_num,'price': old_ins.price,'ratings_count': old_ins.ratings_count, 'rating':old_ins.rating,'catogories':l}, status=status.HTTP_201_CREATED) class RestaurantCatViewSet(viewsets.ModelViewSet): serializer_class = RestaurantCatSerializer queryset = RestaurantCat.objects.all() def retrieve(self, request, pk=None): cat_l = RestaurantCat.objects.filter(restaurant=pk) l = [] for c in cat_l: l += [c.title] return Response({"restaurant":pk, "categories":l}, status=status.HTTP_200_OK) def get_queryset(self): cat = self.request.query_params.get('catogory', None) queryset = RestaurantCat.objects.all() if cat is not None: queryset = queryset.filter(title=cat) return queryset def iniGen(restaurant, l): for cat in l: instance = RestaurantCat(restaurant = restaurant, title=cat) instance.save() <file_sep>from django.db import models from Table.models import TableType from Restaurant.models import Restaurant from django.contrib.auth.models import User class WSNumber(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) waitingNumber = models.IntegerField(default=0) servedNumber = models.IntegerField(default=0) class WaitingUser(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) myNumber = models.IntegerField() first_name = models.CharField(max_length=100, null = True) <file_sep>from rest_framework import permissions from django.contrib.auth.models import User class UserPermission(permissions.BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): if isinstance(obj, User): return request.method in ("GET", "HEAD") or request.user.id == obj.id else: return False <file_sep>self.__precacheManifest = [ { "revision": "a1a17ca01bb25db76a51d27f2fff5a4e", "url": "/static/media/restHome.a1a17ca0.jpg" }, { "revision": "252051bf4fce95657cdb397d4c3739e8", "url": "/static/media/background.252051bf.jpg" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.42ac5946.js" }, { "revision": "fc42189aff04c0024ab7", "url": "/static/js/main.fc42189a.chunk.js" }, { "revision": "064eff8c398b4bb6cacf", "url": "/static/js/2.064eff8c.chunk.js" }, { "revision": "fc42189aff04c0024ab7", "url": "/static/css/main.1b3b4553.chunk.css" }, { "revision": "064eff8c398b4bb6cacf", "url": "/static/css/2.5cd13b6a.chunk.css" }, { "revision": "8a0555c80b3cf7297761f768afe38a42", "url": "/index.html" } ];<file_sep>import uuid from django.db import connection def uuidToStr(): return str(uuid.uuid4()) def executeSQL(sql): with connection.cursor() as cursor: res = cursor.execute(sql) return(res) <file_sep>from django.urls import path from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'restaurants', RestaurantViewSet, basename='restaurant') router.register(r'restaurants-cat', RestaurantCatViewSet, basename='restaurantCat') #router.register(r'reviews', RestaurantReviewViewSet, basename='restaurantReview') urlpatterns = router.urls <file_sep>from django.db import models from Restaurant.models import Restaurant from datetime import datetime, date from django.db.models import DateTimeField class TableType(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) type = models.CharField(max_length=30, null=True) # description supportedNum = models.IntegerField(default=1) # how many tables do we have class TableData(models.Model): tableType = models.ForeignKey(TableType, on_delete=models.CASCADE) type = models.CharField(max_length=30, null=True) # description restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) remainNum = models.IntegerField(default=0) dateTime = DateTimeField(auto_now=False) <file_sep>from django.urls import path from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'preferences', PreferenceViewSet) router.register(r'user-type', UserTypeViewSet) router.register(r'user-vector', UserVectorViewSet) urlpatterns = router.urls <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from .utils import uuidToStr from User.models import * from django.contrib.auth.models import User class Restaurant(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) address = models.CharField(max_length=100, null=True) city = models.CharField(max_length=50) state = models.CharField(max_length=50) name = models.CharField(max_length=100) photo_url = models.CharField(max_length=200) ratings_count = models.IntegerField(default=0) rating = models.DecimalField(default=1.0, decimal_places=1, max_digits=2) price = models.CharField(max_length=10, null=True) phone_num = models.CharField(max_length=100, null=True) class RestaurantCat(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) title = models.CharField(max_length=50) <file_sep>from django.db import connection def executeSQL(sql): with connection.cursor() as cursor: res = cursor.execute(sql) return(res) <file_sep># Instantler serves customers by providing a platform with registered restaurants that helps customers with table reservation and queue management.
aa269e92a7658ecc1649f61d9cedb4cac8775684
[ "JavaScript", "Markdown", "Python", "Text", "Shell" ]
37
Shell
YujiaYan0709/Instantler
283055a5c9a144763b16e37c4166474ebec2cd46
9e990a813132ddefe2574f69393cc1f51d4c3cc2
refs/heads/master
<repo_name>Shadoweh/Holidays<file_sep>/Holidays.Api/Models/HolidayNameModel.cs using Newtonsoft.Json; namespace Holidays.Api.Models { public class HolidayNameModel { [JsonProperty("lang")] public string Language { get; set; } [JsonProperty("text")] public string Name { get; set; } } } <file_sep>/Holidays.Api/Exceptions/HolidayApiException.cs using System; namespace Holidays.Api.Exceptions { public class HolidayApiException : Exception { public HolidayApiException(string message) : base(message) { } } }<file_sep>/Holidays.Api/Repositories/HolidayRepository.cs using Holidays.Api.Exceptions; using Holidays.Api.Interfaces.Repositories; using Holidays.Api.Models; using Newtonsoft.Json; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Holidays.Api.Repositories { public class HolidayRepository : IHolidayRepository { private readonly HttpClient _holidayHttpClient; public HolidayRepository(HttpClient holidayHttpClient) { _holidayHttpClient = holidayHttpClient; } public async Task<IEnumerable<CountryModel>> GetCountries() { var response = await _holidayHttpClient.GetAsync("?action=getSupportedCountries"); if (!response.IsSuccessStatusCode) { throw new HolidayApiException("Failed to retrieve supported countries"); } var content = await response.Content.ReadAsStringAsync(); var countries = JsonConvert.DeserializeObject<IEnumerable<CountryModel>>(content); return countries; } public async Task<IEnumerable<HolidayModel>> GetHolidaysByCountryAndYear(string country, string region, int year) { var paramsQuery = new StringBuilder($"?action=getHolidaysForYear&year={year}&country={country}"); if (!string.IsNullOrEmpty(region)) { paramsQuery.Append($"&region={region}"); } paramsQuery.Append("&holidayType=public_holiday"); var response = await _holidayHttpClient.GetAsync(paramsQuery.ToString()); if (!response.IsSuccessStatusCode) { throw new HolidayApiException("Failed to retrieve holidays"); } var content = await response.Content.ReadAsStringAsync(); var holidays = JsonConvert.DeserializeObject<IEnumerable<HolidayModel>>(content); return holidays; } } } <file_sep>/Holidays.Api/Interfaces/Services/IHolidayService.cs using Holidays.Api.Models.Response; using System.Collections.Generic; using System.Threading.Tasks; namespace Holidays.Api.Interfaces.Services { public interface IHolidayService { Task<IEnumerable<string>> GetCountries(); Task<IEnumerable<HolidaysByMonthResponseModel>> GetHolidaysGrouppedByMonth(string country, string region, int year); } } <file_sep>/Holidays.Api/Models/CountryModel.cs using System; using System.Collections.Generic; namespace Holidays.Api.Models { public class CountryModel { public string CountryCode { get; set; } public IEnumerable<string> Regions { get; set; } public IEnumerable<string> HolidayTypes { get; set; } public string FullName { get; set; } public HolidayDateModel FromDate { get; set; } public HolidayDateModel ToDate { get; set; } } } <file_sep>/Holidays.Api/Models/HolidayModel.cs using System.Collections.Generic; namespace Holidays.Api.Models { public class HolidayModel { public HolidayDateModel Date { get; set; } public IEnumerable<HolidayNameModel> Name { get; set; } public string HolidayType { get; set; } } } <file_sep>/Holidays.Api/Interfaces/Repositories/IHolidayRepository.cs using Holidays.Api.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace Holidays.Api.Interfaces.Repositories { public interface IHolidayRepository { Task<IEnumerable<CountryModel>> GetCountries(); Task<IEnumerable<HolidayModel>> GetHolidaysByCountryAndYear(string country, string region, int year); } } <file_sep>/Holidays.Api/Models/Response/HolidaysByMonthResponseModel.cs using System.Collections.Generic; namespace Holidays.Api.Models.Response { public class HolidaysByMonthResponseModel { public int Month { get; set; } public IEnumerable<HolidayResponseModel> Holidays { get; set; } } } <file_sep>/Holidays.Api/Models/Response/HolidayResponseModel.cs using System; namespace Holidays.Api.Models.Response { public class HolidayResponseModel { public DateTime Date { get; set; } public string Name { get; set; } } } <file_sep>/Holidays.Api/Services/HolidayService.cs using Holidays.Api.Interfaces.Repositories; using Holidays.Api.Interfaces.Services; using Holidays.Api.Models; using Holidays.Api.Models.Response; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Holidays.Api.Services { public class HolidayService : IHolidayService { private readonly IHolidayRepository _holidayRepository; public HolidayService(IHolidayRepository holidayRepository) { _holidayRepository = holidayRepository; } public async Task<IEnumerable<string>> GetCountries() { var countries = await _holidayRepository.GetCountries(); return countries.Select(x => x.FullName); } public async Task<IEnumerable<HolidaysByMonthResponseModel>> GetHolidaysGrouppedByMonth(string country, string region, int year) { var holidays = await _holidayRepository.GetHolidaysByCountryAndYear(country, region, year); var holidaysByMonth = holidays.GroupBy(x => x.Date.Month); var result = holidaysByMonth.Select(x => new HolidaysByMonthResponseModel { Month = x.Key, Holidays = x.Select(y => new HolidayResponseModel { Date = new DateTime(y.Date.Year, y.Date.Month, y.Date.Day), Name = (y.Name.FirstOrDefault(z => z.Language == "en") ?? y.Name.First()).Name }) }); return result; } } } <file_sep>/Holidays.Api/Controllers/HolidayController.cs using Holidays.Api.Interfaces.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Holidays.Api.Controllers { [ApiController] [Route("api/v1/[controller]/[action]")] public class HolidayController : Controller { private readonly IHolidayService _holidayService; public HolidayController(IHolidayService holidayService) { _holidayService = holidayService; } [HttpGet] public async Task<IActionResult> GetCountries() { var countries = await _holidayService.GetCountries(); return Ok(countries); } [HttpGet] public async Task<IActionResult> GetHolidaysGrouppedByMonth(string country, int year, string region = null) { if (string.IsNullOrEmpty(country) || year == 0) { return BadRequest("Empty country or year"); } var holidaysByMonth = await _holidayService.GetHolidaysGrouppedByMonth(country, region, year); return Ok(holidaysByMonth); } } }
fe59960d00fa40b17da2b8cd64061f3551b8d4c6
[ "C#" ]
11
C#
Shadoweh/Holidays
2c10ac42e8f3b984d05e9c90fb2a43e1d12dce8e
c53fda7de12c37edee66dfe8bdc76f84bcb72f8a
refs/heads/main
<repo_name>Neskoff/wordoftheday-backend<file_sep>/src/main/java/com/rbt/wordoftheday/webControllers/PrizeController.java package com.rbt.wordoftheday.webControllers; import com.rbt.wordoftheday.domain.Prize; import com.rbt.wordoftheday.services.prizeService.PrizeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; @Controller public class PrizeController { @Autowired private PrizeService prizeService; @PostMapping("/home/newPrize") public String newPrize(@Valid Prize newprize) { Prize p = new Prize(0, RootController.currentListId, newprize.getPrize(), 0); this.prizeService.insertNewPrize(p); RootController.campaignsRedirect = false; RootController.wordsRedirect = false; RootController.prizesRedirect = true; return "redirect:/home"; } @PostMapping("/home/deletePrize") public String deletePrize(@Valid Prize newprize) { this.prizeService.deletePrize(newprize.getId()); RootController.campaignsRedirect = false; RootController.wordsRedirect = false; RootController.prizesRedirect = true; return "redirect:/home"; } } <file_sep>/src/main/java/com/rbt/wordoftheday/services/userService/UserService.java package com.rbt.wordoftheday.services.userService; import com.rbt.wordoftheday.domain.User; public interface UserService { boolean sendMessage(String email, String prize); boolean insertUser(User user); } <file_sep>/src/main/java/com/rbt/wordoftheday/WordofthedayApplication.java package com.rbt.wordoftheday; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WordofthedayApplication { public static void main(String[] args) { SpringApplication.run(WordofthedayApplication.class, args); } } <file_sep>/src/main/java/com/rbt/wordoftheday/services/prizeListService/PrizeListServiceImpl.java package com.rbt.wordoftheday.services.prizeListService; import com.rbt.wordoftheday.domain.PrizeList; import com.rbt.wordoftheday.repositories.PrizeListRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class PrizeListServiceImpl implements PrizeListService { @Autowired private PrizeListRepository prizeListRepository; @Override public PrizeList getCurrentPrizeList() { return this.prizeListRepository.findByIsactiveIsTrue(); } @Override public List<PrizeList> getInactivePrizeLists() { return this.prizeListRepository.findAllByIsactiveIsFalse(); } @Override public boolean insertPrizeList(PrizeList prizeList) { return this.prizeListRepository.insertPrizeList(prizeList.isIsactive()) != 0 ; } @Override public boolean resetPrizeList() { return this.prizeListRepository.resetPrizeList() != 0; } @Override public boolean updateCurrentPrizeList(int Id) { return this.prizeListRepository.updateCurrentPrizeList(Id) != 0; } } <file_sep>/src/main/java/com/rbt/wordoftheday/domain/PrizeList.java package com.rbt.wordoftheday.domain; import javax.persistence.*; @Entity @Table(name = "prizelists") public class PrizeList { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "isactive") private boolean isactive; public PrizeList() { } public PrizeList(int id, boolean isactive) { this.id = id; this.isactive = isactive; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isIsactive() { return isactive; } public void setIsactive(boolean isactive) { this.isactive = isactive; } } <file_sep>/wotd_db.sql CREATE SEQUENCE Users_seq START 1 INCREMENT 1; CREATE SEQUENCE Admins_seq START 1 INCREMENT 1; CREATE SEQUENCE Words_seq START 1 INCREMENT 1; CREATE SEQUENCE PrizeList_seq START 1 INCREMENT 1; CREATE SEQUENCE Campaigns_seq START 1 INCREMENT 1; CREATE SEQUENCE Prize_seq START 1 INCREMENT 1; CREATE TABLE Users( Id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('Users_seq'), Username VARCHAR(30) NOT NULL, Email VARCHAR(50), BirthDate VARCHAR(10) ); CREATE TABLE Admins( Id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('Admins_seq'), Username VARCHAR(30) NOT NULL, Password VARCHAR(100) NOT NULL ); CREATE TABLE Words( Id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('Words_seq'), Word VARCHAR(30) NOT NULL, Is_word_of_the_day BOOLEAN NOT NULL ); CREATE TABLE PrizeLists( Id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('PrizeList_seq'), isActive BOOLEAN NOT NULL ); CREATE TABLE Prizes( PrizeListId INT NOT NULL, PrizeId INT NOT NULL DEFAULT NEXTVAL('Prize_seq'), Prize VARCHAR(30) NOT NULL, TimesSelected INT NOT NULL, CONSTRAINT Fk_PrizeList FOREIGN KEY(PrizeListId) REFERENCES PrizeLists(Id), PRIMARY KEY(PrizeListId, PrizeId) ); CREATE TABLE Campaigns( Id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('Campaigns_seq'), Name VARCHAR(30) NOT NULL, isactive BOOLEAN NOT NULL ); CREATE TABLE Reports( CampaignId INT PRIMARY KEY , NoUsers INT NOT NULL, NoCorrect INT NOT NULL, NoFail INT NOT NULL, CONSTRAINT Fk_CampaingId FOREIGN KEY(CampaignId) REFERENCES Campaigns(Id) ); --To avoid errors alter sequences after tables have been created ALTER SEQUENCE Users_seq OWNED BY Users.Id; ALTER SEQUENCE Admins_seq OWNED BY Admins.Id; ALTER SEQUENCE Words_seq OWNED BY Words.Id; ALTER SEQUENCE PrizeList_seq OWNED BY PrizeLists.Id; ALTER SEQUENCE Campaigns_seq OWNED BY Campaigns.Id; ALTER SEQUENCE Prize_seq OWNED BY Prizes.PrizeId; --Insert Test Data INSERT INTO Admins(Username, Password) VALUES ('Ilija','<PASSWORD>'); INSERT INTO Words(Word, Is_word_of_the_day) VALUES ('Jelena',TRUE); INSERT INTO Words(word, is_word_of_the_day) VALUES ('Ilija',FALSE); INSERT INTO Campaigns(name, isactive) VALUES ('Campaign 1', TRUE); INSERT INTO Campaigns(name, isactive) VALUES ('Campaign 2', FALSE); INSERT INTO Reports(campaignid, nousers, nocorrect, nofail) VALUES (1,0,0,0); INSERT INTO PrizeLists(isActive) VALUES (TRUE); INSERT INTO PrizeLists(isActive) VALUES (FALSE); INSERT INTO Prizes(prizelistid, prize, timesselected) VALUES (1 'Prize 1', 0); INSERT INTO Prizes(prizelistid, prize, timesselected) VALUES (1 'Prize 2', 0); INSERT INTO Prizes(prizelistid, prize, timesselected) VALUES (1 'Prize 3', 0); <file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:postgresql://localhost:5432/wordoftheday spring.datasource.username=ilija spring.datasource.password=<PASSWORD> spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=<EMAIL> spring.mail.password=<PASSWORD> spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true <file_sep>/src/main/java/com/rbt/wordoftheday/domain/Report.java package com.rbt.wordoftheday.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "reports") public class Report { @Id @Column(name ="campaignid") private int CampaignId; @Column(name = "nousers") private int NoUsers; @Column(name = "nocorrect") private int NoCorrect; @Column(name = "nofail") private int NoFail; public Report() { } public Report(int campaignId, int noUsers, int noCorrect, int noFail) { CampaignId = campaignId; NoUsers = noUsers; NoCorrect = noCorrect; NoFail = noFail; } public int getCampaignId() { return CampaignId; } public int CampaignId() { return CampaignId; } public void setCampaignId(int campaignId) { CampaignId = campaignId; } public int getNoUsers() { return NoUsers; } public int NoUsers() { return NoUsers; } public void setNoUsers(int noUsers) { NoUsers = noUsers; } public int getNoCorrect() { return NoCorrect; } public int NoCorrect() { return NoCorrect; } public void setNoCorrect(int noCorrect) { NoCorrect = noCorrect; } public int getNoFail() { return NoFail; } public int NoFail() { return NoFail; } public void setNoFail(int noFail) { NoFail = noFail; } } <file_sep>/src/main/java/com/rbt/wordoftheday/domain/Prize.java package com.rbt.wordoftheday.domain; import javax.persistence.*; @Entity @Table(name = "prizes") public class Prize { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "prizeid") private int id; @Column(name = "prizelistid") private int prizelistid; @Column(name = "prize") private String prize; @Column(name = "timesselected") private int timesselected; public Prize() { } public Prize(int id, int prizelistid, String prize, int timesselected) { this.id = id; this.prizelistid = prizelistid; this.prize = prize; this.timesselected = timesselected; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPrizelistid() { return prizelistid; } public void setPrizelistid(int prizelistid) { this.prizelistid = prizelistid; } public String Prize() { return prize; } public String getPrize() { return prize; } public void setPrize(String prize) { this.prize = prize; } public int getTimesselected() { return timesselected; } public void setTimesselected(int timesselected) { this.timesselected = timesselected; } } <file_sep>/src/main/java/com/rbt/wordoftheday/services/reportService/ReportService.java package com.rbt.wordoftheday.services.reportService; import com.rbt.wordoftheday.domain.Report; public interface ReportService { Report getCampaignReport(int id); boolean insertCampaignReport(Report report); boolean updateCampaignReport(Report report); } <file_sep>/src/main/java/com/rbt/wordoftheday/services/campaignService/CampaignService.java package com.rbt.wordoftheday.services.campaignService; import com.rbt.wordoftheday.domain.Campaign; import java.util.List; public interface CampaignService { Campaign getCurrentCampaign(); List<Campaign> getAllCampaigns(); boolean resetCampaigns(); boolean updateCampaign(Campaign campaign); boolean updateName(Campaign campaign); boolean insertNewCampaign(Campaign campaign); } <file_sep>/src/main/java/com/rbt/wordoftheday/repositories/AdminRepository.java package com.rbt.wordoftheday.repositories; import com.rbt.wordoftheday.domain.Admin; import org.springframework.data.repository.CrudRepository; public interface AdminRepository extends CrudRepository<Admin, Long> { int countByUsernameAndPassword(String Username, String Password); } <file_sep>/src/main/java/com/rbt/wordoftheday/services/adminService/AdminServiceImpl.java package com.rbt.wordoftheday.services.adminService; import com.rbt.wordoftheday.repositories.AdminRepository; import com.rbt.wordoftheday.services.adminService.AdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AdminServiceImpl implements AdminService { @Autowired private AdminRepository adminRepository; @Override public boolean adminExists(String Username, String Password) { return this.adminRepository.countByUsernameAndPassword(Username, Password) != 0; } } <file_sep>/src/main/java/com/rbt/wordoftheday/domain/Word.java package com.rbt.wordoftheday.domain; import javax.persistence.*; @Entity @Table(name = "words") public class Word { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "word") private String word; @Column(name = "isWordOfTheDay") private boolean wordOfTheDay; public Word() { } public Word(int id, String word, boolean wordOfTheDay) { this.id = id; this.word = word; this.wordOfTheDay = wordOfTheDay; } public int getId() { return id; } public void setId(int id) { this.id = id; } //Thymeleaf Compatibility public String Word() { return word; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public void setWordOfTheDay(boolean wordOfTheDay) { this.wordOfTheDay = wordOfTheDay; } public boolean isWordOfTheDay() { return wordOfTheDay; } } <file_sep>/src/main/java/com/rbt/wordoftheday/domain/User.java package com.rbt.wordoftheday.domain; import javax.persistence.*; @Entity @Table(name = "uses") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int Id; private String Username; private String Email; private String BirthDate; public User(){}; public User(int id, String username, String email, String birthDate) { Id = id; Username = username; Email = email; BirthDate = birthDate; } public int getId() { return Id; } public String getUsername() { return Username; } public String getEmail() { return Email; } public String getBirthDate() { return BirthDate; } public void setId(int id) { Id = id; } public void setUsername(String username) { Username = username; } public void setEmail(String email) { Email = email; } public void setBirthDate(String birthDate) { BirthDate = birthDate; } } <file_sep>/src/main/java/com/rbt/wordoftheday/resources/AdminResource.java package com.rbt.wordoftheday.resources; import com.rbt.wordoftheday.services.adminService.AdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/admins") public class AdminResource { @Autowired private AdminService adminService; @GetMapping public ResponseEntity<Boolean> adminExists(String Username, String Password) { return ResponseEntity.ok(this.adminService.adminExists(Username, Password)); } } <file_sep>/src/main/java/com/rbt/wordoftheday/services/prizeService/PrizeService.java package com.rbt.wordoftheday.services.prizeService; import com.rbt.wordoftheday.domain.Prize; import java.util.List; public interface PrizeService { List<Prize> findAllByPrizeListId(int id); boolean updateTimesSelected(Prize prize); boolean insertNewPrize(Prize prize); boolean deletePrize(int Id); } <file_sep>/src/main/java/com/rbt/wordoftheday/webControllers/RootController.java package com.rbt.wordoftheday.webControllers; import com.rbt.wordoftheday.domain.*; import com.rbt.wordoftheday.services.campaignService.CampaignService; import com.rbt.wordoftheday.services.prizeListService.PrizeListService; import com.rbt.wordoftheday.services.prizeService.PrizeService; import com.rbt.wordoftheday.services.reportService.ReportService; import com.rbt.wordoftheday.services.wordService.WordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import java.util.List; @Controller public class RootController { @Autowired private WordService wordService; @Autowired private CampaignService campaignService; @Autowired private ReportService reportService; @Autowired private PrizeListService prizeListService; @Autowired private PrizeService prizeService; public static String currentAdmin; public static Word currentWordOfTheDay; public static String resultSet = ""; public static boolean wordsRedirect = true; public static boolean campaignsRedirect; public static boolean prizesRedirect; public static int currentListId; private void generateModelAttributes(Model model) { currentWordOfTheDay = this.wordService.findByWordOfTheDayIsTrue(); List<Word> allWords = this.wordService.allWords(); Campaign currentCampaign = this.campaignService.getCurrentCampaign(); List<Campaign> allCampaigns = this.campaignService.getAllCampaigns(); Report currentReport = this.reportService.getCampaignReport(currentCampaign.getId()); PrizeList currentPrizeList = this.prizeListService.getCurrentPrizeList(); currentListId = currentPrizeList.getId(); List<PrizeList> allPrizeLists = this.prizeListService.getInactivePrizeLists(); List<Prize> currentPrizes = this.prizeService.findAllByPrizeListId(currentPrizeList.getId()); this.feedback(); model.addAttribute("name", currentAdmin); model.addAttribute("WOTD", currentWordOfTheDay); model.addAttribute("allWords", allWords); model.addAttribute("currentCampaign", currentCampaign); model.addAttribute("allCampaigns", allCampaigns); model.addAttribute("currentReport", currentReport); model.addAttribute("campaignsRedirect", campaignsRedirect); model.addAttribute("wordsRedirect", wordsRedirect); model.addAttribute("prizesRedirect", prizesRedirect); model.addAttribute("newCampaign",new Campaign()); model.addAttribute("currentPrizeList", currentPrizeList); model.addAttribute("allPrizeLists", allPrizeLists); model.addAttribute("currentPrizes", currentPrizes); model.addAttribute("newPrizes", new Prize()); } @ModelAttribute("resultSet") public String feedback() { return resultSet; } @GetMapping("/home") public String getHomePage(Model model) { if (currentAdmin == null) { return "redirect:/"; } else { generateModelAttributes(model); return "index"; } } } <file_sep>/src/main/java/com/rbt/wordoftheday/services/reportService/ReportServiceImpl.java package com.rbt.wordoftheday.services.reportService; import com.rbt.wordoftheday.domain.Report; import com.rbt.wordoftheday.repositories.ReportRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ReportServiceImpl implements ReportService { @Autowired private ReportRepository reportRepository; @Override public Report getCampaignReport(int id) { return this.reportRepository.getCampaignReport(id); } @Override public boolean insertCampaignReport(Report report) { return this.reportRepository.insertCampaignReport(report.CampaignId(), report.getNoUsers(), report.getNoCorrect(), report.getNoFail()) != 0; } @Override public boolean updateCampaignReport(Report report) { return this.reportRepository.updateCampaignReport(report.CampaignId(), report.getNoUsers(), report.getNoCorrect(), report.getNoFail()) != 0; } }
d5fe2e71a4eaa7cba178c4da80ada33ff3f9a5b0
[ "Java", "SQL", "INI" ]
19
Java
Neskoff/wordoftheday-backend
25af3376d8b12a546db37e67e70086b1aa1459dd
c1a23b9795e25efa24c3955ce423f6c92c70443d
refs/heads/master
<file_sep><?php //Desde aca manejaremos la aplicacion. require_once 'controllers/errores.php'; class App { function __construct () { $url = isset($_GET['url']) ? $_GET['url'] : NULL; $url = rtrim($url, '/'); //quitar los slash del URL. $url = explode('/', $url); //Dividir URL por slashs. //si un usuario ha iniciado sesion if( isset( $_SESSION['usuario'] ) ){ //si no se ingresa ningun controlador if (empty($url[0])) { $archivoController = 'controllers/main.php'; require_once $archivoController; $controller = new Main(); $controller->loadModel('main'); $controller->setUsuario($_SESSION['usuario']); $controller->render(); //funcion para aparecer en pantalla. return false; } //convertimos el URL en un directorio para cargar controladores. $archivoController = 'controllers/' . $url[0] . '.php'; if ( file_exists($archivoController) ) { require_once $archivoController; //inicializar el controlador $controller = new $url[0]; //URL[0] es el controlador $controller->loadModel($url[0]); $controller->setUsuario($_SESSION['usuario']); // # elementos del array URL $nparam = sizeof($url); if ($nparam > 1) { if ($nparam > 2) { $param = []; for ($i=2; $i < $nparam; $i++) { array_push($param, $url[$i]); } $controller->load($url[1], $param); }else { $controller->load($url[1]); } } else { $controller->render(); } } else { //en caso de que no encuentre el archivo... $controller = new Errores(); //esto muestra un mensaje de error. } } else { //DESDE AQUI ES EL IF DE USUARIO $archivoController = 'controllers/' . $url[0] . '.php'; if ( file_exists($archivoController) && $archivoController === 'controllers/restaurar.php' ||file_exists($archivoController) && $archivoController === 'controllers/contacto.php') { require_once $archivoController; $controller = new $url[0]; $controller->loadModel($url[0]); if ( isset($url[1]) ){ $controller->{$url[1]}(); } else{ $controller->render(); } } else { $archivoController = 'controllers/login.php'; require_once $archivoController; $controller = new Login(); $controller->loadModel('Login'); if ( isset($url[1]) ){ $controller->{$url[1]}(); } else{ $controller->render(); } } } } } ?> <file_sep><?php if (isset($this->error)) { ?> <div class="modal-back"> <div class="modal"> <div class="modal-header"> <p>Ha ocurrido un error!</p> </div> <div class="modal__box"> <p><?php echo $this->error;?></p> </div> <div class="bottom"> <button id="close-modal" class="botom">Ok</button> </div> </div> </div> <?php } ?><file_sep>document.addEventListener("DOMContentLoaded", function() { document.getElementById("formulario").addEventListener('submit', validarFormulario); }); function validarFormulario(evento) { var nombreruta = document.getElementById('nombre_ruta').value; var direccion = document.getElementById('direccion_ruta').value; if(nombreruta.length==0|| direccion.length == 0 ){ alert("Todos los campos son obligatorios"); return false } else if(nombreruta.length == 0|| /^\s+$/.test(nombreruta)) { alert('Debes llenar el campo ruta'); return false; } else if (direccion.length == 0 ) { alert('La direccion no puede estar vacia'); return false; }else if (direccion.length < 6) { alert ('La direccion debe ser más larga'); return false; } var select = document.getElementById("select").selectedIndex; if(select == null || select == 0){ alert("Debe seleccionar la unidad encargada de esta ruta"); return false; } return true }<file_sep><?php if ( $this->model->talleres->drop($param[0]) ) { $mensaje = 'Taller eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><?php require 'libs/classes/usuarios.class.php'; require 'source/usuarios/CRUD.php'; class UsuariosModel extends Model { public $usuarios; function __construct() { parent::__construct(); $this->usuarios = new usuariosCRUD(); } } ?><file_sep>(function(){ var formulario = document.getElementsByName('formulario')[0], elementos = formulario.elements, contrasena = document.getElementById('password1'), boton = document.getElementById('btn'); var validarPass = function(e){ if (formulario.password1.value == 0 || formulario.password2.value == 0 ) { alert("Todos los campos son obligatorios"); e.preventDefault() }else{ validarCambio(e); } } var validarCambio = function(e){ if (formulario.password1.value != formulario.password2.value){ alert("las contraseñas no coinciden"); e.preventDefault() }else{ expresion(e); } } var expresion = function(e){ var er = /^[a-z0-9]{5,20}$/i; var respuesta = er.test(contrasena.value); if (respuesta == false) { alert("La contraseña solo pude estar formada por alfanumericos, es decir no acepta signos como '$!&%¨:;.><*¨@', ni espacios y debe estar formada por mas de 5 caracteres."); e.preventDefault() }else{ confirmar(e); } } function confirmar(e) { var opcion = confirm("¿Estas seguro que quieres cambiar la contraseña?"); if (opcion == true) { } else { alert("se ha cancelado"); e.preventDefault() } document.getElementById("ejemplo").innerHTML = mensaje; } formulario.addEventListener("submit", validarPass); }()) <file_sep><?php if ( $this->model->vehiculos->drop($param[0]) ) { $mensaje = 'vehiculo Eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><?php if(isset($_POST['btn'])){ $password1 = ($_POST['password1'] !== "") ? $_POST['password1'] : NULL ; if($this->model->cambiar($password1)){ $this->view->mensaje = 'Cambio de contraseña efectuado con exito.'; $this->view->render('login/index'); } else{ $this->view->mensaje = 'No se pudo realizar el cambio de contraseña.'; $this->view->render('login/index'); } } ?><file_sep><?php class Bitacora extends Controller{ function __construct () { parent::__construct(); } function render () { if ($_SESSION['usuario'] == 'admin') { $this->view->mensaje = 'Bitacora del sistema'; $bitacora = $this->model->bitacora->get(); $this->view->bitacora = $bitacora; $this->view->render('bitacora/index'); }else{ $this->view->render('errores/bloquear'); } } public function load ($metodo, $param = null) { $ruta = 'source/bitacora/'.$metodo.'.php'; require_once $ruta; } } ?><file_sep> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Usuarios</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de usuarios</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarUsuario"> <div> <table> <tr> <th>ID</th><th>Nombre</th><th>Apellido</th><th>Username</th><th>C.I.</th><th>Contraseña</th><th>Rol</th> <th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-usuarios"> <?php foreach($this->usuarios as $row){ $usuario = new UsuariosClass(); $usuario = $row; ?> </tr > <tr id="fila-<?php echo $usuario->getId(); ?>"> <td><?php echo $usuario->getId(); ?></td> <td><?php echo $usuario->getNombre(); ?></td> <td><?php echo $usuario->getApellido(); ?></td> <td><?php echo $usuario->getUsuario(); ?></td> <td><?php echo $usuario->getCedula(); ?></td> <td><?php echo $usuario->getContrasena(); ?></td> <td><?php echo $usuario->getRol(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>usuarios/modificarUsuario/<?php echo $usuario->getId();?>">Modificar</a></td> <td> <button class="crud eliminar" data-id="<?php echo $usuario->getId(); ?>" <?php if ( $usuario->getId() == '1' ) {?> disabled="disabled" <?php }?>>Eliminar</button> </td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>usuarios/registrarUsuario">Registrar</a> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php require 'libs/classes/vehiculos.class.php'; require 'libs/classes/rutas.class.php'; require 'source/rutas/CRUD.php'; class RutasModel extends Model { public $rutas; function __construct() { parent::__construct(); $this->rutas = new rutasCRUD(); } } ?><file_sep><?php // Clase de usuario para BD class UsuariosClass { private $id_usuario; private $cedula; private $nombre; private $apellido; private $usuario; private $contrasena; private $rolusuario; public function getId() { return $this->id_usuario; } public function getCedula() { return $this->cedula; } public function getNombre() { return $this->nombre; } public function getApellido() { return $this->apellido; } public function getUsuario() { return $this->usuario; } public function getContrasena() { return $this->contrasena; } public function getRol() { return $this->rol; } //SETTERS public function setId($id) { $this->id_usuario = $id; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setApellido($apellido) { $this->apellido = $apellido; } public function setCedula($cedula) { $this->cedula = $cedula; } public function setUsuario($usuario) { $this->usuario = $usuario; } public function setContrasena($contrasena) { $this->contrasena = $contrasena; } public function setRol($rol) { $this->rol = $rol; } } ?><file_sep><?php class OpcionModel extends Model { public $rutas; function __construct() { parent::__construct(); } } ?><file_sep><?php require 'libs/classes/tipos.class.php'; require 'source/tipos/CRUD.php'; class TiposModel extends Model { public $tipos; function __construct() { parent::__construct(); $this->tipos = new tiposCRUD(); } } ?><file_sep><?php if(isset($_POST['modificarChofer'])) { $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $apellido = ($_POST['apellido'] !== "") ? $_POST['apellido'] : NULL; $telefono = ($_POST['telefono'] !== "") ? $_POST['telefono'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $cedula = ($_POST['cedula'] !== "") ? $_POST['cedula'] : NULL; if ($this->model->choferes->update(['nombre'=>$nombre, 'apellido'=>$apellido, 'placa'=>$placa, 'cedula'=>$cedula, 'telefono'=>$telefono])){ $this->view->mensaje = '¡Chofer Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('choferes/mensaje'); } else { $choferes = $this->model->choferes->get($param[0]); $vehiculos = $this->model->choferes->getVehiculos(); $this->view->vehiculos = $vehiculos; if (isset($choferes)){ $this->view->choferes = $choferes[0]; $this->view->render('choferes/actualizar'); } else { $this->view->mensaje = 'Chofer no encontrado'; $this->view->render('choferes/mensaje'); } } ?><file_sep><?php class Tipos extends Controller{ function __construct () { parent::__construct(); } function render () { $this->view->mensaje = 'Esta pagina controla los tipos mantenimientos'; $tipos = $this->model->tipos->get(); $this->view->tipos = $tipos; $this->view->render('tipos/index'); } public function load ($metodo, $param = null) { $ruta = 'source/tipos/'.$metodo.'.php'; require_once $ruta; } } ?> <file_sep><?php require 'libs/classes/vehiculos.class.php'; require 'libs/classes/choferes.class.php'; require 'source/choferes/CRUD.php'; class ChoferesModel extends Model { public $choferes; function __construct() { parent::__construct(); $this->choferes = new choferesCRUD(); } } ?><file_sep>CREATE TABLE usuarios ( id_usuario int not null AUTO_INCREMENT, cedula varchar (8), usuario varchar (15), nombre varchar (20), apellido varchar (20), contrasena varchar (20), rol varchar (20), primary key (id_usuario) ); INSERT INTO usuarios (id_usuario, cedula, usuario, nombre, apellido, contrasena, rol) VALUES ( 0, 1234, 'admin', 'admin', 'istrador', 'admin', 'admin'); CREATE TABLE bitacora ( id_bitacora int not null AUTO_INCREMENT, id_usuario int not null, fecha date, hora time, accion varchar (200), primary key (id_bitacora), CONSTRAINT fk_usuarios_bitacora foreign key (id_usuario) references usuarios (id_usuario) on delete cascade on update cascade ); CREATE TABLE taller ( id_taller int not null, rif varchar (10) not null, nombre varchar (30) not null, direccion varchar (200), primary key (nombre) ); CREATE TABLE vehiculos ( id_vehiculo int not null, placa varchar (10) not null, modelo varchar (20), funcionamiento varchar (20), primary key (placa) ); CREATE TABLE choferes( id_choferes int not null AUTO_INCREMENT, placa varchar (10), nombre varchar (20), apellido varchar (20), cedula varchar (8), telefono varchar (11), primary key (id_choferes), CONSTRAINT fk_placa_vehiculo foreign key (placa) references vehiculos (placa) on delete cascade on update cascade ); CREATE TABLE rutas ( id_ruta int not null AUTO_INCREMENT, placa varchar (10) not null, nombre_ruta varchar (50), direccion_ruta varchar (250), hora_salida time, primary key (id_ruta), CONSTRAINT fk2_placa foreign key (placa) references vehiculos (placa) on delete cascade on update cascade ); CREATE TABLE tipos ( id_tipos int not null, nombre_tipo varchar (50), descripcion varchar (200), tiempo varchar (20), primary key (nombre_tipo) ); CREATE TABLE mantenimientos ( id_mantenimiento int not null AUTO_INCREMENT, nombre_tipo varchar (30) not null, placa varchar (10) not null, nombre varchar (30) not null, costo varchar (30) not null, fecha date, primary key (id_mantenimiento), CONSTRAINT fk_nombre_tipo foreign key (nombre_tipo) references tipos (nombre_tipo) on delete cascade on update cascade, CONSTRAINT fk1_placa foreign key (placa) references vehiculos (placa) on delete cascade on update cascade, CONSTRAINT fk1_nombre foreign key (nombre) references taller (nombre) on delete cascade on update cascade ); CREATE TABLE reparaciones ( id_reparaciones int not null AUTO_INCREMENT, nombre varchar (30) not null, placa varchar (10) not null, costo varchar (30) not null, fecha date, descripcion varchar (200), primary key (id_reparaciones), CONSTRAINT fk_nombre foreign key (nombre) references taller (nombre) on delete cascade on update cascade, CONSTRAINT fk_placa foreign key (placa) references vehiculos (placa) on delete cascade on update cascade ); <file_sep><?php class tiposCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { $id= 0; $mayor = 0; try{ $query = $this->db->connect()->query('SELECT * FROM tipos'); while($row = $query->fetch()){ $item = new TiposCLass(); if ($row['id_tipos'] >= $mayor) { $mayor = $row['id_tipos']; } } $id = $mayor + 1; $query = $this->db->connect()->prepare('INSERT INTO tipos (id_tipos, nombre_tipo, descripcion, tiempo) VALUES(:id_tipos, :nombre_tipo, :descripcion, :tiempo )'); $query->execute(['id_tipos'=>$id, 'nombre_tipo'=>$data['nombre_tipo'], 'descripcion'=>$data['descripcion'], 'tiempo'=>$data['tiempo']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $nombre_tipo = null) { $items = []; try { if ( isset($nombre_tipo) ) { $query = $this->db->connect()->prepare('SELECT * FROM tipos WHERE nombre_tipo = :nombre_tipo'); $query->execute(['nombre_tipo'=>$nombre_tipo]); } else { $query = $this->db->connect()->query('SELECT * FROM tipos'); } while($row = $query->fetch()){ $item = new TiposCLass(); $item->setId($row['id_tipos']); $item->setNombre($row['nombre_tipo']); $item->setDescripcion($row['descripcion']); $item->setTiempo($row['tiempo']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM tipos WHERE id_tipos = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE tipos SET descripcion = :descripcion, tiempo = :tiempo WHERE nombre_tipo = :nombre_tipo'); $query->execute(['nombre_tipo'=>$data['nombre_tipo'], 'descripcion'=>$data['descripcion'], 'tiempo'=>$data['tiempo']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><?php if(isset($_POST['modificarUsuario'])) { $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $apellido = ($_POST['apellido'] !== "") ? $_POST['apellido'] : NULL; $usuario = ($_POST['usuario'] !== "") ? $_POST['usuario'] : NULL; $rol = ($_POST['rol'] !== "") ? $_POST['rol'] : NULL; $cedula = ($_POST['cedula'] !== "") ? $_POST['cedula'] : NULL; $contrasena = ($_POST['contrasena'] !== "") ? $_POST['contrasena'] : NULL; if ($this->model->usuarios->update(['nombre'=>$nombre, 'apellido'=>$apellido, 'contrasena'=>$contrasena, 'rol'=>$rol, 'usuario'=>$usuario, 'cedula'=>$cedula])){ $this->view->mensaje = '¡Usuario Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('usuarios/mensaje'); } else { $usuarios = $this->model->usuarios->get($param[0]); if (isset($usuarios)){ $this->view->usuarios = $usuarios[0]; $this->view->render('usuarios/actualizar'); } else { $this->view->mensaje = 'Usuario no encontrado'; $this->view->render('usuarios/mensaje'); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Vehiculos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>vehiculos/registrarVehiculo" method="POST" class="form" id="formulario" name="formulario" name="form"> <div class="form__box"> <div> <label for="placa">Placa:</label> <input type="text" maxlength="6" name="placa" id="placa" placeholder="ABC-123" data-patron="[A-Z]{3}[0-9]{3}" pattern="[A-Z]{3}[0-9]{3}" title="El formato debe coincidir con 3 letras mayúsculas y 3 números."/ required> <!-- validacion de la placa 3 letras y numeros --> </div> <div> <label for="modelo" >Modelo:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" maxlength="12" name="modelo" id="modelo" placeholder="Encava/Otro" pattern="[a-zA-Z]{3,12}$" required title="El formato solo acepta caracteres entre mayúsculas y minusculas"> </div> <div> <label for="funcionamiento">Funcionamiento:</label> <select name="funcionamiento" id="funcionamiento" class="select"> <option value="">...</option> <option value="Operativo">Operativo</option> <option value="Inoperante">Inoperante</option> </select> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit" onclick="validarFormulario()" >Agregar</button> <a href="<?php echo constant('URL')?>vehiculos" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/vehiculos/validarvehiculo.js"></script> <script src="<?php echo constant('URL')?>public/js/vehiculos/validacion.js"></script> </body> </html> <file_sep>document.getElementById("eliminar").addEventListener("click", function(e){ respuesta = confirm("¿Estas seguro que quieres eliminar?"); if (respuesta == false) { e.preventDefault() } }); <file_sep><?php class RutasClass { private $id_ruta; private $placa; private $nombre; private $direccion; private $hora_salida; public function getId() { return $this->id_ruta; } public function getPlaca() { return $this->placa; } public function getNombre() { return $this->nombre; } public function getDireccion() { return $this->direccion; } public function getHoraSalida() { return $this->hora_salida; } //SETTERS public function setId($id_ruta) { $this->id_ruta = $id_ruta; } public function setPlaca($placa) { $this->placa = $placa; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setDireccion($direccion) { $this->direccion = $direccion; } public function setHoraSalida($hora_salida) { $this->hora_salida = $hora_salida; } } ?><file_sep><?php class Talleres extends Controller{ function __construct () { parent::__construct(); } function render () { $this->view->mensaje = 'Esta pagina controla las talleres'; $talleres = $this->model->talleres->get(); $this->view->talleres = $talleres; $this->view->render('talleres/index'); } public function load ($metodo, $param = null) { $ruta = 'source/talleres/'.$metodo.'.php'; require_once $ruta; } } ?><file_sep> <?php if(isset($_POST['agregar'])){ $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $descripcion = ($_POST['descripcion'] !== "") ? $_POST['descripcion'] : NULL; $costo = ($_POST['costo'] !== "") ? $_POST['costo'] : NULL; $fecha = ($_POST['fecha'] !== "") ? $_POST['fecha'] : NULL; if ($this->model->reparaciones->insert(['placa'=>$placa, 'nombre'=>$nombre, 'descripcion'=>$descripcion, 'costo'=>$costo, 'fecha'=>$fecha])){ $this->view->mensaje = '¡Reparacion agregada exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un errores!'; $this->view->error = $this->model->reparaciones->getError(); } $this->view->render('reparaciones/mensaje'); }else{ $this->view->mensaje = 'Rellene los campos'; $vehiculos = $this->model->reparaciones->getVehiculos(); $this->view->vehiculos = $vehiculos; $talleres = $this->model->reparaciones->getTalleres(); $this->view->talleres = $talleres; $this->view->render('reparaciones/agregar'); } ?><file_sep><?php if(isset($_POST['agregar'])){ $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $apellido = ($_POST['apellido'] !== "") ? $_POST['apellido'] : NULL; $telefono = ($_POST['telefono'] !== "") ? $_POST['telefono'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $cedula = ($_POST['cedula'] !== "") ? $_POST['cedula'] : NULL; if ($this->model->choferes->insert(['nombre'=>$nombre, 'apellido'=>$apellido, 'placa'=>$placa, 'cedula'=>$cedula, 'telefono'=>$telefono])){ $this->view->mensaje = '¡Chofer agregado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; $this->view->error = $this->model->choferes->getError(); } $this->view->render('choferes/mensaje'); }else{ $this->view->mensaje = 'Rellene los campos'; //Función en modelo choferes para obtener vehiculos $vehiculos = $this->model->choferes->getVehiculos(); $this->view->vehiculos = $vehiculos; $this->view->render('choferes/agregar'); } ?><file_sep><?php if(isset($_POST['agregar'])){ $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $taller = ($_POST['taller'] !== "") ? $_POST['taller'] : NULL; $tipo = ($_POST['tipo'] !== "") ? $_POST['tipo'] : NULL; $costo = ($_POST['costo'] !== "") ? $_POST['costo'] : NULL; $fecha = ($_POST['fecha'] !== "") ? $_POST['fecha'] : NULL; if ($this->model->mantenimientos->insert(['placa'=>$placa, 'taller'=>$taller, 'costo'=>$costo, 'fecha'=>$fecha, 'tipo'=>$tipo])){ $this->view->mensaje = '¡Mantenimiento agregado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; $this->view->error = $this->model->mantenimientos->getError(); } $this->view->render('mantenimientos/mensaje'); }else{ $this->view->mensaje = 'Rellene los campos'; $vehiculos = $this->model->mantenimientos->getVehiculos(); $this->view->vehiculos = $vehiculos; $tipos = $this->model->mantenimientos->getTipos(); $this->view->tipos = $tipos; $talleres = $this->model->mantenimientos->getTalleres(); $this->view->talleres = $talleres; $this->view->render('mantenimientos/agregar'); } ?><file_sep><?php define('URL', 'http://localhost/ut/'); define('HOST', 'localhost'); define('DB', 'mysql'); define('DBNAME', 'ut'); define('USER', 'admin'); define('PASS', '<PASSWORD>'); define('CHARSET', 'utf8'); ?><file_sep><?php if(isset($_POST['modificar'])) { $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $modelo = ($_POST['modelo'] !== "") ? $_POST['modelo'] : NULL; $funcionamiento = ($_POST['funcionamiento'] !== "") ? $_POST['funcionamiento'] : NULL; if ($this->model->vehiculos->update(['placa'=>$placa, 'modelo'=>$modelo, 'funcionamiento'=>$funcionamiento])){ $this->view->mensaje = '¡Vehiculo modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('vehiculos/mensaje'); } else { $vehiculos = $this->model->vehiculos->get($param[0]); if (isset($vehiculos)){ $this->view->vehiculos = $vehiculos[0]; $this->view->render('vehiculos/actualizar'); } else { $this->view->mensaje = 'vehiculo no encontrado'; $this->view->render('vehiculos/mensaje'); } } ?><file_sep><?php class choferesCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO choferes (cedula, nombre, apellido, telefono, placa) VALUES(:cedula, :nombre, :apellido, :telefono, :placa)'); $query->execute(['cedula'=>$data['cedula'], 'nombre'=>$data['nombre'], 'apellido'=>$data['apellido'], 'telefono'=>$data['telefono'], 'placa'=>$data['placa']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM choferes WHERE id_choferes = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM choferes'); } while($row = $query->fetch()){ $item = new ChoferesClass(); $item->setId($row['id_choferes']); $item->setCedula($row['cedula']); $item->setNombre($row['nombre']); $item->setApellido($row['apellido']); $item->setTelefono($row['telefono']); $item->setPlaca($row['placa']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET VEHICULOS ********************************************************************************/ function getVehiculos ( $id = null) { $items = []; try { if ( isset($id) ) { //Lo mas probable es que lo quieren condicionar a que solo se muestre los operativos asi que cambien el query $query = $this->db->connect()->prepare('SELECT * FROM vehiculos WHERE id_vehiculo = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM vehiculos'); } while($row = $query->fetch()){ $item = new VehiculosClass(); $item->setId($row['id_vehiculo']); $item->setPlaca($row['placa']); $item->setModelo($row['modelo']); $item->setFuncionamiento($row['funcionamiento']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM choferes WHERE id_choferes = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE choferes SET nombre = :nombre, apellido = :apellido, telefono = :telefono, placa = :placa WHERE cedula = :cedula'); $query->execute(['cedula'=>$data['cedula'], 'nombre'=>$data['nombre'], 'apellido'=>$data['apellido'], 'telefono'=>$data['telefono'],'placa'=>$data['placa']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Rutas</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar Ruta</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>rutas/registrarRuta" method="POST" class="form" id="formulario"> <div class="form__box"> <div> <label for="nombre_ruta">Nombre de la ruta:</label> <input type="text" name="nombre_ruta" id="nombre_ruta" data-patron="^[a-zA-Z]{5,30}$" pattern="[a-zA-Z]{5,30}" placeholder="Ingrese el nombre" title="Solo se aceptan caracteres en este campo" maxlength="30"> </div> <div> <label for="direccion_ruta">Dirección:</label> <input type="text" name="direccion_ruta" id="direccion_ruta" placeholder="Ingrese la dirección" data-patron="[a-zA-Z]{10,30}$" title="Solo se aceptan caracteres en este campo" maxlength="30"> </div> <div> <label for="hora_salida" >Hora de salida:</label> <input type="time" name="hora_salida" id="hora_salida" required> </div> <div> <label for="vehiculo">Unidad encargada:</label> <select class="select" id="select" name="placa"> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" onclick= "validarFormulario()" id="submit">Agregar</button> <a href="<?php echo constant('URL')?>rutas" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/rutas/validar.js"></script> </body> </html> <file_sep><?php class talleresCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { $id= 0; $mayor = 0; try{ $query = $this->db->connect()->query('SELECT * FROM taller'); while($row = $query->fetch()){ $item = new TalleresClass(); if ($row['id_taller'] >= $mayor) { $mayor = $row['id_taller']; } } $id = $mayor + 1; $query = $this->db->connect()->prepare('INSERT INTO taller (id_taller, rif, nombre, direccion) VALUES(:id_taller, :rif, :nombre, :direccion)'); $query->execute(['id_taller' => $id, 'rif'=>$data['rif'], 'nombre'=>$data['nombre'], 'direccion'=>$data['direccion']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $rif = null) { $items = []; try { if ( isset($rif) ) { $query = $this->db->connect()->prepare('SELECT * FROM taller WHERE rif = :rif'); $query->execute(['rif'=>$rif]); } else { $query = $this->db->connect()->query('SELECT * FROM taller'); } while($row = $query->fetch()){ $item = new TalleresClass(); $item->setId($row['id_taller']); $item->setRif($row['rif']); $item->setNombre($row['nombre']); $item->setDireccion($row['direccion']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM taller WHERE id_taller = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE taller SET nombre = :nombre, direccion = :direccion WHERE rif = :rif'); $query->execute(['rif'=>$data['rif'], 'nombre'=>$data['nombre'], 'direccion'=>$data['direccion']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Highcharts Example</title> <style type="text/css"> #container { height: 400px; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 800px; margin: 1em auto; } .highcharts-data-table table { font-family: Verdana, sans-serif; border-collapse: collapse; border: 1px solid #EBEBEB; margin: 10px auto; text-align: center; width: 100%; max-width: 500px; } .highcharts-data-table caption { padding: 1em 0; font-size: 1.2em; color: #555; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.5em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } .highcharts-data-table tr:hover { background: #f1f7ff; } </style> </head> <body> <script src="../../graficos/code/highcharts.js"></script> <script src="../../graficos/code/highcharts-3d.js"></script> <script src="../../graficos/code/modules/exporting.js"></script> <script src="../../graficos/code/modules/export-data.js"></script> <script src="../../graficos/code/modules/accessibility.js"></script> <figure class="highcharts-figure"> <div id="container"></div> <p class="highcharts-description"> A variation of a 3D pie chart with an inner radius added. These charts are often referred to as donut charts. </p> </figure> <script type="text/javascript"> Highcharts.chart('container', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Contents of Highsoft\'s weekly fruit delivery' }, subtitle: { text: '3D donut in Highcharts' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Delivered amount', data: [ ['kiji', 10], ['toronja', 27.0], ['tomate', 15.7] ] }] }); </script> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | UPTAEB</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/inicio.css"> </head> <body> <?php require 'views/header.php'; ?> <div class="text-header"> <center><h2>Bienvenido al sistema UT</h2></center> </div> <div class="container"> <div class="main"> <div class="slides"> <img src="<?php echo constant('URL')?>public/img/slider/1.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/2.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/3.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/4.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/5.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/6.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/7.jpg" alt=""> <img src="<?php echo constant('URL')?>public/img/slider/8.jpg" alt=""> </div> </div> <main> <div class="tablaAlerta" id="form"> <table> <tr> <th colspan="3">Alertas del sistema</th> </tr> <tr> <th>Vehiculo</th><th>Chofer</th><th>Mantenimiento</th> <tr> <td>AS1-123</td> <td><NAME></td> <td>Cambio de aceite</td> </tr> <tr> <td>VAS-123</td> <td><NAME></td> <td>Cambio de bateria</td> </tr> <tr> <td>ATE-123</td> <td><NAME></td> <td>Cambio de caucho</td> </tr> <tr> <td>HAF-124</td> <td><NAME></td> <td>Cambio de aceite</td> </tr> <tr> <td>LKA-124</td> <td><NAME></td> <td>Cambio de bujias</td> </tr> <tr> <td>ASF-124</td> <td><NAME></td> <td>Cambio de bujias</td> </tr> </table> </div> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/slider/jquery.js"></script> <script src="<?php echo constant('URL')?>public/js/slider/jquery.slides.js"></script> <script> </script> </body> </html> <file_sep><?php require 'libs/classes/talleres.class.php'; require 'source/talleres/CRUD.php'; class TalleresModel extends Model { public $talleres; function __construct() { parent::__construct(); $this->talleres = new talleresCRUD(); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar reparación</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>mantenimientos/registrarMantenimiento" method="POST" class="form"> <div class="form__box"> <div> <label for="placa">Vehiculo</label> <select class="select" id="select" name="placa" required> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> <div> <label for="taller">Taller</label> <select class="select" id="select" name="taller"> <option value="0" required >Seleccione</option> <?php foreach($this->talleres as $row){ $taller = new TalleresClass(); $taller = $row; ?> <option value="<?php echo $taller->getNombre()?>"><?php echo $taller->getNombre(); ?></option> <?php } ?> </select> </div> <div> <label for="tipo">Tipo de mantenimiento</label> <select class="select" id="select" name="tipo"> <option value="0">Seleccione</option> <?php foreach($this->tipos as $row){ $tipo = new TiposClass(); $tipo = $row; ?> <option value="<?php echo $tipo->getNombre()?>"><?php echo $tipo->getNombre(); ?></option> <?php } ?> </select> </div> <div> <label for="costo">Costo:</label> <input type="text" data-pront="" name="costo" id="costo" placeholder="Costo de la reparacion" required> </div> <div> <label for="fecha">Fecha:</label> <input type="date" name="fecha" id="fecha" required> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit">Agregar</button> <a href="<?php echo constant('URL')?>mantenimientos" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/mantenimientos/validar.js" ></script> </body> </html> <file_sep># Sistema-transporte Este repositorio alojara todos los archivos del sistema de transporte de la uptaeb ORIANA ARMAS ACTUALICE EL PROYECTO Y AGREGRE LA TABLA RUTAS EN LARAVEL <file_sep><?php require 'libs/classes/usuarios.class.php'; class RestaurarModel extends Model { function __construct() { parent::__construct(); } function usuarioExiste ($nombre, $apellido, $cedula) { try { $query = $this->db->connect()->prepare('SELECT * FROM usuarios WHERE nombre = :nombre AND apellido = :apellido AND cedula = :cedula'); $query->execute(['nombre' => $nombre,'apellido' => $apellido, 'cedula' => $cedula]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } function cambiar($contrasena){ try { $query = $this->db->connect()->prepare(' UPDATE usuarios SET contrasena = :contrasena WHERE cedula = :cedula'); $query->execute(['contrasena' => $contrasena, 'cedula' => $_SESSION['restaurarUsuario']]); return true; } catch (PDOException $e) { echo "Error en: ".$e; return false; } } } ?><file_sep><?php class usuariosCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO usuarios (cedula, nombre, apellido, usuario, contrasena, rol) VALUES(:cedula, :nombre, :apellido, :usuario, :contrasena, :rol)'); $query->execute(['cedula'=>$data['cedula'], 'nombre'=>$data['nombre'], 'apellido'=>$data['apellido'], 'usuario'=>$data['usuario'], 'contrasena'=>$data['contrasena'], 'rol'=>$data['rol']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM usuarios WHERE id_usuario = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM usuarios'); } while($row = $query->fetch()){ $item = new UsuariosClass(); $item->setId($row['id_usuario']); $item->setCedula($row['cedula']); $item->setNombre($row['nombre']); $item->setApellido($row['apellido']); $item->setUsuario($row['usuario']); $item->setContrasena($row['contrasena']); $item->setRol($row['rol']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM usuarios WHERE id_usuario = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE usuarios SET nombre = :nombre, apellido = :apellido, usuario = :usuario, contrasena = :contrasena, rol = :rol WHERE cedula = :cedula'); $query->execute(['cedula'=>$data['cedula'], 'nombre'=>$data['nombre'], 'apellido'=>$data['apellido'], 'usuario'=>$data['usuario'], 'contrasena'=>$data['contrasena'], 'rol'=>$data['rol']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><?php class Reportes extends Controller{ public function __construct(){ parent::__construct(); $this->view->modelos=[]; $this->view->partes=[]; } public function render(){ $this->view->render('reportes/index'); } public function load ($metodo, $param = null) { $ruta = 'source/reportes/'.$metodo.'.php'; require_once $ruta; } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Choferes</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar Usuario</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>choferes/registrarChofer" method="POST" id="formulario" class="form"> <div class="form__box"> <div> <label for="nombre">Nombre:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="nombre" id="nombre" placeholder="Ingrese el nombre" pattern="[a-zA-Z]{3,12}$" maxlength="12" title="El formato solo acepta caracteres entre mayúsculas y minusculas"/> </div> <div> <label for="apellido">Apellido:</label> <input type="text" maxlength="12" name="apellido" id="apellido" placeholder="Ingrese el apellido" pattern="[a-zA-Z]{3,12}$" data-patron="^[a-zA-Z]{3,12}$" title="El formato solo acepta caracteres entre mayúsculas y minusculas"/> </div> <div> <label for="cedula">Cedula:</label> <input type="text" name="cedula" id="cedula" placeholder="xx.xxx.xxx" maxlength="8" data-patron="[0-9]{7,8}"title="De 6 a 9 numeros"/> </div> <div> <label for="telefono">Telefono:</label> <input type="text" name="telefono" id="telefono" placeholder="04xx-xxxxxxx" maxlength="11" data-patron="[0-9]{11,12}" title="Solo se permiten numeros del 0 al 9" /> </div> <div> <label for="vehiculo">Vehiculo</label> <select class="select" id="select" name="placa" required> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit" onclick= "validarFormulario()" >Agregar</button> <a href="<?php echo constant('URL')?>choferes" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/choferes/agregar.js"></script> </body> </html> <file_sep><?php if ( $this->model->choferes->drop($param[0]) ) { $mensaje = 'Chofer Eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep> <?php class Controller { function __construct() { $this->view = new View(); } function loadModel($model, $param = null) { $url = 'models/' . $model. 'model.php'; if( file_exists($url) ) { require_once $url; $modelName = $model .'Model'; $this->model = new $modelName(); } } //Conigurar usuario y devolver datos a la vista; public function setUsuario ($usuario) { $query = $this->model->db->connect()->prepare ('SELECT * FROM usuarios WHERE usuario = :usuario'); $query->execute(['usuario' => $usuario]); foreach($query as $usuarioActual) { $this->view->nombre = $usuarioActual['nombre']; $this->view->apellido = $usuarioActual['apellido']; $this->view->usuario = $usuarioActual['usuario']; $this->view->cedula = $usuarioActual['cedula']; $this->view->rol = $usuarioActual['rol']; } } } ?> <file_sep><?php if ( $this->model->tipos->drop($param[0]) ) { $mensaje = 'Tipo de mantenimiento eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Reparaciones</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar reparacion</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>reparaciones/registrarReparacion" method="POST" class="form"> <div class="form__box"> <div> <label for="vehiculo" id>Vehiculo</label> <select class="select" id="select" name="placa"> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> <div> <label for="nombre">Taller</label> <select class="select" id="select" name="nombre"> <option value="0">Seleccione</option> <?php foreach($this->talleres as $row){ $taller = new TalleresClass(); $taller = $row; ?> <option value="<?php echo $taller->getNombre()?>"><?php echo $taller->getNombre(); ?></option> <?php } ?> </select> </div> <div> <label for="descripcion">Descripcion:</label> <input type="text" name="descripcion" id="descripcion" id="descripcion" placeholder="Describa la reparacion" data-patron="^[a-zA-Z]{3,12}$"> </div> <div> <label for="costo">Costo:</label> <input type="text" data-patron="[0-9]{11,12}" name="costo" id="costo" placeholder="Costo de la reparacion" id="costo"> </div> <div> <label for="fecha">Fecha:</label> <input type="date" name="fecha" id="fecha" required> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit">Agregar</button> <a href="<?php echo constant('URL')?>reparaciones" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/reparaciones/validar.js"></script> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Talleres</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar taller</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>talleres/registrartaller" method="POST" class="form"> <div class="form__box"> <div> <label for="rif">Rif:</label> <input type="text" name="rif" id="rif" data-patron="[VEPGJ]-?\d{6,10}.?\d?" pattern="[VEPGJ]-?\d{6,10}.?\d?" title="El formato es una letra (V-E-P-G) seguido por 8 o 9 numeros, si faltan numeros complete con un 0" placeholder="V-123456789-0"> </div> <div> <label for="nombre">Nombre:</label> <input type="text" name="nombre" id="nombre" data-patron="[a-zA-Z]{5,30}$" placeholder="Nombre del taller"> </div> <div> <label for="direccion">Direccion:</label> <input type="text" name="direccion" id="direccion" data-patron="[a-zA-Z]{5,30}$" placeholder="direccion del taller"> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit" >Agregar</button> <a href="<?php echo constant('URL')?>talleres" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/taller/validar.js"></script> </body> </html> <file_sep><?php require 'libs/classes/vehiculos.class.php'; require 'libs/classes/talleres.class.php'; require 'libs/classes/tipos.class.php'; require 'libs/classes/mantenimientos.class.php'; require 'source/mantenimientos/CRUD.php'; class MantenimientosModel extends Model { public $mantenimientos; function __construct() { parent::__construct(); $this->mantenimientos = new mantenimientosCRUD(); } } ?><file_sep><?php if(isset($_POST['agregar'])){ $nombre_tipo = ($_POST['nombre_tipo'] !== "") ? $_POST['nombre_tipo'] : NULL; $descripcion = ($_POST['descripcion'] !== "") ? $_POST['descripcion'] : NULL; $tiempo = ($_POST['tiempo'] !== "") ? $_POST['tiempo'] : NULL; if ($this->model->tipos->insert(['nombre_tipo'=>$nombre_tipo, 'descripcion'=>$descripcion, 'tiempo'=>$tiempo])){ $this->view->mensaje = '¡Tipo de mantenimiento agregado exitosamente!.'; }else{ $this->view->mensaje = 'Ha ocurrido un error!'; $this->view->error = $this->model->tipos->getError(); } }else{ $this->view->mensaje = 'Rellene los campos'; } $this->view->render('tipos/agregar'); ?> <file_sep><?php class restaurar extends Controller { public function __construct() { parent::__construct(); if ( isset( $_POST['ingresar'] ) ){ $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $apellido = ($_POST['apellido'] !== "") ? $_POST['apellido'] : NULL; $cedula = ($_POST['cedula'] !== "") ? $_POST['cedula'] : NULL; $this->loadModel('restaurar'); if($this->verificacion( $nombre, $apellido, $cedula )) { session_start(); $_SESSION['restaurarUsuario'] = $cedula; header('location:'. constant('URL').'restaurar/recuperar'); } } } public function load ($metodo, $param = null) { $ruta = 'source/restaurar/'.$metodo.'.php'; require_once $ruta; } public function recuperar () { $this->view->render('restaurar/restaurar'); } public function render () { $this->view->render('restaurar/index'); } //Chequear si existe el usuario; public function verificacion( $nombre, $apellido, $cedula ) { if ( $this->model->usuarioExiste($nombre, $apellido, $cedula) ) { return true; } else { $this->view->mensaje = 'Datos incorrectos'; return false; } } public function actualizar() { if(isset($_POST['btn'])){ $contrasena = ($_POST['contrasena'] !== "") ? $_POST['contrasena'] : NULL ; if($this->model->cambiar($contrasena)){ session_unset(); session_destroy(); $this->view->mensaje = 'Cambio de contraseña efectuado con exito.'; $this->view->render('login/index'); } else{ $this->view->mensaje = 'No se pudo realizar el cambio de contraseña.'; $this->view->render('login/index'); } } } } ?><file_sep><?php class partesCRUD extends Model { public function __construct() { parent::__construct(); } function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO partes ( idmodelo,serializable, codpartes,stockmaximo,stockminimo,puntoreorden,estatus, stockactual ) VALUES(:idmodelo, :serializable, :codpartes, :stockmaximo, :stockminimo, :puntoreorden, :estatus, :stockactual)'); $query->execute(['idmodelo'=>$data['idmodelo'], 'serializable'=>$data['serializable'],'codpartes'=>$data['codpartes'],'stockmaximo'=>$data['stockmaximo'],'stockminimo'=>$data['stockminimo'],'puntoreorden'=>$data['puntoreorden'],'estatus'=>$data['estatus'], 'stockactual'=>0 ]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function drop ($id) { try{ $query = $this->db->connect()->prepare('DELETE FROM Partes WHERE codpartes = :id'); $query->execute(['id'=>$id]); return true; } catch(PDOException $e){ echo $e->getMessage(); return false; } } function update ($data, $tipo = null) { try{ switch ($tipo) { case "1": $query = $this->db->connect()->prepare('UPDATE partes SET stockactual = stockactual + :cantidadparte WHERE codpartes = :codpartes'); $query->execute(['codpartes'=>$data['codpartes'], 'cantidadparte'=>$data['cantidadparte']]); break; case "2": $query = $this->db->connect()->prepare('UPDATE partes SET stockactual = stockactual - :cantidadparte WHERE codpartes = :codpartes'); $query->execute(['codpartes'=>$data['codpartes'], 'cantidadparte'=>$data['cantidadparte']]); break; default: $query = $this->db->connect()->prepare('UPDATE partes SET idmodelo = :idmodelo, serializable = :serializable, stockmaximo = :stockmaximo, stockminimo = :stockminimo, puntoreorden = :puntoreorden WHERE codpartes = :codpartes'); $query->execute(['idmodelo'=>$data['idmodelo'], 'serializable'=>$data['serializable'],'codpartes'=>$data['codpartes'],'stockmaximo'=>$data['stockmaximo'],'stockminimo'=>$data['stockminimo'],'puntoreorden'=>$data['puntoreorden']]); break; } return true; } catch(PDOException $e){ echo $e->getMessage(); return false; } } public function get ($id = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM partes WHERE codpartes = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM partes'); } while($row = $query->fetch()){ $item = new PartesClass(); $item->setCod($row['codpartes']); $item->setSerializable($row['serializable']); $item->setStockAct($row['stockactual']); $item->setStockMax($row['stockmaximo']); $item->setStockMin($row['stockminimo']); $item->setPuntoRe($row['puntoreorden']); $item->setEstatus($row['estatus']); $item->setIdModelo($row['idmodelo']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } public function getError () { return $this->error; } } ?><file_sep><?php require 'libs/classes/choferes.class.php'; require 'libs/classes/mantenimientos.class.php'; require 'libs/classes/reparaciones.class.php'; require 'libs/classes/talleres.class.php'; require 'libs/classes/rutas.class.php'; require 'libs/classes/vehiculos.class.php'; require 'source/choferes/CRUD.php'; require 'source/mantenimientos/CRUD.php'; require 'source/reparaciones/CRUD.php'; require 'source/talleres/CRUD.php'; require 'source/rutas/CRUD.php'; require 'source/vehiculos/CRUD.php'; class ReportesModel extends Model { public $choferes; public $mantenimientos; public $reparaciones; public $talleres; public $rutas; public $vehiculos; function __construct() { parent::__construct(); $this->choferes = new choferesCRUD(); $this->mantenimientos = new mantenimientosCRUD(); $this->reparaciones = new reparacionesCRUD(); $this->talleres = new talleresCRUD(); $this->rutas = new rutasCRUD(); $this->vehiculos = new vehiculosCRUD(); } } ?><file_sep><?php ob_start(); require 'plantilla.php'; $pdf = new PDF(); $pdf->AddPage(); $pdf->SetLeftMargin($pdf->GetPageWidth() / 2 - 80); $pdf->SetFont('Helvetica','B',15);//Tipo de letra, negrita, tamaño $pdf->Ln(10);//salto de linea $choferes = $this->model->choferes->get(); //MODELOS $pdf->Cell(160, 10, 'CHOFERES',2, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','B',12);//Tipo de letra, negrita, tamaño $pdf->Cell(15, 10, 'ID',1, 0,'C', 0); $pdf->Cell(30, 10, 'Placa',1, 0,'C', 0); $pdf->Cell(30, 10, 'Nombre',1, 0,'C', 0); $pdf->Cell(30, 10, 'Apellido',1, 0,'C', 0); $pdf->Cell(25, 10, 'Cedula',1, 0,'C', 0); $pdf->Cell(30, 10, 'Telefono',1, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','',10);//Tipo de letra, negrita, tamaño foreach ($choferes as $row) { $pdf->Cell(15,10, $row->getId(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getPlaca(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getNombre(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getApellido(), 1, 0,'C', 0); $pdf->Cell(25,10, $row->getCedula(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getTelefono(), 1, 0,'C', 0); $pdf->Ln(10);//salto de linea } //$pdf->AddPage(); $pdf->Output(); ob_end_flush(); ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>UT | Recuperar contraseña</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <body> <header class="header"> <div class="wrapper"> <div class="logo"></div> <nav> <a href="Manual.pdf" target="blank" title="Manual del sistema">Manual</a> <a href="<?php echo constant('URL')?>contacto">Contacto</a> </nav> </div> </header> <main> <div class="login__restaurar" > <?php if (isset($this->mensaje) ) { ?> <h2 id="mensaje"> <?php echo $this->mensaje; ?> </h2> <?php } ?> <form class="restaurar__form" method="POST" name="formulario"> <input class="login_input" type="text" name="nombre" placeholder="Nombre" id="nombre" /> <br> <input class="login_input" type="text" name="apellido" placeholder="Apellido" id="apellido" /> <br> <input class="login_input" type="text" name="cedula" placeholder="Cedula" id="cedula" /> <br> <button type="submit" name="ingresar" class="boton" value="ingresar">Restaurar contraseña</button> <input type="button" class="boton" value="Cancelar" onClick="history.go(-1);"> </form> </div> </main> <script src="<?php echo constant('URL')?>public/js/validacion/restaurar.js"></script> </body> </html> </html> <file_sep><?php class LoginModel extends Model { function __construct() { parent::__construct(); } function usuarioExiste ( $usuario, $contrasena ) { try { $query = $this->db->connect()->prepare('SELECT * FROM usuarios WHERE usuario = :usuario AND contrasena = :contrasena'); $query->execute(['usuario' => $usuario, 'contrasena' => $contrasena]); return $query->rowCount(); } catch(PDOException $e) { return false; } } } ?><file_sep><?php if(isset($_POST['agregar'])){ $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $modelo = ($_POST['modelo'] !== "") ? $_POST['modelo'] : NULL; $funcionamiento = ($_POST['funcionamiento'] !== "") ? $_POST['funcionamiento'] : NULL; if ($this->model->vehiculos->insert( ['placa'=>$placa, 'modelo'=>$modelo, 'funcionamiento'=>$funcionamiento])){ $this->view->mensaje = '¡Vehiculo agregado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; $this->view->error = $this->model->vehiculos->getError(); } }else{ $this->view->mensaje = 'Rellene los campos'; } $this->view->render('vehiculos/agregar'); ?><file_sep><?php if(isset($_POST['modificarTaller'])) { $rif = ($_POST['rif'] !== "") ? $_POST['rif'] : NULL; $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $direccion = ($_POST['direccion'] !== "") ? $_POST['direccion'] : NULL; if ($this->model->talleres->update(['rif'=>$rif, 'nombre'=>$nombre, 'direccion'=>$direccion])){ $this->view->mensaje = '¡Taller Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('talleres/mensaje'); } else { $talleres = $this->model->talleres->get($param[0]); if (isset($talleres)){ $this->view->talleres = $talleres[0]; $this->view->render('talleres/actualizar'); } else { $this->view->mensaje = 'Taller no encontrado'; $this->view->render('talleres/mensaje'); } } ?><file_sep><?php if ( $this->model->rutas->drop($param[0]) ) { $mensaje = 'Ruta eliminada'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Vehiculos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Actualizar vehiculo</h2> </div> <div class="modal-container"> <?php include 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>vehiculos/modificarVehiculo" method="POST" class="form"> <div class="form__box "> <div> <label for="placa">Placa:</label> <input type="text" name="placa" id="placa" value="<?php echo $this->vehiculos->getPlaca();?>" readonly> </div> <div> <label for="modelo">Modelo:</label> <input type="text" name="modelo" id="modelo" value="<?php echo $this->vehiculos->getModelo();?>"> </div> <div> <label for="funcionamiento">Funcionamiento:</label> <select name="funcionamiento" id="funcionamiento" class="select" required > <option value="">...</option> <option value="Operativo">Operativo</option> <option value="Inoperante">Inoperante</option>> </select> </div> </div> <div class="bottom"> <button type="submit" id="submit" name="modificar" value="modificar">Modificar Vehiculo</button> <a href="<?php echo constant('URL')?>vehiculos/">Cancelar</a> </div> </form> </main> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Agregar tipo de mantenimiento</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>tipos/registrarTipo" method="POST" class="form"> <div class="form__box"> <div> <label for="nombre_tipo">Nombre del mantenimiento:</label> <input type="text" name="nombre_tipo" id="nombre_tipo"> </div> <div> <label for="descripcion">Descripcion:</label> <input type="text" name="descripcion" id="descripcion"> </div> <div> <label for="tiempo">Cada cuanto tiempo se debe realizar:</label> <input type="text" name="tiempo" id="tiempo"> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit">Agregar</button> <a href="<?php echo constant('URL')?>tipos" >Volver</a> </div> </form> </main> </div> </body> </html> <file_sep>(function(){ var formulario = document.getElementsByName('formulario')[0], elementos = formulario.elements, usuario = document.getElementById('usuario'), contrasena = document.getElementById('contrasena'); var campos = function(e){ if (formulario.usuario.value == 0 || formulario.contrasena.value == 0 ) { alert("Todos los campos son obligatorios"); e.preventDefault() } } formulario.addEventListener("submit", campos); }()) <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Usuarios</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> </h2> <h2>Registrar Usuario</h2> </div> <div class="modal-container"> <?php require_once 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>usuarios/registrarUsuario" method="POST" class="form"> <div class="form__box"> <div> <label for="nombre">Nombre:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="nombre" id="nombre"> <p class="ayuda esconder">*3 a 12 letras.</p> </div> <div> <label for="apellido">Apellido:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="apellido" id="apellido"> <p class="ayuda esconder">*3 a 12 letras.</p> </div> <div> <label for="usuario">Username:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="usuario" id="username"> <p class="ayuda esconder">*3 a 12 letras.</p> </div> <div> <label for="rol">Rol:</label> <select name="rol" id="rol" class="select" required> <option value="">...</option> <option value="admin">Admin</option> <option value="usuario">Usuario</option>> </select> </div> <div> <label for="contrasena">Contraseña:</label> <input type="password" name="contrasena" data-patron="^[a-zA-Z0-9]*$" id="pass" required> <p class="ayuda esconder">*hasta 16 caracteres alfanumericos</p> </div> <div> <label for="pass">Confirmar contraseña:</label> <input type="password" name="pass-confirmar" data-patron="^([a-zA-Z0-9]){3,16}$"id="conPass" required> <p class="ayuda esconder">*hasta 16 caracteres alfanumericos</p> </div> <div> <label for="cedula">Pregunta de seguridad(Cedula:)</label> <input type="text" name="cedula" id="cedula" data-patron="^[0-9]{6,9}$" placeholder="Ingrese su cedula" required> <p class="ayuda esconder">*6 a 9 numeros</p> </div> </div> <div class="bottom"> <button type="submit" name="agregar" value="agregar" id="submit">Agregar</button> <a href="<?php echo constant('URL')?>usuarios" >Volver</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/usuarios/agregar.js"></script> </body> </html> <file_sep><?php class bitacoraCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function consultarBitacora(){ $tabla ="SELECT * FROM bitacora"; $respuestaArreglo =''; try{ $datos = $this->conexion->prepare($tabla); $datos->execute(); $datos->setFetchMode(PDO::FETCH_ASSOC); $respuestaArreglo = $datos->fetchAll(PDO::FETCH_ASSOC); return $respuestaArreglo; }catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO bitacora (fecha,hora,accion) VALUES(:fecha, :hora, :acccion)'); $query->execute(['fecha'=>$data['fecha'], 'hora'=>$data['hora'], 'accion'=>$data['accion']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id_bitacora = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM bitacora WHERE id_bitacora = :id_bitacora'); $query->execute(['id_bitacora'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM bitacora'); } while($row = $query->fetch()){ $item = new BitacoraModel(); $item->setIdBitacora($row['id_bitacora']); $item->setIdUsuario($row['id_usuario']); $item->setFecha($row['fecha']); $item->setHora($row['hora']); $item->setAccion($row['accion']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id_bitacora) { try { $query = $this->db->connect()->prepare('DELETE FROM bitacora WHERE id_bitacora = :id_bitacora'); $query->execute(['id_bitacora'=>$id_bitacora]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function registroSalida ($data) { try { $query = $this->db->connect()->prepare('UPDATE bitacora SET hora = :hora WHERE id_bitacora = :id_bitacora'); $query->execute(['hora'=>$data['hora'], 'id_bitacora'=>$data['id_bitacora'], 'id_usuario'=>$data['id_usuario'], 'fecha'=>$data['fecha'], 'accion'=>$data['accion']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>UT | Recuperar contraseña</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <body> <header class="header"> <div class="wrapper"> <div class="logo"></div> <nav> <a href="Manual.pdf" target="blank" title="Manual del sistema">Manual</a> <a href="<?php echo constant('URL')?>contacto">Contacto</a> </nav> </div> </header> <main> <div class="loign__form" > <form class="login__restaurar" method="post" name="formulario" action="<?php echo constant('URL')?>restaurar/actualizar"> <input class="login_input" type="text" name="cuenta" value="<?php echo $_SESSION['restaurarUsuario'];?>" id="cuenta" disabled/> <br> <input class="login_input" type="password" name="contrasena" placeholder="<PASSWORD>" id="password1"/> <br> <input class="login_input" type="password" name="contrasena" placeholder="<PASSWORD>" id="<PASSWORD>"/> <br> <input type="submit" name="btn" id="btn" class="boton" value="Actualizar" > <input type="button" class="boton" value="Cancelar" onClick="history.go(-2);"> </form> </div> </main> <script type="text/javascript" src="<?php echo constant('URL')?>public/js/validacion/validar_password.js"></script> </body> </html> <file_sep><?php $RUTA = 'menus/' . $this->rol . '.php'; require ($RUTA); ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Taller</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Actualizar taller</h2> </div> <div class="modal-container"> <?php include 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>talleres/modificarTaller" method="POST" class="form"> <div class="form__box "> <div> <label for="rif">Rif:</label> <input type="text" name="rif" id="rif" value="<?php echo $this->talleres->getRif();?>"> </div> <div> <label for="nombre">Nombre:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="nombre" id="nombre" value="<?php echo $this->talleres->getNombre();?>"> </div> <div> <label for="direccion">Direccion:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="direccion" id="direccion" value="<?php echo $this->talleres->getDireccion();?>"> </div> </div> <div class="bottom"> <button type="submit" id="submit" name="modificarTaller" value="modificarTaller">Modificar Taller</button> <a href="<?php echo constant('URL')?>talleres/">Cancelar</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/usuarios/actualizar.js"></script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Reparaciones</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de reparacion</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarReparacion"> <div> <table> <tr><th>ID</th> <th>Taller</th><th>Vehiculo</th><th>Costo</th><th>Fecha</th><th>Descripcion</th> <th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-reparaciones"> <?php foreach($this->reparaciones as $row){ $reparaciones = new ReparacionesClass(); $reparaciones = $row; ?> </tr > <tr id="fila-<?php echo $reparaciones->getId(); ?>"> <td><?php echo $reparaciones->getId(); ?></td> <td><?php echo $reparaciones->getNombre(); ?></td> <td><?php echo $reparaciones->getPlaca(); ?></td> <td><?php echo $reparaciones->getCosto(); ?></td> <td><?php echo $reparaciones->getFecha(); ?></td> <td><?php echo $reparaciones->getDescripcion(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>reparaciones/modificarReparacion/<?php echo $reparaciones->getId();?>">Modificar</a></td> <td> <button class="crud eliminar" data-id="<?php echo $reparaciones->getId(); ?>">Eliminar</button> </td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>reparaciones/registrarReparacion">Registrar</a> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Choferes</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Actualizar chofer</h2> </div> <div class="modal-container"> <?php include 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>choferes/modificarChofer" method="POST" class="form"> <div class="form__box "> <div> <label for="nombre">Nombre:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="nombre" id="nombre" placeholder="Ingrese el nombre" value="<?php echo $this->choferes->getNombre();?>"> <p class="ayuda esconder">*3 a 12 letras.</p> </div> <div> <label for="apellido">Apellido:</label> <input type="text" data-patron="^[a-zA-Z]{3,12}$" name="apellido" id="apellido" placeholder="Ingrese el apellido" value="<?php echo $this->choferes->getApellido();?>"> <p class="ayuda esconder">*3 a 12 letras.</p> </div> <div> <label for="cedula">Cedula:</label> <input type="text" name="cedula" id="cedula" data-patron="^[0-9]{6,9}$" placeholder="xx.xxx.xxx" required readonly value="<?php echo $this->choferes->getCedula();?>"> <p class="ayuda esconder">*6 a 9 numeros</p> </div> <div> <label for="telefono">Telefono:</label> <input type="text" name="telefono" id="telefono" data-patron="^[0-9]{6,9}$" placeholder="04xx-xxxxxxx" required value="<?php echo $this->choferes->getTelefono();?>"> <p class="ayuda esconder">*6 a 9 numeros</p> </div> <div> <label for="vehiculo">Vehiculo</label> <select class="select" id="select" name="placa"> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> </div> <div class="bottom"> <button type="submit" id="submit" name="modificarChofer" value="modificarChofer">Modificar Chofer</button> <a href="<?php echo constant('URL')?>choferes/">Cancelar</a> </div> </form> </main> </div> <script src="<?php echo constant('URL')?>public/js/usuarios/actualizar.js"></script> </body> </html><file_sep><?php // Clase de usuario para BD class VehiculosClass { private $id; private $placa; private $modelo; private $funcionamiento; public function getID() { return $this->id; } public function getPlaca() { return $this->placa; } public function getModelo() { return $this->modelo; } public function getFuncionamiento() { return $this->funcionamiento; } //SETTERS public function setId($id) { $this->id = $id; } public function setPlaca($placa) { $this->placa = $placa; } public function setModelo($modelo) { $this->modelo = $modelo; } public function setFuncionamiento($funcionamiento) { $this->funcionamiento = $funcionamiento; } } ?><file_sep><?php if(isset($_POST['agregar'])){ $rif = ($_POST['rif'] !== "") ? $_POST['rif'] : NULL; $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $direccion = ($_POST['direccion'] !== "") ? $_POST['direccion'] : NULL; if ($this->model->talleres->insert(['rif'=>$rif, 'nombre'=>$nombre, 'direccion'=>$direccion])){ $this->view->mensaje = 'Taller agregado exitosamente!.'; }else{ $this->view->mensaje = 'Ha ocurrido un error!'; $this->view->error = $this->model->talleres->getError(); } }else{ $this->view->mensaje = 'Rellene los campos'; } $this->view->render('talleres/agregar'); ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Seleccione una opcion</h2> </div> <div class="tabla"> <table> <th><a class="crud" href="<?php echo constant('URL')?>tipos"><img src="<?php echo constant('URL')?>public/img/tipos.png"><br>Tipos</a></th> <th><a class="crud" href="<?php echo constant('URL')?>mantenimientos"><img src="<?php echo constant('URL')?>public/img/realizar.png"><br>Realizar</a></th> </table> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php if(isset($_POST['modificarReparacion'])) { $id_reparaciones = ($_POST['id_reparaciones'] !== "") ? $_POST['id_reparaciones'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $descripcion = ($_POST['descripcion'] !== "") ? $_POST['descripcion'] : NULL; $costo = ($_POST['costo'] !== "") ? $_POST['costo'] : NULL; $fecha = ($_POST['fecha'] !== "") ? $_POST['fecha'] : NULL; if ($this->model->reparaciones->update(['placa'=>$placa,'id_reparaciones'=>$id_reparaciones, 'nombre'=>$nombre, 'descripcion'=>$descripcion, 'costo'=>$costo, 'fecha'=>$fecha])){ $this->view->mensaje = '¡Reparacion Modificada exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('reparaciones/mensaje'); } else { $reparaciones = $this->model->reparaciones->get($param[0]); $vehiculos = $this->model->reparaciones->getVehiculos(); $this->view->vehiculos = $vehiculos; $talleres = $this->model->reparaciones->getTalleres(); $this->view->talleres = $talleres; if (isset($reparaciones)){ $this->view->reparaciones = $reparaciones[0]; $this->view->render('reparaciones/actualizar'); } else { $this->view->mensaje = 'Chofer no encontrado'; $this->view->render('reparaciones/mensaje'); } } ?><file_sep><?php if(isset($_POST['agregar'])){ $nombre = ($_POST['nombre'] !== "") ? $_POST['nombre'] : NULL; $apellido = ($_POST['apellido'] !== "") ? $_POST['apellido'] : NULL; $usuario = ($_POST['usuario'] !== "") ? $_POST['usuario'] : NULL; $rol = ($_POST['rol'] !== "") ? $_POST['rol'] : NULL; $cedula = ($_POST['cedula'] !== "") ? $_POST['cedula'] : NULL; $contrasena = ($_POST['contrasena'] !== "") ? $_POST['contrasena'] : NULL; if ($this->model->usuarios->insert(['nombre'=>$nombre, 'apellido'=>$apellido, 'contrasena'=>$contrasena, 'rol'=>$rol, 'cedula'=>$cedula, 'usuario'=>$usuario])){ $this->view->mensaje = '¡Usuario agregado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; $this->view->error = $this->model->usuarios->getError(); } }else{ $this->view->mensaje = 'Rellene los campos'; } $this->view->render('usuarios/agregar'); ?><file_sep> <div id="menu"> <ul> <li><a href="<?php echo constant('URL')?>usuarios">Usuario</a></li> <li><a href="<?php echo constant('URL')?>vehiculos">Vehiculo</a></li> <li><a href="<?php echo constant('URL')?>choferes">Chofer</a></li> <li><a href="<?php echo constant('URL')?>rutas">Ruta</a></li> <li><a href="<?php echo constant('URL')?>talleres">Taller</a></li> <li><a href="<?php echo constant('URL')?>opcion">Mantenimiento</a></li> <li><a href="<?php echo constant('URL')?>reparaciones">Reparaciones</a></li> <li><a href="<?php echo constant('URL')?>bitacora">Seguridad</a></li> <li><a href="<?php echo constant('URL')?>reportes">Reportes</a></li> <li><a href="<?php echo constant('URL')?>main/cerrarSession">Cerrar sesion</a></li> </ul> </div> <file_sep><?php class Login extends Controller { public function __construct() { parent::__construct(); if ( isset( $_POST['usuario'] ) && $_POST['usuario'] !== ""){ $usuario = ($_POST['usuario'] !== "") ? $_POST['usuario'] : NULL; $contrasena = ($_POST['contrasena'] !== "") ? $_POST['contrasena'] : NULL; $this->loadModel('login'); if($this->verificacion( $usuario, $contrasena )) { header('location:'. constant('URL')); } } } public function render () { $this->view->render('login/index'); } //Chequear si existe el usuario; public function verificacion( $usuario, $contrasena ) { if ( $this->model->usuarioExiste($usuario, $contrasena) ) { $this->setUsuarioActual( $_POST['usuario'] ); return true; } else { $this->view->mensaje = 'Datos incorrectos'; return false; } } //asignar valores a la variable de sesion; public function setUsuarioActual($usuario) { $_SESSION['usuario'] = $usuario; } } ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de tipos de mantenimientos</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarTipo"> <div> <table> <tr> <tr> <th>Nombre</th> <th>Descripción</th> <th>Cada cuanto tiempo</th><th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-tipos"> <?php foreach($this->tipos as $row){ $tipo = new TiposClass(); $tipo = $row; ?> </tr > <tr id="fila-<?php echo $tipo->getId(); ?>"> <td><?php echo $tipo->getNombre(); ?></td> <td><?php echo $tipo->getDescripcion(); ?></td> <td><?php echo $tipo->getTiempo(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>tipos/modificarTipo/<?php echo $tipo->getNombre();?>">Modificar</a></td> <td><button class="crud eliminar" data-id="<?php echo $tipo->getId(); ?>">Eliminar</button></td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>tipos/registrarTipo">Registrar</a> <a href="<?php echo constant('URL')?>opcion">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php if(isset($_POST['modificarRuta'])) { $id_ruta = ($_POST['id_ruta'] !== "") ? $_POST['id_ruta'] : NULL; $nombre_ruta = ($_POST['nombre_ruta'] !== "") ? $_POST['nombre_ruta'] : NULL; $direccion_ruta = ($_POST['direccion_ruta'] !== "") ? $_POST['direccion_ruta'] : NULL; $hora_salida = ($_POST['hora_salida'] !== "") ? $_POST['hora_salida'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; if ($this->model->rutas->update(['id_ruta'=>$id_ruta, 'nombre_ruta'=>$nombre_ruta, 'direccion_ruta'=>$direccion_ruta, 'placa'=>$placa, 'hora_salida'=>$hora_salida])){ $this->view->mensaje = '¡Ruta Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('rutas/mensaje'); } else { $rutas = $this->model->rutas->get($param[0]); $vehiculos = $this->model->rutas->getVehiculos(); $this->view->vehiculos = $vehiculos; if (isset($rutas)){ $this->view->rutas = $rutas[0]; $this->view->render('rutas/actualizar'); } else { $this->view->mensaje = 'Ruta no encontrado'; $this->view->render('rutas/mensaje'); } } ?><file_sep><?php class BitacoraClass extends Model { public $id_bitacora; public $id_usuario; public $fecha; public $hora; public $accion; function __construct() { parent::__construct(); } public function getIdBitacora() { return $this->id_bitacora; } public function getIdUsuario() { return $this->id_usuario; } public function getFecha() { return $this->fecha; } public function getHora() { return $this->hora; } public function getAccion() { return $this->accion; } //SETTERS public function setIdBitacora($id_bitacora) { $this->id_bitacora = $id_bitacora; } public function setUsuario($id_usuario) { $this->id_usuario = $id_usuario; } public function setFecha($fecha) { $this->fecha = $fecha; } public function setHora($hora) { $this->hora = $hora; } public function setAccion($accion) { $this->accion = $accion; } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Rutas</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Actualizar ruta</h2> </div> <div class="modal-container"> <?php include 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>rutas/modificarRuta" method="POST" class="form"> <div class="form__box "> <div> <label for="id_ruta">ID de la ruta</label> <input type="text" name="id_ruta" id="id_ruta" readonly value="<?php echo $this->rutas->getId();?>"> </div> <div> <label for="nombre_ruta">Nombre de la ruta:</label> <input type="text" name="nombre_ruta" id="nombre_ruta" placeholder="Ingrese el nombre_ruta" value="<?php echo $this->rutas->getNombre();?>"> </div> <div> <label for="direccion_ruta">Dirección:</label> <input type="text" name="direccion_ruta" id="direccion_ruta" value="<?php echo $this->rutas->getDireccion();?>"> </div> <div> <label for="hora_salida">Hora de salida:</label> <input type="time" name="hora_salida" id="hora_salida" value="<?php echo $this->rutas->getHoraSalida();?>"> </div> <div> <label for="vehiculo">Unidad encargada:</label> <select class="select" id="select" name="placa"> <option value="0">Seleccione</option> <?php foreach($this->vehiculos as $row){ $vehiculo = new VehiculosClass(); $vehiculo = $row; ?> <option value="<?php echo $vehiculo->getPlaca()?>"><?php echo $vehiculo->getPlaca().' - '.$vehiculo->getModelo(); ?></option> <?php } ?> </select> </div> </div> <div class="bottom"> <button type="submit" id="submit" name="modificarRuta" value="modificarRuta">Modificar ruta</button> <a href="<?php echo constant('URL')?>rutas/">Cancelar</a> </div> </form> </main> </div> </body> </html><file_sep><?php class mantenimientosCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO mantenimientos (nombre_tipo, placa , nombre, costo, fecha) VALUES(:tipo, :placa, :taller, :costo, :fecha)'); $query->execute(['tipo'=>$data['tipo'], 'placa'=>$data['placa'], 'taller'=>$data['taller'], 'costo'=>$data['costo'], 'fecha'=>$data['fecha']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id_mantenimiento = null) { $items = []; try { if ( isset($id_mantenimiento) ) { $query = $this->db->connect()->prepare('SELECT * FROM mantenimientos WHERE id_mantenimiento = :id_mantenimiento'); $query->execute(['id_mantenimiento'=>$id_mantenimiento]); } else { $query = $this->db->connect()->query('SELECT * FROM mantenimientos'); } while($row = $query->fetch()){ $item = new MantenimientosClass(); $item->setId($row['id_mantenimiento']); $item->setNombre_tipo($row['nombre_tipo']); $item->setPlaca($row['placa']); $item->setNombre($row['nombre']); $item->setCosto($row['costo']); $item->setFecha($row['fecha']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET VEHICULOS ********************************************************************************/ function getVehiculos ( $id = null) { $items = []; try { if ( isset($placa) ) { //Lo mas probable es que lo quieren condicionar a que solo se muestre los operativos asi que cambien el query $query = $this->db->connect()->prepare('SELECT * FROM vehiculos WHERE placa = :placa'); $query->execute(['placa'=>$placa]); } else { $query = $this->db->connect()->query('SELECT * FROM vehiculos'); } while($row = $query->fetch()){ $item = new VehiculosClass(); $item->setPlaca($row['placa']); $item->setModelo($row['modelo']); $item->setFuncionamiento($row['funcionamiento']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET Talleres ********************************************************************************/ function getTalleres ( $rif = null) { $items = []; try { if ( isset($rif) ) { $query = $this->db->connect()->prepare('SELECT * FROM taller WHERE rif = :rif'); $query->execute(['rif'=>$rif]); } else { $query = $this->db->connect()->query('SELECT * FROM taller'); } while($row = $query->fetch()){ $item = new TalleresClass(); $item->setRif($row['rif']); $item->setNombre($row['nombre']); $item->setDireccion($row['direccion']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET Tipos de mantenimientos ********************************************************************************/ function getTipos ( $id = null) { $items = []; try { if ( isset($nombre_tipo) ) { $query = $this->db->connect()->prepare('SELECT * FROM tipos WHERE nombre_tipo = :nombre_tipo'); $query->execute(['nombre_tipo'=>$nombre_tipo]); } else { $query = $this->db->connect()->query('SELECT * FROM tipos'); } while($row = $query->fetch()){ $item = new TiposCLass(); $item->setNombre($row['nombre_tipo']); $item->setDescripcion($row['descripcion']); $item->setTiempo($row['tiempo']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM mantenimientos WHERE id_mantenimiento = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE mantenimientos SET nombre_tipo = :nombre_tipo, placa = :placa, nombre = :nombre, costo = :costo, fecha = :fecha WHERE id_mantenimiento = :id_mantenimiento'); $query->execute(['id_mantenimiento'=>$data['id_mantenimiento'], 'nombre_tipo'=>$data['nombre_tipo'], 'placa'=>$data['placa'], 'nombre'=>$data['nombre'], 'costo'=>$data['costo'], 'fecha'=>$data['fecha']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Talleres</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> <?php echo $this->mensaje ?> <a class="mensaje-button" href="<?php echo constant('URL')?>talleres/" class="boton">Volver</a></h2> </div> </main> </div> </body> </html><file_sep><?php ob_start(); require 'plantilla.php'; $pdf = new PDF(); $pdf->AddPage(); $pdf->SetLeftMargin($pdf->GetPageWidth() / 2 - 100); $pdf->SetFont('Helvetica','B',15);//Tipo de letra, negrita, tamaño $pdf->Ln(10);//salto de linea $mantenimientos = $this->model->mantenimientos->get(); //MODELOS $pdf->Cell(200, 10, 'MANTENIMIENTO',2, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','B',12);//Tipo de letra, negrita, tamaño $pdf->Cell(10, 10, 'ID',1, 0,'C', 0); $pdf->Cell(65, 10, 'Nombre_mantenimiento',1, 0,'C', 0); $pdf->Cell(25, 10, 'Placa',1, 0,'C', 0); $pdf->Cell(45, 10, 'Taller',1, 0,'C', 0); $pdf->Cell(30, 10, 'Costo',1, 0,'C', 0); $pdf->Cell(25, 10, 'Fecha',1, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','',10);//Tipo de letra, negrita, tamaño foreach ($mantenimientos as $row) { $pdf->Cell(10,10, $row->getId(), 1, 0,'C', 0); $pdf->Cell(65,10, $row->getNombre_tipo(), 1, 0,'C', 0); $pdf->Cell(25,10, $row->getPlaca(), 1, 0,'C', 0); $pdf->Cell(45,10, $row->getNombre(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getCosto(), 1, 0,'C', 0); $pdf->Cell(25,10, $row->getFecha(), 1, 0,'C', 0); $pdf->Ln(10);//salto de linea } //$pdf->AddPage(); $pdf->Output(); ob_end_flush(); ?><file_sep><?php class partesequiposCRUD extends Model{ function __construct() { parent::__construct(); } function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO partesequipos (codequipo, codpartes, cantidadparteequipo, estatusparteequipo, codequipopartes) VALUES(:codequipo, :codpartes, :cantidadparteequipo,:estatusparteequipo, :codequipopartes)'); $query->execute(['codequipo'=>$data['codequipo'], 'codpartes'=>$data['codpartes'], 'cantidadparteequipo'=>$data['cantidadparteequipo'], 'estatusparteequipo'=>$data['estatusparteequipo'], 'codequipopartes'=>$data['codequipopartes']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM partesequipos WHERE codequipo = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM partesequipos'); } while($row = $query->fetch()){ $item = new PartesEquiposClass(); $item->setCod($row['codequipo']); $item->setCodParte($row['codpartes']); $item->setCantidadPartes($row['cantidadparteequipo']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } public function getError () { return $this->error; } } ?><file_sep><?php $libreria = 'fpdf/fpdf.php'; include ($libreria); class PDF extends FPDF { function Header(){ $this->setY(0); $this->setX(0); $this->SetFont('Helvetica','B',20);//Tipo de letra, negrita, tamaño $this->setFillColor(50,50,50); $this->SetTextColor(255,255,255); $this->Cell($this->GetPageWidth(),20,'Reporte',0,0,'C', TRUE); $this->Image(constant('URL').'/public/img/1.1.jpg', 0,0,50); $this->Image(constant('URL').'/public/img/UPTAEB.png', $this->GetPageWidth() - 25 ,0,23,19); $this->Ln(10); } } ?> <file_sep><?php class reparacionesCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO reparaciones (placa, nombre, descripcion, costo, fecha) VALUES(:placa, :nombre, :descripcion, :costo, :fecha)'); $query->execute(['placa'=>$data['placa'], 'nombre'=>$data['nombre'], 'descripcion'=>$data['descripcion'], 'costo'=>$data['costo'], 'fecha'=>$data['fecha']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id = null) { $items = []; try { if ( isset($id) ) { $query = $this->db->connect()->prepare('SELECT * FROM reparaciones WHERE id_reparaciones = :id'); $query->execute(['id'=>$id]); } else { $query = $this->db->connect()->query('SELECT * FROM reparaciones'); } while($row = $query->fetch()){ $item = new ReparacionesClass(); $item->setId($row['id_reparaciones']); $item->setNombre($row['nombre']); $item->setPlaca($row['placa']); $item->setCosto($row['costo']); $item->setFecha($row['fecha']); $item->setDescripcion($row['descripcion']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET VEHICULOS ********************************************************************************/ function getVehiculos ( $id = null) { $items = []; try { if ( isset($placa) ) { //Lo mas probable es que lo quieren condicionar a que solo se muestre los operativos asi que cambien el query $query = $this->db->connect()->prepare('SELECT * FROM vehiculos WHERE placa = :placa'); $query->execute(['placa'=>$placa]); } else { $query = $this->db->connect()->query('SELECT * FROM vehiculos'); } while($row = $query->fetch()){ $item = new VehiculosClass(); $item->setPlaca($row['placa']); $item->setModelo($row['modelo']); $item->setFuncionamiento($row['funcionamiento']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET Talleres ********************************************************************************/ function getTalleres ( $rif = null) { $items = []; try { if ( isset($rif) ) { $query = $this->db->connect()->prepare('SELECT * FROM taller WHERE rif = :rif'); $query->execute(['rif'=>$rif]); } else { $query = $this->db->connect()->query('SELECT * FROM taller'); } while($row = $query->fetch()){ $item = new TalleresClass(); $item->setRif($row['rif']); $item->setNombre($row['nombre']); $item->setDireccion($row['direccion']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM reparaciones WHERE id_reparaciones = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE reparaciones SET nombre = :nombre, descripcion = :descripcion, costo = :costo, fecha = :fecha, placa = :placa WHERE id_reparaciones = :id_reparaciones'); $query->execute(['id_reparaciones'=>$data['id_reparaciones'], 'nombre'=>$data['nombre'], 'descripcion'=>$data['descripcion'], 'costo'=>$data['costo'],'fecha'=>$data['fecha'],'placa'=>$data['placa']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { return false; } } public function getError () { return $this->error; } } ?> <file_sep><?php if ( $this->model->reparaciones->drop($param[0]) ) { $mensaje = 'Reparacion eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><?php if(isset($_POST['modificarTipo'])) { $nombre_tipo = ($_POST['nombre_tipo'] !== "") ? $_POST['nombre_tipo'] : NULL; $descripcion = ($_POST['descripcion'] !== "") ? $_POST['descripcion'] : NULL; $tiempo = ($_POST['tiempo'] !== "") ? $_POST['tiempo'] : NULL; if ($this->model->tipos->update(['nombre_tipo'=>$nombre_tipo, 'descripcion'=>$descripcion, 'tiempo'=>$tiempo])){ $this->view->mensaje = '¡Tipo de mantenimiento Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('tipos/mensaje'); } else { $tipos = $this->model->tipos->get($param[0]); if (isset($tipos)){ $this->view->tipos = $tipos[0]; $this->view->render('tipos/actualizar'); } else { $this->view->mensaje = 'Tipo de mantenimiento no encontrado'; $this->view->render('tipos/mensaje'); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Talleres</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de talleres</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarTaller"> <div> <table> <tr> <th>Rif</th> <th>Nombre</th> <th>Direccion</th> <th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-talleres"> <?php foreach($this->talleres as $row){ $taller = new TalleresClass(); $taller = $row; ?> </tr > <tr id="fila-<?php echo $taller->getId(); ?>"> <td><?php echo $taller->getRif(); ?></td> <td><?php echo $taller->getNombre(); ?></td> <td><?php echo $taller->getDireccion(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>talleres/modificarTaller/<?php echo $taller->getRif();?>">Modificar</a></td> <td><button class="crud eliminar" data-id="<?php echo $taller->getId(); ?>">Eliminar</button></td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>talleres/registrarTaller">Registrar</a> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php // Clase de mantenimientos para BD class MantenimientosClass { private $id_mantenimiento; private $nombre_tipo; private $placa; private $nombre; private $costo; private $fecha; public function getId() { return $this->id_mantenimiento; } public function getNombre_tipo() { return $this->nombre_tipo; } public function getPlaca() { return $this->placa; } public function getNombre() { return $this->nombre; } public function getCosto() { return $this->costo; } public function getFecha() { return $this->fecha; } //SETTERS public function setId($id_mantenimiento) { $this->id_mantenimiento = $id_mantenimiento; } public function setPlaca($placa) { $this->placa = $placa; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setNombre_tipo($nombre_tipo) { $this->nombre_tipo = $nombre_tipo; } public function setCosto($costo) { $this->costo = $costo; } public function setFecha($fecha) { $this->fecha = $fecha; } } ?><file_sep><?php if ( $this->model->usuarios->drop($param[0]) ) { $mensaje = 'Usuario Eliminado'; } else { $mensaje = 'Ha ocurrido un Error'; } echo $mensaje; ?><file_sep><?php require 'libs/classes/vehiculos.class.php'; require 'libs/classes/talleres.class.php'; require 'libs/classes/reparaciones.class.php'; require 'source/reparaciones/CRUD.php'; class ReparacionesModel extends Model { public $reparaciones; function __construct() { parent::__construct(); $this->reparaciones = new reparacionesCRUD(); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de mantenimientos</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarMantenimiento"> <div> <table> <tr><th>ID</th> <th>Taller</th><th>Vehiculo</th><th>Tipo de mantenimiento</th><th>Costo</th><th>Fecha</th> <th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-mantenimientos"> <?php foreach($this->mantenimientos as $row){ $mantenimientos = new MantenimientosClass(); $mantenimientos = $row; ?> </tr> <tr id="fila-<?php echo $mantenimientos->getId(); ?>"> <td><?php echo $mantenimientos->getId(); ?></td> <td><?php echo $mantenimientos->getNombre(); ?></td> <td><?php echo $mantenimientos->getPlaca(); ?></td> <td><?php echo $mantenimientos->getNombre_tipo(); ?></td> <td><?php echo $mantenimientos->getCosto(); ?></td> <td><?php echo $mantenimientos->getFecha(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>mantenimientos/modificarMantenimiento/<?php echo $mantenimientos->getId();?>">Modificar</a></td> <td> <button class="crud eliminar" data-id="<?php echo $mantenimientos->getId(); ?>">Eliminar</button> </td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>mantenimientos/registrarMantenimiento">Registrar</a> <a href="<?php echo constant('URL')?>opcion">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php class rutasCRUD extends Model{ public $error; function __construct() { parent::__construct(); } public function insert ($data) { try{ $query = $this->db->connect()->prepare('INSERT INTO rutas (nombre_ruta, direccion_ruta, hora_salida, placa) VALUES(:nombre_ruta, :direccion_ruta, :hora_salida, :placa)'); $query->execute(['nombre_ruta'=>$data['nombre_ruta'], 'direccion_ruta'=>$data['direccion_ruta'], 'hora_salida'=>$data['hora_salida'], 'placa'=>$data['placa']]); return true; } catch(PDOException $e){ $this->error = $e->getMessage(); return false; } } function get ( $id_ruta = null) { $items = []; try { if ( isset($id_ruta) ) { $query = $this->db->connect()->prepare('SELECT * FROM rutas WHERE id_ruta = :id_ruta'); $query->execute(['id_ruta'=>$id_ruta]); } else { $query = $this->db->connect()->query('SELECT * FROM rutas'); } while($row = $query->fetch()){ $item = new RutasClass(); $item->setId($row['id_ruta']); $item->setPlaca($row['placa']); $item->setNombre($row['nombre_ruta']); $item->setdireccion($row['direccion_ruta']); $item->setHoraSalida($row['hora_salida']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } /********************************************************************************* GET VEHICULOS ********************************************************************************/ function getVehiculos ( $id = null) { $items = []; try { if ( isset($placa) ) { //Lo mas probable es que lo quieren condicionar a que solo se muestre los operativos asi que cambien el query $query = $this->db->connect()->prepare('SELECT * FROM vehiculos WHERE placa = :placa'); $query->execute(['placa'=>$placa]); } else { $query = $this->db->connect()->query('SELECT * FROM vehiculos'); } while($row = $query->fetch()){ $item = new VehiculosClass(); $item->setPlaca($row['placa']); $item->setModelo($row['modelo']); $item->setFuncionamiento($row['funcionamiento']); array_push($items, $item); } return $items; } catch (PDOException $e) { return []; } } function drop ($id) { try { $query = $this->db->connect()->prepare('DELETE FROM rutas WHERE id_ruta = :id'); $query->execute(['id'=>$id]); if ( $query->rowCount() ) { return true; } else { return false; } } catch ( PDOException $e ) { return false; } } function update ($data) { try { $query = $this->db->connect()->prepare('UPDATE rutas SET nombre_ruta = :nombre_ruta, direccion_ruta = :direccion_ruta, hora_salida = :hora_salida, placa = :placa WHERE id_ruta = :id_ruta'); $query->execute (['nombre_ruta'=>$data['nombre_ruta'], 'direccion_ruta'=>$data['direccion_ruta'], 'hora_salida'=>$data['hora_salida'],'placa'=>$data['placa'],'id_ruta'=>$data['id_ruta']]); if ( $query->rowCount() ) { return true; } else { return false; } } catch (PDOException $e) { echo $e; return false; } } public function getError () { return $this->error; } } ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="<?php echo constant('URL')?>public/css/main.css"> <title>UT | Contacto</title> </head> <body> <header class="header"> <div class="wrapper"> <div class="logo"></div> <nav> <a href="Manual.pdf" target="blank" title="Manual del sistema">Manual</a> <a href="<?php echo constant('URL')?>login">Login</a> </nav> </div> </header> <main> <table class="tabla"> <tr> <th colspan="4" align="center">Desarroladores</th> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/desarrolladores/alejandro.png" width= "70px" class="desarrolladores"></td> <td><NAME></td> <td>0416-3154826</td> <td><EMAIL></td> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/desarrolladores/oriana.png" width= "70px"class="desarrolladores"></td> <td><NAME></td> <td>0414-5448669</td> <td><EMAIL></td> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/desarrolladores/ricardo.png" width= "70px"class="desarrolladores"></td> <td><NAME></td> <td>0412-5173238</td> <td><EMAIL></td> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/desarrolladores/antoni.png" width= "70px"class="desarrolladores"></td> <td><NAME></td> <td>0414-5373009</td> <td><EMAIL></td> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/desarrolladores/rafael.png" width= "70px"class="desarrolladores"></td> <td><NAME></td> <td>0416-2596465</td> <td><EMAIL></td> </tr> <tr> <th colspan="4" align="center">Institucion</th> </tr> <tr> <td><img src="<?php echo constant('URL')?>public/img/uptaeb.png" width= "70px"></td> <td>UPTAEB</td> <td>0414-5481970</td> <td> Av. Los Horcones, Avenida La Salle, Barquisimeto 3001, Lara</td> </tr> </table> </main> </body> </html><file_sep><?php class ReparacionesClass { private $id_reparacion; private $nombre; private $placa; private $costo; private $fecha; private $descripcion; public function getId() { return $this->id_reparacion; } public function getNombre() { return $this->nombre; } public function getPlaca() { return $this->placa; } public function getCosto() { return $this->costo; } public function getFecha() { return $this->fecha; } public function getDescripcion() { return $this->descripcion; } //SETTERS public function setId($id) { $this->id_reparacion = $id; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setPlaca($placa) { $this->placa = $placa; } public function setCosto($costo) { $this->costo = $costo; } public function setFecha($fecha) { $this->fecha = $fecha; } public function setDescripcion($descripcion) { $this->descripcion = $descripcion; } } ?><file_sep><?php // Clase de talleres para BD class TalleresClass { private $id; private $rif; private $nombre; private $direccion; public function getId() { return $this->id; } public function getRif() { return $this->rif; } public function getNombre() { return $this->nombre; } public function getDireccion() { return $this->direccion; } //SETTERS public function setId($id) { $this->id = $id; } public function setRif($rif) { $this->rif = $rif; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setDireccion($direccion) { $this->direccion = $direccion; } } ?><file_sep>document.addEventListener("DOMContentLoaded", function() { document.getElementById("formulario").addEventListener('submit', validarFormulario); }); function validarFormulario(evento) { var select = document.getElementById("select").selectedIndex; if(select == null || select == 0){ alert("Debe seleccionar la unidad que maneja el chofer registrado"); return false; } }<file_sep>(function(){ var formulario = document.getElementsByName('formulario')[0], elementos = formulario.elements, nombre = document.getElementById('nombre'), apellido = document.getElementById('apellido'); cedula = document.getElementById('cedula'); var campos = function(e){ if (formulario.nombre.value == 0 || formulario.apellido.value == 0 || formulario.cedula.value == 0) { alert("Todos los campos son obligatorios"); e.preventDefault() } } formulario.addEventListener("submit", campos); }()) <file_sep><!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></title> </head> <body> <header class="header"> <div class="wrapper"> <table class="icono_usuario"> <tr> <td><div class="logo"></div> </td> <td><p style="color: white;"><?php echo $this->nombre.' - Rol: '. $this->rol; ?></p></td> </tr> </table> <nav> <a href="Manual.pdf" target="blank" title="Manual del sistema">Manual</a> <a href="<?php echo constant('URL')?>main">Inicio</a> </nav> </div> <?php require 'views/menu.php'; ?> </header> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> UT| Reportes</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2> Reportes </h2> </div> <div class="tabla" id="form"> <div> <table> <th><a class="crud" href="<?php echo constant('URL')?>reportes/choferes"><img src="<?php echo constant('URL')?>public/img/icoReportes/chofer.png" whith><br>Choferes</a></th> <th><a class="crud" href="<?php echo constant('URL')?>reportes/mantenimientos"><img src="<?php echo constant('URL')?>public/img/icoReportes/mantenimiento.png"><br>Mantenimiento</a></th> <th><a class="crud" href="<?php echo constant('URL')?>reportes/reparaciones"><img src="<?php echo constant('URL')?>public/img/icoReportes/reparacion.png"><br>Reparaciones</a></th> <th><a class="crud" href="<?php echo constant('URL')?>reportes/talleres"><img src="<?php echo constant('URL')?>public/img/icoReportes/taller.png"><br>Talleres</a></th> <th><a class="crud" href="<?php echo constant('URL')?>reportes/rutas"><img src="<?php echo constant('URL')?>public/img/icoReportes/ruta.png"><br>Rutas</a></th> <th><a class="crud" href="<?php echo constant('URL')?>reportes/vehiculos"><img src="<?php echo constant('URL')?>public/img/icoReportes/vehiculo.png"><br>Vehiculos</a></th> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> </main> </div> </body> </html> <file_sep><?php include 'models/plantilla.php'; require 'conexion.php';//no es esto pero no se cual es la que se pone $query="SELECT...//aqui obtiene los datos que van al pdf"; $pdf=new PDF(); $pdf->AliasPages();//esta funcion reconoce a {nb} y reconozca las pg del doc $pdf->AddPage(); $pdf->SetFillColor(232,232,232); $pdf->SetFont('Arial', 'B', 15); $pdf->Cell(90, 10, 'idmodelo',1, 0,'c', 0); $pdf->Cell(90, 10, 'estatus',1, 0,'c', 0); $pdf->Cell(90, 10, 'codigo parte',1, 1,'c', 0);//esta hace un salto de linea para ir al contenido $pdf->SetFont('Arial', 'B', 15); while($row=$resultado->fetch_assoc()){ $pdf->Cell(90, 10, 'idmodelo',1, 0,'c'); $pdf->Cell(90, 10, 'estatus',1, 0,'c'); $pdf->Cell(90, 10, 'codigo parte',1, 1,'c'); } $pdf->Output('F','Reporte_modelos.pdf'); ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Rutas</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de rutas</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarRuta"> <div> <table> <tr> <th>Id</th><th>Unidad encargada</th><th>Nombre de la ruta</th><th>Dirección</th><th>Hora de salida</th> <th>Modificar</th><th>Eliminar</th> <tbody id="tbody-rutas"> <?php foreach($this->rutas as $row){ $ruta = new RutasClass(); $ruta = $row; ?> </tr > <tr id="fila-<?php echo $ruta->getId(); ?>"> <td><?php echo $ruta->getId(); ?></td> <td><?php echo $ruta->getPlaca(); ?></td> <td><?php echo $ruta->getNombre(); ?></td> <td><?php echo $ruta->getDireccion(); ?></td> <td><?php echo $ruta->getHoraSalida(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>rutas/modificarRuta/<?php echo $ruta->getId();?>">Modificar</a></td> <td> <button class="crud eliminar" data-id="<?php echo $ruta->getId(); ?>">Eliminar</button> </td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>rutas/registrarRuta">Registrar</a> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> </body> </html> <file_sep><?php ob_start(); require 'plantilla.php'; $pdf = new PDF(); $pdf->AddPage(); $pdf->SetLeftMargin($pdf->GetPageWidth() / 2 - 100); $pdf->SetFont('Helvetica','B',15);//Tipo de letra, negrita, tamaño $pdf->Ln(10);//salto de linea $talleres = $this->model->talleres->get(); //MODELOS $pdf->Cell(200, 10, 'TALLERES',2, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','B',12);//Tipo de letra, negrita, tamaño $pdf->Cell(10, 10, 'ID',1, 0,'C', 0); $pdf->Cell(30, 10, 'RIF',1, 0,'C', 0); $pdf->Cell(45, 10, 'Nombre',1, 0,'C', 0); $pdf->Cell(115, 10, 'Direccion',1, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','',10);//Tipo de letra, negrita, tamaño foreach ($talleres as $row) { $pdf->Cell(10,10, $row->getId(), 1, 0,'C', 0); $pdf->Cell(30,10, $row->getRif(), 1, 0,'C', 0); $pdf->Cell(45,10, $row->getNombre(), 1, 0,'C', 0); $pdf->Cell(115,10, $row->getDireccion(), 1, 0,'C', 0); $pdf->Ln(10);//salto de linea } //$pdf->AddPage(); $pdf->Output(); ob_end_flush(); ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Mantenimientos</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> </head> <body> <!-- Uso esta clase por el fondo rojo --> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Actualizar tipos de mantenimientos</h2> </div> <div class="modal-container"> <?php include 'views/errores/mensaje.php'?> </div> <form action="<?php echo constant('URL')?>tipos/modificarTipo" method="POST" class="form"> <div class="form__box "> <div> <label for="nombre_tipo">Nombre:</label> <input type="text" name="nombre_tipo" readonly id="nombre_tipo" value="<?php echo $this->tipos->getNombre();?>"> </div> <div> <label for="descripcion">Descripcion:</label> <input type="text" name="descripcion" id="nombre" value="<?php echo $this->tipos->getDescripcion();?>"> </div> <div> <label for="tiempo">Cada cuanto tiempo se realiza:</label> <input type="text" name="tiempo" id="tiempo" value="<?php echo $this->tipos->getTiempo();?>"> </div> </div> <div class="bottom"> <button type="submit" id="submit" name="modificarTipo" value="modificarTipo">Modificar Tipo</button> <a href="<?php echo constant('URL')?>tipos/">Cancelar</a> </div> </form> </main> </div> </body> </html><file_sep><?php if(isset($_POST['agregar'])){ $nombre_ruta = ($_POST['nombre_ruta'] !== "") ? $_POST['nombre_ruta'] : NULL; $direccion_ruta = ($_POST['direccion_ruta'] !== "") ? $_POST['direccion_ruta'] : NULL; $hora_salida = ($_POST['hora_salida'] !== "") ? $_POST['hora_salida'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; if ($this->model->rutas->insert(['nombre_ruta'=>$nombre_ruta, 'direccion_ruta'=>$direccion_ruta, 'placa'=>$placa, 'hora_salida'=>$hora_salida])){ $this->view->mensaje = '¡Ruta agregada exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; $this->view->error = $this->model->rutas->getError(); } $this->view->render('rutas/mensaje'); }else{ $this->view->mensaje = 'Rellene los campos'; $vehiculos = $this->model->rutas->getVehiculos(); $this->view->vehiculos = $vehiculos; $this->view->render('rutas/agregar'); } ?><file_sep><?php class TiposClass { private $id; private $nombre_tipo; private $descripcion; private $tiempo; public function getId() { return $this->id; } public function getNombre() { return $this->nombre_tipo; } public function getDescripcion() { return $this->descripcion; } public function getTiempo() { return $this->tiempo; } //SETTERS public function setId($id) { $this->id = $id; } public function setNombre($nombre_tipo) { $this->nombre_tipo = $nombre_tipo; } public function setDescripcion($descripcion) { $this->descripcion = $descripcion; } public function setTiempo($tiempo) { $this->tiempo = $tiempo; } } ?><file_sep><?php ob_start(); require 'plantilla.php'; $pdf = new PDF(); $pdf->AddPage(); $pdf->SetLeftMargin($pdf->GetPageWidth() / 2 - 63); $pdf->SetFont('Helvetica','B',15);//Tipo de letra, negrita, tamaño $pdf->Ln(10);//salto de linea $vehiculos = $this->model->vehiculos->get(); //MODELOS $pdf->Cell(130, 10, 'VEHICULOS REGISTRADOS',2, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','B',12);//Tipo de letra, negrita, tamaño $pdf->Cell(10, 10, 'ID',1, 0,'C', 0); $pdf->Cell(25, 10, 'Placa',1, 0,'C', 0); $pdf->Cell(40, 10, 'Modelo',1, 0,'C', 0); $pdf->Cell(50, 10, 'Funcionamiento',1, 0,'C', 0); $pdf->Ln(10); $pdf->SetFont('Arial','',10);//Tipo de letra, negrita, tamaño foreach ($vehiculos as $row) { $pdf->Cell(10,10, $row->getId(), 1, 0,'C', 0); $pdf->Cell(25,10, $row->getPlaca(), 1, 0,'C', 0); $pdf->Cell(40,10, $row->getModelo(), 1, 0,'C', 0); $pdf->Cell(50,10, $row->getFuncionamiento(), 1, 0,'C', 0); $pdf->Ln(10);//salto de linea } //$pdf->AddPage(); $pdf->Output(); ob_end_flush(); ?><file_sep><?php if(isset($_POST['modificarMantenimiento'])) { $id_mantenimiento = ($_POST['id_mantenimiento'] !== "") ? $_POST['id_mantenimiento'] : NULL; $placa = ($_POST['placa'] !== "") ? $_POST['placa'] : NULL; $nombre = ($_POST['taller'] !== "") ? $_POST['taller'] : NULL; $nombre_tipo = ($_POST['tipo'] !== "") ? $_POST['tipo'] : NULL; $costo = ($_POST['costo'] !== "") ? $_POST['costo'] : NULL; $fecha = ($_POST['fecha'] !== "") ? $_POST['fecha'] : NULL; if ($this->model->mantenimientos->update(['id_mantenimiento'=>$id_mantenimiento, 'placa'=>$placa, 'nombre'=>$nombre, 'costo'=>$costo, 'fecha'=>$fecha, 'nombre_tipo'=>$nombre_tipo])){ $this->view->mensaje = '¡Mantenimiento Modificado exitosamente!'; }else{ $this->view->mensaje = '¡Ha ocurrido un error!'; } $this->view->render('mantenimientos/mensaje'); } else { $mantenimientos = $this->model->mantenimientos->get($param[0]); $vehiculos = $this->model->mantenimientos->getVehiculos(); $this->view->vehiculos = $vehiculos; $tipos = $this->model->mantenimientos->getTipos(); $this->view->tipos = $tipos; $talleres = $this->model->mantenimientos->getTalleres(); $this->view->talleres = $talleres; if (isset($mantenimientos)){ $this->view->mensaje = 'Actualizar mantenimientos'; $this->view->mantenimientos = $mantenimientos[0]; $this->view->render('mantenimientos/actualizar'); } else { $this->view->mensaje = 'Actualizar mantenimientos'; $this->view->mensaje = 'Mantenimiento no encontrado'; $this->view->render('mantenimientos/mensaje'); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>UT | Iniciar sesion</title> <link rel="stylesheet" type="text/css" href="<?php echo constant('URL')?>public/css/main.css"> <body> <header class="header"> <div class="wrapper"> <div class="logo"> </div> <nav> <a href="Manual.pdf" target="blank" title="Manual del sistema">Manual</a> <a href="<?php echo constant('URL')?>contacto">Contacto</a> </nav> </div> </header> <main> <div class="login" > <?php if (isset($this->mensaje) ) { ?> <h2 id="mensaje"> <?php echo $this->mensaje; ?> </h2> <?php } ?> <form id="login" name="formulario" action="<?php echo constant('URL')?>login" class="login__form"method="POST"> <div class="img_logo"></div> <input class="login_input" type="text" name="usuario" placeholder="Usuario" data-id="Campo de nombre de usuario" id="usuario " /> <input class="login_input" type="password" name="contrasena" placeholder="********" data-id="Campo de Contraseña" id="contrasena" /> <button type="submit" name="ingresar" class="boton" value="ingresar">Iniciar Sesion</button> <p class="restaurar"> <a href="<?php echo constant('URL')?>restaurar">¿Olvidaste la contraseña?</a> </p> </form> </div> </main> <script src="<?php echo constant('URL')?>public/js/validacion/login.js"></script> </body> </html> <file_sep><?php // Clase de usuario para BD class SessionUsuario extends Controller { public $nombre; public $rol; public $cedula; //para validar si existe public function userExists( $nombre, $contrasena ) { $query = $this->model->db->connect()->prepare('SELECT * FROM usuarios WHERE nombre = :nombre AND contrasena = :contrasena'); $query->execute(['nombre' => $nombre, 'contrasena' => $contrasena]); if($query->rowCount()){ return true; } else{ return false; } } //Para configurar los valores public function setUsuario ($nombre) { $query = $this->model->db->connect()->prepare('SELECT * FROM usuarios WHERE nombre = :nombre'); $query->execute(['nombre' => $nombre]); foreach($query as $usuarioActual) { $this->nombre = $usuarioActual['nombre']; $this->cedula = $usuarioActual['cedula']; $this->rol = $usuarioActual['rol']; } } public function getNombre() { return $this->nombre; } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="<?php echo constant('URL')?>public/img/uptaeb1.png" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>UT | Choferes</title> <link rel="stylesheet" href="<?php echo constant('URL')?>public/css/main.css"> <script src="<?php echo constant('URL')?>public/js/jquery-3.4.1.min.js"></script> </head> <body> <?php require 'views/header.php'; ?> <!-- MENU --> <div class="container"> <main> <div class="text-header"> <h2>Gestion de choferes</h2> </div> <div class="tabla" id="form" data-eliminar="eliminarChofer"> <div> <table> <tr><th>ID</th> <th>Nombre</th><th>Apellido</th><th>C.I.</th><th>Telefono</th><th>Vehiculo</th> <th>Modificar</th> <th>Eliminar</th> <tbody id="tbody-choferes"> <?php foreach($this->choferes as $row){ $choferes = new ChoferesClass(); $choferes = $row; ?> </tr > <tr id="fila-<?php echo $choferes->getId(); ?>"> <td><?php echo $choferes->getId(); ?></td> <td><?php echo $choferes->getNombre(); ?></td> <td><?php echo $choferes->getApellido(); ?></td> <td><?php echo $choferes->getCedula(); ?></td> <td><?php echo $choferes->getTelefono(); ?></td> <td><?php echo $choferes->getPlaca(); ?></td> <td><a class="crud" href="<?php echo constant('URL')?>choferes/modificarChofer/<?php echo $choferes->getId();?>">Modificar</a></td> <td> <button class="crud eliminar" data-id="<?php echo $choferes->getId(); ?>">Eliminar</button> </td> </tr> <?php } ?> </tbody> </table> </div> <div class="bottom"> <a href="<?php echo constant('URL')?>choferes/registrarChofer">Registrar</a> <a href="<?php echo constant('URL')?>">Volver</a> </div> </div> </main> </div> <script src="<?php echo constant('URL')?>public/js/AJAX/eliminar.js"></script> </body> </html> <file_sep><?php require 'libs/classes/bitacora.class.php'; require 'libs/classes/usuarios.class.php'; require 'source/bitacora/CRUD.php'; class BitacoraModel extends Model { public $bitacora; function __construct() { parent::__construct(); $this->bitacora = new bitacoraCRUD(); } } ?><file_sep><?php class Mantenimientos extends Controller{ function __construct () { parent::__construct(); } function render () { $this->view->mensaje = 'Esta pagina controla los mantenimientos'; $mantenimientos = $this->model->mantenimientos->get(); $this->view->mantenimientos = $mantenimientos; $this->view->render('mantenimientos/index'); } public function load ($metodo, $param = null) { $ruta = 'source/mantenimientos/'.$metodo.'.php'; $ruta == "source/mantenimientos/index.php"; require_once $ruta; } } ?> <file_sep><?php class ChoferesClass { private $id_chofer; private $cedula; private $nombre; private $apellido; private $telefono; private $placa; public function getId() { return $this->id_chofer; } public function getCedula() { return $this->cedula; } public function getNombre() { return $this->nombre; } public function getApellido() { return $this->apellido; } public function getTelefono() { return $this->telefono; } public function getPlaca() { return $this->placa; } //SETTERS public function setId($id) { $this->id_chofer = $id; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setApellido($apellido) { $this->apellido = $apellido; } public function setCedula($cedula) { $this->cedula = $cedula; } public function setTelefono($telefono) { $this->telefono = $telefono; } public function setPlaca($placa) { $this->placa = $placa; } } ?><file_sep>(( c, d, a )=>{ d.addEventListener('DOMContentLoaded',()=>{ submit.addEventListener('click', (e)=>{ if (validacionEstaBien()) { //function principal de validacion c('validacion correcta!') }else{ c('validacion incorrecta') e.preventDefault() //prevenir que se envie el formulario } }) }) const validacionEstaBien = ()=> { //tomar inputs y botones let rif = d.querySelector('#costo') //input de nombre let submit = d.querySelector('#submit') //input de submit if (estaVacio(costo)){ alert('Todos los campos son requeridos') return false } return true } const estaVacio = (...elementos) => { let validacion = false elementos.forEach(elemento => { let valor = elemento.value.trim() //en caso de que haya alguno vacio if (valor.length <= 3) { //si entra en la condicional es porque //hay uno vacio validacion = true elemento.classList.add('alerta-input') } else { elemento.classList.remove('alerta-input') } }) return validacion } const coincideExpresionRegular = (...elementos) => { let validacion = true elementos.forEach(elemento => { let patron = elemento.dataset.patron let valor = elemento.value.trim() if (!valor.match(patron)) { validacion = false elemento.classList.add('alerta-input') elemento.nextElementSibling.classList.remove('esconder') } else { elemento.classList.remove('alerta-input') elemento.nextElementSibling.classList.add('esconder') } }) return validacion } })(console.log, document, alert) <file_sep><?php require 'libs/classes/vehiculos.class.php'; require 'source/vehiculos/CRUD.php'; class VehiculosModel extends Model { public $vehiculos; function __construct() { parent::__construct(); $this->vehiculos = new vehiculosCRUD(); } } ?>
5aa4408d25837c0edc5d2f10f004c1c96b87a328
[ "JavaScript", "SQL", "Markdown", "PHP" ]
115
PHP
RAAO-uptaeb/Sistema-transporte
2b1b2be408b2056cc137c6084311cb708d3cc44d
8cc51f8dce5dde9f89569fb4610e054b87178c40
refs/heads/master
<file_sep><?php $zoo = array ( "Africa" => array("Smilodon", "Equus grevyi", "Calotragus scoparius"), "North America" => array("Stylinodon", "Coryphodon", "Embolotherium ergilense"), "South America" => array("Astrapotherium magnum", "Toxodon", "Thalassocnus"), "Eurasia" => array("Platybelodon", "Coelodonta antiquitatis"), "Australia" => array("Palorchestes azael", "Diprotodon") ); print_r ($zoo); #echo count($animals); колличество элементов в массиве echo "<hr><table border = \"10\">"; foreach($zoo as $continent=>$ziv) { echo "<tr><td><b>$continent</b></td>"; for ($i = 0; $i < count($ziv); $i ++) { #if (preg_match ("/\w+ \w+/",$ziv[$i])) { echo "<td>".$ziv[$i]."</td>"; } } echo "</tr>\n"; } echo "</table><hr>"; echo "<hr><table border = \"10\">"; foreach($zoo as $continent=>$ziv) { $spisok = null; echo "<tr><td><b>$continent</b></td>"; for ($i = 0; $i < count($ziv); $i ++) { if (preg_match ("/\w+ \w+/",$ziv[$i])) { echo "<td>".$ziv[$i]."</td>"; $spisok[] = $ziv[$i]; } } $zoo[$continent] = $spisok; echo "</tr>\n"; #echo "*"; #print_r($spisok); #echo "*"; #echo $spisok; #print_r($spisok); } echo "</table><hr>"; #$zoo['Africa']=$spisok; #echo $zoo['Africa'][0]; print_r ($zoo); ?><file_sep><?php # наш массив $zoo заданный пользователем $zoo = array ( "Africa" => array("Smildoon", "Equus grevyi", "Calotragus scoparius"), "North America" => array("Stylinodon", "Coryphodon", "Embolotherium ergilense", "Mammuthus primigenius"), "South America" => array("Astrapotherium magnum", "Toxodon", "Thalassocnus", "Mammuthus columbi"), "Eurasia" => array("Platybelodon", "Coelodonta antiquitatis"), "Australia" => array("Palorchestes azael", "Diprotodon") ); #в переменной $zoo1 храниться ассоциативный массив континент => слово из имени животного $zoo1 = null; # выводим наш массив на экран echo "выводим наш массив zoo на экран"; echo "<hr><table border = \"10\">"; foreach($zoo as $continent => $ziv) { echo "<tr><td><b>$continent</b></td>"; for ($i = 0; $i < count($ziv); $i ++) { echo "<td>".$ziv[$i]."</td>"; $zoo1[$continent][] = $names[0]; ############################## формируем массив zoo1 if ($names[1] == true) {$zoo1[$continent][] = $names[1];} ##### формируем массив zoo1 } echo "</tr>\n"; } echo "</table><hr>"; ######################################################### конец вывода ######################################################### Создаем массив названий из имен с двумя словами zoo2 echo "Создаем массив названий из имен с двумя словами - zoo2"; echo "<hr><table border = \"10\">"; foreach($zoo as $continent => $ziv) { foreach($ziv as $name) { if (strpos ($name, " ") == true){ $zoo2[$continent][] = $name; //echo $name; } } } var_dump($zoo2); echo "<hr>"; foreach ($zoo2 as $continent => $ziv) { foreach ($ziv as $name) { $names = str_word_count($name, 1); $zoo3[$continent][] = $names[0]; //Создаем два массива, в одном только первые слова zoo2, во втором вторые $zoo4[$continent][] = $names[1]; } } echo "Печатаем два массива, в одном только первые слова zoo2, во втором вторые"; echo "<hr>"; print_r($zoo3); echo "<hr>"; print_r($zoo4); echo "<hr>"; //$result = array_merge($zoo3, $zoo4); $keys = array_keys ($zoo3); //Создаем массив континентов echo "<hr>"; echo count($zoo4); print_r($keys); echo "<hr>"; //print_r($result); /* # создаем массив fantazy = zoo3 + перемешаный zoo4 фантазийных животных shuffle($zoo4); print_r($zoo4); echo count($zoo4); echo "<hr>"; echo "*****"; var_dump($zoo3); echo "*****"; foreach ($zoo3 as $continent => $fziv) { echo $fziv[0]; echo $fziv[1]; for ($i = 0;$i < count($fziv); $i ++;) { echo $fziv[$i] } } } echo "*****"; #$fz = $fziv[0]; #$sword = array_shift ($fziv); #$fziv[] = $zoo4[$continent][0]; #foreach($fziv as $name) #{ # $fantazy[$continent][] = $zoo3[$continent][$fziv[0]] #{ #} #$cont_arr foreach ($zoo4 as $continent => $ziv1) { $zoo4_lite[]=$ziv1[0]; } print_r($zoo4_lite); echo "<hr>"; # перезаписываем zoo3 массив //var_dump($zoo5); echo "<hr><table border = \"10\">"; foreach($zoo5 as $continent => $ziv) { echo "<tr><td><b>$continent</b></td>"; for ($i = 0; $i < count($ziv); $i ++) { echo "<td>".$ziv[$i]."</td>"; $zoo1[$continent][] = $names[0]; ############################## формируем массив zoo1 if ($names[1] == true) {$zoo1[$continent][] = $names[1];} ##### формируем массив zoo1 } echo "</tr>\n"; } echo "</table><hr>"; $zoo[$continent] = $spisok; #### перезаписываем массив zoo на новый массив из имен с двумя словами echo "</tr>\n"; echo "</table><hr>"; ######################################################### конец вывода ######################################################### Выводим массив zoo1 названий из имен с одним словом echo "Выводим массив zoo1 названий из имен с одним словом"; echo "<hr><table border = \"10\">"; foreach($zoo1 as $continent => $ziv) { echo "<tr><td><b>$continent</b></td>"; for ($i = 0; $i < count($ziv); $i ++) { echo "<td>".$ziv[$i]."</td>"; } echo "</tr>\n"; } echo "</table><hr>"; ######################################################### конец вывода # ниже приведены примеры функции print_r ($zoo); #str_split; $str = "<NAME>"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1); echo "<hr>"; print_r($arr2); echo "<hr>"; print_r($zoo1); echo "<hr>"; */ ?>
76ec9ee761cc1eb97b4a6f1f010099f1af033419
[ "PHP" ]
2
PHP
a-alex2000/zoo
60ee91489ab4b5f4e1f85a2abc697976ec9b9700
ccdcb38ccf469f927bbbf8185a1ce1484fb07243
refs/heads/master
<repo_name>AugustArchive/qtradio.js<file_sep>/readme.md # qtradio.moe API > :tulip: **API wrapper for qtradio.moe made in JavaScript** > > :warning: **This wrapper is deprecated, don't use this because it will not work!** ## Usage ```js const qtradio = require('qtradio.js'); const radio = qtradio.createInstance(); radio.getInfo(); ``` ## License > [qtradio.js](https://github.com/auguwu/qtradio.js) is made by auguwu & is released under the MIT license > > [qtradio.moe](https://qtradio.moe) is owned by [LiquidBlast](https://github.com/LiquidBlast); this isn't an official wrapper for qtradio.moe ``` Copyright (c) 2019-present auguwu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` <file_sep>/tests/qtradio.test.js const UwU = require('../lib'); const cli = UwU.createInstance(); cli.getInfo().then(console.log);<file_sep>/index.d.ts // Typescript Typings for npm package: qtradio.js // Project and Typings made by auguwu declare module 'qtradio.js' { /** * Version constant for qtradio.ts */ export const version: string; /** * Create an instance of the qtradio.ts client * You can do `new RadioClient()` but this is for lazy people * like the creator * @returns The instance */ export function createInstance(): RadioClient; /** The client itself */ export class RadioClient { constructor(); public getInfo(): Promise<InfoData>; } /** Info data */ export interface InfoData { icestats: { admin: string; host: string; location: string; server_id: string; server_start: string; server_start_iso8601: string; source: { artist: string; audio_bitrate: number; audio_channels: number; audio_info: string; audio_samplerate: number; channels: number; genre: string; 'ice-bitrate': number; listener_peak: number; listeners: number; listenurl: string; samplerate: number; server_description: string; server_name: string; server_type: string; server_url: string; stream_start: string; stream_start_iso8601: string; subtype: string; title: string; dummy?: string; }[]; } } }<file_sep>/lib/index.js const Client = require('./client'); module.exports = { /** * Create a new instance of the client * You can still use `new RadioClient` but this * is far easier for us lazy people * @returns {Client} The instance */ createInstance: () => new Client(), RadioClient: Client, version: require('../package').version };<file_sep>/lib/client.js const wump = require('wumpfetch'); module.exports = class RadioClient { /** * Gets the information * @returns {Promise<InfoData>} */ async getInfo() { const req = await wump .get('https://qtradio.moe/stats') .send(); return req.json(); }; }; /** * @typedef {Object} InfoData * @prop {IceStats} icestats qtradio.moe's server info * * @typedef {Object} IceStats * @prop {string} admin Admin name * @prop {string} host The host * @prop {string} location The location * @prop {string} server_id The server ID * @prop {string} server_start When the server started * @prop {string} server_start_iso8601 ISO-8601 code of the server start * @prop {Source[]} source An array of the song that qtradio is playing * * @typedef {Object} Source * @prop {string} artist The artist * @prop {number} audio_bitrate The audio bitrate * @prop {number} audio_channels The number of audio channels are avaliable * @prop {string} audio_info Information about the audio? * @prop {number} audio_samplerate The audio samplerate * @prop {number} channels The number of channels * @prop {string} genre The genere that it's playing * @prop {number} listener_peak The listener peak number * @prop {number} listeners The number of listeners that is listening * @prop {string} listenurl The URL of the song, don't use this since it can break (it uses localhost:8080; which is from qtradio.moe's server) * @prop {number} samplerate The samplerate * @prop {string} server_description The server descripion * @prop {string} server_name The server name * @prop {string} server_type The server type * @prop {string} server_url The server url (it uses localhost:8080; don't use!) * @prop {string} stream_start When the song started playing * @prop {string} stream_start_iso8601 When the song started playing in ISO-8601 form * @prop {string} subtype The subtype, usally `Vorbis` * @prop {string} title The title * @prop {string} [dummy] The dummy string (don't use since it's null) */
c9146678096e669cdddae9b2c2204c298bcbaaad
[ "Markdown", "TypeScript", "JavaScript" ]
5
Markdown
AugustArchive/qtradio.js
fd6d320eeed177359745d0574ca736fe227e4664
8c1a083682f6684d47824d19c73d0a805c7f5513
refs/heads/master
<file_sep><?php namespace application\contorllers; class BoardController extends contorllers { public function index($category, $idx, $pageNo) { $model = new \application\models\BoardModel(); $list = $model->selectList($category, $idx, $pageNo); require_once 'application/views.board.index.php'; } public function writeView($category, $idx, $pageNo) { require_once 'application/views/board/write.php'; } public function insertBoard($category, $idne, $pageNo) { $model = new \application\models\BoardModel(); if (isset($_POST["submit_inset_board"])) { $model->insertBoard($_POST["title"], $_POST["content"]); } header('location:/board/index'); } }<file_sep><h1>게시판</h1> <a href="/board.writeView">글쓰기</a> <?php if ($list[0] == 0){ echo '현재 작성된 글이 없습니다.<br>'; } else { foreach ($list[1] as $item){ ?> <a href="localhost:8081/board/view/board/<?php echo $item->idx; ?>"> <h3>제목 : <?php echo $item->title; ?></h3> </a> <?php } } ?><file_sep><?php define('_DBTYPE', 'mysql'); define('_HOST', 'localhost'); define('_DBNAME', 'chobo'); define('_DBUSER', 'root'); define('_DBPASSWORD', '<PASSWORD>'); define('_CHARSET', 'utf8');<file_sep><?php require_once 'application/libs/config.php'; require_once _ROOT.'/application/vender/autoload.php'; new \application\libs\application(); <file_sep># php-MVC # 자료 정리중... [환경설정 포스팅 완료](https://velog.io/@sik2/PHP-MVC-%EA%B2%8C%EC%8B%9C%ED%8C%90-%EB%A7%8C%EB%93%A4%EA%B8%B0) # 맥설정 완료 2019.12.26 시작 # 2019-12-30 튜토리얼 끝
6281803040c49fb859ddc9958a738cd6a84616a2
[ "Markdown", "PHP" ]
5
PHP
devpang20/php-mvc
ba86aa1ae1cf58d1fa613629bfae469ec3edb6d5
716fe1107a4f4b1090c94de64a2ca2779184350c
refs/heads/master
<file_sep>package com.btc.web.service; import com.btc.web.notification.EmailAlertNotification; import com.btc.web.web.WebServiceController; import com.google.common.collect.Maps; import org.quartz.DisallowConcurrentExecution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * Created by Chris on 12/19/15. */ @Service @DisallowConcurrentExecution public class SchedulerService { @Value("${playlist.widget}") private String playlistWidget; @Value("${playlist.widget_feed}") private String playlistWidgetFeed; @Value("${playlist.comix}") private String playlistComix; @Value("${playlist.comix_feed}") private String playlistComixFeed; @Value("${widget_scheduler.enabled}") private boolean widgetSchedulerEnabled; @Value("${widget_scheduler.email.enabled}") private boolean widgetSchedulerEmailEnabled; @Value("${widget_scheduler.email.alert.subject}") private String widgetEmailAlertSubject; @Value("${widget_scheduler.email.alert.recipient.list}") private String widgetEmailAlertRecipientList; @Value("${widget_scheduler.cron}") private String widgetCronSchedule; @Value("${comix_scheduler.enabled}") private boolean comixSchedulerEnabled; @Value("${comix_scheduler.email.enabled}") private boolean comixSchedulerEmailEnabled; @Value("${comix_scheduler.email.alert.subject}") private String comixEmailAlertSubject; @Value("${comix_scheduler.email.alert.recipient.list}") private String comixEmailAlertRecipientList; @Value("${comix_scheduler.cron}") private String comixCronSchedule; @Autowired private PlaylistService playlistService; @Autowired private WebServiceController ws; @Autowired private EmailAlertNotification emailAlertNotification; private final static Logger logger = LoggerFactory.getLogger(SchedulerService.class); @Scheduled(cron = "${widget_scheduler.cron}") public void updateWidget() throws Exception { if (widgetSchedulerEnabled) { WidgetFeedReturn widgetFeedReturn = playlistService.getWidgetFeedInfo(playlistWidgetFeed); if (widgetFeedReturn.getPlaylistCount() > 0 && playlistService.insertPlaylistItem(playlistWidget, widgetFeedReturn.getVideoId()) && playlistService.deletePlaylistItem(widgetFeedReturn.getId())) { ws.updatePlaylist(playlistWidget); widgetFeedReturn.setSuccess(true); widgetFeedReturn.setMessage(new StringBuilder() .append("Widget updated with '") .append(widgetFeedReturn.getVideoTitle()) .append("', '") .append(widgetFeedReturn.getVideoJoke()) .append("'<br>") .append("There are ") .append(widgetFeedReturn.getPlaylistCount() - 1) .append(" videos left to draw from.").toString()); logger.info("Widget updated"); } else { widgetFeedReturn.setSuccess(false); widgetFeedReturn.setMessage("WIDGET WAS NOT UPDATED, PLEASE CHECK YOUR FEED"); logger.error("Widget was not updated"); } sendWidgetUpdateAlert(widgetFeedReturn, widgetEmailAlertRecipientList, widgetEmailAlertSubject, widgetSchedulerEmailEnabled); } } @Scheduled(cron = "${comix_scheduler.cron}") public void updateComix() throws Exception { if (comixSchedulerEnabled) { WidgetFeedReturn comixFeedReturn = playlistService.getWidgetFeedInfo(playlistComixFeed); if (comixFeedReturn.getPlaylistCount() > 0 && playlistService.insertPlaylistItem(playlistComix, comixFeedReturn.getVideoId()) && playlistService.deletePlaylistItem(comixFeedReturn.getId())) { ws.updatePlaylist(playlistComix); comixFeedReturn.setSuccess(true); comixFeedReturn.setMessage(new StringBuilder() .append("Comix updated with '") .append(comixFeedReturn.getVideoTitle()) .append("', '") .append(comixFeedReturn.getVideoJoke()) .append("'<br>") .append("There are ") .append(comixFeedReturn.getPlaylistCount() - 1) .append(" videos left to draw from.").toString()); logger.info("Comix updated"); } else { comixFeedReturn.setSuccess(false); comixFeedReturn.setMessage("COMIX WAS NOT UPDATED, PLEASE CHECK YOUR FEED"); logger.error("Comix was not updated"); } sendWidgetUpdateAlert(comixFeedReturn, comixEmailAlertRecipientList, comixEmailAlertSubject, comixSchedulerEmailEnabled); } } private void sendWidgetUpdateAlert(WidgetFeedReturn widgetFeedReturn, String mailTo, String subject, boolean emailEnabled) throws Exception { if (!emailEnabled) return; Map<String, Object> model = Maps.newHashMap(); model.put("alertMessage", widgetFeedReturn.getMessage()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm a"); model.put("alertDate", sdf.format(new Date())); SimpleDateFormat day = new SimpleDateFormat("MM/dd/yyyy"); model.put("day", day.format(new Date())); model.put("serviceName", "Beyond the Comics"); model.put("alertTitle", "Beyond the Comics Alert"); model.put("footerMessage", "THIS IS AN AUTOMATED MAIL MESSAGE. PLEASE DO NOT REPLY."); if (widgetFeedReturn.isSuccess()) { model.put("videoThumbnail", widgetFeedReturn.getVideoThumbnail()); } Map<String, String> imageResources = Maps.newHashMap(); imageResources.put("btc_logo", "btc_logo.gif"); try { emailAlertNotification.send(model, mailTo, subject, emailEnabled, null, imageResources); } catch (MessagingException e) { logger.error(e.getMessage()); } } } <file_sep>package com.btc.web.config; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.jpa.JpaDialect; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement @EnableJpaRepositories public class DataSourceConfig { @Autowired private Environment env; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.btc.web"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaDialect(jpaDialect()); em.setJpaProperties(hibernateProperties()); return em; } @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("btc_svc.driverClassName")); dataSource.setUrl(env.getProperty("btc_svc.database.url")); dataSource.setUsername(env.getProperty("btc_svc.database.username")); dataSource.setPassword(env.getProperty("btc_svc.database.password")); dataSource.setTestOnBorrow(true); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(true); dataSource.setValidationQueryTimeout(0); return dataSource; } @Bean public JdbcTemplate jdbcTemplate() { JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource()); return jdbcTemplate; } @Bean public JpaDialect jpaDialect() { return new HibernateJpaDialect(); } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } private Properties hibernateProperties() { Properties properties = new Properties(); if ("true".equals(env.getProperty("db.auto"))) { properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); } properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); properties.put("hibernate.globally_quoted_identifiers", "true"); return properties; } } <file_sep>package com.btc.web.conversion; import java.io.File; /** * Created by Chris on 9/19/15. */ public class FileConversionImpl implements FileConversion { public File convertFile(File sourceFile, File targetFile) { return null; } } <file_sep>rootProject.name = 'btc-svc' <file_sep>CREATE SCHEMA IF NOT EXISTS btc_service; <file_sep>package com.btc.web.notification; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; /** * Created by Eric on 9/29/14. */ @Component public class EmailAlertNotification extends AbstractEmailNotification { private Resource emailTemplate = new ClassPathResource("META-INF/email/alert_message.html"); public String getMessage(Map<String, Object> model) throws UnsupportedEncodingException, IOException { return Emailer.renderTemplate(emailTemplate, model); } public Resource getEmailTemplate() { return emailTemplate; } public void setEmailTemplate(Resource emailTemplate) { this.emailTemplate = emailTemplate; } @Override public String getSubject(Map<String, Object> model, String emailAlertSubject) { return Emailer.renderTemplate(emailAlertSubject, model); } }<file_sep>package com.btc.web.web; import com.btc.web.model.ComicsGrid; import com.btc.web.model.Playlist; import com.btc.web.service.PlaylistService; import com.btc.web.service.SchedulerService; import com.btc.web.service.TemplateService; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mobile.device.Device; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; //import it.sauronsoftware.jave.*; /** * Created by Chris on 1/8/15. */ @RequestMapping("/ws") @RestController public class WebServiceController { private static Logger logger = LoggerFactory.getLogger(WebServiceController.class); @JsonAutoDetect(fieldVisibility = ANY) static class DataBean { String json; public DataBean(String str) { this.json = str; } } @Autowired private PlaylistService playlistService; @Autowired private TemplateService templateService; @Autowired private SchedulerService schedulerService; @RequestMapping(value = "updateWidget", produces = MediaType.APPLICATION_JSON_VALUE) public DataBean updateWidget() { try { schedulerService.updateWidget(); return new DataBean("{'updated':'true'}"); } catch (Exception e) { return new DataBean("{'updated': 'false', 'error': " + e.getMessage() + "}"); } } @RequestMapping(value = "evictAllPlaylists", produces = MediaType.APPLICATION_JSON_VALUE) public DataBean evictAllPlaylists() { playlistService.evictAllPlaylists(); return new DataBean("{'evicted':'true'}"); } @RequestMapping(value = "evictPlaylist/{playlistId}", produces = MediaType.APPLICATION_JSON_VALUE) public DataBean evictPlaylist(@PathVariable(value = "playlistId") String playlistId) { playlistService.evictPlaylist(playlistId); return new DataBean("{'evicted':'true', 'playlist' : " + playlistId + "}"); } @RequestMapping(value = "getTemplate", produces = MediaType.APPLICATION_JSON_VALUE) public DataBean getTemplate(@RequestParam("templateType") TemplateService.TemplateType templateType) throws Exception { return new DataBean(templateService.getTemplate(templateType)); } @RequestMapping(value = "getPlaylistProps/{playlistId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public DataBean getPlaylistProps(@PathVariable(value = "playlistId") String playlistId) throws Exception { return new DataBean(playlistService.findByPlaylistId(playlistId).getPlaylistJSON()); } @Transactional @RequestMapping(value = "updatePlaylist/{playlistId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void updatePlaylist(@PathVariable(value = "playlistId") String playlistId) throws Exception { BiMap<String, String> playlistMap = getPlaylistMap(); List<ComicsGrid> comicsGridList = new ArrayList<>(); JsonObject jsonObject = playlistService.getPlaylistItemsByPlaylistId(playlistId); JsonArray jsonArray = jsonObject.getAsJsonArray("items"); for (int j = 0; j < jsonArray.size(); j++) { ComicsGrid comicsGrid = new ComicsGrid(); JsonObject item = jsonArray.get(j).getAsJsonObject(); logger.info("Grid item: {}", item.toString()); JsonObject snippet = item.get("snippet").getAsJsonObject(); String comic = snippet.get("description").getAsString(); String joke = snippet.get("title").getAsString(); String publishedAt = snippet.get("publishedAt").getAsString(); publishedAt = Date.from(ZonedDateTime.parse(publishedAt).toInstant()).toString(); String thumb = snippet.get("thumbnails") .getAsJsonObject() .get("medium") .getAsJsonObject() .get("url").getAsString(); String videoId = snippet.get("resourceId") .getAsJsonObject() .get("videoId") .getAsString(); PlaylistService.TalentAndDate talentAndDate = playlistService.getTalentAndDateByVideoId(videoId); comicsGrid.setPlaylistId(playlistMap.get(comic)); comicsGrid.setComic(comic); comicsGrid.setJoke(joke); comicsGrid.setThumb(thumb); comicsGrid.setVideoId(videoId); comicsGrid.setTalent(talentAndDate.getTalent()); comicsGrid.setPublishedAt(talentAndDate.getDate() == null ? publishedAt : talentAndDate.getDate()); comicsGridList.add(comicsGrid); } Playlist playlist = playlistService.findByPlaylistId(playlistId); if (playlist != null) playlistService.deleteByPlaylistId(playlistId); playlist = new Playlist(); playlist.setPlaylistId(playlistId); playlist.setPlaylistName(playlistMap.inverse().get(playlistId)); playlist.setPlaylistJSON(new Gson().toJson(comicsGridList)); playlistService.save(playlist); } @Transactional @RequestMapping(value = "updateAllPlaylists", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void updateAllPlaylists() throws Exception { Map<String, String> playlistMap = getPlaylistMap(); for (Map.Entry<String, String> entry : playlistMap.entrySet()) { updatePlaylist(entry.getValue()); } } private BiMap<String, String> getPlaylistMap() { BiMap<String, String> playlistMap = HashBiMap.create(); JsonObject playlistJsonObject = playlistService.getAllPlaylistsForChannel(); JsonArray playlistJsonArray = playlistJsonObject.getAsJsonArray("items"); for (int i = 0; i < playlistJsonArray.size(); i++) { JsonObject playlistItem = playlistJsonArray .get(i) .getAsJsonObject(); playlistMap.put( playlistItem .get("snippet") .getAsJsonObject() .get("title") .getAsString(), playlistItem .get("id") .getAsString() ); } return playlistMap; } @RequestMapping("/detect-device") public @ResponseBody String detectDevice(Device device) { String deviceType = "unknown"; if (device.isNormal()) { deviceType = "normal"; } else if (device.isMobile()) { deviceType = "mobile"; } else if (device.isTablet()) { deviceType = "tablet"; } return "Hello " + deviceType + " browser!"; } } <file_sep>package com.btc.web.service; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.StringWriter; /** * Created by Chris on 11/18/15. */ @Service public class TemplateService { private static Logger logger = LoggerFactory.getLogger(TemplateService.class); public enum TemplateType { GRID("assets/header.html", "assets/grid_template.html", "assets/footer.html"), PLAYER("assets/header.html", "assets/grid_player_template.html", "assets/footer.html"), HOME("assets/blank.html", "assets/home_template.html", "assets/blank.html"), COMIX("assets/blank.html", "assets/comix_template.html", "assets/blank.html"); private final String header; private final String content; private final String footer; TemplateType(String header, String content, String footer) { this.header = header; this.content = content; this.footer = footer; } private String getHeader() { return header; } private String getContent() { return content; } private String getFooter() { return footer; } } @Cacheable(value = "templates") public String getTemplate(TemplateType templateType) throws Exception { logger.info("Getting template for {}", templateType.toString()); Resource headerTemplate = new ClassPathResource(templateType.getHeader()); StringWriter header = new StringWriter(); IOUtils.copy(headerTemplate.getInputStream(), header, Charsets.UTF_8); Resource gridTemplate = new ClassPathResource(templateType.getContent()); StringWriter content = new StringWriter(); IOUtils.copy(gridTemplate.getInputStream(), content, Charsets.UTF_8); Resource footerTemplate = new ClassPathResource(templateType.getFooter()); StringWriter footer = new StringWriter(); IOUtils.copy(footerTemplate.getInputStream(), footer, Charsets.UTF_8); return header.toString() + content.toString() + footer.toString(); } } <file_sep>//package com.btc.web.app; // //import com.btc.web.model.ComicsGrid; //import com.google.gson.JsonArray; //import com.google.gson.JsonObject; //import com.google.gson.JsonParser; //import com.sun.deploy.util.StringUtils; //import org.springframework.web.client.RestTemplate; // //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // ///** // * Created by Chris on 11/8/15. // */ //public class YouTube { // public static void main(String[] args) { // // String gridId = ""; // List<String> videoIds = new ArrayList<>(); // Map<String, String> playlists = new HashMap<>(); // List<ComicsGrid> comicsGridList = new ArrayList<>(); // // String uri; // RestTemplate restTemplate; // String result; // JsonObject jsonObject; // JsonArray jsonArray; // // uri = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCrw5nc-6MP632Mx_-3_O4OQ&maxResults=50&key=<KEY>"; // restTemplate = new RestTemplate(); // result = restTemplate.getForObject(uri, String.class); // // jsonObject = new JsonParser().parse(result).getAsJsonObject(); // jsonArray = jsonObject.getAsJsonArray("items"); // // for (int i = 0; i < jsonArray.size(); i++) { // JsonObject item = jsonArray.get(i).getAsJsonObject(); // String playlistId = item.get("id").getAsString(); // // JsonObject snippet = item.get("snippet").getAsJsonObject(); // String playlistTitle = snippet.get("title").getAsString(); // if (playlistTitle.toLowerCase().equals("grid")) gridId = playlistId; // // playlists.put(playlistTitle, playlistId); // // } // // System.out.println(gridId); // System.out.println(playlists); // // uri = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + gridId + "&key=<KEY>"; // restTemplate = new RestTemplate(); // result = restTemplate.getForObject(uri, String.class); // // jsonObject = new JsonParser().parse(result).getAsJsonObject(); // jsonArray = jsonObject.getAsJsonArray("items"); // // for (int i = 0; i < jsonArray.size(); i++) { // // ComicsGrid comicsGrid = new ComicsGrid(); // // JsonObject item = jsonArray.get(i).getAsJsonObject(); // // JsonObject snippet = item.get("snippet").getAsJsonObject(); // // String playlistId = playlists.get(snippet.get("title").getAsString()); // String comic = snippet.get("title").getAsString(); // String joke = snippet.get("description").getAsString(); // // String thumb = snippet.get("thumbnails") // .getAsJsonObject() // .get("medium") // .getAsJsonObject() // .get("url").getAsString(); // // String videoId = snippet.get("resourceId") // .getAsJsonObject() // .get("videoId") // .getAsString(); // // videoIds.add(videoId); // // comicsGrid.setPlaylistId(playlistId); // comicsGrid.setComic(comic); // comicsGrid.setJoke(joke); // comicsGrid.setThumb(thumb); // comicsGrid.setVideoId(videoId); // comicsGridList.add(comicsGrid); // System.out.println(playlistId); // System.out.println(comic); // System.out.println(joke); // System.out.println(thumb); // System.out.println(videoId + "\n\n"); // // } // // uri = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + StringUtils.join(videoIds, ",") + "&maxResults=50&key=<KEY>"; // restTemplate = new RestTemplate(); // result = restTemplate.getForObject(uri, String.class); // // jsonObject = new JsonParser().parse(result).getAsJsonObject(); // jsonArray = jsonObject.getAsJsonArray("items"); // // for (int i = 0; i < jsonArray.size(); i++) { // String videoId = jsonArray.get(i).getAsJsonObject() // .get("id") // .getAsString(); // // String talent = jsonArray.get(i).getAsJsonObject() // .get("snippet") // .getAsJsonObject() // .get("tags") // .getAsJsonArray() // .get(0) // .getAsString(); // // for (ComicsGrid comicsGrid : comicsGridList) { // if (comicsGrid.getVideoId().equals(videoId)) { // comicsGrid.setTalent(talent); // break; // } // // } // } // // // System.out.println(result); // // // } // //} <file_sep>buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE") } } plugins { id "org.sonarqube" version "2.5" } apply plugin: 'java' apply plugin: 'groovy' apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'application' apply plugin: 'maven' mainClassName = "com.btc.web.Application" sourceCompatibility = 1.8 version = '1.0' compileJava { allprojects { tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:deprecation" << "-Xlint:unchecked" } } } ext { springBootVersion = "1.2.2.RELEASE" springSecurityVersion = "3.2.4.RELEASE" springContextVersion = "4.2.2.RELEASE" springContextSupportVersion = "4.2.4.RELEASE" plexusCoreVersion = "1.0" janinoVersion = "2.7.5" mysqlConnectorVersion = "5.1.8" hsqldbVersion = "2.3.2" commonsDbcpVersion = "1.4" guavaVersion = "18.0" lombokVersion = "1.12.6" commonsIOVersion = "2.4" gsonVersion = "2.4" orgJsonVersion = "20150729" ehcacheVersion = "2.6.11" youTubeClientAPIVersion = "1.19.1" youTubeServiceAPIVersion = "v3-rev153-1.21.0" googleOauthClientVersion = "1.18.0-rc" quartzSchedulerVersion = "2.1.5" javaMailVersion = "1.4.6" } repositories { mavenCentral() mavenLocal() } dependencies { //Spring compile "org.springframework:spring-context:$springContextVersion" compile "org.springframework:spring-context-support:$springContextSupportVersion" compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion" compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion", { exclude group: "org.apache.tomcat.embed" } compile "org.springframework.security:spring-security-web:$springSecurityVersion", { exclude group: "org.apache.tomcat.embed" } compile "org.springframework.security:spring-security-core:$springSecurityVersion" compile "org.springframework.security:spring-security-config:$springSecurityVersion" compile "org.springframework.mobile:spring-mobile-device" //Miscellaneous compile "org.codehaus.janino:janino:$janinoVersion" compile "commons-io:commons-io:$commonsIOVersion" //Database compile "commons-dbcp:commons-dbcp:$commonsDbcpVersion" compile "mysql:mysql-connector-java:$mysqlConnectorVersion" compile "org.hsqldb:hsqldb:$hsqldbVersion" //Scheduling compile "org.quartz-scheduler:quartz:$quartzSchedulerVersion" //Guava compile "com.google.guava:guava:$guavaVersion" //JSON compile "com.google.code.gson:gson:$gsonVersion" compile "org.json:json:$orgJsonVersion" //Cacheing compile "net.sf.ehcache:ehcache-core:$ehcacheVersion" //Lombok compile "org.projectlombok:lombok:$lombokVersion" //Mail compile "javax.mail:mail:$javaMailVersion" //YouTube API compile "com.google.api-client:google-api-client:$youTubeClientAPIVersion" compile "com.google.apis:google-api-services-youtube:$youTubeServiceAPIVersion" compile "com.google.oauth-client:google-oauth-client-jetty:$googleOauthClientVersion" } <file_sep>package com.btc.web.notification; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.io.CharStreams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.activation.DataSource; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by Eric on 9/15/14. */ @Component public class Emailer { private final static Logger logger = LoggerFactory.getLogger(Emailer.class); private final static Splitter RECIPIENT_LIST_SPLITTER = Splitter.on(CharMatcher.anyOf(";, ")).trimResults().omitEmptyStrings(); @javax.annotation.Resource private transient JavaMailSender javaMailSender; @Value("${email.from}") private String emailFrom; public void sendMessage(String mailTo, String subject, String message, List<DataSource> attachments, Map<String, String> imageResources) throws UnsupportedEncodingException, MessagingException { if (Strings.isNullOrEmpty(mailTo)) { logger.warn("No valid recipients. Email is not sent."); } else { sendMessage(parseAddressList(mailTo), subject, message, attachments, imageResources); } } private void sendMessage(String[] mailTo, String subject, String message, List<DataSource> attachments, Map<String, String> imageResources) throws MessagingException, UnsupportedEncodingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); InternetAddress[] internetAddresses = InternetAddress.parse(Joiner.on(",").join(mailTo)); mimeMessageHelper.setFrom(new InternetAddress(emailFrom)); mimeMessageHelper.setTo(internetAddresses); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(message, true); if (attachments != null && attachments.size() > 0) { for (DataSource dataSource : attachments) { System.out.println("adding " + dataSource.getName()); mimeMessageHelper.addAttachment(dataSource.getName(), dataSource); } } if (imageResources != null && imageResources.size() > 0) { Set<String> keys = imageResources.keySet(); for (String key : keys) { System.out.println("adding image " + key); Resource imageResource = new ClassPathResource("META-INF/images/" + imageResources.get(key)); mimeMessageHelper.addInline(key, imageResource); } } javaMailSender.send(mimeMessageHelper.getMimeMessage()); logger.info("email sent"); } public static String[] parseAddressList(String addressList) { return Iterables.toArray(RECIPIENT_LIST_SPLITTER.split(addressList), String.class); } public static String renderTemplate(String template, Map<String, Object> model) { for (Map.Entry<String, Object> entry : model.entrySet()) { template = template.replace("${" + entry.getKey() + "}", entry.getValue().toString()); } return template; } public static String renderTemplate(Resource template, Map<String, Object> model) throws IOException { String asString = CharStreams.toString(new InputStreamReader(template.getInputStream(), "UTF-8")); return renderTemplate(asString, model); } } <file_sep>package com.btc.web.service; import com.btc.web.model.Playlist; import com.btc.web.model.repository.PlaylistRepository; import com.google.api.client.auth.oauth2.Credential; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.PlaylistItem; import com.google.api.services.youtube.model.PlaylistItemSnippet; import com.google.api.services.youtube.model.ResourceId; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.time.ZonedDateTime; import java.util.List; /** * Created by Chris on 11/14/15. */ @Service public class PlaylistService { private static Logger logger = LoggerFactory.getLogger(PlaylistService.class); @Autowired private PlaylistRepository playlistRepository; private YouTube youtube; @Value("${yt.key}") private String youTubeKey; @Value("${yt.channel}") private String youTubeChannel; @Data public class TalentAndDate { String talent = "Unknown"; String date = null; } @PostConstruct private void init() throws Exception { List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); logger.info("Getting the YouTube Authorization credentials."); Credential credential = YouTubeAuth.authorize(scopes, "playlistupdates"); youtube = new YouTube .Builder(YouTubeAuth.HTTP_TRANSPORT, YouTubeAuth.JSON_FACTORY, credential) .setApplicationName("Beyond the Comics") .build(); logger.info("Successfully retrieved the YouTube Authorization credentials."); } @Cacheable(value = "playlists", key = "#playlistId") public Playlist findByPlaylistId(String playlistId) { logger.info("Playlist cached: {}", playlistId); Playlist playlist = playlistRepository.findByPlaylistId(playlistId); return playlist; } @CacheEvict(value = "playlists", key = "#playlist.playlistId") public Playlist save(Playlist playlist) { logger.info("Playlist evicted: {}", playlist.getPlaylistId()); return playlistRepository.save(playlist); } @CacheEvict(value = "playlists", allEntries = true) public void evictAllPlaylists() { logger.info("All playlists evicted."); } @CacheEvict(value = "playlists", key = "#playlistId") public void evictPlaylist(String playlistId) { logger.info("Playlist {} evicted", playlistId); } public void deleteByPlaylistId(String playlistId) { playlistRepository.deleteByPlaylistId(playlistId); } public boolean insertPlaylistItem(String playlistId, String videoId) throws Exception { try { ResourceId resourceId = new ResourceId(); resourceId.setKind("youtube#video"); resourceId.setVideoId(videoId); PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet(); playlistItemSnippet.setTitle("First video in the test playlist"); playlistItemSnippet.setPlaylistId(playlistId); playlistItemSnippet.setResourceId(resourceId); PlaylistItem playlistItem = new PlaylistItem(); playlistItem.setSnippet(playlistItemSnippet); YouTube.PlaylistItems.Insert playlistItemsInsertCommand = youtube.playlistItems().insert("snippet,contentDetails", playlistItem); PlaylistItem returnedPlaylistItem = playlistItemsInsertCommand.execute(); logger.info("New widget item: {}", returnedPlaylistItem.getSnippet().getTitle()); return true; } catch (Exception e) { logger.error("Error updating widget {}", e.getMessage()); return false; } } public boolean deletePlaylistItem(String id) throws Exception { try { YouTube.PlaylistItems.Delete playlistItemDeleteCommand = youtube.playlistItems().delete(id); playlistItemDeleteCommand.execute(); logger.info("Deleted playlist item: {}", id); return true; } catch (Exception e) { logger.error("Error updating widget {}", e.getMessage()); return false; } } public WidgetFeedReturn getWidgetFeedInfo(String playlistFeed) { WidgetFeedReturn widgetFeedReturn = new WidgetFeedReturn(); JsonArray widgetFeedJsonArray = getPlaylistItemsByPlaylistId(playlistFeed) .getAsJsonArray("items"); widgetFeedReturn.setPlaylistCount(widgetFeedJsonArray.size()); if (widgetFeedJsonArray.size() > 0) { widgetFeedReturn.setId(widgetFeedJsonArray .get(0) .getAsJsonObject() .get("id") .getAsString()); JsonObject snippet = widgetFeedJsonArray .get(0) .getAsJsonObject() .get("snippet") .getAsJsonObject(); widgetFeedReturn.setVideoId(snippet .get("resourceId") .getAsJsonObject() .get("videoId") .getAsString()); widgetFeedReturn.setVideoTitle(snippet .get("title") .getAsString()); widgetFeedReturn.setVideoJoke(snippet .get("description") .getAsString()); widgetFeedReturn.setVideoThumbnail(snippet .get("thumbnails") .getAsJsonObject() .get("medium") .getAsJsonObject() .get("url") .getAsString()); } return widgetFeedReturn; } public JsonObject getAllPlaylistsForChannel() { String uri = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=" + youTubeChannel + "&maxResults=50&key=" + youTubeKey; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); return new JsonParser().parse(result).getAsJsonObject(); } public JsonObject getPlaylistItemsByPlaylistId(String gridId) { String uri = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + gridId + "&key=" + youTubeKey; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); return new JsonParser().parse(result).getAsJsonObject(); } public TalentAndDate getTalentAndDateByVideoId(String videoId) { String uri = "https://www.googleapis.com/youtube/v3/videos?part=snippet,recordingDetails&id=" + videoId + "&maxResults=50&key=" + youTubeKey; RestTemplate restTemplate = new RestTemplate(); try { String result = restTemplate.getForObject(uri, String.class); JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject(); JsonArray jsonArray = jsonObject.getAsJsonArray("items"); TalentAndDate talentAndDate = new TalentAndDate(); try { talentAndDate.setTalent(jsonArray.get(0).getAsJsonObject() .get("snippet") .getAsJsonObject() .get("tags") .getAsJsonArray() .get(0) .getAsString()); } catch (Exception e) { logger.info("Couldn't get talent, leave as default"); } try { String recordedDate = jsonArray.get(0).getAsJsonObject() .get("recordingDetails") .getAsJsonObject() .get("recordingDate") .getAsString(); recordedDate = ZonedDateTime.parse(recordedDate).toInstant().toString(); talentAndDate.setDate(recordedDate); } catch (Exception e) { logger.info("Couldn't get date, leave as default"); } return talentAndDate; } catch (Exception e) { return new TalentAndDate(); } } } <file_sep>package com.btc.web.conversion; import java.io.File; /** * Created by Chris on 9/19/15. */ public interface FileConversion { public File convertFile(File sourceFile, File targetFile); } <file_sep># BTCGrid # BTCGrid
26c48450897b3c42d77deb17ded19a830f8e3f76
[ "Markdown", "Java", "SQL", "Gradle" ]
14
Java
everettwolf/btc-service
5400e338b7a80bd244961a8839c4797558dc79e6
fcd9fbfcf2e1f6855d06769b28666e957d8a6c49
refs/heads/master
<file_sep>package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "sync" "time" ) type Long struct { LongUrl string `json:longUrl` } func crawl(half []string, ab []string, a string, key string) { var wg sync.WaitGroup addr := "https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/" for _, b := range ab { wg.Add(1922) for _, c := range half { for _, d := range ab { id := fmt.Sprintf("%s%s%s%s", a, b, c, d) url := fmt.Sprintf("%s%s&key=%s", addr, id, key) go func(url string, id string) { l := Long{} resp, err := http.Get(url) if err == nil { result, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() e := json.Unmarshal(result, &l) if e != nil { fmt.Println("Problem") } else { fmt.Printf("%s -> %s\n", id, l.LongUrl) } } else { fmt.Println("Error") } wg.Done() }(url, id) } } wg.Wait() } } func main() { var ab = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} var half1 = []string{"0", "1", "2", "3", "4", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"} var half2 = []string{"5", "6", "7", "8", "9", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} flag.Parse() args := flag.Args() if len(args) < 2 { log.Fatal("This program will expand 238,328 urls from goo.gl.\nUsage: googlcrawler <startingString> <APIKey>") } start := args[0] if len(start) > 3 { log.Fatal("Starting string must be up to 3 characters long") } key := args[1] crawl(half1, ab, start, key) time.Sleep(10 * time.Second) crawl(half2, ab, start, key) }
6376c56c1144ac6ae9138950cc0d5fb2bae44627
[ "Go" ]
1
Go
shortOS3/googlcrawler
e3c5d854734f51835a7761b1133ab34211205d3e
eb539c69081ec26ec99ebe6853b62d5ff87a09ad
refs/heads/main
<file_sep>#!/usr/bin/python3 """ Function that finds a peak in a list of unsorted integers. """ def find_peak(list_of_integers): """ Function that finds a peak in a list of unsorted integers. """ a = 0 b = len(list_of_integers) - 1 if len(list_of_integers) == 0: return(None) while (a < b): m = int((a + b) / 2) if list_of_integers[m] < list_of_integers[m + 1]: a = m + 1 else: b = m return(list_of_integers[a])
6e82a53dda77397c1b15ad4c0dc0f41974bf1d61
[ "Python" ]
1
Python
MedJarraya/google-higher_level_programming
61ddbbd1e2acc1ac65b79ba423128a20dd976227
038bd87e170a1e2aaa427c574a463a1f1a2dcdd0
refs/heads/master
<file_sep>package me.phelps.andenginedemo.activity; import org.andengine.engine.camera.Camera; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.modifier.PathModifier; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.RepeatingSpriteBackground; import org.andengine.entity.scene.background.SpriteBackground; import org.andengine.entity.util.FPSLogger; import org.andengine.ui.activity.BaseGameActivity; import me.phelps.andenginedemo.App; import me.phelps.andenginedemo.scene.GameScene; import me.phelps.andenginedemo.utils.ResourceManager; import me.phelps.toolbox.util.SizeUtil; public class GameActivity extends BaseGameActivity { // private static final int CAMERA_WIDTH = SizeUtil.getScreenWidth(App.instance); public static final int CAMERA_WIDTH = 96*3+72*7; public static final int CAMERA_HEIGHT = 96*6+72*9;//xiaoxiongzuode // private static final int CAMERA_HEIGHT = SizeUtil.getScreenHeight(App.instance); Camera camera; @Override public EngineOptions onCreateEngineOptions() { camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getRenderOptions().setDithering(true); return engineOptions; } @Override public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception { ResourceManager.getInstance().init(getEngine(),this,getVertexBufferObjectManager(),camera); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws Exception { this.mEngine.registerUpdateHandler(new FPSLogger()); Scene scene = new GameScene(); pOnCreateSceneCallback.onCreateSceneFinished(scene); } @Override public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception { ((GameScene)pScene).populate(); pOnPopulateSceneCallback.onPopulateSceneFinished(); } } <file_sep>package me.phelps.andenginedemo.utils; import android.graphics.Typeface; import org.andengine.engine.Engine; import org.andengine.engine.camera.Camera; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.font.StrokeFont; import org.andengine.opengl.texture.ITexture; import org.andengine.opengl.texture.Texture; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder; import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder; import org.andengine.opengl.texture.bitmap.BitmapTexture; import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.texture.region.TextureRegionFactory; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.util.color.Color; import me.phelps.andenginedemo.activity.GameActivity; /** * Created by User on 2016/10/13. */ public class ResourceManager { private static ResourceManager instance = new ResourceManager(); private ResourceManager(){} public static ResourceManager getInstance(){ return instance; } public Engine engine; public GameActivity gameActivity; public VertexBufferObjectManager vbom; public Camera camera; public void init(Engine engine, GameActivity gameActivity, VertexBufferObjectManager vbom, Camera camera){ this.engine = engine; this.gameActivity = gameActivity; this.vbom = vbom; this.camera = camera; loadGameGraphics(); loadFont(); } private static final int FONT_SIZE = 48; public Font font; public Font fontStroke; public Font fontStrokeOnly; public void loadFont() { final ITexture fontTexture = new BitmapTextureAtlas(gameActivity.getTextureManager(), 256, 256, TextureOptions.BILINEAR); final ITexture strokeFontTexture = new BitmapTextureAtlas(gameActivity.getTextureManager(), 256, 256, TextureOptions.BILINEAR); final ITexture strokeOnlyFontTexture = new BitmapTextureAtlas(gameActivity.getTextureManager(), 256, 256, TextureOptions.BILINEAR); font = new Font( gameActivity.getFontManager(), fontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK); font.load(); fontStroke = new StrokeFont( gameActivity.getFontManager(), strokeFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE); fontStroke.load(); fontStrokeOnly = new StrokeFont( gameActivity.getFontManager(), strokeOnlyFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE, true); fontStrokeOnly.load(); } //资源 private BuildableBitmapTextureAtlas textureAtlas; public ITextureRegion[] blockTRArr = new ITextureRegion[15]; public ITextureRegion playerTR; public ITextureRegion diceTR; public ITextureRegion horTR; public ITextureRegion porTR; public ITiledTextureRegion diceTTR; //加载游戏图片资源 public void loadGameGraphics(){ textureAtlas = new BuildableBitmapTextureAtlas( gameActivity.getTextureManager(), 1024, 512, BitmapTextureFormat.RGBA_8888, TextureOptions.BILINEAR_PREMULTIPLYALPHA); //加载资源 for (int i=1;i<=blockTRArr.length;i++){ ITextureRegion block = generateTRByPath("monopoly/block"+i+".png"); blockTRArr[i-1] = block; } playerTR = generateTRByPath("monopoly/player.png"); diceTR = generateTRByPath("monopoly/dice.png"); horTR = generateTRByPath("monopoly/hor.png"); porTR = generateTRByPath("monopoly/por.png"); diceTTR = new TiledTextureRegion(textureAtlas,blockTRArr[0],blockTRArr[1],blockTRArr[2],blockTRArr[3],blockTRArr[4],blockTRArr[5]); try { textureAtlas.build( new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0,0,0)); textureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { e.printStackTrace(); } } private TextureRegion generateTRByPath(String path){ return BitmapTextureAtlasTextureRegionFactory.createFromAsset( textureAtlas, gameActivity.getAssets(), path); } } <file_sep>package org.andengine.ui.activity; import org.andengine.entity.scene.Scene; import org.andengine.ui.IGameInterface; public abstract class SimpleBaseGameActivity extends BaseGameActivity { protected abstract void onCreateResources(); protected abstract Scene onCreateScene(); @Override public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception { this.onCreateResources(); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws Exception { final Scene scene = this.onCreateScene(); pOnCreateSceneCallback.onCreateSceneFinished(scene); } @Override public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception { pOnPopulateSceneCallback.onPopulateSceneFinished(); } } <file_sep>package me.phelps.andenginedemo.charactor; import org.andengine.opengl.vbo.VertexBufferObjectManager; import me.phelps.andenginedemo.utils.ResourceManager; /** * Created by User on 2016/10/14. */ public class PlayerFactory { private static PlayerFactory INSTANCE = new PlayerFactory(); private VertexBufferObjectManager vbom; private PlayerFactory() { } public static PlayerFactory getInstance() { return INSTANCE; } public void create(VertexBufferObjectManager vbom) { this.vbom = vbom; } public Player createPlayer(float x, float y) { Player player = new Player(x, y, ResourceManager.getInstance().playerTR, vbom); player.setZIndex(2); return player; } } <file_sep>package me.phelps.andenginedemo.charactor; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.entity.sprite.Sprite; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; /** * Created by User on 2016/10/14. */ public class Player extends Sprite { public Player(float pX, float pY, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) { super(pX, pY, pTextureRegion, pVertexBufferObjectManager); } } <file_sep>package me.phelps.andenginedemo.scene; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import org.andengine.engine.camera.hud.HUD; import org.andengine.entity.Entity; import org.andengine.entity.IEntity; import org.andengine.entity.modifier.LoopEntityModifier; import org.andengine.entity.modifier.PathModifier; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.AutoWrap; import org.andengine.entity.text.Text; import org.andengine.entity.text.TextOptions; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.input.sensor.acceleration.AccelerationData; import org.andengine.input.sensor.acceleration.IAccelerationListener; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.util.HorizontalAlign; import org.andengine.util.modifier.ease.EaseExponentialIn; import org.andengine.util.modifier.ease.EaseExponentialInOut; import org.andengine.util.modifier.ease.IEaseFunction; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import me.phelps.andenginedemo.activity.GameActivity; import me.phelps.andenginedemo.charactor.Player; import me.phelps.andenginedemo.charactor.PlayerFactory; import me.phelps.andenginedemo.charactor.RoadBlock; import me.phelps.toolbox.util.L; /** * Created by User on 2016/10/14. */ public class GameScene extends AbstractScene{ //棋盘 private Sprite[] blockArr = new Sprite[15];//路障 private Sprite[] roadArr = new Sprite[32];//路 private Player player; private AnimatedSprite dice; public GameScene(){ PlayerFactory.getInstance().create(vbom); } @Override public void populate() { createBackground(); createPlayer(); createHUD(); } @Override public void onPause() { } @Override public void onResume() { } private void createBackground(){ Entity entity = new Entity(); //创建棋盘背景 float bW = res.blockTRArr[0].getWidth(); float bH = res.blockTRArr[0].getHeight(); float rW = res.porTR.getWidth(); float rH = res.porTR.getHeight(); //起点开始 int rIndex = 0; int rLeft1 = (int) (bH*2+rW*7); int rLeft2 = (int) (rLeft1+bW-rW); //block0 start blockArr[0] = new RoadBlock(rLeft1,bW,res.blockTRArr[0],res.vbom,0); entity.attachChild(blockArr[0]); //road for (int i=rIndex;i<=rIndex+3;i++){ roadArr[i] = new Sprite(rLeft2,getSpriteBottom(blockArr[0])+rW*(i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=3; //block1 blockArr[1] = new RoadBlock(rLeft1,getSpriteBottom(roadArr[rIndex]),res.blockTRArr[1],res.vbom,1); entity.attachChild(blockArr[1]); //road for (int i=rIndex;i<=rIndex+1;i++){ roadArr[i] = new Sprite(rLeft2,getSpriteBottom(blockArr[1])+rW*(i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=1; //block2 blockArr[2] = new RoadBlock(rLeft1,getSpriteBottom(roadArr[rIndex]),res.blockTRArr[2],res.vbom,2); entity.attachChild(blockArr[2]); //block3 blockArr[3] = new RoadBlock(rLeft1,getSpriteBottom(blockArr[2]),res.blockTRArr[3],res.vbom,3); entity.attachChild(blockArr[3]); //road for (int i=rIndex;i<=rIndex+2;i++){ roadArr[i] = new Sprite(rLeft2,getSpriteBottom(blockArr[3])+rW*(i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=2; //block4 blockArr[4] = new RoadBlock(rLeft1,getSpriteBottom(roadArr[rIndex]),res.blockTRArr[4],res.vbom,4); entity.attachChild(blockArr[4]); //下排 int bTop1 = (int) blockArr[4].getY(); int bTop2 = (int) (getSpriteBottom(blockArr[4])-rH); //road roadArr[rIndex] = new Sprite(blockArr[4].getX()-rW,bTop2,res.horTR,res.vbom); entity.attachChild(roadArr[rIndex]); //block5 blockArr[5] = new RoadBlock(roadArr[rIndex].getX()-bW,bTop1,res.blockTRArr[5],res.vbom,5); entity.attachChild(blockArr[5]); //road rIndex++; for (int i=rIndex;i<=rIndex+2;i++){ roadArr[i] = new Sprite(blockArr[5].getX()-rW*(1+i-rIndex),bTop2,res.horTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=2; //block6 blockArr[6] = new RoadBlock(roadArr[rIndex].getX()-bW,bTop1,res.blockTRArr[6],res.vbom,6); entity.attachChild(blockArr[6]); //road for (int i=rIndex;i<=rIndex+2;i++){ roadArr[i] = new Sprite(blockArr[6].getX()-rW*(1+i-rIndex),bTop2,res.horTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=2; //左侧 int lLeft1 = 0; int lLeft2 = 0; //block7 blockArr[7] = new RoadBlock(lLeft1,roadArr[rIndex].getY()-bH,res.blockTRArr[7],res.vbom,7); entity.attachChild(blockArr[7]); //road for (int i=rIndex;i<=rIndex+2;i++){ roadArr[i] = new Sprite(lLeft2,blockArr[7].getY()-rH*(1+i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=2; //block8 blockArr[8] = new RoadBlock(lLeft1,roadArr[rIndex].getY()-bH,res.blockTRArr[8],res.vbom,8); entity.attachChild(blockArr[8]); //road roadArr[rIndex] = new Sprite(lLeft2,blockArr[8].getY()-rH,res.porTR,res.vbom); entity.attachChild(roadArr[rIndex]); //block9 blockArr[9] = new RoadBlock(lLeft1,roadArr[rIndex].getY()-bH,res.blockTRArr[9],res.vbom,9); entity.attachChild(blockArr[9]); //block10 blockArr[10] = new RoadBlock(lLeft1,blockArr[9].getY()-bH,res.blockTRArr[10],res.vbom,10); entity.attachChild(blockArr[10]); //road rIndex++; for (int i=rIndex;i<=rIndex+1;i++){ roadArr[i] = new Sprite(lLeft2,blockArr[10].getY()-rH*(1+i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=1; //block11 blockArr[11] = new RoadBlock(lLeft1,roadArr[rIndex].getY()-bH,res.blockTRArr[11],res.vbom,11); entity.attachChild(blockArr[11]); //road for (int i=rIndex;i<=rIndex+1;i++){ roadArr[i] = new Sprite(lLeft2,blockArr[11].getY()-rH*(1+i-rIndex),res.porTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=1; //block12 blockArr[12] = new RoadBlock(lLeft1,roadArr[rIndex].getY()-bH,res.blockTRArr[12],res.vbom,12); entity.attachChild(blockArr[12]); //上侧 int tTop1 = 0; int tTop2 = 0; //road for (int i=rIndex;i<=rIndex+2;i++){ roadArr[i] = new Sprite(getSpriteRight(blockArr[12])+rW*(i-rIndex),tTop1,res.horTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=2; //block13 blockArr[13] = new RoadBlock(getSpriteRight(roadArr[rIndex]),tTop2,res.blockTRArr[13],res.vbom,13); entity.attachChild(blockArr[13]); //road for (int i=rIndex;i<=rIndex+3;i++){ roadArr[i] = new Sprite(getSpriteRight(blockArr[13])+rW*(i-rIndex),tTop1,res.horTR,res.vbom); entity.attachChild(roadArr[i]); } rIndex+=3; //block14 blockArr[14] = new RoadBlock(getSpriteRight(roadArr[rIndex]),tTop2,res.blockTRArr[14],res.vbom,14); entity.attachChild(blockArr[14]); // setBackground(new EntityBackground(entity)); attachChild(entity); } public void createPlayer(){ int left = (int) (GameActivity.CAMERA_WIDTH-res.blockTRArr[0].getWidth()/2-res.playerTR.getWidth()/2); int top = (int) (res.blockTRArr[0].getHeight()/2*3-res.playerTR.getHeight()/2); player = PlayerFactory.getInstance().createPlayer(left,top); attachChild(player); } AtomicBoolean diceEnable = new AtomicBoolean(true); public void createHUD(){ HUD hud = new HUD(); dice = new AnimatedSprite( (GameActivity.CAMERA_WIDTH-res.diceTTR.getWidth())/2, (GameActivity.CAMERA_HEIGHT-res.diceTTR.getWidth())/2, res.diceTTR, res.vbom){ @Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown() && diceEnable.get() &&!win.get()){ diceEnable.set(false); dice.animate(50, 2, new IAnimationListener() { @Override public void onAnimationStarted(AnimatedSprite pAnimatedSprite, int pInitialLoopCount) {} @Override public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite, int pOldFrameIndex, int pNewFrameIndex) {} @Override public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite, int pRemainingLoopCount, int pInitialLoopCount) {} @Override public void onAnimationFinished(AnimatedSprite pAnimatedSprite) { Random random = new Random(); int stepNumber = random.nextInt(5); dice.setCurrentTileIndex(stepNumber); //实际移动棋子步数 move(stepNumber+1); } }); } return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); } }; hud.attachChild(dice); hud.registerTouchArea(dice); camera.setHUD(hud); } AtomicBoolean win = new AtomicBoolean(false); public void move(int stepNumber){ //move int currentPosition = 0; final IEntity background = getChildByIndex(0); //获取当前所在的index for (int i=0;i<background.getChildCount();i++){ Sprite sprite = (Sprite)background.getChildByIndex(i); if (sprite.collidesWith(player)){ currentPosition = i; break; } } //设置要行走的路径 PathModifier.Path path = new PathModifier.Path(stepNumber+1);//包括起始点 int limit = currentPosition+stepNumber; if(limit>=background.getChildCount()-1){ limit = background.getChildCount()-1; } Sprite start = (Sprite)background.getChildByIndex(currentPosition); path.to(getMoveX(start), getMoveY(start)); currentPosition++; for (;currentPosition<=limit;currentPosition++){ Sprite next = (Sprite)background.getChildByIndex(currentPosition); path.to(getMoveX(next), getMoveY(next)); } final PathModifier pathModifier = new PathModifier((stepNumber+1)/2,path, EaseExponentialInOut.getInstance()); pathModifier.setPathModifierListener(new PathModifier.IPathModifierListener() { @Override public void onPathStarted(PathModifier pPathModifier, IEntity pEntity) { } @Override public void onPathWaypointStarted(PathModifier pPathModifier, IEntity pEntity, int pWaypointIndex) { } @Override public void onPathWaypointFinished(PathModifier pPathModifier, IEntity pEntity, int pWaypointIndex) { //collides for (int i=0;i<background.getChildCount();i++){ if(background.getChildByIndex(i) instanceof RoadBlock){ final RoadBlock roadBlock = (RoadBlock)background.getChildByIndex(i); if(roadBlock.collidesWith(player)){ gameActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(gameActivity,"碰撞block"+roadBlock.getBlockIndex(),Toast.LENGTH_SHORT).show(); } }); } } } //判断终点 final IEntity background = getChildByIndex(0); Sprite sprite = (Sprite)background.getChildByIndex(background.getChildCount()-1); if (sprite.collidesWith(player)){ win.set(true); player.unregisterEntityModifier(pathModifier); gameActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(gameActivity,"赢了!!!",Toast.LENGTH_SHORT).show(); } }); } } @Override public void onPathFinished(PathModifier pPathModifier, IEntity pEntity) { diceEnable.set(true); } }); player.registerEntityModifier(pathModifier); } }
e1b73d19aa0a91a43c61f62b287ed590c73a8f03
[ "Java" ]
6
Java
chenqian2651489/AndEngine
cd4308c00af9fa0a8d8156cae777c8936fea3531
e7028909e1be1576b61344fea4d95183949b2adc
refs/heads/master
<repo_name>droquo/koha_bib_export<file_sep>/koha_config-example.py '''copy this file as koha_config.py and change the credentials and settings below''' '''your koha credentials''' user = 'admin' #put your admin username here passwd = '<PASSWORD>' #put your admin password here domain = 'http://mykohastaffclientdomain.com' #this is to be filled with the root domain for your hosted koha STAFF client '''export configurations''' xml_status = 1 #set this to 1 if you want the export to return as XML, else it returns as MARC by default no_items = 0 #this is set to the default of exporting items, set to 1 if you don't want to export items total = 250000 #this is the total number of bibliographic records you have increment = 5000 #this is increments in which the records will be downloaded - I have found that more than 5000 records cause a timeout.<file_sep>/koha_bib_export.py #!/usr/bin/env python import mechanize import koha_config import os import time #set up headers for the bot, though i don't think we need these if we are just ignoring robot.txt all together headers = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0')] #set config and path information user = koha_config.user passwd = <PASSWORD> domain = koha_config.domain xml_status = koha_config.xml_status no_items = koha_config.no_items export_path = '/cgi-bin/koha/tools/export.pl' data_path = './data/'+ time.strftime("%Y-%m-%d_%H%M%S") + '/' #create path if not os.path.exists(data_path): os.makedirs(data_path) #create url url = domain + export_path #set export configuration total = koha_config.total increment = koha_config.increment curr = 1 stop = curr + increment - 1 start_time = time.time() #initiate and prepare bot b = mechanize.Browser() b.addheaders = headers b.set_handle_robots(False) #seems to be the only surefire way to get around the robots.txt declaraction #go bot, go! b.open(url) #select form (not sure if this would be different for other versions of koha - this is tested on PTFS/Liblime Academic Koha 5.8 and Community Koha 3.16) b.select_form(nr=0) #authenticate b["userid"] = user b["password"] = <PASSWORD> b.submit() #use the export form to export bib records in increments while stop < total + 1: b.select_form(nr=3) b["StartingBiblionumber"] = str(curr) b["EndingBiblionumber"] = str(stop) if xml_status == 1: b["output_format"] = ['xml'] else: pass #check the dont_export_item box if you don't want items exported if no_items == 1: b.form.find_control(name="dont_export_item").items[0].selected = True else: pass print 'Getting export data records %s - %s ready, this may take a moment...' % (str(curr), str(stop)) data = b.submit() print 'Writing to filesystem...' res = data.read() #print curr, stop, '====\n', res, '====\n' #this is a string that can be saved to marc or xml if xml_status == 1: filename = data_path+'export-'+ str(curr) + '-' + str(stop) + '.xml' else: filename = data_path+'export-'+ str(curr) + '-' + str(stop) + '.mrc' with open(filename, 'w') as f: f.write(res) f.close() curr = stop + 1 stop += increment b.open(url) #tell us how long it took in seconds print time.time() - start_time, "seconds to export %s bibliographic records" %(total) <file_sep>/readme.md ###Export Bibliographic Records for Large Koha Catalogs This is primarily for hosted Koha catalogs as I am sure there is a much easier way to dump your catalog data if you are hosting it yourself or have access to the server that is hosting it. If your Koha instance is hosted, you can export your data from the admin interface, but I have found that it will timeout should you want to export more than 5,000 - 10,000 bibibliographic records. If like many libraries you have records on the order of hundreds of thousands to millions, it can be quite tedious to export in these small chunks manually. This script is pretty basic but will do all the work of downloading your catalog while you can focus on something else (anything else). ####Usage You will only need to install the `mechanize` module for this to work. `easy_install mechanize` documentation [here](http://wwwsearch.sourceforge.net/mechanize/download.html) copy the `koha_config-example.py` file as `koha_config.py` and modify the configurations to match your setup. This script could be done way more flexibly, with more configurability, but I don't think something like this is in high demand so it is distributed as is. ####Notes Again, this script is for automating the process of downloading all records and is not configured to handling customized chunks in between (though if you were to set the `start` variable to something other than `1`, it would start at that bib record, of course.) The way this handles total records in increments is pretty lazy. So if you have 246000 bibliographic records, and you set the increment to 5000, it is going to miss those last 1000. You can avoid this by rounding up the total number of records by a magnitude of the increment you've set. So if you have 246000 records, just set the `total` to 250000. **.mrc vs .xml** - be aware that should you choose to output as XML rather than MARC, the data read into the buffer will be much larger as the white space probably triples the size of the data returned. May need to play around with increments in the case this becomes a problem.
dcf9ac6b76e49ee14e945a4916a89a5487dd927e
[ "Markdown", "Python" ]
3
Python
droquo/koha_bib_export
e65ebce8d72b52abdddbe5e18da0c41299f87b9a
b4531cd15af3d111c12c1a3842b7c95690942d9d
refs/heads/master
<file_sep>package com.example.project_uas.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Product { @SerializedName("idProduct") @Expose var idProduct:Int? = null @SerializedName("nama") @Expose var nama:String? = null @SerializedName("deskripsi") @Expose var deskripsi:String? = null @SerializedName("harga") @Expose var harga:Int? = null @SerializedName("foto") @Expose var foto:String? = null @SerializedName("kategori") @Expose var kategori:Kategori? = null }<file_sep>package com.example.project_uas.service import com.google.gson.JsonObject import retrofit2.http.GET interface ProductAPI { @GET("nmp160418117/get_products.php") fun getProducts() : retrofit2.Call<JsonObject> }<file_sep>package com.example.project_uas.service import com.google.gson.JsonObject import retrofit2.http.* interface UserAPI { @FormUrlEncoded @POST("nmp160418117/sign_up.php") fun createUser(@Field("nama") nama: String, @Field("email") email: String, @Field("password") password: String ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/login.php") fun getUser(@Field("email") email: String, @Field("password") password: String ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/ganti_nama.php") fun gantiNama(@Field("idUser") idUser: Int, @Field("nama") nama: String ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/ganti_password.php") fun gantiPassword(@Field("idUser") idUser: Int, @Field("password") password: String ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/top_up_saldo.php") fun topUpSaldo(@Field("idUser") idUser: Int, @Field("saldoTambahan") saldoTambahan: String ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/check_transaction.php") fun checkTransaction(@Field("idUser") idUser: Int ) : retrofit2.Call<JsonObject> }<file_sep>package com.example.project_uas.data const val URL = "http://ubaya.prototipe.net/"<file_sep>package com.example.project_uas.ui import android.app.AlertDialog import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.project_uas.R import com.example.project_uas.adapter.CardViewCartAdapter import com.example.project_uas.data.URL import com.example.project_uas.model.Cart import com.example.project_uas.model.Product import com.example.project_uas.model.User import com.example.project_uas.service.CartAPI import com.example.project_uas.service.OrderAPI import com.example.project_uas.service.UserAPI import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import kotlinx.android.synthetic.main.fragment_cart.* import kotlinx.android.synthetic.main.fragment_cart.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.net.HttpRetryException import java.net.HttpURLConnection import java.text.NumberFormat import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* class CartFragment : Fragment() { var arrListProduct = arrayListOf<Cart>() val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_cart, container, false) root.rvCart.layoutManager = LinearLayoutManager(activity) return root } fun implementToRecyclerView() { val cardViewCartAdapter = CardViewCartAdapter(arrListProduct, arguments!!.getInt("idUser")) rvCart.adapter = cardViewCartAdapter } fun implementSubTotal() { text_sub_total.setText(formatRupiah.format(subTotal)) } internal fun getCartItems() { arrListProduct.clear() val retro = Retro().getRetroClientInstance(URL).create(CartAPI::class.java) retro.getCartItems(arguments!!.getInt("idUser")).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>?, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>?, response: Response<JsonObject>) { if (response.code() == 200) { val result = response.body().get("result").asString if (result == "OK") { val datas = response.body().getAsJsonArray("data") for (data in datas) { val cart = Cart() cart.idCart = data.asJsonObject.get("idCart").asInt val productC = Product() productC.idProduct = data.asJsonObject.get("idProduct").asInt productC.nama = data.asJsonObject.get("nama").asString productC.foto = data.asJsonObject.get("foto").asString cart.product = productC cart.subTotal = data.asJsonObject.get("sub_total").asInt cart.quantity = data.asJsonObject.get("quantity").asInt subTotal = data.asJsonObject.get("total_sub_total").asInt arrListProduct.add(cart) } implementToRecyclerView() implementSubTotal() } else { val snackBar = Snackbar.make( cartView, "Keranjang masih kosong", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } }) } override fun onResume() { super.onResume() getCartItems() btn_check_out.setOnClickListener { // ceck jumlah saldo apakah mencukupi checkTransaction() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) CardViewCartAdapter.context = this.context } internal fun checkTransaction() { val retro = Retro().getRetroClientInstance(URL).create(UserAPI::class.java) retro.checkTransaction(arguments!!.getInt("idUser")).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } @RequiresApi(Build.VERSION_CODES.O) override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.code() == 200) { val result = response.body().get("result").asString if (result == "ERROR") { val message = response.body().get("message").asString val snackBar = Snackbar.make( cartView, message, Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { val message = response.body().get("message").asString if (message == "TRUE") { insertOrder() } else if (text_sub_total.text == "Rp0"){ val snackBar = Snackbar.make( cartView, "Keranjang anda masih kosong, isi terlebih dahulu", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { val snackBar = Snackbar.make( cartView, "Saldo anda tidak mencukupi", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } } }) } @RequiresApi(Build.VERSION_CODES.O) internal fun insertOrder() { val curDateTime = LocalDate.now() val formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd") val curDate = formatDate.format(curDateTime) // val curDate = "2020-11-30" val arrIdCart = arrayListOf<Int>() for(item in arrListProduct) { arrIdCart.add(item.idCart!!) } val retro = Retro().getRetroClientInstance(URL).create(OrderAPI::class.java) retro.insertCartItems(arguments!!.getInt("idUser"), curDate, arrIdCart).enqueue(object : Callback<JsonObject>{ override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>?, response: Response<JsonObject>?) { if (response!!.code() == 200) { val result = response.body().get("result").asString if (result == "OK") { // DIalog view result checkout sukses val mDialogView = LayoutInflater.from(this@CartFragment.context).inflate(R.layout.layout_order_sukses, null) //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this@CartFragment.context) .setView(mDialogView) //show dialog mBuilder.show() val idOrder = response.body().get("idOrder").asString val sisaSaldo = response.body().get("sisa_saldo").asString // PASS DATA idOrder Ke Fragment order history ProfileFragment.SISA_SALDO = sisaSaldo arrListProduct.clear() rvCart.adapter!!.notifyDataSetChanged() text_sub_total.setText("Rp0") } else { Toast.makeText(this@CartFragment.context, response.body().get("message").asString, Toast.LENGTH_SHORT).show() } } else if (response.code() == 500) { Toast.makeText(this<EMAIL>, "try " + response.code().toString(), Toast.LENGTH_LONG).show() } } }) } companion object { var subTotal = 0 fun newInstance(user: User) = CartFragment().apply { val fragment = CartFragment() val args = Bundle() args.putInt("idUser", user.idUser!!) fragment.arguments = args return fragment } } } <file_sep>package com.example.project_uas import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.fragment.app.Fragment import androidx.viewpager2.widget.ViewPager2 import com.example.project_uas.adapter.ViewPagerAdapter import com.example.project_uas.model.User import com.example.project_uas.ui.CartFragment import com.example.project_uas.ui.HistoryFragment import com.example.project_uas.ui.HomeFragment import com.example.project_uas.ui.ProfileFragment import kotlinx.android.synthetic.main.activity_home.* class Home : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) setSupportActionBar(toolbar) supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_baseline_dehaze_24) supportActionBar?.setDisplayHomeAsUpEnabled(true) val toggle = ActionBarDrawerToggle(this, container, R.string.title_open_nav_drawer, R.string.title_close_nav_drawer) container.addDrawerListener(toggle) toggle.syncState() val user = User() user.idUser = intent.getIntExtra(USER_ID, 0) user.nama = intent.getStringExtra(USER_NAMA) user.email = intent.getStringExtra(USER_EMAIL) user.password = <PASSWORD>(<PASSWORD>) user.foto = intent.getStringExtra(USER_FOTO) user.saldo = intent.getIntExtra(USER_SALDO, 0) val fragments: ArrayList<Fragment> = ArrayList() fragments.add(HomeFragment.newInstance(user)) fragments.add(CartFragment.newInstance(user)) fragments.add(HistoryFragment.newInstance(user)) fragments.add(ProfileFragment.newInstance(user)) view_pager.adapter = ViewPagerAdapter(this, fragments) view_pager.registerOnPageChangeCallback(object:ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { val menu = arrayOf(R.id.navigation_home, R.id.navigation_cart, R.id.navigation_history, R.id.navigation_profile) nav_view.selectedItemId=menu[position] } }) nav_view.setOnNavigationItemSelectedListener { if(it.itemId == R.id.navigation_home) { view_pager.currentItem = 0 } else if(it.itemId == R.id.navigation_cart) { view_pager.currentItem = 1 } else if(it.itemId == R.id.navigation_history) { view_pager.currentItem = 2 } else { view_pager.currentItem = 3 } true } nav_drawer.setNavigationItemSelectedListener { if(it.itemId == R.id.navigation_home) { container.closeDrawer(GravityCompat.START) view_pager.currentItem = 0 } else if(it.itemId == R.id.navigation_cart) { container.closeDrawer(GravityCompat.START) view_pager.currentItem = 1 } else if(it.itemId == R.id.navigation_history) { container.closeDrawer(GravityCompat.START) view_pager.currentItem = 2 } else if (it.itemId == R.id.navigation_profile){ container.closeDrawer(GravityCompat.START) view_pager.currentItem = 3 } else { val intent = Intent(this@Home, Login::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) } true } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { android.R.id.home -> container.openDrawer(GravityCompat.START) } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (container.isDrawerOpen(GravityCompat.START)) { container.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } companion object { const val USER_ID = "extra_id" const val USER_NAMA = "extra_nama" const val USER_EMAIL = "extra_email" const val USER_SALDO = "extra_saldo" const val USER_FOTO = "extra_foto" const val USER_PASSWORD = "<PASSWORD>" } } <file_sep>package com.example.project_uas.ui import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.project_uas.R import com.example.project_uas.adapter.CardViewOrderAdapter import com.example.project_uas.adapter.CardViewProductAdapter import com.example.project_uas.data.URL import com.example.project_uas.model.Kategori import com.example.project_uas.model.Order import com.example.project_uas.model.Product import com.example.project_uas.model.User import com.example.project_uas.service.OrderAPI import com.example.project_uas.service.ProductAPI import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import kotlinx.android.synthetic.main.fragment_cart.* import kotlinx.android.synthetic.main.fragment_history.* import kotlinx.android.synthetic.main.fragment_history.view.* import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.fragment_home.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class HistoryFragment : Fragment() { var arrListOrder = arrayListOf<Order>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_history, container, false) root.rvOrders.layoutManager = LinearLayoutManager(activity) return root } internal fun getOrders() { arrListOrder.clear() val retro = Retro().getRetroClientInstance(URL).create(OrderAPI::class.java) retro.getOrders(arguments!!.getInt("idUser")).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.code() == 200) { val result = response.body().get("result").asString if (result == "OK") { val arrOrder = response.body().getAsJsonArray("data") for (item in arrOrder) { val order = Order() order.idOrder = item.asJsonObject.get("idOrder").asInt order.tanggal = item.asJsonObject.get("tanggal").asString order.totalQuantity = item.asJsonObject.get("total_quantity").asInt order.totalJenisItem = item.asJsonObject.get("total_jenis_item").asInt order.grandTotal = item.asJsonObject.get("grand_total").asInt arrListOrder.add(order) } implementToRecyclerView() } else { val message = response.body().get("message").asString val snackBar = Snackbar.make( historyView, message, Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } }) } fun implementToRecyclerView() { val cardViewOrderAdapter = CardViewOrderAdapter(arrListOrder) rvOrders.adapter = cardViewOrderAdapter } override fun onResume() { super.onResume() getOrders() } companion object { fun newInstance(user: User) = HistoryFragment().apply { val fragment = HistoryFragment() val args = Bundle() args.putInt("idUser", user.idUser!!) fragment.arguments = args return fragment } } }<file_sep>package com.example.project_uas.ui import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.project_uas.R import com.example.project_uas.adapter.CardViewProductAdapter import com.example.project_uas.data.URL import com.example.project_uas.model.Kategori import com.example.project_uas.model.Product import com.example.project_uas.model.User import com.example.project_uas.service.ProductAPI import com.example.project_uas.util.Retro import com.google.gson.JsonObject import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.fragment_home.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class HomeFragment : Fragment() { var arrListProduct = arrayListOf<Product>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) getProducts() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_home, container, false) root.rvProducts.layoutManager = LinearLayoutManager(activity) return root } internal fun getProducts() { arrListProduct.clear() val retro = Retro().getRetroClientInstance(URL).create(ProductAPI::class.java) retro.getProducts().enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.code() == 200) { val result = response.body().get("result").asString if (result == "OK") { val arrProduct = response.body().getAsJsonArray("data") for (item in arrProduct) { val product = Product() product.idProduct = item.asJsonObject.get("idProduct").asInt product.nama = item.asJsonObject.get("nama_barang").asString product.deskripsi = item.asJsonObject.get("deskripsi").asString product.harga = item.asJsonObject.get("harga").asInt product.foto = item.asJsonObject.get("foto").asString val kategori = Kategori() kategori.idKategori = item.asJsonObject.get("idKategori").asInt kategori.nama = item.asJsonObject.get("nama_kategori").asString product.kategori = kategori arrListProduct.add(product) } implementToRecyclerView() } else { Toast.makeText(activity!!.baseContext, result, Toast.LENGTH_LONG).show() } } } }) } fun implementToRecyclerView() { val cardViewProductAdapter = CardViewProductAdapter(arrListProduct, arguments!!.getInt("idUser")) rvProducts.adapter = cardViewProductAdapter } override fun onResume() { super.onResume() } companion object { fun newInstance(user: User) = HomeFragment().apply { val fragment = HomeFragment() val args = Bundle() args.putInt("idUser", user.idUser!!) fragment.arguments = args return fragment } } }<file_sep>package com.example.project_uas.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.project_uas.R import com.example.project_uas.model.Order import java.text.NumberFormat import java.util.* class CardViewOrderAdapter(private val listOrder: ArrayList<Order>) : RecyclerView.Adapter<CardViewOrderAdapter.CardViewViewHolder>() { inner class CardViewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var tvIdOrder: TextView = itemView.findViewById(R.id.tv_order_id) var tvTanggalOrder: TextView = itemView.findViewById(R.id.tv_order_date) var tvTotalQty: TextView = itemView.findViewById(R.id.tv_order_qty) var tvTotalJenis: TextView = itemView.findViewById(R.id.tv_order_total_jenis) var tvGrandTotal: TextView = itemView.findViewById(R.id.tv_order_grand_total) var tvTextTotalQty: TextView = itemView.findViewById(R.id.text_total_qty) var tvTextTotalJenisItem: TextView = itemView.findViewById(R.id.text_total_jenis_item) var tvTextGrandTotal: TextView = itemView.findViewById(R.id.text_grand_total) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_cardview_order, parent, false) return CardViewViewHolder(view) } override fun getItemCount(): Int { return listOrder.size } override fun getItemId(position: Int): Long { return listOrder[position].idOrder!!.toLong() } override fun onBindViewHolder(holder: CardViewViewHolder, position: Int) { val order = listOrder[position] val strIdOrder = "#NMP" + order.idOrder.toString() holder.tvIdOrder.setText(strIdOrder) holder.tvTanggalOrder.setText(order.tanggal) holder.tvTotalQty.setText(order.totalQuantity.toString()) holder.tvTotalJenis.setText(order.totalJenisItem.toString()) holder.tvTextTotalQty.setText("Total Quantity: ") holder.tvTextTotalJenisItem.setText("Total Jenis Item: ") holder.tvTextGrandTotal.setText("Grand Total: ") val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) holder.tvGrandTotal.setText(formatRupiah.format(order.grandTotal)) } }<file_sep>package com.example.project_uas.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Kategori { @SerializedName("idKategori") @Expose var idKategori:Int? = null @SerializedName("nama") @Expose var nama:String? = null }<file_sep>package com.example.project_uas.ui import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import com.example.project_uas.Login import com.example.project_uas.R import com.example.project_uas.adapter.CardViewCartAdapter import com.example.project_uas.data.URL import com.example.project_uas.model.User import com.example.project_uas.service.UserAPI import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_cart.* import kotlinx.android.synthetic.main.fragment_profile.* import kotlinx.android.synthetic.main.layout_ganti_nama.view.* import kotlinx.android.synthetic.main.layout_ganti_nama.view.dialogCancelNamaBtn import kotlinx.android.synthetic.main.layout_ganti_nama.view.dialogSimpanNamaBtn import kotlinx.android.synthetic.main.layout_ganti_password.view.* import kotlinx.android.synthetic.main.layout_top_up_saldo.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.text.NumberFormat import java.util.* class ProfileFragment : Fragment() { val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_profile, container, false) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val foto = arguments!!.getString("foto")!!.toString() if (foto == "") { Picasso.get() .load(R.drawable.photo_user) .placeholder(R.drawable.photo_user) .error(R.drawable.photo_user) .into(user_image_profile) } else { Picasso.get() .load(arguments!!.getString("foto")!!.toString()) .placeholder(R.drawable.photo_user) .error(R.drawable.photo_user) .into(user_image_profile) } text_nama_user.text = arguments!!.getString("nama").toString() text_email_user.text = arguments!!.getString("email").toString() val saldo = arguments!!.getInt("saldo") text_saldo_user.setText(formatRupiah.format(saldo)) buttonGantiNama.setOnClickListener { openDialogGantiNama() } buttonGantiPassword.setOnClickListener { openDialogGantiPassword() } buttonTopUpSaldo.setOnClickListener { openDialogTopUpSaldo() } buttonSignOut.setOnClickListener { val intent = Intent(this@ProfileFragment.context, Login::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) } } override fun onResume() { super.onResume() if (SISA_SALDO != "") { text_saldo_user.setText(formatRupiah.format(SISA_SALDO.toInt())) } } fun openDialogGantiNama() { val mDialogView = LayoutInflater.from(this@ProfileFragment.context).inflate(R.layout.layout_ganti_nama, null) //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this@ProfileFragment.context) .setView(mDialogView) .setTitle("Ganti Nama") //show dialog val mAlertDialog = mBuilder.show() //login button click of custom layout mDialogView.dialogSimpanNamaBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() if (mDialogView.edit_nama_user_baru.text.toString() == "") { val snackBar = Snackbar.make( profile_view, "Harap isi semua informasi terlebih dahulu", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { //get text from EditTexts of custom layout val nama = mDialogView.edit_nama_user_baru.text.toString() gantiNama(nama) //set the input text in TextView text_nama_user.setText(nama) } } //cancel button click of custom layout mDialogView.dialogCancelNamaBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() } } fun openDialogGantiPassword() { val passwordLama = arguments!!.getString("password").toString() val mDialogView = LayoutInflater.from(this@ProfileFragment.context).inflate(R.layout.layout_ganti_password, null) //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this@ProfileFragment.context) .setView(mDialogView) .setTitle("Ganti Password") //show dialog val mAlertDialog = mBuilder.show() //login button click of custom layout mDialogView.dialogSimpanPassBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() if (mDialogView.edit_password_lama.text.toString() == "" || mDialogView.edit_password_baru.text.toString() == "" || mDialogView.edit_konfirmasi_password.text.toString() == "") { val snackBar = Snackbar.make( profile_view, "Harap isi semua informasi terlebih dahulu", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else if (mDialogView.edit_password_lama.text.toString() != passwordLama) { val snackBar = Snackbar.make( profile_view, "Password lama anda tidak sesuai", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else if (mDialogView.edit_password_baru.text.toString() != mDialogView.edit_konfirmasi_password.text.toString()) { val snackBar = Snackbar.make( profile_view, "Harap ketik ulang password dengan benar", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { //get text from EditTexts of custom layout val password = mDialogView.edit_password_baru.text.toString() gantiPassword(password) } } //cancel button click of custom layout mDialogView.dialogCancelPassBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() } } fun openDialogTopUpSaldo() { val mDialogView = LayoutInflater.from(this@Profile<EMAIL>).inflate(R.layout.layout_top_up_saldo, null) //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this@ProfileFragment.context) .setView(mDialogView) .setTitle("Top Up Saldo") //show dialog val mAlertDialog = mBuilder.show() //login button click of custom layout mDialogView.dialogSimpanNamaBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() if (mDialogView.edit_top_up_saldo.text.toString() == "") { val snackBar = Snackbar.make( profile_view, "Harap isi semua informasi terlebih dahulu", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { //get text from EditTexts of custom layout val saldoTambahan = mDialogView.edit_top_up_saldo.text.toString() topUpSaldo(saldoTambahan) Toast.makeText(this.context, "Data berhasil disimpan", Toast.LENGTH_SHORT).show() } } //cancel button click of custom layout mDialogView.dialogCancelNamaBtn.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() } } internal fun gantiNama(nama: String) { val idUser = arguments!!.getInt("idUser") val retro = Retro().getRetroClientInstance(URL).create(UserAPI::class.java) retro.gantiNama(idUser, nama).enqueue(object: Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString val message = response.body().get("message").asString if (result == "OK") { Toast.makeText(this@ProfileFragment.context, message, Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@ProfileFragment.context, message, Toast.LENGTH_SHORT).show() } } } }) } internal fun gantiPassword(password: String) { val idUser = arguments!!.getInt("idUser") val retro = Retro().getRetroClientInstance(URL).create(UserAPI::class.java) retro.gantiPassword(idUser, password).enqueue(object: Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString val message = response.body().get("message").asString if (result == "OK") { Toast.makeText(this@ProfileFragment.context, message, Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@ProfileFragment.context, message, Toast.LENGTH_SHORT).show() } } } }) } internal fun topUpSaldo(saldoTambahan: String) { val idUser = arguments!!.getInt("idUser") val retro = Retro().getRetroClientInstance(URL).create(UserAPI::class.java) retro.topUpSaldo(idUser, saldoTambahan).enqueue(object: Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString val message = response.body().get("message").asString if (result == "OK") { implementToTextSaldo(message) } else { Toast.makeText(this@ProfileFragment.context, message, Toast.LENGTH_SHORT).show() } } } }) } fun implementToTextSaldo(saldo: String) { val rpSaldo = formatRupiah.format(saldo.toInt()) text_saldo_user.setText(rpSaldo) } companion object { var SISA_SALDO = "" fun newInstance(user: User) = ProfileFragment().apply { val fragment = ProfileFragment() val args = Bundle() args.putInt("idUser", user.idUser!!) args.putString("nama", user.nama) args.putString("email", user.email) args.putString("foto", user.foto) args.putString("password", <PASSWORD>) args.putInt("saldo", user.saldo!!) fragment.arguments = args return fragment } } } <file_sep>package com.example.project_uas.adapter import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.example.project_uas.Detail import com.example.project_uas.Home import com.example.project_uas.R import com.example.project_uas.data.URL import com.example.project_uas.model.Cart import com.example.project_uas.model.Product import com.example.project_uas.service.CartAPI import com.example.project_uas.service.ProductAPI import com.example.project_uas.ui.CartFragment import com.example.project_uas.ui.HomeFragment import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.fragment_cart.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.text.NumberFormat import java.util.* import kotlin.collections.ArrayList class CardViewProductAdapter(private val listProduct: ArrayList<Product>, private val idUser:Int) : RecyclerView.Adapter<CardViewProductAdapter.CardViewViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): CardViewProductAdapter.CardViewViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_cardview_product, parent, false) return CardViewViewHolder(view) } override fun getItemCount(): Int { return listProduct.size } override fun onBindViewHolder( holder: CardViewProductAdapter.CardViewViewHolder, position: Int ) { val product = listProduct[position] holder.tvName.text = product.nama holder.tvDeskripsi.text = product.deskripsi val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) holder.tvPrice.setText(formatRupiah.format(product.harga)) Picasso.get() .load(product.foto) .placeholder(R.drawable.photo_barang) .error(R.drawable.photo_barang) .fit() .into(holder.imgUser) holder.btnDetail.setOnClickListener { val intent = Intent(holder.itemView.context, Detail::class.java) intent.putExtra(Detail.USER_ID, idUser) intent.putExtra(Detail.PRODUCT_ID, product.idProduct) intent.putExtra(Detail.PRODUCT_NAME, product.nama) intent.putExtra(Detail.PRODUCT_DESCRIPTION, product.deskripsi) intent.putExtra(Detail.PRODUCT_PRICE, product.harga) intent.putExtra(Detail.PRODUCT_CATEGORY, product.kategori!!.nama) intent.putExtra(Detail.PRODUCT_PHOTO, product.foto) holder.itemView.context.startActivity(intent) } holder.btnAddToCart.setOnClickListener { val retro = Retro().getRetroClientInstance(URL).create(CartAPI::class.java) retro.insertCartItems(idUser, product.idProduct!!, product.harga!!).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>?, t: Throwable?) { Log.e("Failed", "Pesan kesalahan: " + t!!.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString val message = response.body().get("message").asString if (result == "ERROR") { Toast.makeText(holder.itemView.context, message, Toast.LENGTH_SHORT).show() } else { val snackBar = Snackbar.make( holder.itemView, "Data berhasil ditambahkan", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } }) } } inner class CardViewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var tvName: TextView = itemView.findViewById(R.id.tv_item_name) var tvDeskripsi: TextView = itemView.findViewById(R.id.tv_item_description) var tvPrice: TextView = itemView.findViewById(R.id.tv_item_price) var imgUser: ImageView = itemView.findViewById(R.id.img_item_photo) var btnDetail: Button = itemView.findViewById(R.id.btn_detail_barang) var btnAddToCart: Button = itemView.findViewById(R.id.btn_add_to_cart) } }<file_sep>package com.example.project_uas.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Cart { @SerializedName("idCart") @Expose var idCart:Int? = null @SerializedName("product") @Expose var product:Product? = null @SerializedName("quantity") @Expose var quantity:Int? = null @SerializedName("subTotal") @Expose var subTotal:Int? = null @SerializedName("totalSubTotal") @Expose var totalSubTotal:Int? = null }<file_sep>package com.example.project_uas.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Order { @SerializedName("idOrder") @Expose var idOrder:Int? = null @SerializedName("tanggal") @Expose var tanggal:String? = null @SerializedName("totalQuantity") @Expose var totalQuantity:Int? = null @SerializedName("totalJenisItem") @Expose var totalJenisItem:Int? = null @SerializedName("grandTotal") @Expose var grandTotal:Int? = null }<file_sep>package com.example.project_uas.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class User { @SerializedName("idUser") @Expose var idUser:Int? = null @SerializedName("nama") @Expose var nama:String? = null @SerializedName("email") @Expose var email:String? = null @SerializedName("saldo") @Expose var saldo:Int? = null @SerializedName("password") @Expose var password:String? = null @SerializedName("password") @Expose var foto:String? = null }<file_sep>package com.example.project_uas.service import com.google.gson.JsonObject import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface CartAPI { @FormUrlEncoded @POST("nmp160418117/insert_to_cart.php") fun insertCartItems(@Field("idUser") idUser: Int, @Field("idProduct") idProduct: Int, @Field("subTotal") subTotal: Int ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/get_all_items_cart.php") fun getCartItems(@Field("idUser") idUser: Int ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/add_quantity.php") fun addQuantity(@Field("idCart") idCart: Int, @Field("idUser") idUser: Int ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/substract_quantity.php") fun substractQuantity(@Field("idCart") idCart: Int, @Field("idUser") idUser: Int ) : retrofit2.Call<JsonObject> }<file_sep>package com.example.project_uas import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.MenuItem import android.widget.Toast import androidx.core.view.GravityCompat import com.example.project_uas.data.URL import com.example.project_uas.service.CartAPI import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_detail.* import kotlinx.android.synthetic.main.activity_detail.toolbar import kotlinx.android.synthetic.main.activity_home.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.text.NumberFormat import java.util.* class Detail : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) setSupportActionBar(toolbar) supportActionBar?.setTitle(R.string.app_name) supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_24) supportActionBar?.setDisplayHomeAsUpEnabled(true) val idUser = intent.getIntExtra(USER_ID, 0) val idProduct = intent.getIntExtra(PRODUCT_ID, 0) val nama = intent.getStringExtra(PRODUCT_NAME) val desc = intent.getStringExtra(PRODUCT_DESCRIPTION) val price = intent.getIntExtra(PRODUCT_PRICE, 0) val category = intent.getStringExtra(PRODUCT_CATEGORY) val photo = intent.getStringExtra(PRODUCT_PHOTO) text_name_detail.text = nama text_desc_detail.text = desc text_category_detail.text = category val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) text_price_detail.setText(formatRupiah.format(price)) Picasso.get() .load(photo) .placeholder(R.drawable.photo_barang) .error(R.drawable.photo_barang) .resize(400, 460) .centerInside() .into(imageView) btn_add_to_cart.setOnClickListener { val retro = Retro().getRetroClientInstance(URL).create(CartAPI::class.java) retro.insertCartItems(idUser, idProduct, price).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>?, t: Throwable?) { Log.e("Failed", "Pesan kesalahan: " + t!!.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString val message = response.body().get("message").asString if (result == "ERROR") { Toast.makeText(this@Detail.baseContext, message, Toast.LENGTH_SHORT).show() } else { val snackBar = Snackbar.make( detailView, "Data berhasil ditambahkan", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } }) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { android.R.id.home -> finish() } return super.onOptionsItemSelected(item) } companion object { const val USER_ID = "extra_user_id" const val PRODUCT_ID = "extra_product_id" const val PRODUCT_NAME = "extra_name" const val PRODUCT_DESCRIPTION = "extra_desc" const val PRODUCT_PRICE = "extra_price" const val PRODUCT_CATEGORY = "extra_category" const val PRODUCT_PHOTO = "extra_photo" } }<file_sep>package com.example.project_uas import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.MenuItem import android.widget.Toast import androidx.core.view.GravityCompat import com.example.project_uas.data.URL import com.example.project_uas.model.User import com.example.project_uas.service.UserAPI import com.example.project_uas.util.Retro import com.google.android.material.snackbar.Snackbar import com.google.gson.JsonObject import kotlinx.android.synthetic.main.activity_home.* import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.activity_sign_up.* import kotlinx.android.synthetic.main.activity_sign_up.editTextTextEmailAddress import kotlinx.android.synthetic.main.activity_sign_up.editTextTextPassword import kotlinx.android.synthetic.main.activity_sign_up.toolbar import retrofit2.Call import retrofit2.Callback import retrofit2.Response class SignUp : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) setSupportActionBar(toolbar) supportActionBar?.setTitle(R.string.app_name) supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_24) supportActionBar?.setDisplayHomeAsUpEnabled(true) buttonSubmit.setOnClickListener { if (editTextTextEmailAddress.text.toString() == "" || editTextTextName.text.toString() == "" || editTextTextPassword.text.toString() == "") { val snackBar = Snackbar.make( signUpView, "Harap isi semua informasi terlebih dahulu", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else if (editTextTextPassword.text.toString() != editTextTextPassword2.text.toString()) { val snackBar = Snackbar.make( signUpView, "Harap ketik ulang password dengan benar", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } else { signUp() } } } internal fun signUp() { val user = User() user.email = editTextTextEmailAddress.text.toString() user.nama = editTextTextName.text.toString() user.password = <PASSWORD>TextTextPassword.text.toString() val retro = Retro().getRetroClientInstance(URL).create(UserAPI::class.java) retro.createUser( user.nama.toString(), user.email.toString(), user.password.toString() ).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { Log.e("Failed", "Pesan kesalahan: " + t.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.code() == 200) { val result = response.body().get("result").asString if (result == "OK") { // start activity ke Home val intent = Intent(this@SignUp, Home::class.java) val datas = response.body().getAsJsonArray("data") for (data in datas) { val idUser = data.asJsonObject.get("idUser").asInt val nama = data.asJsonObject.get("nama").asString val email = data.asJsonObject.get("email").asString val saldo = data.asJsonObject.get("saldo").asInt val foto = data.asJsonObject.get("foto").asString val password = data.asJsonObject.get("password").asString intent.putExtra(Home.USER_ID, idUser) intent.putExtra(Home.USER_NAMA, nama) intent.putExtra(Home.USER_EMAIL, email) intent.putExtra(Home.USER_SALDO, saldo) intent.putExtra(Home.USER_FOTO, foto) intent.putExtra(Home.USER_PASSWORD, password) } startActivity(intent) } else { val message = response.body().get("message").asString if (result == "ERROR" && message == "Email sudah dipakai") { val snackBar = Snackbar.make( signUpView, "Email sudah dipakai, mohon gunakan email lain", Snackbar.LENGTH_SHORT ).setAction("Action", null) snackBar.show() } } } else { Toast.makeText(applicationContext, "Server tidak merespon", Toast.LENGTH_SHORT) .show() } } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { android.R.id.home -> finish() } return super.onOptionsItemSelected(item) } } <file_sep>package com.example.project_uas.service import com.google.gson.JsonObject import retrofit2.http.* interface OrderAPI { @FormUrlEncoded @POST("nmp160418117/insert_order_history.php") fun insertCartItems(@Field("idUser") idUser: Int, @Field("tanggal") tanggal: String, @Field("arrIdCart[]") arrIdCart: ArrayList<Int> ) : retrofit2.Call<JsonObject> @FormUrlEncoded @POST("nmp160418117/get_order_info.php") fun getOrders(@Field("idUser") idUser: Int) : retrofit2.Call<JsonObject> }<file_sep>package com.example.project_uas.adapter import android.app.Activity import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.example.project_uas.R import com.example.project_uas.data.URL import com.example.project_uas.model.Cart import com.example.project_uas.service.CartAPI import com.example.project_uas.util.Retro import com.google.gson.JsonObject import com.squareup.picasso.Picasso import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.text.NumberFormat import java.util.* class CardViewCartAdapter(private val listProduct: ArrayList<Cart>, private val idUser: Int) : RecyclerView.Adapter<CardViewCartAdapter.CardViewViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): CardViewCartAdapter.CardViewViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_cardview_cart, parent, false) return CardViewViewHolder(view) } override fun getItemCount(): Int { return listProduct.size } inner class CardViewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var tvName: TextView = itemView.findViewById(R.id.tv_item_name) var tvPrice: TextView = itemView.findViewById(R.id.tv_item_price) var imgCart: ImageView = itemView.findViewById(R.id.img_item_photo) var edtQuantity: EditText = itemView.findViewById(R.id.edit_quantity) var btnAddQty: ImageButton = itemView.findViewById(R.id.btn_add_quantity) var btnMinQty: ImageButton = itemView.findViewById(R.id.btn_min_quantity) } override fun onBindViewHolder(holder: CardViewViewHolder, position: Int) { val product = listProduct[position] holder.tvName.text = product.product!!.nama val localeID = Locale("in", "ID") val formatRupiah: NumberFormat = NumberFormat.getCurrencyInstance(localeID) holder.tvPrice.setText(formatRupiah.format(product.subTotal)) Picasso.get() .load(product.product!!.foto) .placeholder(R.drawable.photo_barang) .error(R.drawable.photo_barang) .fit() .into(holder.imgCart) holder.edtQuantity.setText(product.quantity!!.toString(), TextView.BufferType.EDITABLE) holder.btnAddQty.setOnClickListener { val retro = Retro().getRetroClientInstance(URL).create(CartAPI::class.java) retro.addQuantity(product.idCart!!, idUser).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>?, t: Throwable?) { Log.e("Failed", "Pesan kesalahan: " + t!!.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString if (result == "ERROR") { Toast.makeText(holder.itemView.context, "Data gagal ditambahkan", Toast.LENGTH_SHORT).show() } else { val quantity = response.body().get("quantity").asString val subTotal = response.body().get("sub_total").asInt val totalSubTotal = response.body().get("total_sub_total").asInt holder.edtQuantity.setText(quantity, TextView.BufferType.EDITABLE) holder.tvPrice.setText(formatRupiah.format(subTotal)) val txtTotal = (context as Activity).findViewById<View>(R.id.text_sub_total) as TextView txtTotal.setText(formatRupiah.format(totalSubTotal)) } } } }) } holder.btnMinQty.setOnClickListener { if (holder.edtQuantity.text.toString() == "1") { Toast.makeText(holder.itemView.context, "Maaf quantity tidak bisa dikurangi lagi", Toast.LENGTH_SHORT).show() } else { val retro = Retro().getRetroClientInstance(URL).create(CartAPI::class.java) retro.substractQuantity(product.idCart!!, idUser).enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>?, t: Throwable?) { Log.e("Failed", "Pesan kesalahan: " + t!!.message.toString()) } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful) { val result = response.body().get("result").asString if (result == "ERROR") { Toast.makeText(holder.itemView.context, "Data gagal dikurangi", Toast.LENGTH_SHORT).show() } else { val quantity = response.body().get("quantity").asString val subTotal = response.body().get("sub_total").asInt val totalSubTotal = response.body().get("total_sub_total").asInt holder.edtQuantity.setText(quantity, TextView.BufferType.EDITABLE) holder.tvPrice.setText(formatRupiah.format(subTotal)) val txtTotal = (context as Activity).findViewById<View>(R.id.text_sub_total) as TextView txtTotal.setText(formatRupiah.format(totalSubTotal)) } } } }) } } } override fun getItemId(position: Int): Long { return listProduct[position].idCart!!.toLong() } companion object { var context: Context? = null } }
4fea9aa57af94eb60c8dfe1c1111dab8f9d4ace5
[ "Kotlin" ]
20
Kotlin
mosanidev/shop_kotlin
8e197bd4f0201e4ec574f00034c6f4827bb249bb
2ecde3a375e81997ea3ec861ad94ccf6b21e0747
refs/heads/master
<repo_name>davcache/MegaDeskWebApp---JeaninaAndCache<file_sep>/MegaDeskWebApp - JeaninaAndCache/Desk.cs public class Desk { public int Width { get; set; } public int Depth { get; set; } public int NumberOfDrawers { get; set; } public enum SurfaceMaterial { Laminate, Oak, Rosewood, Veneer, Pine } public SurfaceMaterial DeskMaterial { get; set; } } <file_sep>/MegaDeskWebApp - JeaninaAndCache/DeskQuote.cs public class DeskQuote { public Desk Desk { get; set; } public string CustomerName { get; set; } public string RushOption { get; set; } public int FinalQuote { get; set; } public string QuoteDate { get; set; } const int basePrice = 200; const int drawerPrice = 50; const int surfaceAreaPrice = 1; const int oakPrice = 200; const int laminatePrice = 100; const int pinePrice = 50; const int rosewoodPrice = 300; const int veneerPrice = 200; public int GetRushOrder(string rushOrder, int deskSurfaceArea) { int rushOrderRate = 0; switch (rushOrder) { case "3-Day Delivery": if (deskSurfaceArea < 1000) { rushOrderRate = 60; } else if (deskSurfaceArea > 1000 && deskSurfaceArea < 2000) { rushOrderRate = 70; } else if (deskSurfaceArea > 2000) { rushOrderRate = 80; } break; case "5-Day Delivery": if (deskSurfaceArea < 1000) { rushOrderRate = 40; } else if (deskSurfaceArea > 1000 && deskSurfaceArea < 2000) { rushOrderRate = 50; } else if (deskSurfaceArea > 2000) { rushOrderRate = 60; } break; case "7-Day Delivery": if (deskSurfaceArea < 1000) { rushOrderRate = 30; } else if (deskSurfaceArea > 1000 && deskSurfaceArea < 2000) { rushOrderRate = 35; } else if (deskSurfaceArea > 2000) { rushOrderRate = 40; } break; default: rushOrderRate = 0; break; } return rushOrderRate; } public int CalcQuote() { // find surface area of desk int surfaceArea = Desk.Depth * Desk.Width; int surfaceAreaRate = 0; int materialPrice = 0; int rushOrderPrice = 0; // read rushOrdertxt and place into two dimensional array // get surface area rate if (surfaceArea > 1000) { surfaceAreaRate = surfaceArea * surfaceAreaPrice; } // get drawer rate int drawerNumberRate = Desk.NumberOfDrawers * drawerPrice; // get material rate if (Desk.DeskMaterial == Desk.SurfaceMaterial.Laminate) { materialPrice = laminatePrice; } else if (Desk.DeskMaterial == Desk.SurfaceMaterial.Oak) { materialPrice = oakPrice; } else if (Desk.DeskMaterial == Desk.SurfaceMaterial.Rosewood) { materialPrice = rosewoodPrice; } else if (Desk.DeskMaterial == Desk.SurfaceMaterial.Veneer) { materialPrice = veneerPrice; } else if (Desk.DeskMaterial == Desk.SurfaceMaterial.Pine) { materialPrice = pinePrice; } // get rush order rate rushOrderPrice = GetRushOrder(RushOption, surfaceArea); int quote = basePrice + surfaceAreaRate + drawerNumberRate + materialPrice + rushOrderPrice; return quote; } }
fd53e6623dd758004ef5969a5de6708b0ba391cb
[ "C#" ]
2
C#
davcache/MegaDeskWebApp---JeaninaAndCache
0ca33c2274552a474ba5a4db9e6fa1251b8df427
19f017bc01acb1405d3fdc6d0f26b18138f7bcce
refs/heads/master
<file_sep>import os import sys from ExcelLoader import Generator class CSharpGenerator(Generator): def __init__(self, excel, workspace): super(CSharpGenerator, self).__init__(excel, workspace) def export_csharp(self): provider_template = open(os.path.join(self.workspace, self.cfg['provider_template'])) content = provider_template.read() dir_to_save = os.path.join(self.workspace, self.cfg['export_csharp']) for raw_data in self.loader.all_raw_data: data_node_fields = [] for i, field_name in enumerate(raw_data.field_names): if field_name == '': continue data_node_fields.append( " public {type_name} {field_name};".format(field_name=field_name, type_name=raw_data.type_names[i])) code_str = content.format(ClassName=raw_data.cfg_file_name, CfgName=raw_data.cfg_file_name, DataNodeFields='\n'.join(data_node_fields)) filename = os.path.join(dir_to_save, raw_data.cfg_file_name) + '.cs' with open(filename, 'w') as fp: fp.write(code_str) if __name__ == '__main__': excel_file = r'..\Sample\template.xlsx' excel_dir = os.path.dirname(os.path.abspath(excel_file)) gen = Generator(os.path.abspath(excel_file), os.path.abspath(os.path.join(excel_dir, 'config.json'))) gen.export_json() <file_sep>import unittest import os from ExcelLoader.Loader import * from ExcelLoader.Generator import Generator from GenCSharp.Generator import CSharpGenerator class TestGenerator(unittest.TestCase): def test_export_json(self): gen = Generator('test.xlsx', '') gen.export_json() self.assertTrue(len(os.listdir('./data')) > 0) self.assertTrue(os.path.exists('./data/Test.json')) class TestSCharpGenerator(unittest.TestCase): def test_export_json(self): gen = CSharpGenerator('test.xlsx', '') gen.export_json() def test_export_csharp(self): gen = CSharpGenerator('test.xlsx', '') gen.export_csharp() <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using LitJson; using System.IO; using UnityEngine; namespace Data{{ public class {ClassName} {{ private static {ClassName} instance; public static {ClassName} Instance {{ get {{ return instance == null ? instance = new {ClassName}() : instance; }} }} public Dictionary<string,DataNode> Data {{ get;private set; }} private {{ClassName}}() {{ TextAsset textAsset = CfgProvider.Get("{CfgName}"); Data = JsonMapper.ToObject<Dictionary<string,DataNode>>(textAsset.text); }} public DataNode this[int index] {{ get {{ return Data[index.ToString()]; }} }} public class DataNode {{ {DataNodeFields} }} }} }}<file_sep># CSharp导出器 CSharp导出器本身不生成任何的数据,只负责导出供Json库反序列化用的代理类代码, 也就是CSharpDataProvider。导出器根据配置表的名字生成对应的Provider类。 不过存在一个问题, 那就是我们无法确定json配置文件和对应的Provider类的放置路径,因此我多写了个SampleCfgProvider。 CSharpDataProviderTemplate里默认通过SampleCfgProvider来加载json,如何加载去哪里加载由 SampleCfgProvider控制。SampleCfgProvider只是个参考,代码很简单,你可以根据自己项目的需要去修改。 <file_sep>import json import os import sys import argparse from GenCSharp.Generator import CSharpGenerator excel_file = sys.argv[1] excel_dir = os.path.dirname(os.path.abspath(excel_file)) default_config = {"export": "", "provider_template": "CSharpDataProviderTemplate.cs", "export_csharp": "provider"} config_file = os.path.join(excel_dir, 'config.json') # 如果没有默认配置就自动创建一个 if not os.path.exists(config_file): fp = open(config_file, 'w') json.dump(default_config, fp, indent=True) fp.close() cfg_file = open(config_file, 'r') config = json.load(cfg_file) # 如果没有data目录就自动创建一个 export_dir = os.path.join(excel_dir, config['export']) if not os.path.exists(export_dir): os.mkdir(export_dir) provider_dir = os.path.join(excel_dir, config['export_csharp']) if not os.path.exists(provider_dir): os.mkdir(provider_dir) gen = CSharpGenerator(os.path.abspath(excel_file), excel_dir) gen.export_json() gen.export_csharp() print("导出>>", os.path.split(excel_file)[1])<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Data { public class CfgProvider { public static readonly string directoryPath = ""; public static string Get(string cfgName) { return directoryPath+cfgName + ".json"; } } } <file_sep>import json import os from ExcelLoader.Loader import ExcelLoader from . import create_loader class Generator(object): """ 导出器 定义了导出过程,可以继承这个导出器,自己实现具体的加工rawdata的导出器。 """ def __init__(self, excel: str, workspace: str): self.excel = excel self.workspace = os.path.abspath(workspace) self.loader = create_loader(excel) # type:ExcelLoader @property def cfg(self): fp = open(os.path.join(self.workspace, 'config.json')) _cfg = json.load(fp) return _cfg def export_json(self): dir_to_save = os.path.join(self.workspace, self.cfg['export']) for raw_data in self.loader.all_raw_data: filename = os.path.join(self.workspace, dir_to_save, raw_data.cfg_file_name) + '.json' fp = open(filename, 'w', encoding='utf-8') json.dump(raw_data.data, fp, indent=4, ensure_ascii=False, separators=(',', ':'), skipkeys=True, check_circular=True, sort_keys=True) self.loader.close() <file_sep>import os import openpyxl from openpyxl.cell import Cell from openpyxl.styles.colors import Color from openpyxl.workbook import Workbook from openpyxl.worksheet import worksheet class RawData(object): """ 原始数据 """ def __init__(self, cfg_name: str, type_names: list, field_names: list, data: dict): self.type_names = type_names self.field_names = field_names self.data = data self.cfg_file_name = cfg_name class Setting(object): """ 标志设置 每个配置表左上角是标志信息,标志了类型行、字段行、结束行、配置名这几个属性 """ def __init__(self, cfg_name, type_row: int, field_row: int, data_range: tuple): self.__cfg_name = cfg_name self.__type_row = type_row self.__field_row = field_row self.__range = data_range @property def type_row(self): return self.__type_row @property def field_row(self): return self.__field_row @property def range(self): return self.__range @property def cfg_name(self): return self.__cfg_name class ExcelLoader(object): def __init__(self, file_name: str): self.file_name = file_name self.workbook = self.open_workbook(self.file_name) def open_workbook(self) -> Workbook: raise NotImplementedError() def get_raw_data(self, sheet_index) -> RawData: """获取某个sheet的原始数据""" return @property def all_raw_data(self): for i, sheet in enumerate(self.workbook.worksheets): yield self.get_raw_data(i) def setting(self, sheet_index) -> Setting: raise NotImplementedError() def close(self): self.workbook.close() def Parse(t: str, value): if t == 'int': try: return int(value) except: return 0 if t == 'float': try: return float(value) except: return 0.0 if t == 'string': try: return str(value) if value else '' except: return '' if t.startswith('dict'): try: return eval(value) except: return None try: return eval(value) except: return str(value) class XLSXLoader(ExcelLoader): def __init__(self, file_name: str): super(XLSXLoader, self).__init__(file_name) def open_workbook(self, file_name: str) -> worksheet: workbook = openpyxl.open(file_name) # type: Workbook return workbook def setting(self, sheet_index=0) -> Setting: """设置数据""" sheet = self.workbook.worksheets[sheet_index] # type: worksheet # 写死读取设置 type_color = sheet.cell(1, 2).fill.fgColor # type: Color field_name_color = sheet.cell(2, 2).fill.fgColor # type:Color end_color = sheet.cell(3, 2).fill.fgColor # type: Color cfg_name = sheet.cell(4, 2).value # row最小是1,而range是[ )左闭右开区间,所以右边要+1 for row in range(1, sheet.max_row + 1): cell = sheet.cell(row, 1) # type:Cell if cell.fill.fgColor == type_color: type_row = row if cell.fill.fgColor == field_name_color: field_row = row if cell.fill.fgColor == end_color: end_row = row break i = 1 while True: cell = sheet.cell(type_row, i) if cell.fill.fgColor != type_color: data_max_col = i break i += 1 return Setting(cfg_name, type_row, field_row, (end_row, data_max_col)) def get_raw_data(self, sheet_index=0): sheet = self.workbook.worksheets[sheet_index] # type: worksheet setting = self.setting(sheet_index) cfg_name = setting.cfg_name # 获取字段名 # 获取字段类型名,默认int field_names = [''] type_names = [''] for col in range(1, setting.range[1]): field_cell = sheet.cell(setting.field_row, col) # type: Cell type_cell = sheet.cell(setting.type_row, col) # type: Cell field_names.append(field_cell.value) type_names.append(type_cell.value or 'int') # 如果类型为空默认当int # 遍历每行数据,用字典的方式组织 data = {} for row in range(setting.field_row + 1, setting.range[0]): item = {} for col in range(1, setting.range[1]): cell = sheet.cell(row, col) field_name = field_names[col] # 跳过空id的数据 if field_name == 'id' and not cell.value: break else: item[field_name] = Parse(type_names[col], cell.value) if len(item) > 0: data[item['id']] = item raw_data = RawData(cfg_name, type_names, field_names, data) return raw_data class XLSLoader(ExcelLoader): def __init__(self, filename: str): super(XLSLoader, self).__init__(filename) def create_loader(filename: str) -> ExcelLoader: extension = os.path.splitext(filename)[1] if extension == '.xlsx': loader = XLSXLoader(filename) return loader elif extension == '.xls': loader = XLSLoader(filename) return loader <file_sep>import os import json import sys from GenCSharp.Generator import Generator excel_file = sys.argv[1] excel_dir = os.path.dirname(os.path.abspath(excel_file)) default_config = {"export": ""} config_file = os.path.join(excel_dir, 'config.json') # 如果没有默认配置就自动创建一个 if not os.path.exists(config_file): fp = open(config_file, 'w') json.dump(default_config, fp, indent=True) fp.close() cfg_file = open(config_file, 'r') config = json.load(cfg_file) # 如果没有data目录就自动创建一个 export_dir = os.path.join(excel_dir, config['export']) if not os.path.exists(export_dir): os.mkdir(export_dir) gen = Generator(os.path.abspath(excel_file), excel_dir) gen.export_json() print("导出>>", os.path.split(excel_file)[1]) <file_sep>from setuptools import setup, find_packages setup(name='Excel2Json', version='1.0', description='Excel转json导表工具', author='dengxuan', author_email='<EMAIL>', url = 'https://github.com/kaluluosi/Excel2Json', packages=['ExcelLoader'], install_requires = ['openpyxl', 'xlrd'] ) <file_sep> from .Loader import create_loader from .Generator import Generator <file_sep>import unittest from ExcelLoader.Loader import XLSXLoader class TestXLSXLoader(unittest.TestCase): @classmethod def setUpClass(cls): cls.loader = XLSXLoader('test.xlsx') def test_load_setting(self): setting = self.loader.setting(0) self.assertTrue(setting.cfg_name) self.assertTrue(setting.range) self.assertTrue(setting.field_row) self.assertTrue(setting.type_row) def test_get_raw_data(self): raw_data = self.loader.get_raw_data(0) self.assertTrue(raw_data.type_names) self.assertTrue(raw_data.field_names) self.assertTrue(raw_data.data) self.assertEqual(len(raw_data.type_names), len(raw_data.field_names)) @classmethod def tearDownClass(cls): cls.loader.close() if __name__ == '__main__': unittest.main() <file_sep># README ## 更新日志 ### ver 1.0 1. 增加config.json配置用来记录输出路径 2. 重写Excel Addin (因为源码已经丢失了) 3. 将原始数据获取和自定义导出过程(数据加工)剥离 ## 如何使用 本工具依赖`openpyxl`和`xlrd`,先用pip安装这两个库 >pip install openpyxl >pip install xlrd Sample目录下有使用示例,直接把`template.xlsx`拖到`Export.bat`即可导出数据。
8d7cc2eafcce7eb2e9c52c3dfb994f8bcc86a139
[ "Markdown", "C#", "Python" ]
13
Python
kaluluosi/Excel2Json
5c4d7441cb957087fe1fa5706dc1a9a800152811
1fa870e69031a0ca2552eea4e3aaa0b553425209
refs/heads/master
<file_sep>#include <iostream> #include <string> #include <fstream> #include <algorithm> #include <array> #include <cstring> using namespace std; void MergeInts(int arr[], int low, int high, int mid); // Combines sorted values void MergeSortInts(int *arr, int low, int high); // Splits array into two halves void MergeStrings(string arr[], int low, int high, int mid); void MergeSortStrings(string *arr, int low, int high); string* readStrings(string f1, int &size); int * readInts(string f1, int &size); // function to combine values in order from two halves (subarrays from low, mid and mid+1, high) void MergeInts(int arr[], int low, int high, int mid) { int left[mid-low+1]; int right[high-mid]; // copy data from array into left and right halves for (int i = 0; i < mid-low+1; i++) { left[i] = arr[low+i]; } for (int j = 0; j < high-mid; j++) { right[j] = arr[mid+1+j]; } int i = 0; // increment value for left half of array int j = 0; // increment value for right half of array int k = low; // intial index of new array while (i < mid-low+1 && j < high-mid) { // add values from left and right arrays in order into a if (left[i] <= right[j]) { // Left value goes first arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } while (i < mid-low+1) { // copy remaining elements in case of odd division arr[k] = left[i]; i++; k++; } while (j < high-mid) { arr[k] = right[j]; j++; k++; } } // function for splitting arrays in half recursively until only one value void MergeSortInts(int *arr, int low, int high) { int mid; if (low < high) { // stop when equal or crossed mid = (low+high)/2; MergeSortInts(arr, low, mid); // call recursively on left half until you reach one value MergeSortInts(arr, mid+1, high); // call revursively on right half until you reach one value MergeInts(arr, low, high, mid); } } void MergeSortStrings(string arr[], int low, int high) { int mid; if (low < high) { // stop when equal or crossed mid = (low+high)/2; MergeSortStrings(arr, low, mid); // call recursively on left half MergeSortStrings(arr, mid+1, high); // recursive call on right half MergeStrings(arr, low, high, mid); // } } void MergeStrings(string arr[], int low, int high, int mid) { string left[mid-low+1]; string right[high-mid]; // copy data from original array into left and right halves for (int i = 0; i < mid-low+1; i++) { left[i] = arr[low+i]; } for (int j = 0; j < high-mid; j++) { right[j] = arr[mid+1+j]; } int i = 0; int j = 0; int k = low; // intial index while (i < mid-low+1 && j < high-mid) { // copy data from halves into new array in order if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } while (i < mid-low+1) { // copy remaining elements arr[k] = left[i]; i++; k++; } while (j < high-mid) { arr[k] = right[j]; j++; k++; } } // function to read strings from file string* readStrings(string f1, int &size) { ifstream in1; in1.open(f1); if (!in1.is_open()) { cout << "Could not open file " << f1 << endl; } string currString; int count1 = 0; while (!in1.eof()) { // count number of strings in file in1 >> currString; if (!in1.fail()) { count1++; } } in1.clear(); in1.close(); in1.open(f1); // reopen for reading string *array = new string[count1]; size = count1; for (int i = 0; i < count1; i++) { // add strings into array from file in1 >> array[i]; } return array; } // function to read in an array of its from a file int* readInts(string f1, int &size) { ifstream in1; in1.open(f1); if (!in1.is_open()) { cout << "Could not open file " << f1 << endl; } int currNum; int count1 = 0; while (!in1.eof()) { // count number of ints in file 1 in1 >> currNum; if (!in1.fail()) { count1++; } } in1.clear(); in1.close(); in1.open(f1); // reopen file for reading int *array = new int[count1]; // array to hold ints for (int i = 0; i < count1; i++) { // store ints from file into array in1 >> array[i]; } size = count1; return array; } int main(int argc, char** argv) { string argv1 = argv[1]; string argv2 = argv[2]; string argv3 = argv[3]; if (argv1 == "i") { // read integers int size1 = 0; int *array1 = readInts(argv2, size1); int size2 = 0; int *array2 = readInts(argv3, size2); MergeSortInts(array1, 0, size1-1); // sort both arrays by themselves MergeSortInts(array2, 0, size2-1); for (int i = 0; i < size1; i++) { for (int j = i+1; j < size1; j++) { if (array1[i] == array1[j]) { i++; // skip duplicate values } } if (find(array2, array2+size2, array1[i]) != array2+size2) { // element found in both cout << array1[i] << endl; // output unique values that appear in both arrays } } } else if (argv1 == "s") { // must read strings int size1 = 0; int size2 = 0; string *array1 = readStrings(argv2, size1); // first file string *array2 = readStrings(argv3, size2); // second file MergeSortStrings(array1, 0, size1-1); // sort both arrays by themselves MergeSortStrings(array2, 0, size2-1); for (int i = 0; i < size1; i++) { for (int j = i+1; j < size1; j++) { if (array1[i] == array1[j]) { i++; // skip duplicate values } } if (find(array2, array2+size2, array1[i]) != array2+size2) { // element found in both cout << array1[i] << endl; // output unique values that appear in both arrays } } } return 0; }
d0cc0054abc64daa845556b2a885ca0b554c22d0
[ "C++" ]
1
C++
ebuinevicius/TwoFileMatchFinder
8951a816ad37df12447e59d0222b37cd342d77ca
5a9b44d0448a149c42704415f2d1e92a48057762
refs/heads/master
<file_sep>string(43) "/usr/local/phpbin/pg_dump -i -n '"BOOK"' -a" -- -- PostgreSQL database dump -- SET statement_timeout = 0; SET client_encoding = 'LATIN1'; SET standard_conforming_strings = off; SET check_function_bodies = false; SET client_min_messages = warning; SET escape_string_warning = off; SET search_path = "BOOK", pg_catalog; -- -- Name: Uuid_generator; Type: SEQUENCE SET; Schema: BOOK; Owner: ppradier -- SELECT pg_catalog.setval('"Uuid_generator"', 1, false); -- -- Data for Name: Company; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Company" (uuid, label, country) FROM stdin; \. -- -- Data for Name: Book; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Book" (uuid, title, creation_date, uuid_company) FROM stdin; \. -- -- Data for Name: Volume; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Volume" (uuid, title, uuid_book) FROM stdin; \. -- -- Data for Name: Chapter; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Chapter" (uuid, title, uuid_volume) FROM stdin; \. -- -- Data for Name: Organization; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Organization" (uuid, label, country) FROM stdin; \. -- -- Data for Name: WorkPackage; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "WorkPackage" (uuid, label, maturity, uuid_user_lock, uuid_organization) FROM stdin; \. -- -- Data for Name: Content; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Content" (uuid, uuid_content, type_content, uuid_workpackage) FROM stdin; \. -- -- Data for Name: Paragraph; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Paragraph" (uuid, title, content, uuid_chapter) FROM stdin; \. -- -- Data for Name: User; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "User" (uuid, login, password, email, country, name, firstname) FROM stdin; \. -- -- Data for Name: WorkSpace; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "WorkSpace" (uuid, label, uuid_user) FROM stdin; \. -- -- Data for Name: Temporary_content; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY "Temporary_content" (uuid, uuid_content, type_content, title_content, content, uuid_workspace) FROM stdin; \. -- -- Data for Name: organization_relation; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY organization_relation (uuid_organization_mother, uuid_organization_daughter) FROM stdin; \. -- -- Data for Name: user_linked_book; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY user_linked_book (uuid_user, uuid_book) FROM stdin; \. -- -- Data for Name: user_role_organization; Type: TABLE DATA; Schema: BOOK; Owner: ppradier -- COPY user_role_organization (uuid_user, uuid_organization, role) FROM stdin; \. -- -- PostgreSQL database dump complete -- <file_sep>package fr.umlv.book.controller.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.organization.Right; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.service.OrganizationService; public class CreateOrgControllerTest { @Test public void testToEditOrg() { CreateOrgController createOrgController = new CreateOrgController(); assertEquals(createOrgController.toEditOrg(), "book_organisation_gestion"); } @Test public void testIsAbleToCreate() { CreateOrgController createOrgController = new CreateOrgController(); Organization organization = new Organization(); User user = new User(); user.setUuid(1); user.setLogin("John"); List<Right> rights = new ArrayList<Right>();; rights.add(Right.Read); rights.add(Right.Responsable); Map<User, List<Right>> map = new HashMap<User, List<Right>>(); map.put(user, rights); organization.setUsers(map); assertEquals(true, createOrgController.isAbleToCreate(user, organization)); } @Test public void testCreate() { CreateOrgController createOrgController = new CreateOrgController(); OrganizationService organizationService = new OrganizationService(); Organization organization = new Organization(); organization.setLabel("ServiceTop"); createOrgController.create("Equipe B", organization); assertTrue(organizationService.getOrganizationsByRegExp("Equipe B") != null); } } <file_sep>package fr.umlv.book.model.beans.bookelement; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import fr.umlv.book.model.beans.organization.Company; import fr.umlv.book.model.beans.workpackage.WorkPackage; /** * Represents a Book. * * @author <NAME> * */ @Entity @Table(name = "BOOK") public class Book implements BookElement, Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "BOOK_UUID") private int uuid; @Column(name = "BOOK_TITLE") private String title; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "COMPANY_UUID") private Company company; @OneToMany(mappedBy = "parentBook") private List<Volume> volumes; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "WORKPACKAGE_UUID") private WorkPackage parentWP; @Override public int getUuid() { return uuid; } @Override public void setUuid(int uuid) { this.uuid = uuid; } @Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = title; } @Override public WorkPackage getParent() { return parentWP; } @Override public void setParent(WorkPackage parent) { this.parentWP = parent; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public List<Volume> getVolumes() { return volumes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((company == null) ? 0 : company.hashCode()); result = prime * result + ((parentWP == null) ? 0 : parentWP.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + uuid; result = prime * result + ((volumes == null) ? 0 : volumes.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Book)) { return false; } Book other = (Book) obj; if (uuid != other.uuid) return false; return true; } }<file_sep>package fr.umlv.book.controller.edit; import static org.junit.Assert.assertTrue; import org.junit.Test; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.service.UserService; public class EditUserControllerTest { @Test public void testModify() { EditUserController editUserController = new EditUserController(); UserService userService = new UserService(); User user = userService.createUser("<EMAIL>", "fu", "France", "<EMAIL>", "sky", "luc"); assertTrue(editUserController.modify(user.getUuid(), "lol", "lol", "lol", "<EMAIL>", "lol")); } @Test public void testdelete() { EditUserController editUserController = new EditUserController(); UserService userService = new UserService(); User user = userService.createUser("<EMAIL>", "fu", "France", "<EMAIL>", "sky", "luc"); assertTrue(editUserController.delete(user.getUuid())); } } <file_sep>package fr.umlv.book.controller.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; import org.junit.Test; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.organization.Right; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.service.UserService; public class CreateUserControllerTest { @Test public void testIsAbleToCreate() { CreateOrgController createOrgController = new CreateOrgController(); Organization organization = new Organization(); User user = new User(); user.setUuid(1); user.setLogin("John"); List<Right> rights = null; rights.add(Right.Read); rights.add(Right.SuperAdmin); Map<User, List<Right>> map = null; map.put(user, rights); organization.setUsers(map); assertEquals(true, createOrgController.isAbleToCreate(user, organization)); } @Test public void testAjaxExistMail() { CreateUserController createUserController = new CreateUserController(); createUserController.create("Luc", "Walker", "sky", "<EMAIL>", "France"); assertTrue(createUserController.ajaxExistMail("<EMAIL>")); } @Test public void testCreate() { CreateUserController createUserController = new CreateUserController(); createUserController.create("Luc", "Walker", "sky", "<EMAIL>", "France"); UserService userService = new UserService(); assertTrue(userService.getUserByMail("<EMAIL>") != null); } } <file_sep>package fr.umlv.book.model.dao; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Chapter; @Transactional @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/book-test-context.xml" }) public class TestChapterDAO { protected static int uuidChapter = TestVolumeDAO.uuidVolume + 1; @Autowired private IChapterDAO dao; @Test public void testFindChapterElementByUuid() { Chapter exampleChapter = createExampleChapter(); assertEquals(exampleChapter, dao.findBookElementByUuid(uuidChapter)); } @Test public void testGetAllChapterFromVolume() { List<Chapter> chapters = dao .getAllChapterFromVolume(TestVolumeDAO.uuidVolume); assertEquals(1, chapters.size()); assertEquals(createExampleChapter().getUuid(), chapters.get(0).getUuid()); } protected static Chapter createExampleChapter() { Chapter chapter = new Chapter(); chapter.setTitle("CH1"); chapter.setUuid(uuidChapter); chapter.setParentVolume(TestVolumeDAO.createExampleVolume()); return chapter; } } <file_sep>package fr.umlv.book.model.dao; import java.util.List; import fr.umlv.book.model.beans.bookelement.Volume; public interface IVolumeDAO extends IBookElementDAO<Volume> { public List<Volume> getAllVolumeFromBook(int uuid); public Volume findVolumeByTitle(String title); } <file_sep>package fr.umlv.book.model.dao; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Volume; @Transactional @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/book-test-context.xml" }) public class TestVolumeDAO { protected static int uuidVolume = TestBookDAO.uuidBook + 1; @Autowired private IVolumeDAO dao; @Test public void testFindVolumeElementByUuid() { Volume exampleVolume = createExampleVolume(); assertEquals(exampleVolume, dao.findBookElementByUuid(uuidVolume)); } protected static Volume createExampleVolume() { Volume volume = new Volume(); volume.setTitle("relou"); volume.setUuid(uuidVolume); volume.setParent(null); volume.setParentBook(TestBookDAO.createExampleBook()); return volume; } @Test public void testGetAllVolumeFromBook() { List<Volume> elements = dao.getAllVolumeFromBook(TestBookDAO.uuidBook); assertEquals(1, elements.size()); assertEquals(createExampleVolume(), elements.get(0)); } } <file_sep>package fr.umlv.book.controller.create; import java.util.List; import fr.umlv.book.controller.general.OrgChoiceController; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.organization.Right; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.service.UserService; /** * * @author Anthony * */ public class CreateUserController { /** * * @param user objet User contenant toutes les informations de l'User * @param organization objet Organization contenant toutes les informations de l'Organization * @return vrai si l'User peut cr�er un User, faux si non */ public Boolean isAbleToCreate(User user, Organization organization){ OrgChoiceController orgC = new OrgChoiceController(); List<Right> listR = orgC.ajaxGetRightByOrg(user.getUuid(), organization); return listR.contains(Right.SuperAdmin); } /** * * @param name chaine de caract�res du nom de l'User * @param firstName chaine de caract�res du prenom de l'User * @param password chaine de caract�res du mot de passe de l'User * @param mail chaine de caract�res du mail de l'User (sert �galement de login) * @param localite chaine de caract�res du pays de l'User * @return vrai si la cr�ation s'est bien pass�e, faux sinon */ public Boolean create(String name, String firstName, String password, String mail, String localite){ UserService userService = new UserService(); if(userService.createUser(mail, password, localite, mail, firstName, name) == null) { return false; } return true; } /** * * @param mail chaine de caract�res du mail de l'User (sert �galement de login) * @return vrai si le mail existe d�j� dans la base de donn�es, faux sinon */ public Boolean ajaxExistMail(String mail){ UserService userService = new UserService(); User user = null; user = userService.getUserByMail(mail); if (user != null){ return true; } return false; } } <file_sep>package fr.umlv.book.model.beans.bookelement; import static org.junit.Assert.assertEquals; import org.junit.Test; import fr.umlv.book.model.beans.workpackage.WorkPackage; public class VolumeTest { @Test public void testTitle() { String title = "title"; Volume volume = new Volume(); volume.setTitle(title); assertEquals(title, volume.getTitle()); } @Test public void testUuid() { int id = 1; Volume volume = new Volume(); volume.setUuid(id); assertEquals(id, volume.getUuid()); } @Test public void testParent() { WorkPackage parent = new WorkPackage(); Volume volume = new Volume(); volume.setParent(parent); assertEquals(parent, volume.getParent()); } @Test public void testBook() { Book parentBook = new Book(); Volume volume = new Volume(); volume.setParentBook(parentBook); assertEquals(parentBook, volume.getParentBook()); } } <file_sep>package fr.umlv.book.model.dao; import java.util.List; import fr.umlv.book.model.beans.bookelement.Chapter; public interface IChapterDAO extends IBookElementDAO<Chapter> { public List<Chapter> getAllChapterFromVolume(int uuid); public Chapter findChapterByTitle(String title); } <file_sep>package fr.umlv.book.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import javax.persistence.NoResultException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.beans.workpackage.WorkPackage; import fr.umlv.book.model.dao.IOrganizationDAO; import fr.umlv.book.model.dao.IUserDAO; import fr.umlv.book.model.dao.IWorkPackageDAO; import fr.umlv.book.model.service.OrganizationService; import fr.umlv.book.model.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/book-test-context.xml" }) public class TestOrganizationService { @Autowired private IUserDAO userDAO; @Autowired private IWorkPackageDAO wpDAO; @Autowired private IOrganizationDAO orgDAO; protected static Organization createExampleOrganization() { Organization org = new Organization(); org.setCountry("country"); org.setLabel("label"); org.setUsers(new ArrayList<User>()); return org; } @Test @Transactional public void testCreateOrganization() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization example = createExampleOrganization(); Organization result = service.createOrganization("label", " country"); int uuid = result.getUuid(); example.setUuid(uuid); assertEquals(example, orgDAO.findOrganizationByUuid(uuid)); } @Test @Transactional public void testGetOrganizationByUuid() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); assertEquals(org, service.getOrganizationByUuid(uuid)); } @Test(expected = NoResultException.class) @Transactional public void testDeleteOrganization() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); assertEquals(org, service.getOrganizationByUuid(uuid)); service.deleteOrganization(uuid); service.getOrganizationByUuid(uuid); } @Test @Transactional public void testEditLabel() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); String newLabel = "newLabel"; assertTrue(service.editLabel(uuid, newLabel)); org = service.getOrganizationByUuid(uuid); assertEquals(newLabel, org.getLabel()); } @Test @Transactional public void testEditCountry() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); String newCountry = "newCountry"; assertTrue(service.editCountry(uuid, newCountry)); org = service.getOrganizationByUuid(uuid); assertEquals(newCountry, org.getCountry()); } @Test @Transactional public void testAddUser() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); User user = new User(); int uuidUser = 1000; user.setUuid(uuidUser); userDAO.persist(user); service.addUser(uuid, uuidUser, 1); org = service.getOrganizationByUuid(uuid); List<User> users = org.getUsers(); assertEquals(1, users.size()); assertEquals(user, users.get(0)); } @Test @Transactional public void testChangeUserRight() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); UserService userService = new UserService(userDAO); User user = userService.createUser("login", "password", "country", "mail", "firstname", "name", "1"); int uuidUser = user.getUuid(); service.addUser(uuid, uuidUser, 1); service.changeUserRight(uuid, uuidUser, 2); user = userDAO.findUserByUuid(uuidUser); assertEquals(2, user.getRights()); } @Test @Transactional public void testAddWorkPackage() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); int wpUuid = 10012; WorkPackage wp = new WorkPackage(); wp.setUuid(wpUuid); wpDAO.persist(wp); service.addWorkPackage(uuid, wpUuid, "label"); org = service.getOrganizationByUuid(uuid); assertEquals(1, org.getWorkpackages().size()); assertEquals(wpUuid, org.getWorkpackages().get(0).getUuid()); } @Test @Transactional public void testDeleteUserOfOrganization() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); Organization org = service.createOrganization("label", " country"); int uuid = org.getUuid(); User user = new User(); int uuidUser = 19875; user.setUuid(uuidUser); userDAO.persist(user); service.addUser(uuid, uuidUser, 1); org = service.getOrganizationByUuid(uuid); List<User> users = org.getUsers(); assertEquals(1, users.size()); assertEquals(user, users.get(0)); assertTrue(service.deleteUserOfOrganization(uuid, uuidUser)); org = service.getOrganizationByUuid(uuid); users = org.getUsers(); assertEquals(0, users.size()); } @Test @Transactional public void testGetOrganizationByRegExp() { OrganizationService service = new OrganizationService(orgDAO, userDAO, wpDAO); service.createOrganization("label1", " country"); service.createOrganization("label2", " country"); assertEquals(2, service.getOrganizationsByRegExp("label:abe").size()); } } <file_sep>package fr.umlv.book.model.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Book; import fr.umlv.book.model.dao.IBookDAO; @Transactional @Service("serviceBook") public class BookService { @Autowired IBookDAO bookDAO; public BookService() { } public BookService(IBookDAO bookDAO) { this.bookDAO = bookDAO; } public Book findBookByUuid(int uuid) { return bookDAO.findBookElementByUuid(uuid); } /* public List<Book> getAllBooks() { return bookDAO.getAllBooks(); }*/ public void editBook(int uuidBook, String newTitle) { System.out.println("NEW TITLE"+newTitle); Book book = bookDAO.findBookElementByUuid(uuidBook); book.setTitle(newTitle); bookDAO.merge(book); } } <file_sep>package fr.umlv.book.controller.edit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import fr.umlv.book.controller.home.HomeController; import fr.umlv.book.model.beans.bookelement.Label; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.beans.workpackage.Maturity; import fr.umlv.book.model.beans.workpackage.WorkPackage; public class EditWPControllerTest { @Test public void testPromotWP() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); editWPController.promoteWP(workPackage.getUuid()); assertEquals(workPackage.getMaturity(), Maturity.Promoted); } @Test public void testValidateTemporaryContentOnWP() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); editWPController.validateTemporaryContentOnWP(workPackage.getUuid()); assertEquals(workPackage.getMaturity(),Maturity.Promoted); } @Test public void testRefuseTemporaryContentOnWP() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); editWPController.refuseTemporaryContentOnWP(workPackage.getUuid()); assertEquals(workPackage.getMaturity(), Maturity.Initial); } @Test public void testDeleteTemporaryContentOnWP() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); editWPController.deleteTemporaryContentOnWP(workPackage.getUuid()); assertNull(workPackage); } @Test public void testChangeName() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); workPackage.setTitle("Top"); editWPController.changeName(workPackage.getUuid(), "Flop"); assertEquals(workPackage.getTitle(), "Flop"); } @Test public void testAjaxDeleteChange() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); workPackage.setTitle("Top"); assertTrue(editWPController.ajaxDeleteElement(workPackage.getUuid())); } @Test public void testAjaxAddElement() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); workPackage.setTitle("Top"); User user = new User(); user.setUuid(0); user.setName("luc"); assertTrue(editWPController.ajaxAddElement(workPackage.getUuid(), user , Label.Chapter, "Fu", "Fu fufu fuufu.")); } @Test public void testChangeTitle() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); workPackage.setTitle("Top"); User user = new User(); user.setUuid(0); user.setName("luc"); editWPController.ajaxAddElement(workPackage.getUuid(), user , Label.Chapter, "Fu", "Fu fufu fuufu."); assertTrue(editWPController.changeTitle(workPackage.getUuid(), user.getUuid(), 0, 0, "lol")); } @Test public void testChangeContent() { EditWPController editWPController = new EditWPController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); workPackage.setTitle("Top"); User user = new User(); user.setUuid(0); user.setName("luc"); editWPController.ajaxAddElement(workPackage.getUuid(), user , Label.Chapter, "Fu", "Fu fufu fuufu."); assertTrue(editWPController.changeContent(workPackage.getUuid(), user.getUuid(), 0, 0, "newContent")); } } <file_sep>package fr.umlv.book.model.beans.user; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.workspace.WorkSpace; @Entity @Table(name="USER") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "USER_UUID") private int uuid; @Column(name="USER_LOGIN") private String login; @Column(name="USER_MAIL") private String mail; @Column(name="USER_COUNTRY") private String country; @Column(name="USER_NAME") private String name; @Column(name="USER_FIRSTNAME") private String firstname; @Column(name="USER_PASSWORD") private String password; @Column(name = "USER_RIGHTS") private int rights; @OneToOne @JoinColumn(name = "WORKSPACE_UUID") private WorkSpace workspace; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "ORGANIZATION_UUID") private Organization organization; public int getUuid() { return uuid; } public void setUuid(int uuid) { this.uuid = uuid; } public WorkSpace getWorkSpace() { return workspace; } public void setWorkSpace(WorkSpace ws) { this.workspace = ws; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public WorkSpace getWorkspace() { return workspace; } public void setWorkspace(WorkSpace workspace) { this.workspace = workspace; } public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } public int getRights() { return rights; } public void setRights(int rights) { this.rights = rights; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + uuid; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof User)) return false; User other = (User) obj; if (uuid != other.uuid) return false; return true; } } <file_sep>package fr.umlv.book.model.dao; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.m2.jee.dao.hibernate.IHibernateDAO; public interface IOrganizationDAO extends IHibernateDAO<Integer, Organization>{ Organization findOrganizationByUuid(int uuid); } <file_sep>package fr.umlv.book.controller.edit; import fr.umlv.book.model.beans.bookelement.Label; import fr.umlv.book.model.beans.user.User; /** * * @author Anthony * */ public class EditWPController { /** * * @param uuid identifiant unique du WorkPackage * @return retourne vrai si le WorkPackage à pu être promu, faux si non */ public Boolean promoteWP(int uuid){ WorkPackageService wpService = new WorkPackageService(); return wpService.promoteWorkPackage(uuid); } /** * * @param uuid identifiant unique du BookElement * @return vrai si le contenu à été validé, faux si non */ public Boolean validateTemporaryContentOnWP(int uuid){ WorkPackageService wpService = new WorkPackageService(); return wpService.validateTemporaryContent(uuid); } /** * * @param uuid identifiant unique du BookElement * @return vrai si le contenu à été refusé, faux si non */ public Boolean refuseTemporaryContentOnWP(int uuid){ WorkPackageService wpService = new WorkPackageService(); return wpService.refuseTemporaryContent(uuid); } /** * * @param uuid identifiant unique du BookElement * @return vrai si le contenu à été supprimé, faux si non */ public Boolean deleteTemporaryContentOnWP(int uuid){ WorkPackageService wpService = new WorkPackageService(); return wpService.deleteTemporaryContent(uuid); } /** * * @param uuid identifiant unique du WorkPackage * @param newName * @return vrai si le nom du WorkPackage a bien été changé, faux si non */ public Boolean changeName(int uuid, String newName){ WorkPackageService wpService = new WorkPackageService(); return wpService.editLabel(uuid, newName); } /** * * @param uuid identifiant unique du BookElement * @return vrai si l'élément a été supprimé, faux si non */ public Boolean ajaxDeleteElement(int uuid){ WorkPackageService wpService = new WorkPackageService(); return wpService.deleteTemporaryContent(uuid); } /** * * @param wpUuid identifiant unique du WorkPackage * @param user identifiant unique de l'User * @param element identifiant unique du BookElement * @param title chaine de caratères contenant le titre * @param content chaine de caratères contenant le contenu * @return vrai si l'élément a bien été ajouté, faux si non */ public Boolean ajaxAddElement(int wpUuid, User user, Label element, String title, String content){ WorkPackageService wpService = new WorkPackageService(); return wpService.createTemporaryContent(wpUuid, user, element, title, content); } /** * * @param uuidWP identifiant unique du WorkPackage * @param uuidUser identifiant unique de l'User * @param uuidOrga identifiant unique de l'Organization * @param uuidElement identifiant unique du BookElement * @param newTitle chaine de caratères contenant le nouveau titre * @return vrai si le titre a bien été changé, faux si non */ public Boolean changeTitle(int uuidWP, int uuidUser, int uuidOrga, int uuidElement, String newTitle){ WorkPackageService wpService = new WorkPackageService(); return wpService.editTemporaryContent(uuidWP, uuidElement, uuidUser, newTitle, null); } /** * * @param uuidWP identifiant unique du WorkPackage * @param uuidUser identifiant unique de l'User * @param uuidOrga identifiant unique de l'Organization * @param uuidElement identifiant unique du BookElement * @param newContent chaine de caratères contenant le nouveau contenu * @return vrai si le contenu a bien été changé, faux si non */ public Boolean changeContent(int uuidWP, int uuidUser, int uuidOrga, int uuidElement, String newContent){ WorkPackageService wpService = new WorkPackageService(); return wpService.editTemporaryContent(uuidWP, uuidElement, uuidUser, null, newContent); } } <file_sep>package fr.umlv.book.controller.create; import java.util.List; import fr.umlv.book.controller.general.OrgChoiceController; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.organization.Right; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.service.OrganizationService; /** * * @author Anthony * */ public class CreateOrgController { /** * * @return retourne le nom de la prochaine page */ public String toEditOrg() { return "book_organisation_gestion"; } /** * * @param user objet User contenant toutes les information d'un utilisateur * @param organization objet Organization contenant toutes les information d'une Organization * @return vrai si l'User peut cr�er dans l'Organization, faux sinon */ public Boolean isAbleToCreate(User user, Organization organization){ OrgChoiceController orgC = new OrgChoiceController(); List<Right> listR = orgC.ajaxGetRightByOrg(user.getUuid(), organization); return listR.contains(Right.Responsable); } /** * * @param name nom de l'Organisation � cr�er * @param organization objet Organization contenant toutes les information d'une Organization * @return vrai si l'Organization a �t� cr��e, faux sinon */ public Boolean create(String name, Organization organization){ OrganizationService orgService = new OrganizationService(); if(orgService.createOrganization(name, organization.getCountry(), organization) == null) { return false; } return true; } } <file_sep>package fr.umlv.book.model.beans.workpackage; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import fr.umlv.book.model.beans.bookelement.Book; import fr.umlv.book.model.beans.bookelement.Chapter; import fr.umlv.book.model.beans.bookelement.Paragraph; import fr.umlv.book.model.beans.bookelement.Volume; import fr.umlv.book.model.beans.organization.Organization; @Entity @Table(name = "WORKPACKAGE") public class WorkPackage implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "WORKPACKAGE_UUID") private int uuid; @Column(name = "WORKPACKAGE_TITLE") private String title; @Column(name = "WORKPACKAGE_LOCKED") private boolean locked; @Column(name = "WORKPACKAGE_MATURITY") private Maturity maturity; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "ORGANIZATION_UUID") private Organization parent; @OneToMany(mappedBy = "parentWP") @LazyCollection(LazyCollectionOption.FALSE) private List<Book> books; @OneToMany(cascade = { CascadeType.MERGE }, mappedBy = "parentWP") @LazyCollection(LazyCollectionOption.FALSE) private List<Volume> volumes; @OneToMany(cascade = { CascadeType.MERGE }, mappedBy = "parentWP") @LazyCollection(LazyCollectionOption.FALSE) private List<Chapter> chapters; @OneToMany(cascade = { CascadeType.MERGE }, mappedBy = "parentWP") @LazyCollection(LazyCollectionOption.FALSE) private List<Paragraph> paragraphs; public int getUuid() { return uuid; } public void setUuid(int uuid) { this.uuid = uuid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Maturity getMaturity() { return maturity; } public void setMaturity(Maturity maturity) { this.maturity = maturity; } public Organization getParent() { return parent; } public void setParent(Organization parent) { this.parent = parent; } public List<Book> getBooks() { return books; } public void addBook(Book book) { if (books == null) { books = new ArrayList<Book>(); } books.add(book); } public List<Volume> getVolumes() { return volumes; } public void addVolume(Volume volume) { if (volumes == null) { volumes = new ArrayList<Volume>(); } volumes.add(volume); } public List<Chapter> getChapters() { return chapters; } public void addChapter(Chapter chapter) { if (chapters == null) { chapters = new ArrayList<Chapter>(); } chapters.add(chapter); } public List<Paragraph> getParagraphs() { return paragraphs; } public void addParagraph(Paragraph paragraph) { if (paragraphs == null) { paragraphs = new ArrayList<Paragraph>(); } paragraphs.add(paragraph); } public boolean getLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + uuid; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof WorkPackage)) return false; WorkPackage other = (WorkPackage) obj; if (uuid != other.uuid) return false; return true; } public void setBooks(List<Book> elements) { this.books = elements; } public void setVolumes(List<Volume> elements) { this.volumes = elements; } public void setChapters(List<Chapter> elements) { this.chapters = elements; } public void setParagraphs(List<Paragraph> elements) { this.paragraphs = elements; } } <file_sep>package fr.umlv.book.controller.general; /** * * @author Anthony * */ public class GeneralController { /** * * @return retourne le nom de la prochaine page */ public String toHome() { return "book_role_accueil"; } /** * * @return retourne le nom de la prochaine page */ public String toLogin() { return "index"; } /** * * @return retourne le nom de la page de Login */ public String disconnect(int uuidUser){ return "index"; } } <file_sep>package fr.umlv.book.model.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Volume; import fr.umlv.book.model.dao.IVolumeDAO; @Transactional @Service("volumeService") public class VolumeService { @Autowired IVolumeDAO volumeDAO; public Volume findVolumeByUuid(int uuid) { Volume volume = volumeDAO.findBookElementByUuid(uuid); return volume; } public List<Volume> getAllVolumeFromBook(int uuid) { List<Volume> lists = volumeDAO.getAllVolumeFromBook(uuid); return lists; } public void editVolume(int uuidVolume, String newTitle) { Volume volume = volumeDAO.findBookElementByUuid(uuidVolume); volume.setTitle(newTitle); volumeDAO.merge(volume); } public void removeVolume(int volumeUuid) { Volume volume = volumeDAO.findBookElementByUuid(volumeUuid); volumeDAO.remove(volume); } } <file_sep>package fr.umlv.book.model.dao.impl; import javax.persistence.Query; import org.springframework.stereotype.Repository; import fr.umlv.book.model.beans.organization.Company; import fr.umlv.book.model.dao.ICompanyDAO; import fr.umlv.m2.jee.dao.hibernate.AbstractHibernateDAO; @Repository public class CompanyDAO extends AbstractHibernateDAO<Integer, Company> implements ICompanyDAO { @Override public Company findCompanyByUuid(int uuid) { Query query = createQuery("SELECT a FROM Company a where a.uuid =:uuid"); query.setParameter("uuid", uuid); return (Company) query.getSingleResult(); } } <file_sep>package fr.umlv.book.model.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Paragraph; import fr.umlv.book.model.dao.IParagraphDAO; @Transactional @Service("paragraphService") public class ParagraphService { @Autowired IParagraphDAO paragraphDAO; public Paragraph getParagraphByUuid(int uuid) { return paragraphDAO.findBookElementByUuid(uuid); } public List<Paragraph> getAllParagraphFromChapter(int uuid) { return paragraphDAO.getAllParagraphFromChapter(uuid); } public void editParagraph(int uuidParagraph, String newTitle, String newContent) { Paragraph paragraph = paragraphDAO.findBookElementByUuid(uuidParagraph); paragraph.setTitle(newTitle); paragraph.setContent(newContent); paragraphDAO.merge(paragraph); } public void removeParagraph(int paragraphUuid) { Paragraph paragraph = paragraphDAO.findBookElementByUuid(paragraphUuid); paragraphDAO.remove(paragraph); } } <file_sep>package fr.umlv.book.model.dao; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.bookelement.Book; @Transactional @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/book-test-context.xml" }) public class TestBookDAO { protected static int uuidBook = TestCompanyDAO.uuid + 1; @Autowired private IBookDAO dao; @Test public void testFindBookElementByUuid() { Book exampleBook = createExampleBook(); Book result = dao.findBookElementByUuid(uuidBook); assertEquals(exampleBook, result); } @Test public void testGetAllBook() { assertEquals(1, dao.getAllBooks().size()); } protected static Book createExampleBook() { Book book = new Book(); book.setTitle("Galere"); book.setUuid(uuidBook); book.setParent(null); book.setCompany(TestCompanyDAO.createExampleCompany()); return book; } } <file_sep>package fr.umlv.book.controller.home; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; import org.junit.Test; import fr.umlv.book.controller.create.CreateOrgController; import fr.umlv.book.controller.create.CreateUserController; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.beans.workpackage.Maturity; import fr.umlv.book.model.beans.workpackage.WorkPackage; import fr.umlv.book.model.service.OrganizationService; import fr.umlv.book.model.service.UserService; public class HomeControllerTest { @Test public void testToCreateUser() { HomeController homeController = new HomeController(); assertEquals(homeController.toCreateUser(), "book_user_creation"); } @Test public void testToEditUser() { HomeController homeController = new HomeController(); assertEquals(homeController.toEditUser(), "book_user_gestion"); } @Test public void testToCreateOrg() { HomeController homeController = new HomeController(); assertEquals(homeController.toCreateOrg(), "book_organisation_creation"); } @Test public void testToEditOrg() { HomeController homeController = new HomeController(); assertEquals(homeController.toEditOrg(), "book_organisation_gestion"); } @Test public void testToViewWP() { HomeController homeController = new HomeController(); assertEquals(homeController.toViewWP(), "book_WP_consult"); } @Test public void testToEditWP() { HomeController homeController = new HomeController(); assertEquals(homeController.toEditWP(), "book_WP_edit"); } @Test public void testToCreateWP() { HomeController homeController = new HomeController(); assertEquals(homeController.toCreateWP(), "book_WP_creation"); } @Test public void testAjaxGetOrgByName() { HomeController homeController = new HomeController(); Organization organization = new Organization(); organization.setLabel("Top"); OrganizationService organizationService = new OrganizationService(); Organization organization2 = organizationService.createOrganization("Up", "France", organization); assertEquals(organization2, homeController.ajaxGetOrgByName("Up")); } @Test public void testAjaxGetUserByName() { HomeController homeController = new HomeController(); UserService service = new UserService(); User user = service.createUser("<EMAIL>", "l", "France", "<EMAIL>", "sky", "luc"); assertEquals(user, homeController.ajaxGetUserByName("Luc")); } @Test public void testAjaxGetWPByName() { HomeController homeController = new HomeController(); Organization organization = new Organization(); organization.setLabel("Test"); WorkPackage workPackage = new WorkPackage(); workPackage.setTitle("WP"); WorkPackage workPackage2 = new WorkPackage(); workPackage2.setTitle("WP"); Map<String, Integer> map = null; map.put(workPackage.getTitle(), workPackage.getUuid()); map.put(workPackage2.getTitle(), workPackage2.getUuid()); organization.setWorkPackageLabels(map); List<WorkPackage> list = null; list.add(workPackage); list.add(workPackage2); assertEquals(list, homeController.ajaxGetWPByName(organization, "WP")); } @Test public void testValidateWP() { HomeController homeController = new HomeController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); homeController.validateWP(workPackage.getUuid()); assertTrue(workPackage.getMaturity() != Maturity.Initial); } @Test public void testRefuseWP() { HomeController homeController = new HomeController(); WorkPackage workPackage = new WorkPackage(); workPackage.setUuid(3); homeController.validateWP(workPackage.getUuid()); assertTrue(workPackage.getMaturity() == Maturity.Initial); } } <file_sep>package fr.umlv.book.controller.general; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.Map; import org.junit.Test; import static org.junit.Assert.assertSame; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.organization.Right; import fr.umlv.book.model.beans.user.User; public class OrgChoiceControllerTest { @Test public void testAjaxGetRightByOrg() { OrgChoiceController orgChoiceController= new OrgChoiceController(); Organization organization = new Organization(); Map<User, List<Right>> users = null ; User user = new User(); user.setLogin("Luc"); User user2 = new User(); user2.setLogin("Yoda"); List<Right> rights = null; rights.add(Right.Read); rights.add(Right.Write); List<Right> rights2 = null; rights2.add(Right.SuperAdmin); users.put(user, rights); users.put(user2, rights2); organization.setUsers(users); assertSame(rights2, orgChoiceController.ajaxGetRightByOrg(user2.getUuid(), organization)); } } <file_sep>package fr.umlv.book.model.beans.bookelement; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import fr.umlv.book.model.beans.workpackage.WorkPackage; @Entity @Table(name = "CHAPTER") public class Chapter implements BookElement, Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "CHAPTER_UUID") @GeneratedValue private int uuid; @Column(name = "CHAPTER_TITLE") private String title; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "VOLUME_UUID") private Volume parentVolume; @OneToMany(mappedBy = "parentChapter", cascade = CascadeType.ALL) private List<Paragraph> paragraphs; @ManyToOne @JoinColumn(name = "WORKPACKAGE_UUID") private WorkPackage parentWP; @Override public int getUuid() { return uuid; } @Override public void setUuid(int uuid) { this.uuid = uuid; } @Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = title; } @Override public WorkPackage getParent() { return parentWP; } @Override public void setParent(WorkPackage parent) { this.parentWP = parent; } public Volume getParentVolume() { return parentVolume; } public void setParentVolume(Volume parentVolume) { this.parentVolume = parentVolume; } public List<Paragraph> getParagraphs() { return paragraphs; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + uuid; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Chapter)) { return false; } Chapter other = (Chapter) obj; if (uuid != other.uuid) { return false; } return true; } } <file_sep>package fr.umlv.book.model.dao; import fr.umlv.book.model.beans.user.User; import fr.umlv.m2.jee.dao.hibernate.IHibernateDAO; public interface IUserDAO extends IHibernateDAO<Integer, User> { User findUserByUuid(int uuid); User findUserByLoginAndPassword(String login, String password); User findUserByLogin(String login); } <file_sep>Todo List Module hibernate et dao : à fusionner dans model ? Model->Beans : Ajouter les annotations.<file_sep>package fr.umlv.book.model.dao; import fr.umlv.book.model.beans.organization.Company; import fr.umlv.m2.jee.dao.hibernate.IHibernateDAO; public interface ICompanyDAO extends IHibernateDAO<Integer, Company> { Company findCompanyByUuid(int uuid); } <file_sep>package fr.umlv.book.model.beans.workspace; import static org.junit.Assert.assertEquals; import org.junit.Test; import fr.umlv.book.model.beans.user.User; public class WorkSpaceTest { @Test public void testUuid() { int uuid = 10; WorkSpace workspace = new WorkSpace(); workspace.setUuid(uuid); assertEquals(uuid, workspace.getUuid()); } @Test public void testOwner() { User owner = new User(); owner.setFirstname("MacDonald"); WorkSpace workspace = new WorkSpace(); workspace.setOwner(owner); assertEquals(owner, workspace.getOwner()); } @Test public void testTemporaryContent() { TemporaryContent tc = new TemporaryContent(); WorkSpace workspace = new WorkSpace(); workspace.setTemporaryContent(tc); assertEquals(tc, workspace.getTemporaryContent()); } } <file_sep>package fr.umlv.book.controller.edit; import fr.umlv.book.model.service.UserService; /** * * @author Anthony * */ public class EditUserController { /** * * @param uuid identifiant unique de l'User * @param name nom de l'User * @param firstName prenom de l'User * @param password <PASSWORD> l'User * @param mail adresse mail de l'User * @param locatite pays de l'User * @return vrai si toutes les modifications se sont bien pass�e, faux sinon */ public Boolean modify(int uuid, String name, String firstName, String password, String mail, String locatite){ UserService userService = new UserService(); return userService.editLogin(uuid, mail) && userService.editMail(uuid, mail) && userService.editPassword(uuid, password) && userService.editCountry(uuid, locatite); } /** * * @param uuid identifiant unique de l'User * @return vrai si l'User a �t� supprim�, faux sinon */ public Boolean delete(int uuid){ UserService userService = new UserService(); return userService.deleteUser(uuid); } } <file_sep>package fr.umlv.book.model.service; import java.util.ArrayList; import java.util.List; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.user.User; import fr.umlv.book.model.beans.workpackage.WorkPackage; import fr.umlv.book.model.dao.IOrganizationDAO; import fr.umlv.book.model.dao.IUserDAO; import fr.umlv.book.model.dao.IWorkPackageDAO; @Transactional @Service("organizationService") public class OrganizationService { @Autowired private IOrganizationDAO organizationDAO; @Autowired private IUserDAO userDAO; @Autowired private IWorkPackageDAO wpDAO; public OrganizationService() { } public OrganizationService(IOrganizationDAO orgDAO, IUserDAO userDAO, IWorkPackageDAO wpDAO) { this.organizationDAO = orgDAO; this.userDAO = userDAO; this.wpDAO = wpDAO; } public Organization createOrganization(String label, String country) { Organization organization = new Organization(); organization.setLabel(label); organization.setCountry(country); organization.setUuid(UuidGenerator.getNextUuid()); organization.setUsers(new ArrayList<User>()); organizationDAO.persist(organization); return organization; } @Transactional public Organization getOrganizationByUuid(int uuid) { System.out.println("orgDAO"); System.out.println(organizationDAO); System.out.println(userDAO); return organizationDAO.findOrganizationByUuid(uuid); } @Transactional public Boolean deleteOrganization(int uuid) { Organization org = organizationDAO.findOrganizationByUuid(uuid); if (org == null) { return false; } organizationDAO.remove(org); return true; } @Transactional public Boolean editLabel(int uuid, String label) { Organization org = organizationDAO.findOrganizationByUuid(uuid); if (org == null) { return false; } org.setLabel(label); organizationDAO.merge(org); return true; } @Transactional public boolean editCountry(int uuid, String country) { Organization org = organizationDAO.findOrganizationByUuid(uuid); if (org == null) { return false; } org.setCountry(country); organizationDAO.merge(org); return true; } @Transactional public boolean addUser(int uuid, int uuidUser, int rights) { Organization org = organizationDAO.findOrganizationByUuid(uuid); if (org == null) { return false; } List<User> users = org.getUsers(); User user = userDAO.findById(uuidUser); if (user == null) { return false; } if(users == null) { users = new ArrayList<User>(); org.setUsers(users); } users.add(user); user.setRights(rights); organizationDAO.merge(org); userDAO.merge(user); return true; } @Transactional public boolean changeUserRight(int uuid, int uuidUser, int newRight) { User user = userDAO.findUserByUuid((uuidUser)); if (user == null) { return false; } user.setRights(newRight); userDAO.merge(user); return true; } @Transactional public boolean addWorkPackage(int uuid, int uuidWorkPackage, String label) { Organization organization = organizationDAO .findOrganizationByUuid(uuid); if (organization == null) { return false; } List<WorkPackage> workpackages = organization.getWorkpackages(); if(workpackages == null) { workpackages = new ArrayList<WorkPackage>(); organization.setWorkpackages(workpackages); } WorkPackage wp = wpDAO.findWorkPackageByUuid(uuidWorkPackage); if (wp == null) { return false; } workpackages.add(wp); wp.setTitle(label); organizationDAO.merge(organization); wpDAO.merge(wp); return true; } @Transactional public boolean deleteUserOfOrganization(int uuid, int userUuid) { Organization organization = organizationDAO .findOrganizationByUuid(uuid); List<User> users = organization.getUsers(); if(users == null) { return false; } if (users.remove(userDAO.findUserByUuid(userUuid)) == false) { return false; } organizationDAO.merge(organization); return true; } // // public boolean addOrganizationChild(int uuid, int uuidParent) { // Organization children = organizationDAO.findOrganizationByUuid(uuid); // Organization parent = organizationDAO.findOrganizationByUuid(uuidParent); // if (children == null) { // return false; // } // if (parent == null) { // return false; // } // List<Organization> list = parent.getChild(); // list.add(children); // parent.setChild(list); // organizationDAO.merge(parent); // return true; // // } // public boolean deleteOrganizationChild(int uuid, int uuidParent) { // Organization children = organizationDAO.findOrganizationByUuid(uuid); // Organization parent = organizationDAO.findOrganizationByUuid(uuidParent); // if (children == null) { // return false; // } // if (parent == null) { // return false; // } // List<Organization> list = parent.getChild(); // list.remove(children); // parent.setChild(list); // organizationDAO.merge(parent); // return true; // } @Transactional public List<Organization> getAllOrganizations() { return organizationDAO.findAll(); } // public List<Organization> getAllOrganizationsChild(int uuid) { // Organization parent = organizationDAO.findOrganizationByUuid(uuid); // return parent.getChild(); // } @Transactional public List<Organization> getOrganizationsByRegExp(String pattern) { int size = pattern.length(); if (size < 3) { return null; } int index = pattern.indexOf(":"); if (index < 1 || index >= pattern.length() - 2) { return null; } String key = pattern.substring(0, index); String value = pattern.substring(index + 1); Criterion criterion = Restrictions.like(key, "%" + value + "%"); return organizationDAO.findByCriteria(criterion); } } <file_sep>Le répertoire workspace contient les sources du projet. Technologies utilisées : java 1.6 maven2. google guava Liste des modules : - superpom - umlv-dao - umlv-hibernate - book - model - view - controller PS : N'oubliez pas de vous synchroniser avant de bosser, et après avoir travaillé !<file_sep>package fr.umlv.book.controller.general; import static org.junit.Assert.assertEquals; import org.junit.Test; import fr.umlv.book.model.beans.user.User; public class LoginControllerTest { @Test public void testToOrgChoice() { LoginController loginController = new LoginController(); assertEquals(loginController.toOrgChoice(), "choix_organisation_role"); } @Test public void testIdentificate() { User user = new User(); user.setLogin("<EMAIL>"); user.setPassword("<PASSWORD>"); LoginController loginController = new LoginController(); assertEquals("choix_organisation_role", loginController.identificate("<EMAIL>", "john")); } } <file_sep>package fr.umlv.book.model.beans.user; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; import fr.umlv.book.model.beans.organization.Organization; import fr.umlv.book.model.beans.workspace.WorkSpace; public class UserTest { @Test public void testUuid() { int uuid = 10; User user = new User(); user.setUuid(uuid); assertEquals(uuid, user.getUuid()); } @Test public void testlogin() { String login = "RMacDonald"; User user = new User(); user.setLogin(login); assertEquals(login, user.getLogin()); } @Test public void testMail() { String mail = "<EMAIL>"; User user = new User(); user.setMail(mail); assertEquals(mail, user.getMail()); } @Test public void testCountry() { String country = "usa"; User user = new User(); user.setCountry(country); assertEquals(country, user.getCountry()); } @Test public void testName() { String name = "Ronald"; User user = new User(); user.setName(name); assertEquals(name, user.getName()); } @Test public void testFirstname() { String fname = "MacDonald"; User user = new User(); user.setFirstname(fname); assertEquals(fname, user.getFirstname()); } @Test public void testOrganizations() { Organization organization = new Organization(); WorkSpace workspace = new WorkSpace(); organization.setLabel("Food"); workspace.setUuid(22); User user = new User(); user.setOrganization(organization); assertSame(organization, user.getOrganization()); } } <file_sep>package fr.umlv.book.model.dao; import fr.umlv.book.model.beans.workspace.WorkSpace; import fr.umlv.m2.jee.dao.hibernate.IHibernateDAO; public interface IWorkSpaceDAO extends IHibernateDAO<Integer, WorkSpace>{ WorkSpace findWorkSpaceByUuid(int uuid); WorkSpace findWorkSpaceByLabel(String label); } <file_sep>package fr.umlv.book.model.dao.impl; import java.util.List; import javax.persistence.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import fr.umlv.book.model.beans.bookelement.Paragraph; import fr.umlv.book.model.dao.IChapterDAO; import fr.umlv.book.model.dao.IParagraphDAO; import fr.umlv.m2.jee.dao.hibernate.AbstractHibernateDAO; @Repository public class ParagraphDAO extends AbstractHibernateDAO<Integer, Paragraph> implements IParagraphDAO { @Autowired private IChapterDAO chapterDAO; @Override public Paragraph findBookElementByUuid(int uuid) { Query query = createQuery("SELECT a FROM Paragraph a where a.uuid =:uuid"); query.setParameter("uuid", uuid); return (Paragraph) query.getSingleResult(); } @Override public List<Paragraph> getAllParagraphFromChapter(int uuid) { return chapterDAO.findBookElementByUuid(uuid).getParagraphs(); } } <file_sep>package fr.umlv.book.model.dao.impl; import javax.persistence.Query; import org.springframework.stereotype.Repository; import fr.umlv.book.model.beans.workpackage.WorkPackage; import fr.umlv.book.model.dao.IWorkPackageDAO; import fr.umlv.m2.jee.dao.hibernate.AbstractHibernateDAO; @Repository public class WorkPackageDAO extends AbstractHibernateDAO<Integer, WorkPackage> implements IWorkPackageDAO{ @Override public WorkPackage findWorkPackageByUuid(int uuid) { Query query = createQuery("SELECT a FROM WorkPackage a where a.uuid =:uuid"); query.setParameter("uuid", uuid); return (WorkPackage) query.getSingleResult(); } @Override public WorkPackage findWorkPackageByTitle(String title) { Query query = createQuery("SELECT a FROM WorkPackage a where a.title =:title"); query.setParameter("title", title); return (WorkPackage) query.getSingleResult(); } } <file_sep>/*package fr.umlv.book.model.beans.workpackage; import java.io.Serializable; import javax.persistence.*; @Entity @Table(name="Content") public class Content implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="CONTENT_UUID_GENERATOR", sequenceName="UUIDGENERATOR") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CONTENT_UUID_GENERATOR") private Integer uuid; @Column(name="type_content") private String typeContent; @Column(name="uuid_content") private Integer uuidContent; //bi-directional many-to-one association to WorkPackage @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="uuid_workpackage") private WorkPackage workPackage; public Content() { } public Integer getUuid() { return this.uuid; } public void setUuid(Integer uuid) { this.uuid = uuid; } public String getTypeContent() { return this.typeContent; } public void setTypeContent(String typeContent) { this.typeContent = typeContent; } public Integer getUuidContent() { return this.uuidContent; } public void setUuidContent(Integer uuidContent) { this.uuidContent = uuidContent; } public WorkPackage getWorkPackage() { return this.workPackage; } public void setWorkPackage(WorkPackage workPackage) { this.workPackage = workPackage; } } */
5b87b247814c26441a61c13d454df7201e04af18
[ "Java", "SQL", "Text" ]
40
SQL
nimajen/Book
545ae61b745e63a6f3ab3a3fbc7da0841254bc5e
0b56a13aa2bd31fc78056dfd917be450fec078ca
refs/heads/master
<file_sep>package com.pattern.chain; import java.util.Arrays; import java.util.List; /** * @author cody * @version V1.0 * @create 2017/10/22 21:32 */ public class ChainClient { static class ChainHandleA extends ChainHandle{ @Override protected void handleProcess() { System.out.println("handler by A"); } } static class ChainHandleB extends ChainHandle{ @Override protected void handleProcess() { System.out.println("handler by B"); } } static class ChainHandleC extends ChainHandle{ @Override protected void handleProcess() { System.out.println("handler by C"); } } public static void main(String[] args) { List<ChainHandle> handlers = Arrays.asList( new ChainHandleA(), new ChainHandleB(), new ChainHandleC() ); Chain chain = new Chain(handlers); chain.proceed(); } } <file_sep>package com.pattern.cglib; import com.pattern.RealSubject; import com.pattern.Subject; import org.springframework.cglib.proxy.Enhancer; /** * @author cody * @version V1.0 * @create 2017/10/22 20:25 */ public class Client { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(RealSubject.class); enhancer.setCallback(new MethodInterceptor()); Subject subject = (Subject) enhancer.create(); subject.sayHello(); } } <file_sep> 一、spring boot 的启动方式 1、直接运行main方法 2、使用shell进入项目目录,使用mvn spring-boot:run启动 3、使用mvn install 一下,然后进入target目录中,使用 java -jar 启动 二、配置管理 在application配置文件中可以配置属性信息 server.port server.context-path 等一些信息 配置文件也可以是yml文件 三、controller的配置 RequestMapping(value={"/hello,"/hi"})配置可以使用多路径进行反问 @GetMapping 是指定请求方法的一个RequestMapping的简单书写方式 四、数据库连接设置 1、在pom文件中引入mysql连接驱动,和jpa包 2、配置application配置文件 五、spring Aop 的理解 1、什么是JoinPoint,连接点就是 允许使用通知 的地方。spring中目前只支持方法级别的连接点。 2、什么是PointCut, 切入点就是在 哪些连接点使用通知。是根据你的需求筛选出需要使用通知的连接点。 3、什么是advice, 通知就是你的特定的需求,也就是你需要在切入点做的事情。 4、什么是aspect, 切面就是切入点和通知的组合就是一个切面。 5、PointCut expression切面表达式 wildcards(通配符) *匹配任意数量的字符 +匹配指定类及其子类 ..匹配任意数的子包或参数 designators(指示器) 匹配方法:execution() 匹配注解: @target() @args() @within() @annotations() 匹配包/类型 within() 匹配对象 this() bean() target() 匹配参数 args() 6、动态代理 jdk动态代理,可以使用一个系统变量来保存动态代理生成的类 System.setProperties().put("sum.misc.ProxyGenerator.saveGeneratedFiles","true")<file_sep>package com.imooc.controller; import com.imooc.config.ApplicationProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author cody * @version V1.0 * @create 2017/10/22 14:22 */ @RestController public class HellWorldController { @Value("${application.version}") private String appVersion; @Value("${application.author}") private String appAuthor; @Autowired private ApplicationProperties applicationProperties; @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET) public String sayHello(){ return "hello spring boot"+appAuthor +" "+ appVersion + applicationProperties; } } <file_sep>package com.pattern; import com.imooc.handler.ExceptionHandler; /** * * 缺点就是,当接口类添加类添加类新方法的时候,不仅实现类要实现新方法,代理类也要实现新方法。 * @author cody * @version V1.0 * @create 2017/10/22 20:02 */ public class Proxy implements Subject{ private RealSubject realSubject; public Proxy(RealSubject realSubject) { this.realSubject = realSubject; } @Override public String sayHello() { System.out.println("berfore"); String result = null; try{ result = realSubject.sayHello(); }catch (Exception e){ System.out.println("exception"); throw e; }finally { System.out.println("after"); } return result; } } <file_sep>package com.pattern.chain; /** * @author cody * @version V1.0 * @create 2017/10/22 20:50 */ public class Client { static class HandlerA extends Handler{ @Override protected void handlePorcess() { System.out.println("handler by a"); } } static class HandlerB extends Handler{ @Override protected void handlePorcess() { System.out.println("handler by b"); } } static class HandlerC extends Handler{ @Override protected void handlePorcess() { System.out.println("handler by C"); } } public static void main(String[] args) { HandlerA handlerA = new HandlerA(); HandlerB handlerB = new HandlerB(); HandlerC handlerC = new HandlerC(); handlerA.setSuccessor(handlerB); handlerB.setSuccessor(handlerC); handlerA.execute(); } } <file_sep>package com.imooc.dao; /** * @author cody * @version V1.0 * @create 2017/10/22 18:59 */ public interface IDao { } <file_sep>package com.imooc.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author cody * @version V1.0 * @create 2017/10/22 14:43 */ @Component @ConfigurationProperties(prefix = "propertyEntity") public class ApplicationProperties { private String author; private Float version; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Float getVersion() { return version; } public void setVersion(Float version) { this.version = version; } @Override public String toString() { return "ApplicationProperties{" + "author='" + author + '\'' + ", version=" + version + '}'; } } <file_sep>package com.imooc.handler; import com.imooc.domain.Result; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody; /** * @author cody * @version V1.0 * @create 2017/10/22 17:07 */ @ControllerAdvice public class ExceptionHandler { @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class) @ResponseBody public Result handler(Exception e){ return new Result(); } } <file_sep>package com.imooc.aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * @author cody * @version V1.0 * @create 2017/10/22 18:54 */ @Aspect @Component public class ObjectAspectConfig { /** * 匹配aop对象的目标对象为指定类型的方法,即DemoDao的aop代理对象的方法 */ @Pointcut("this(com.imooc.dao.DemoDao)") public void objectConfig() { } /** * 匹配实现了IDao接口的目标对象的方法 */ @Pointcut("target(com.imooc.dao.IDao)") public void targetConfig(){ } /** * 匹配所有一dao结尾的bean里面的方法 */ @Pointcut("bean(*Dao)") public void beanConfig() { } } <file_sep>package com.imooc.service; /** * @author cody * @version V1.0 * @create 2017/10/22 18:48 */ public class ProductService { } <file_sep>package com.pattern.jdk; import com.pattern.RealSubject; import com.pattern.Subject; import java.lang.reflect.Proxy; /** * @author cody * @version V1.0 * @create 2017/10/22 20:12 */ public class Client { public static void main(String[] args) { //配置系统属性,可以静动态代理生成的类保存到本地 System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true"); Subject subject = (Subject) Proxy.newProxyInstance(Client.class.getClassLoader(),new Class[]{Subject.class},new JdkInvocation(new RealSubject())); subject.sayHello(); } }
97d5da782568ea40358ba330590717d3911d9efc
[ "Java", "Text" ]
12
Java
yuejhan/springboot
1df65f8e051d9438cf2cd46f95d7f606229284bf
30e0ae7987b096eadd2d62a644e62a0e61c358c4
refs/heads/master
<file_sep> //<NAME> //Period 2 //Computer Systems Research //Citizen class file import java.util.*; public class Citizen { private double happiness; private double workrate; private double health; private double wealth; private double wealthAssess; private double approval; private double spending; public Citizen(double h, double wr,double w, double sp, double wa) { happiness = h; workrate = wr; wealth = w; wealthAssess = wa; spending = sp; } public double judgeWealth() { return wealthAssess; } public double getSpending() { return spending; } public double getHappiness() { return happiness; } public double getWorkRate() { return workrate; } public double getApproval() //too simple? { /* approval = happiness+wealthAssess+health; approval /= 2; */ approval = wealthAssess; return approval; } public double getWealth() { return wealth; } public void happy(double x) { happiness = x; } public void workrate(double x) { workrate += x; } public void wealth(double x) { wealth += x; } public void approve(double x) { approval += x; } public void rateW(double x) { wealthAssess = x; } }<file_sep> //<NAME> //Period 2 //Computer Systems Research //Data input handler import java.util.*; import java.io.*; public class InputTest { static int citz = 1000; static int poolz = 1; static int govtz = 20; public static void main(String[] args) throws IOException { PrintStream cw = new PrintStream(new FileOutputStream("citizen.txt")); PrintStream gw = new PrintStream(new FileOutputStream("govt.txt")); cw.println(citz); //# citizens //happy, workrate, wealth, spending, wealth assessment double h, wr, w, sp, wa; h = 75.0; /*wr = 0.05;*/ wr = 25; w = 500.0; sp = 0.10; wa = 50.0; for(int x = 0;x<citz;x++) { double bleh = Math.random()+0.75; h = 75.0; /*wr = 0.05;*/ wr = 25; w = 500.0; sp = 0.10; wa = 50.0; h*= bleh; wr*= bleh; w*= bleh; sp*= bleh; wa*= bleh; cw.println(h+" "+wr+" "+w+" "+sp + " " + wa); //Citizen traits, for now arbitrary, variation? } gw.println(govtz); //# govts //taxrate, responsiveness, welfare, wealth, happy, approval,wealth assessment,oldApproval, salesTax double tr, r, pw, w2, h2, ap, wa2, oa, st; tr = .050; r = 0.9; pw = 0.0; w2 = 300000.0; h2 = 70.0; ap = 50.0; wa2 = 50.0; oa = ap; st = 0.045; for(int z = 0;z<govtz;z++) { double bleh = 5.0*Math.random()+0.75; tr = .050; r = 0.9; pw = 5.0; w2 = 300000.0; h2 = 70.0; ap = 50.0; wa2 = 50.0; oa = ap; st = 0.045; tr*= bleh; r*= bleh; pw*= bleh; /*w2*= bleh; h2*= bleh; ap*= bleh; wa2*= bleh; oa*= bleh;*/ st*= bleh; gw.println(tr+" "+r+" "+pw+" "+w2+" "+h2+" "+ap+" "+wa2 + " " + oa + " " + st); } } }<file_sep> //<NAME> //Period 2 //Computer Systems Research //Third Quarter Simulation Program (Cycle and output) import java.util.*; import java.io.*; public class Test { static int MONTHS = 144; static Citizen[] population; public static void main(String[] args) throws IOException { //read in data for different kinds of classes BufferedReader citizenReader = new BufferedReader(new FileReader("citizen.txt")); //BufferedReader resourceReader = new BufferedReader(new FileReader("resourcepool.txt")); BufferedReader govtReader = new BufferedReader(new FileReader("govt.txt")); PrintStream p = new PrintStream(new FileOutputStream("results.txt")); //include resourcepool and govt # in output PrintStream goutput = new PrintStream(new FileOutputStream("govtracker.txt")); //track wealth over time PrintStream coutput = new PrintStream(new FileOutputStream("cittracker.txt")); //ditto //Create population int n = Integer.parseInt(citizenReader.readLine()); Citizen[] people = new Citizen[n]; for(int i = 0; i<people.length;i++) { int x = 0; double[] d = new double[5]; StringTokenizer st = new StringTokenizer(citizenReader.readLine()); while (st.hasMoreTokens()) { String s = st.nextToken(); d[x] = Double.parseDouble(s); x++; } people[i] = new Citizen(d[0], d[1], d[2], d[3], d[4]); } citizenReader.close(); //for now just read one Government, later use more for multiple tests n = Integer.parseInt(govtReader.readLine()); Government[] govts = new Government[n]; for(int y = 0; y<govts.length;y++) { int x = 0; double[] d = new double[10]; StringTokenizer st = new StringTokenizer(govtReader.readLine()); while (st.hasMoreTokens()) { String s = st.nextToken(); d[x] = Double.parseDouble(s); x++; } govts[y] = new Government(d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8]); } govtReader.close(); population = people; iterate(MONTHS, govts,people, p, goutput, coutput); } public static void iterate(int time, Government[] govts, Citizen[] people2, PrintStream p, PrintStream goutput, PrintStream coutput) { String[] output = new String[(govts.length)]; String[][] finalAssess = new String[govts.length][time+1]; for(int asdf = 0;asdf<govts.length;asdf++) //cycle through governments { int ccount = 0; int gcount = 0; int gv = asdf; double rating; double[] cwealth = new double[time+1]; double[] gwealth = new double[time+1]; for(int meh = 0;meh<people2.length;meh++) //initial wealth count { cwealth[ccount] += people2[meh].getWealth(); } gwealth[gcount] = govts[gv].getWealth(); for(int i = 0;i<time;i++) //start the cycle, no multiple govts/resources now { boolean wellfair = false; Government g1 = govts[gv]; rating = 0; if(g1.oldApproval()<g1.approvalRating()) //very simple right now, maybe do govt assessment of "need" { if(Math.random()<g1.response()) wellfair = true; } double oldemoney = g1.getWealth(); ccount++; /*********************************************************************************/ for(int cv = 0;cv<people2.length;cv++)//civ cycle { Citizen p1 = people2[cv]; double oldwealth = p1.getWealth(); //receive benefits if(wellfair=true && g1.getWealth()>0.0 && p1.getApproval()<g1.approvalRating()) //MUCH too generous { p1.wealth(g1.welfare()); g1.wealth(-g1.welfare()); } //work + taxes //p1.wealth(p1.getWorkRate()*p1.getWealth()); //rate based p1.wealth(p1.getWorkRate()); p1.wealth(-g1.taxRate()*p1.getWealth()); g1.wealth(g1.taxRate()*p1.getWealth()); //spending p1.wealth(-p1.getSpending()*p1.getWealth()); p1.wealth(-p1.getSpending()*g1.getSalesTax()); g1.wealth(p1.getSpending()*g1.getSalesTax()); /* //consumption p1.wealth(-p1.getSpending()); */ if(p1.getHappiness()>100.0) p1.happy(100.0); double assessW; assessW = assessWealth(oldwealth, p1.getWealth()); //wealth ratio p1.rateW(assessW); rating += p1.getApproval(); //messed up cwealth[ccount] += p1.getWealth(); //p1.getApproval(); } //pay and interact then update govt standing and output + resources rating /= people2.length; //average of approvals = approval rating g1.changeApproval(rating); //Start government action double w; w = assessWealth(oldemoney,g1.getWealth()); g1.rateW(w); g1.happy((w+g1.approvalRating())/2); //"[resource] [govt] [rating]" finalAssess[gv][i] = (i + " " + gv + " " + g1.getHappiness());//update approval each time gcount++; gwealth[gcount] = g1.getWealth(); //track gwealth } printOutGovtCycle(goutput, gv, gwealth); printOutCitizenCycle(coutput, gv, cwealth); } printOut(time, finalAssess, p); } public static void printOut(int time, String[][] s, PrintStream printer) { printer.println(s.length + " " + time); for(int x = 0;x<s.length;x++) for(int y = 0;y<time;y++) printer.println(s[x][y]); } public static void printOutGovtCycle(PrintStream printer, int gnum,double[] gwealth) //print progress of wealth { for(int x = 0;x<gwealth.length;x++) { printer.println(x + " " + gnum + " " + gwealth[x]); } } public static void printOutCitizenCycle(PrintStream printer, int gnum, double[] cwealth) //print progress of wealth stats { for(int x = 0;x<cwealth.length;x++) { printer.println(x + " " + gnum + " " + cwealth[x]); } } public static double assessWealth(double beforeW, double afterW) //need relative wealth measure { double measureW = 0.0; measureW = afterW/beforeW; //percentage if(afterW<0.0 && beforeW<0.0) measureW = beforeW/afterW; /*if(WA>1) measureW = measureW*(WA); else measureW = -measureW*(WA); */ return measureW; } }<file_sep> //<NAME> //Period 2 //Computer Systems Research //Government class file import java.util.*; public class Government { private double taxrate; private double salesTax; private double responsiveness; private double publicWelfare; private double wealth; private double happiness; private double approval; //measure of gov't succes private double wealthAssess; private double oldapproval; public Government(double tr, double r, double pw, double w, double h, double ap, double wa, double oa, double st) { responsiveness = r; taxrate = tr; publicWelfare = pw; wealth = w; happiness = h; approval = ap; wealthAssess = wa; oldapproval = oa; salesTax = st; } public Government(Government g) { responsiveness = g.responsiveness; taxrate = g.taxrate; publicWelfare = g.publicWelfare; wealth = g.wealth; happiness = g.happiness; approval = g.approval; wealthAssess = g.wealthAssess; oldapproval = g.oldapproval; salesTax = g.salesTax; } public double oldApproval() { return oldapproval; } public double judgeWealth() { return wealthAssess; } public void rateW(double x) { wealthAssess = x; } public double response() { return responsiveness; } public double taxRate() { return taxrate; } public double welfare() { return publicWelfare; } public double getWealth() { return wealth; } public double getHappiness() { return happiness; } public double approvalRating() { return approval; } public void changeTRate(double r) { taxrate = r; } public void changeSTRate(double s) { salesTax = s; } public void adjWelfare(double w) { publicWelfare = w; } public void wealth(double x) { wealth += x; } public void happy(double x) { happiness = x; } public void changeApproval(double x) { oldapproval = approval; approval = x; } public void adjResponse(double x) { responsiveness+=x; } public double getSalesTax() { return salesTax; } public void changeWealth(double x) { wealth = x; } }
612054384009dc2b279edc752823fd6c69f87594
[ "Java" ]
4
Java
Formless/GeneticAlgorithmProject
0835deb78fdb38fe8d4458ecfcbee79c1aa55626
67819f779f3058571412e2db6086ad7d459853cf
refs/heads/master
<repo_name>rs-renato/springframework-testing<file_sep>/src/test/java/guru/springframework/MockWithExtensionTest.java package guru.springframework; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) class MockWithExtensionTest { @Mock Map<String, Object> injectedMockMap; @Test void injectedMock() { assertEquals(0, injectedMockMap.size()); } } <file_sep>/src/test/java/guru/springframework/sfgpetclinic/OwnerArgumentProvider.java package guru.springframework.sfgpetclinic; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.util.stream.Stream; public class OwnerArgumentProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { return Stream.of( Arguments.of(1L, "Amanda", "Silva", "%Silva%", "redirect:/owners/1"), Arguments.of(1L, "Amanda", "NotFound", "%NotFound%", "owners/findOwners"), Arguments.of(1L, "Amanda", null, "%%", "owners/findOwners"), Arguments.of(1L, "Amanda", "Souza", "%Souza%", "owners/ownersList") ); } } <file_sep>/src/test/java/guru/springframework/MockTest.java package guru.springframework; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; class MockTest { @Mock Map<String, Object> injectedMockMap; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void inlineMock() { Map<?,?> map = Mockito.mock(Map.class); assertEquals(0, map.size()); } @Test void injectedMock() { assertEquals(0, injectedMockMap.size()); } } <file_sep>/src/test/java/guru/springframework/sfgpetclinic/model/PersonTest.java package guru.springframework.sfgpetclinic.model; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; class PersonTest implements ModelTests { Person person; @BeforeEach void setUp() { person = new Person(1l, "Jhon", "Doe"); } @Test void propertiesShouldBeSet(){ assertAll("Test Properties Set", () -> assertEquals("Jhon", person.getFirstName(), "First name failed"), () -> assertEquals("Doe", person.getLastName(), "Last name failed") ); } @RepeatedTest(value = 10, name = "{displayName} : {currentRepetition}/{totalRepetitions}") @DisplayName("Repeated Test") void repeatedTests(){ } @RepeatedTest(value = 5, name = "{displayName} : {currentRepetition}/{totalRepetitions}") @DisplayName("Repeated Test") void repeatedTestsWithDepInjection(TestInfo testInfo, RepetitionInfo repetitionInfo){ System.out.println(testInfo); System.out.println(repetitionInfo); } }
5090cb1b57853e74038733a5e659088d35f41d0b
[ "Java" ]
4
Java
rs-renato/springframework-testing
2f6440a07d47289d669e7dc72cd29cae3b1582f6
5f95ea1ba983e54ae83224c0eae3e92477e4bcc5
refs/heads/master
<file_sep>package com.company; import javax.management.monitor.GaugeMonitor; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { int player = 3; int opponent = 3; Game(player, opponent); } public static void Game(int P, int O) { Scanner scan = new Scanner(System.in); Random rand = new Random(); if (P == 0) { System.out.println("Player is winner"); return; } if (O == 0) { System.out.println("Bor is winner"); return; } System.out.printf("Player 1, how much rocks do you want to take? (from 0 - %d) ", P); int p1 = scan.nextInt(); System.out.print("How many rocks your opponent has taken? "); int p2 = scan.nextInt(); int sum = p1 + p2; int bot1 = rand.nextInt(O); int bot; for (;;) { int bot2 = rand.nextInt(P); bot = bot2 + bot1; if (bot != sum) { break; } } if (p1 + bot1 == sum) { System.out.println("Player won round"); Game(P-1, O); } else if (p1 + bot1 == bot) { System.out.println("Bot won round"); Game(P, O-1); } else { System.out.println("Draw"); Game(P,O); } } }
0fcba4f4ea47b92cd2b9c855e2b1f9428993589c
[ "Java" ]
1
Java
Kirill-YoSen/Game
b890563cb27604514ef5660229cd4225d859629d
5e22747efe3f9dc4c8d70f089accdf0ad53a113f
refs/heads/master
<file_sep>package view; import controller.ControllerProdutos; import controller.ControllerVendas; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import model.ModelProdutos; import util.BLMascaras; import model.ModelVendas; import util.FormatadorString; public class ViewFinanceiro extends javax.swing.JFrame { BLMascaras bLMascaras = new BLMascaras(); ControllerVendas controllerVendas = new ControllerVendas(); ModelVendas modelVendas = new ModelVendas(); String valorDia; String valorSemana; String valorMes; ArrayList<ModelProdutos> listaModelProdutos = new ArrayList<>(); ControllerProdutos controllerProdutos = new ControllerProdutos(); ModelProdutos modelProdutos = new ModelProdutos(); public ViewFinanceiro() { initComponents(); setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/imagens/icones/logo_lanche.jpg")).getImage()); carregarMaisVendidos(); carregarFinanceiro(); alinharTabela(); } private void carregarFinanceiro() { BLMascaras bLMascaras = new BLMascaras(); modelVendas = controllerVendas.retornarVendaDiaController(); valorDia = FormatadorString.format(modelVendas.getValorVenDia()); jtfVenDia.setText(bLMascaras.converterPontoPraVirgula(valorDia)); modelVendas = controllerVendas.retornarVendaSemanaController(); valorSemana = FormatadorString.format(modelVendas.getValorVenSemana()); jtfVenSemana.setText(bLMascaras.converterPontoPraVirgula(valorSemana)); modelVendas = controllerVendas.retornarVendaMesController(); valorMes = FormatadorString.format(modelVendas.getValorVenMes()); jtfVenMes.setText(bLMascaras.converterPontoPraVirgula(valorMes)); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { painel = new javax.swing.JPanel(); painel1 = new javax.swing.JPanel(); painelTitulo = new javax.swing.JPanel(); title = new javax.swing.JLabel(); painel2 = new javax.swing.JPanel(); label1 = new javax.swing.JLabel(); label2 = new javax.swing.JLabel(); label3 = new javax.swing.JLabel(); jtfVenDia = new javax.swing.JLabel(); jtfVenSemana = new javax.swing.JLabel(); jtfVenMes = new javax.swing.JLabel(); painel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtProdutos = new javax.swing.JTable(); title1 = new javax.swing.JLabel(); painelTarefas = new javax.swing.JPanel(); btnFechar = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel.setBackground(new java.awt.Color(174, 232, 56)); painel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painel.setPreferredSize(new java.awt.Dimension(831, 589)); painel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel1.setBackground(new java.awt.Color(255, 255, 255)); painel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); painel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painelTitulo.setBackground(new java.awt.Color(239, 239, 239)); painelTitulo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); painelTitulo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); title.setBackground(new java.awt.Color(255, 255, 255)); title.setFont(new java.awt.Font("Segoe UI", 1, 48)); // NOI18N title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); title.setText("Fluxo de caixa"); title.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); painelTitulo.add(title, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 1120, 70)); painel1.add(painelTitulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 1140, 70)); painel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); painel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); label1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N label1.setText("Vendas Hoje:"); painel2.add(label1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, 30)); label2.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N label2.setText("Vendas Nesta Semana:"); painel2.add(label2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, -1, 30)); label3.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N label3.setText("Vendas Neste Mês:"); painel2.add(label3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, -1, 30)); jtfVenDia.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N jtfVenDia.setForeground(new java.awt.Color(204, 0, 0)); jtfVenDia.setText("R$10,00"); painel2.add(jtfVenDia, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, -1, 30)); jtfVenSemana.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N jtfVenSemana.setForeground(new java.awt.Color(204, 0, 0)); jtfVenSemana.setText("R$10,00"); painel2.add(jtfVenSemana, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, -1, 30)); jtfVenMes.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N jtfVenMes.setForeground(new java.awt.Color(204, 0, 0)); jtfVenMes.setText("R$10,00"); painel2.add(jtfVenMes, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, -1, 30)); painel1.add(painel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 300, 445)); painel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); painel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtProdutos.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jtProdutos.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jtProdutos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Produto", "Quantidade Total", "Valor Total Rendido" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jtProdutos); if (jtProdutos.getColumnModel().getColumnCount() > 0) { jtProdutos.getColumnModel().getColumn(0).setResizable(false); jtProdutos.getColumnModel().getColumn(0).setPreferredWidth(100); jtProdutos.getColumnModel().getColumn(1).setPreferredWidth(20); jtProdutos.getColumnModel().getColumn(2).setPreferredWidth(20); } painel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 60, 760, 350)); title1.setFont(new java.awt.Font("Segoe UI", 1, 28)); // NOI18N title1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); title1.setText("Mais vendidos"); painel3.add(title1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 800, 40)); painel1.add(painel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 110, 820, 445)); painel.add(painel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 1180, 575)); getContentPane().add(painel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 25, 1200, 595)); painelTarefas.setBackground(new java.awt.Color(126, 178, 20)); painelTarefas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painelTarefas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnFechar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/fechar2.png"))); // NOI18N btnFechar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnFecharMouseClicked(evt); } }); painelTarefas.add(btnFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(1175, 0, 25, 25)); getContentPane().add(painelTarefas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1200, 40)); pack(); }// </editor-fold>//GEN-END:initComponents private void btnFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFecharMouseClicked fechar(); }//GEN-LAST:event_btnFecharMouseClicked private void carregarMaisVendidos() { listaModelProdutos = controllerProdutos.retornarListaProdutoMaisVendidosController(); DefaultTableModel modelo = (DefaultTableModel) jtProdutos.getModel(); modelo.setNumRows(0); int cont = listaModelProdutos.size(); for (int i = 0; i < cont; i++) { modelo.addRow(new Object[]{ listaModelProdutos.get(i).getProNome(), listaModelProdutos.get(i).getProEstoque(), FormatadorString.format(listaModelProdutos.get(i).getProValor()) }); } } public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewFinanceiro().setVisible(true); } }); } private void fechar() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja fechar o Programa?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { dispose(); new ViewMenuPrincipal().setVisible(true); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } private void alinharTabela(){ DefaultTableCellRenderer esquerda = new DefaultTableCellRenderer(); DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer(); DefaultTableCellRenderer direita = new DefaultTableCellRenderer(); esquerda.setHorizontalAlignment(SwingConstants.LEFT); centralizado.setHorizontalAlignment(SwingConstants.CENTER); direita.setHorizontalAlignment(SwingConstants.RIGHT); jtProdutos.getColumnModel().getColumn(0).setCellRenderer(esquerda); jtProdutos.getColumnModel().getColumn(1).setCellRenderer(centralizado); jtProdutos.getColumnModel().getColumn(2).setCellRenderer(centralizado); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnFechar; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jtProdutos; private javax.swing.JLabel jtfVenDia; private javax.swing.JLabel jtfVenMes; private javax.swing.JLabel jtfVenSemana; private javax.swing.JLabel label1; private javax.swing.JLabel label2; private javax.swing.JLabel label3; private javax.swing.JPanel painel; private javax.swing.JPanel painel1; private javax.swing.JPanel painel2; private javax.swing.JPanel painel3; private javax.swing.JPanel painelTarefas; private javax.swing.JPanel painelTitulo; private javax.swing.JLabel title; private javax.swing.JLabel title1; // End of variables declaration//GEN-END:variables } <file_sep>package view; import controller.ControllerProdutos; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.RowFilter; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import model.ModelProdutos; import util.BLMascaras; import util.Formatador; import util.FormatadorString; public class ViewProduto extends javax.swing.JFrame { ArrayList<ModelProdutos> listaModelProdutos = new ArrayList<>(); ControllerProdutos controllerProdutos = new ControllerProdutos(); ModelProdutos modelProdutos = new ModelProdutos(); Formatador formatador = new Formatador(); String salvarAlterar; BLMascaras bLMascaras = new BLMascaras(); public ViewProduto() { initComponents(); setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/imagens/icones/logo_lanche.jpg")).getImage()); //alinharTabela(); carregarProdutos(); habilitarDesabilitarCampos(false); alinharTabela(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jtfNome = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jtfCodigo = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtableProdutos = new javax.swing.JTable(); jtfPesquisar = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jbPesquisa = new javax.swing.JButton(); jtfEstoque = new javax.swing.JFormattedTextField(); jbCancelar = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); jbNovo = new javax.swing.JButton(); jbSalvar = new javax.swing.JButton(); jtfValor = new javax.swing.JTextField(); painelTarefas = new javax.swing.JPanel(); btnFechar = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(174, 232, 56)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jPanel1.setPreferredSize(new java.awt.Dimension(831, 589)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel1.setText("Código:"); jPanel3.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, 20)); jtfNome.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.add(jtfNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 40, 482, -1)); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel2.setText("Nome:"); jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 20, -1, 20)); jtfCodigo.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtfCodigo.setEnabled(false); jPanel3.add(jtfCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 80, -1)); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel3.setText("Qtd Vendida:"); jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, -1, 20)); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel4.setText("Valor:"); jPanel3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 80, -1, 20)); jtableProdutos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Nome", "Quantidade Vendida", "Valor R$" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class }; boolean[] canEdit = new boolean [] { false, false, true, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jtableProdutos); jPanel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 190, 580, 250)); jtfPesquisar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.add(jtfPesquisar, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 150, 410, -1)); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel5.setText("Pesquisar:"); jPanel3.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, -1, 20)); jbPesquisa.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/pesquisar.png"))); // NOI18N jbPesquisa.setText(" Pesquisar"); jbPesquisa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbPesquisaActionPerformed(evt); } }); jPanel3.add(jbPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 147, -1, 26)); jtfEstoque.setEditable(false); jtfEstoque.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); jtfEstoque.setText("0"); jtfEstoque.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.add(jtfEstoque, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 80, -1)); jbCancelar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/cancelar.png"))); // NOI18N jbCancelar.setText(" Cancelar"); jbCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCancelarActionPerformed(evt); } }); jPanel3.add(jbCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 460, 100, 30)); jbAlterar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/alterar.png"))); // NOI18N jbAlterar.setText(" Alterar"); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); jPanel3.add(jbAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 460, 100, 30)); jbNovo.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/novo.png"))); // NOI18N jbNovo.setText(" Novo"); jbNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbNovoActionPerformed(evt); } }); jPanel3.add(jbNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 460, 100, 30)); jbSalvar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/save.png"))); // NOI18N jbSalvar.setText(" Salvar"); jbSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalvarActionPerformed(evt); } }); jPanel3.add(jbSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 460, 100, 30)); jtfValor.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jtfValorKeyTyped(evt); } }); jPanel3.add(jtfValor, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, 90, 20)); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 620, 510)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 25, 640, 530)); painelTarefas.setBackground(new java.awt.Color(126, 178, 20)); painelTarefas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painelTarefas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnFechar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/fechar2.png"))); // NOI18N btnFechar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnFecharMouseClicked(evt); } }); painelTarefas.add(btnFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 0, 30, 25)); getContentPane().add(painelTarefas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 640, 40)); pack(); }// </editor-fold>//GEN-END:initComponents private void jbPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPesquisaActionPerformed DefaultTableModel modelo = (DefaultTableModel) this.jtableProdutos.getModel(); final TableRowSorter<TableModel> classificador = new TableRowSorter<>(modelo); this.jtableProdutos.setRowSorter(classificador); String texto = jtfPesquisar.getText(); classificador.setRowFilter(RowFilter.regexFilter(texto, 1)); }//GEN-LAST:event_jbPesquisaActionPerformed private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed habilitarDesabilitarCampos(false); limparCampos(); }//GEN-LAST:event_jbCancelarActionPerformed private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed habilitarDesabilitarCampos(true); salvarAlterar = "salvar"; }//GEN-LAST:event_jbNovoActionPerformed private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed salvarAlterar = "alterar"; habilitarDesabilitarCampos(true); int linha = this.jtableProdutos.getSelectedRow(); try { int codigoProduto = (int) this.jtableProdutos.getValueAt(linha, 0); modelProdutos = controllerProdutos.retornarProdutoController(codigoProduto); this.jtfCodigo.setText(String.valueOf(modelProdutos.getIdProduto())); this.jtfNome.setText(modelProdutos.getProNome()); this.jtfEstoque.setText(String.valueOf(modelProdutos.getProEstoque())); this.jtfValor.setText(bLMascaras.converterPontoPraVirgula(modelProdutos.getProValor().toString())); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Código invalido, ou nenhum registro selecionado", "AVISO", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jbAlterarActionPerformed private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed if (salvarAlterar.equals("salvar")) { this.salvarProduto(); } else if (salvarAlterar.equals("alterar")) { this.alterarProduto(); } }//GEN-LAST:event_jbSalvarActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void btnFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFecharMouseClicked fechar(); }//GEN-LAST:event_btnFecharMouseClicked private void jtfValorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorKeyTyped String caracteres = "0987654321,"; if (!caracteres.contains(evt.getKeyChar() + "")) { evt.consume(); } }//GEN-LAST:event_jtfValorKeyTyped private void salvarProduto() { modelProdutos.setProNome(this.jtfNome.getText()); modelProdutos.setProEstoque(Integer.parseInt(this.jtfEstoque.getText())); //modelProdutos.setProValor(bLMascaras.arredondamentoComPontoDuasCasasDouble(formatador.converterVirgulaParaPonto(this.jtfValor.getText()))); try { modelProdutos.setProValor(formatador.converterVirgulaParaPonto(this.jtfValor.getText())); try { controllerProdutos.salvarProdutoController(modelProdutos); JOptionPane.showMessageDialog(this, "Seu produto foi cadastrado com sucesso!", "ATENÇAO", JOptionPane.WARNING_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Ocorreu um ERRO ao salvar seu produto!", "ATENÇAO", JOptionPane.WARNING_MESSAGE); } this.carregarProdutos(); this.limparCampos(); this.habilitarDesabilitarCampos(false); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Digite o valor corretamente!", "ATENÇAO", JOptionPane.WARNING_MESSAGE); } } private void alterarProduto() { modelProdutos.setProdutoiD(Integer.parseInt(jtfCodigo.getText())); modelProdutos.setProNome(this.jtfNome.getText()); modelProdutos.setProEstoque(Integer.parseInt(this.jtfEstoque.getText())); try { modelProdutos.setProValor(formatador.converterVirgulaParaPonto(this.jtfValor.getText())); try { controllerProdutos.alterarProdutoController(modelProdutos); JOptionPane.showMessageDialog(this, "Seu produto foi alterado com sucesso!", "ATENÇAO", JOptionPane.WARNING_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Erro ao alterar o produto!", "ERRO", JOptionPane.ERROR_MESSAGE); } this.carregarProdutos(); this.limparCampos(); this.habilitarDesabilitarCampos(false); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Digite o valor corretamente!", "ATENÇAO", JOptionPane.WARNING_MESSAGE); } } private void habilitarDesabilitarCampos(boolean condicao) { jtfNome.setEnabled(condicao); jtfEstoque.setEnabled(condicao); jtfValor.setEnabled(condicao); jbSalvar.setEnabled(condicao); } private void limparCampos() { jtfNome.setText(""); jtfEstoque.setText(""); jtfValor.setText(""); jtfCodigo.setText(""); } private void carregarProdutos() { listaModelProdutos = controllerProdutos.retornarListaProdutoController(); DefaultTableModel modelo = (DefaultTableModel) jtableProdutos.getModel(); modelo.setNumRows(0); int cont = listaModelProdutos.size(); for (int i = 0; i < cont; i++) { modelo.addRow(new Object[]{ listaModelProdutos.get(i).getIdProduto(), listaModelProdutos.get(i).getProNome(), listaModelProdutos.get(i).getProEstoque(), listaModelProdutos.get(i).getProValor() }); } } public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewProduto().setVisible(true); } }); } private void fechar() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja Fechar?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { this.dispose(); new ViewMenuPrincipal().setVisible(true); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } private void alinharTabela() { DefaultTableCellRenderer esquerda = new DefaultTableCellRenderer(); DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer(); DefaultTableCellRenderer direita = new DefaultTableCellRenderer(); esquerda.setHorizontalAlignment(SwingConstants.LEFT); centralizado.setHorizontalAlignment(SwingConstants.CENTER); direita.setHorizontalAlignment(SwingConstants.RIGHT); jtableProdutos.getColumnModel().getColumn(0).setCellRenderer(centralizado); jtableProdutos.getColumnModel().getColumn(1).setCellRenderer(esquerda); jtableProdutos.getColumnModel().getColumn(2).setCellRenderer(centralizado); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnFechar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbCancelar; private javax.swing.JButton jbNovo; private javax.swing.JButton jbPesquisa; private javax.swing.JButton jbSalvar; private javax.swing.JTable jtableProdutos; private javax.swing.JTextField jtfCodigo; private javax.swing.JFormattedTextField jtfEstoque; private javax.swing.JTextField jtfNome; private javax.swing.JTextField jtfPesquisar; private javax.swing.JTextField jtfValor; private javax.swing.JPanel painelTarefas; // End of variables declaration//GEN-END:variables } <file_sep>package view; import controller.ControllerCliente; import controller.ControllerProdutos; import controller.ControllerProdutosVendasProdutos; import controller.ControllerVendas; import controller.ControllerVendasCliente; import controller.ControllerVendasProdutos; import java.sql.Connection; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import model.ModelCliente; import model.ModelProdutos; import model.ModelProdutosVendasProdutos; import model.ModelVendas; import model.ModelVendasCLiente; import model.ModelVendasProdutos; import util.BLDatas; public class ViewVendas extends javax.swing.JFrame { ControllerCliente controllerCliente = new ControllerCliente(); ModelCliente modelCliente = new ModelCliente(); ArrayList<ModelCliente> listaModelCliente = new ArrayList<>(); ControllerProdutos controllerProdutos = new ControllerProdutos(); ModelProdutos modelProdutos = new ModelProdutos(); ArrayList<ModelProdutos> listaModelProdutos = new ArrayList<>(); ArrayList<ModelVendasCLiente> listaModelVendasClientes = new ArrayList<>(); ControllerVendasCliente controllerVendasCliente = new ControllerVendasCliente(); ControllerVendas controllerVendas = new ControllerVendas(); ModelVendas modelVendas = new ModelVendas(); BLDatas bLDatas = new BLDatas(); ControllerVendasProdutos controllerVendasProdutos = new ControllerVendasProdutos(); ModelVendasProdutos modelVendasProdutos = new ModelVendasProdutos(); ArrayList<ModelVendasProdutos> listaModelVendasProdutos = new ArrayList<>(); ControllerProdutosVendasProdutos controllerProdutosVendasProdutos = new ControllerProdutosVendasProdutos(); ModelProdutosVendasProdutos modelProdutosVendasProdutos = new ModelProdutosVendasProdutos(); ArrayList<ModelProdutosVendasProdutos> listaModelProdutosVendasProdutoses = new ArrayList<>(); String alterarSalvar; Connection conexao = null; public ViewVendas() { initComponents(); setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/imagens/icones/logo_lanche.jpg")).getImage()); listarClientes(); listarProdutos(); carregarVendas(); preecherCodigoClientePeloCombobox(); preecherCodigoProdutoPeloCombobox(); alinharTabela(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel3 = new javax.swing.JPanel(); jtfCodigoCli = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jtfNumVenda = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtfCodigoProduto = new javax.swing.JTextField(); jtfQuantidade = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jbAdicionar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jtProdutosVenda = new javax.swing.JTable(); jbSalvar = new javax.swing.JButton(); jbCancelar = new javax.swing.JButton(); jbNovo = new javax.swing.JButton(); jbRemoverProdutos = new javax.swing.JButton(); jtfValorTotal = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jtfDesconto = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jcbNomeProduto = new componentes.UJComboBox(); jcbNomeCli = new componentes.UJComboBox(); jPanel4 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jtVendas = new javax.swing.JTable(); jPanel5 = new javax.swing.JPanel(); jbImprimir = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jtfPesquisa = new javax.swing.JTextField(); jbPesquisar = new javax.swing.JButton(); jbExcluir = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); painelTarefas = new javax.swing.JPanel(); btnFechar = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(174, 232, 56)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jPanel1.setPreferredSize(new java.awt.Dimension(831, 589)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255)); jTabbedPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jTabbedPane1.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtfCodigoCli.setEditable(false); jtfCodigoCli.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtfCodigoCli.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfCodigoCliFocusLost(evt); } }); jPanel3.add(jtfCodigoCli, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 90, -1)); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel1.setText("Código Cliente"); jPanel3.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, 20)); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel2.setText("Nome do Cliente"); jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 20, -1, 20)); jtfNumVenda.setEditable(false); jtfNumVenda.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.add(jtfNumVenda, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 40, 189, -1)); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel3.setText("Número da venda"); jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 20, -1, 20)); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel4.setText("Codigo Produto"); jPanel3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, 20)); jtfCodigoProduto.setEditable(false); jtfCodigoProduto.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtfCodigoProduto.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfCodigoProdutoFocusLost(evt); } }); jPanel3.add(jtfCodigoProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 90, -1)); jtfQuantidade.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel3.add(jtfQuantidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 90, 189, 20)); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel5.setText("Quantidade"); jPanel3.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 70, -1, 20)); jbAdicionar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/add.png"))); // NOI18N jbAdicionar.setText(" Adicionar"); jbAdicionar.setEnabled(false); jbAdicionar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAdicionarActionPerformed(evt); } }); jPanel3.add(jbAdicionar, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 87, -1, -1)); jtProdutosVenda.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtProdutosVenda.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código produto", "Nome", "Quant", "Valor Un", "Valor Total" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jtProdutosVenda); jPanel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 130, 750, 240)); jbSalvar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/save.png"))); // NOI18N jbSalvar.setText(" Salvar"); jbSalvar.setEnabled(false); jbSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalvarActionPerformed(evt); } }); jPanel3.add(jbSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 380, 110, 40)); jbCancelar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/cancelar.png"))); // NOI18N jbCancelar.setText(" Cancelar"); jbCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCancelarActionPerformed(evt); } }); jPanel3.add(jbCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 400, 110, 40)); jbNovo.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/novo.png"))); // NOI18N jbNovo.setText(" Novo"); jbNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbNovoActionPerformed(evt); } }); jPanel3.add(jbNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 400, 110, 40)); jbRemoverProdutos.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jbRemoverProdutos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/remover.png"))); // NOI18N jbRemoverProdutos.setText(" Remover"); jbRemoverProdutos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbRemoverProdutosActionPerformed(evt); } }); jPanel3.add(jbRemoverProdutos, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 400, 110, 40)); jtfValorTotal.setFont(new java.awt.Font("Segoe UI", 0, 36)); // NOI18N jPanel3.add(jtfValorTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 420, 110, 40)); jLabel6.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel6.setText("Valor total"); jPanel3.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 400, -1, 20)); jtfDesconto.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtfDesconto.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfDescontoFocusLost(evt); } }); jPanel3.add(jtfDesconto, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 440, 110, -1)); jLabel7.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel7.setText("Desconto"); jPanel3.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 420, -1, 20)); jLabel9.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel9.setText("Nome do Produto"); jPanel3.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, -1, 20)); jcbNomeProduto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbNomeProdutoActionPerformed(evt); } }); jPanel3.add(jcbNomeProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, 330, -1)); jcbNomeCli.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbNomeCliActionPerformed(evt); } }); jPanel3.add(jcbNomeCli, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 40, 450, -1)); jTabbedPane1.addTab("Cadastro", jPanel3); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtVendas.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtVendas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código Venda", "Caixa", "Data" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(jtVendas); jPanel4.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 760, 330)); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jbImprimir.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jbImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/imprimir.png"))); // NOI18N jbImprimir.setText(" Imprimir"); jbImprimir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jbImprimir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbImprimirActionPerformed(evt); } }); jPanel5.add(jbImprimir, new org.netbeans.lib.awtextra.AbsoluteConstraints(659, 425, 120, 40)); jLabel8.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jLabel8.setText("Pesquisa"); jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, 20)); jtfPesquisa.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jPanel5.add(jtfPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 640, -1)); jbPesquisar.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jbPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/pesquisar.png"))); // NOI18N jbPesquisar.setText(" Pesquisar"); jPanel5.add(jbPesquisar, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 37, -1, -1)); jbExcluir.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/excluir.png"))); // NOI18N jbExcluir.setText(" Excluir"); jbExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbExcluirActionPerformed(evt); } }); jPanel5.add(jbExcluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 425, 110, 40)); jbAlterar.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/alterar.png"))); // NOI18N jbAlterar.setText(" Alterar"); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); jPanel5.add(jbAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 425, 110, 40)); jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 790, 490)); jTabbedPane1.addTab("Consultar/Excluir/Alterar", jPanel4); jPanel2.add(jTabbedPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 510)); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 25, 820, 530)); painelTarefas.setBackground(new java.awt.Color(126, 178, 20)); painelTarefas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painelTarefas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnFechar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/fechar2.png"))); // NOI18N btnFechar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnFecharMouseClicked(evt); } }); painelTarefas.add(btnFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 0, 30, 25)); getContentPane().add(painelTarefas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 820, 40)); pack(); }// </editor-fold>//GEN-END:initComponents private void jtfCodigoCliFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCodigoCliFocusLost modelCliente = controllerCliente.getClienteController(Integer.parseInt(jtfCodigoCli.getText())); jcbNomeCli.setSelectedItem(modelCliente.getCliNome()); }//GEN-LAST:event_jtfCodigoCliFocusLost private void jtfCodigoProdutoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCodigoProdutoFocusLost modelProdutos = controllerProdutos.retornarProdutoController(Integer.parseInt(jtfCodigoProduto.getText())); jcbNomeProduto.setSelectedItem(modelProdutos.getProNome()); }//GEN-LAST:event_jtfCodigoProdutoFocusLost private void jbAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAdicionarActionPerformed if (jtfQuantidade.getText().equals("")) { JOptionPane.showMessageDialog(this, "Você deve preencher todos os campos", "Atenção", JOptionPane.WARNING_MESSAGE); } else { modelProdutos = controllerProdutos.retornarProdutoController(Integer.parseInt(jtfCodigoProduto.getText())); DefaultTableModel modelo = (DefaultTableModel) jtProdutosVenda.getModel(); int cont = 0; double quantidade = 0; quantidade = Double.parseDouble(jtfQuantidade.getText()); for (int i = 0; i < cont; i++) { modelo.setNumRows(0); } modelo.addRow(new Object[]{ modelProdutos.getIdProduto(), modelProdutos.getProNome(), jtfQuantidade.getText(), modelProdutos.getProValor(), quantidade * modelProdutos.getProValor() }); somarValorTotalProdutos(); } }//GEN-LAST:event_jbAdicionarActionPerformed private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed int codigoVenda = 0; int codigoProduto = 0; double desconto = 0; if (jtfDesconto.getText().equals("")) { desconto = 0; } else { desconto = Double.parseDouble(jtfDesconto.getText()); } if (!jtfNumVenda.getText().equals("")) { modelVendas.setIdVenda(Integer.parseInt(jtfNumVenda.getText())); } listaModelVendasProdutos = new ArrayList<>(); modelVendas.setCliente(Integer.parseInt(jtfCodigoCli.getText())); try { modelVendas.setVenDataVenda(bLDatas.converterDataParaDateUS(new java.util.Date(System.currentTimeMillis()))); } catch (Exception e) { } modelVendas.setVenValorLiquido(Double.parseDouble(jtfValorTotal.getText())); modelVendas.setVenValorBruto(Double.parseDouble(jtfValorTotal.getText()) + desconto); modelVendas.setVenDesconto(desconto); if (alterarSalvar.equals("salvar")) { codigoVenda = controllerVendas.salvarVendasController(modelVendas); if (codigoVenda > 0) { JOptionPane.showMessageDialog(this, "Venda Salva com sucesso!", "ATENÇÃO", JOptionPane.WARNING_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Erro ao Salvar a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } int cont = jtProdutosVenda.getRowCount(); for (int i = 0; i < cont; i++) { codigoProduto = (int) jtProdutosVenda.getValueAt(i, 0); modelVendasProdutos = new ModelVendasProdutos(); modelProdutos = new ModelProdutos(); modelVendasProdutos.setProduto(codigoProduto); modelVendasProdutos.setVendas(codigoVenda); modelVendasProdutos.setVenProValor((double) jtProdutosVenda.getValueAt(i, 3)); modelVendasProdutos.setVenProQuantidade(Integer.parseInt(jtProdutosVenda.getValueAt(i, 2).toString())); modelProdutos.setIdProduto(codigoProduto); modelProdutos.setProEstoque(controllerProdutos.retornarProdutoController(codigoProduto).getProEstoque() - Integer.parseInt(jtProdutosVenda.getValueAt(i, 2).toString())); listaModelVendasProdutos.add(modelVendasProdutos); listaModelProdutos.add(modelProdutos); } if (controllerVendasProdutos.salvarVendasProdutosController(listaModelVendasProdutos)) { controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos); carregarVendas(); limparFormulario(); } else { JOptionPane.showMessageDialog(this, "Erro ao Salvar Produtos da venda", "ERRO", JOptionPane.ERROR_MESSAGE); } } else { int linha = jtVendas.getSelectedRow(); codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutos = new ArrayList<>(); listaModelProdutosVendasProdutoses = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosDAOController(codigoVenda); for (int i = 0; i < listaModelProdutosVendasProdutoses.size(); i++) { modelProdutos = new ModelProdutos(); modelProdutos.setIdProduto( listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getIdProduto()); modelProdutos.setProEstoque( listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getProEstoque() + listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProQuantidade()); listaModelProdutos.add(modelProdutos); } if (controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos)) { if (controllerVendasProdutos.excluirVendasProdutosController(codigoVenda)) { carregarVendas(); } else { JOptionPane.showMessageDialog(this, "Erro ao excluir a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Erro ao excluir a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } if (controllerVendas.atualizarVendasController(modelVendas)) { JOptionPane.showMessageDialog(this, "Venda alterada com sucesso!", "ATENÇÃO", JOptionPane.WARNING_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Erro ao alterar a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } int cont = jtProdutosVenda.getRowCount(); for (int i = 0; i < cont; i++) { codigoProduto = (int) jtProdutosVenda.getValueAt(i, 0); modelVendasProdutos = new ModelVendasProdutos(); modelProdutos = new ModelProdutos(); modelVendasProdutos.setProduto(codigoProduto); modelVendasProdutos.setVendas(codigoVenda); modelVendasProdutos.setVenProValor((double) jtProdutosVenda.getValueAt(i, 3)); modelVendasProdutos.setVenProQuantidade(Integer.parseInt(jtProdutosVenda.getValueAt(i, 2).toString())); modelProdutos.setIdProduto(codigoProduto); modelProdutos.setProEstoque(controllerProdutos.retornarProdutoController(codigoProduto).getProEstoque() - Integer.parseInt(jtProdutosVenda.getValueAt(i, 2).toString())); listaModelVendasProdutos.add(modelVendasProdutos); listaModelProdutos.add(modelProdutos); } if (controllerVendasProdutos.salvarVendasProdutosController(listaModelVendasProdutos)) { carregarVendas(); limparFormulario(); } else { JOptionPane.showMessageDialog(this, "Erro ao salvar Produtos!", "ATENÇÃO", JOptionPane.WARNING_MESSAGE); } } jbSalvar.setEnabled(false); jbAdicionar.setEnabled(false); }//GEN-LAST:event_jbSalvarActionPerformed private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed jbSalvar.setEnabled(true); jbAdicionar.setEnabled(true); alterarSalvar = "salvar"; limparFormulario(); }//GEN-LAST:event_jbNovoActionPerformed private void jbRemoverProdutosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRemoverProdutosActionPerformed int linha = jtProdutosVenda.getSelectedRow(); DefaultTableModel modelo = (DefaultTableModel) jtProdutosVenda.getModel(); modelo.removeRow(linha); somarValorTotalProdutos(); }//GEN-LAST:event_jbRemoverProdutosActionPerformed private void jtfDescontoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfDescontoFocusLost somarValorTotalProdutos(); }//GEN-LAST:event_jtfDescontoFocusLost private void jcbNomeProdutoPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jcbNomeProdutoPopupMenuWillBecomeInvisible if (jcbNomeProduto.isVisible()) { preecherCodigoProdutoPeloCombobox(); } }//GEN-LAST:event_jcbNomeProdutoPopupMenuWillBecomeInvisible private void jcbNomeCLiPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jcbNomeCLiPopupMenuWillBecomeInvisible if (jcbNomeCli.isPopupVisible()) { preecherCodigoClientePeloCombobox(); } }//GEN-LAST:event_jcbNomeCLiPopupMenuWillBecomeInvisible private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed int linha = jtVendas.getSelectedRow(); int codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutos = new ArrayList<>(); listaModelProdutosVendasProdutoses = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosDAOController(codigoVenda); for (int i = 0; i < listaModelProdutosVendasProdutoses.size(); i++) { modelProdutos = new ModelProdutos(); modelProdutos.setIdProduto( listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getIdProduto()); modelProdutos.setProEstoque( listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getProEstoque() + listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProQuantidade()); listaModelProdutos.add(modelProdutos); } if (controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos)) { controllerVendasProdutos.excluirVendasProdutosController(codigoVenda); if (controllerVendas.excluirVendasController(codigoVenda)) { JOptionPane.showMessageDialog(this, "Venda excluida com sucesso!", "ATENÇÃO", JOptionPane.WARNING_MESSAGE); carregarVendas(); } else { JOptionPane.showMessageDialog(this, "Erro ao excluir a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Erro ao excluir a venda", "ERRO", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jbExcluirActionPerformed private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed jbSalvar.setEnabled(true); jbAdicionar.setEnabled(true); alterarSalvar = "alterar"; int linha = jtVendas.getSelectedRow(); int codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutosVendasProdutoses = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosDAOController(codigoVenda); DefaultTableModel modelo = (DefaultTableModel) jtProdutosVenda.getModel(); modelo.setNumRows(0); for (int i = 0; i < listaModelProdutosVendasProdutoses.size(); i++) { jtfNumVenda.setText(String.valueOf(listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVendas())); modelo.addRow(new Object[]{ listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getIdProduto(), listaModelProdutosVendasProdutoses.get(i).getModelProdutos().getProNome(), listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProQuantidade(), listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProValor(), listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProQuantidade() * listaModelProdutosVendasProdutoses.get(i).getModelVendasProdutos().getVenProValor(),}); } somarValorTotalProdutos(); jTabbedPane1.setSelectedIndex(0); }//GEN-LAST:event_jbAlterarActionPerformed private void jbImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbImprimirActionPerformed int linha = jtVendas.getSelectedRow(); int codigoVenda = (int) jtVendas.getValueAt(linha, 0); final ViewAguarde carregando = new ViewAguarde(); carregando.setVisible(true); Thread t = new Thread() { public void run() { try { controllerVendas.gerarRelatorioVenda(codigoVenda); carregando.dispose(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao gerar relatório /n " + e, "ERRO", JOptionPane.ERROR_MESSAGE); } } }; t.start(); }//GEN-LAST:event_jbImprimirActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void btnFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFecharMouseClicked fechar(); }//GEN-LAST:event_btnFecharMouseClicked private void jcbNomeProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbNomeProdutoActionPerformed preecherCodigoProdutoPeloCombobox(); }//GEN-LAST:event_jcbNomeProdutoActionPerformed private void jcbNomeCliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbNomeCliActionPerformed preecherCodigoClientePeloCombobox(); }//GEN-LAST:event_jcbNomeCliActionPerformed private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed int intOpcao = JOptionPane.showOptionDialog(null, "Deseja Cancelar?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { limparFormulario(); jbSalvar.setEnabled(false); jbAdicionar.setEnabled(false); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } }//GEN-LAST:event_jbCancelarActionPerformed private void aplicarDescontos() { try { jtfValorTotal.setText(String.valueOf( Double.parseDouble(jtfValorTotal.getText()) - Double.parseDouble(jtfDesconto.getText()))); } catch (NumberFormatException e) { } } private void listarClientes() { listaModelCliente = controllerCliente.getListaClienteController(); jcbNomeCli.removeAllItems(); for (int i = 0; i < listaModelCliente.size(); i++) { jcbNomeCli.addItem(listaModelCliente.get(i).getCliNome()); } } private void listarProdutos() { listaModelProdutos = controllerProdutos.retornarListaProdutoController(); jcbNomeProduto.removeAllItems(); for (int i = 0; i < listaModelProdutos.size(); i++) { jcbNomeProduto.addItem(listaModelProdutos.get(i).getProNome()); } } private void carregarVendas() { DefaultTableModel modelo = (DefaultTableModel) jtVendas.getModel(); listaModelVendasClientes = controllerVendasCliente.getListaVendasClienteController(); int cont = listaModelVendasClientes.size(); modelo.setNumRows(0); for (int i = 0; i < cont; i++) { modelo.addRow(new Object[]{ listaModelVendasClientes.get(i).getModelVendas().getIdVenda(), listaModelVendasClientes.get(i).getModelCliente().getCliNome(), listaModelVendasClientes.get(i).getModelVendas().getVenDataVenda() }); } } private void somarValorTotalProdutos() { double soma = 0, valor; int cont = jtProdutosVenda.getRowCount(); for (int i = 0; i < cont; i++) { valor = (double) jtProdutosVenda.getValueAt(i, 4); soma = soma + valor; } jtfValorTotal.setText(String.valueOf(soma)); aplicarDescontos(); } private void limparFormulario() { jtfQuantidade.setText(""); jtfDesconto.setText(""); jtfValorTotal.setText(""); jtfNumVenda.setText(""); DefaultTableModel modelo = (DefaultTableModel) jtProdutosVenda.getModel(); modelo.setNumRows(0); } private void preecherCodigoClientePeloCombobox() { modelCliente = controllerCliente.getClienteController(jcbNomeCli.getSelectedItem().toString()); jtfCodigoCli.setText(String.valueOf(modelCliente.getIdCliente())); } private void preecherCodigoProdutoPeloCombobox() { modelProdutos = controllerProdutos.retornarProdutoController(jcbNomeProduto.getSelectedItem().toString()); jtfCodigoProduto.setText(String.valueOf(modelProdutos.getIdProduto())); } public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewVendas().setVisible(true); } }); } private void fechar() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja Fechar?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { dispose(); new ViewMenuPrincipal().setVisible(true); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } private void alinharTabela(){ DefaultTableCellRenderer esquerda = new DefaultTableCellRenderer(); DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer(); DefaultTableCellRenderer direita = new DefaultTableCellRenderer(); esquerda.setHorizontalAlignment(SwingConstants.LEFT); centralizado.setHorizontalAlignment(SwingConstants.CENTER); direita.setHorizontalAlignment(SwingConstants.RIGHT); jtProdutosVenda.getColumnModel().getColumn(0).setCellRenderer(centralizado); jtProdutosVenda.getColumnModel().getColumn(1).setCellRenderer(esquerda); jtProdutosVenda.getColumnModel().getColumn(2).setCellRenderer(centralizado); jtProdutosVenda.getColumnModel().getColumn(3).setCellRenderer(centralizado); jtProdutosVenda.getColumnModel().getColumn(4).setCellRenderer(centralizado); jtVendas.getColumnModel().getColumn(0).setCellRenderer(centralizado); jtVendas.getColumnModel().getColumn(1).setCellRenderer(centralizado); jtVendas.getColumnModel().getColumn(2).setCellRenderer(centralizado); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnFechar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton jbAdicionar; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbCancelar; private javax.swing.JButton jbExcluir; private javax.swing.JButton jbImprimir; private javax.swing.JButton jbNovo; private javax.swing.JButton jbPesquisar; private javax.swing.JButton jbRemoverProdutos; private javax.swing.JButton jbSalvar; private componentes.UJComboBox jcbNomeCli; private componentes.UJComboBox jcbNomeProduto; private javax.swing.JTable jtProdutosVenda; private javax.swing.JTable jtVendas; private javax.swing.JTextField jtfCodigoCli; private javax.swing.JTextField jtfCodigoProduto; private javax.swing.JTextField jtfDesconto; private javax.swing.JTextField jtfNumVenda; private javax.swing.JTextField jtfPesquisa; private javax.swing.JTextField jtfQuantidade; private javax.swing.JTextField jtfValorTotal; private javax.swing.JPanel painelTarefas; // End of variables declaration//GEN-END:variables } <file_sep>package view; import controller.ControllerUsuario; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import model.ModelUsuario; public class ViewLogin extends javax.swing.JFrame { ControllerUsuario controllerUsuario = new ControllerUsuario(); ModelUsuario modelUsuario = new ModelUsuario(); public ViewLogin() { initComponents(); setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/imagens/icones/logo_lanche.jpg")).getImage()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { painel = new javax.swing.JPanel(); painel1 = new javax.swing.JPanel(); painel2 = new javax.swing.JPanel(); title = new javax.swing.JLabel(); label1 = new javax.swing.JLabel(); label2 = new javax.swing.JLabel(); jtfLogin = new javax.swing.JTextField(); jtfSenha = new javax.swing.JPasswordField(); painelEntrar = new javax.swing.JPanel(); iconEntrar = new javax.swing.JLabel(); labelEntrar = new javax.swing.JLabel(); painelSair = new javax.swing.JPanel(); iconSair = new javax.swing.JLabel(); labelSair = new javax.swing.JLabel(); painel3 = new javax.swing.JPanel(); icon = new javax.swing.JLabel(); painelTarefas = new javax.swing.JPanel(); btnFechar = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(174, 232, 56)); setName("Login"); // NOI18N setUndecorated(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel.setBackground(new java.awt.Color(174, 232, 56)); painel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel1.setBackground(new java.awt.Color(255, 255, 255)); painel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); painel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel2.setBackground(new java.awt.Color(132, 178, 41)); painel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); painel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); title.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); title.setText("Login no sistema"); painel2.add(title, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 100, 320, -1)); label1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N label1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); label1.setText("Usuário"); painel2.add(label1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 200, 60, 20)); label2.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N label2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); label2.setText("Senha"); painel2.add(label2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, 50, 20)); jtfLogin.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jtfLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtfLoginActionPerformed(evt); } }); painel2.add(jtfLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 200, 200, 20)); jtfSenha.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jtfSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtfSenhaActionPerformed(evt); } }); painel2.add(jtfSenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 230, 200, 20)); painelEntrar.setBackground(new java.awt.Color(99, 132, 31)); painelEntrar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 94, 22))); painelEntrar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { painelEntrarMouseClicked(evt); } }); painelEntrar.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); iconEntrar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); iconEntrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/login (1).png"))); // NOI18N iconEntrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); painelEntrar.add(iconEntrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 48, 28)); labelEntrar.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N labelEntrar.setText("Entrar"); painelEntrar.add(labelEntrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 11, 50, 28)); painel2.add(painelEntrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 310, 138, 50)); painelSair.setBackground(new java.awt.Color(99, 132, 31)); painelSair.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 94, 22))); painelSair.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { painelSairMouseClicked(evt); } }); painelSair.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); iconSair.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); iconSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/exit.png"))); // NOI18N iconSair.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); painelSair.add(iconSair, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 48, 28)); labelSair.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N labelSair.setText("Sair"); painelSair.add(labelSair, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 11, 30, 28)); painel2.add(painelSair, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 310, 138, 50)); painel1.add(painel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 320, 400)); painel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); painel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); painel1.add(painel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 340, 420)); icon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/logo_capa.png"))); // NOI18N painel1.add(icon, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 0, 720, 440)); painel.add(painel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 1070, 440)); getContentPane().add(painel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 25, 1110, 480)); painelTarefas.setBackground(new java.awt.Color(126, 178, 20)); painelTarefas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painelTarefas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnFechar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/fechar2.png"))); // NOI18N btnFechar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnFecharMouseClicked(evt); } }); painelTarefas.add(btnFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(1085, 0, 25, 25)); getContentPane().add(painelTarefas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1110, 40)); pack(); }// </editor-fold>//GEN-END:initComponents private void painelEntrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_painelEntrarMouseClicked entrar(); }//GEN-LAST:event_painelEntrarMouseClicked private void painelSairMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_painelSairMouseClicked fechar(); }//GEN-LAST:event_painelSairMouseClicked private void jtfLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfLoginActionPerformed jtfSenha.requestFocus(); }//GEN-LAST:event_jtfLoginActionPerformed private void jtfSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfSenhaActionPerformed entrar(); }//GEN-LAST:event_jtfSenhaActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void btnFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFecharMouseClicked fechar(); }//GEN-LAST:event_btnFecharMouseClicked public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewLogin().setVisible(true); } }); } private void entrar() { modelUsuario.setUsuLogin(jtfLogin.getText()); modelUsuario.setUsuSenha(String.valueOf(jtfSenha.getPassword())); if (controllerUsuario.getValidarUsuarioController(modelUsuario)) { dispose(); new ViewMenuPrincipal().setVisible(true); } else { JOptionPane.showMessageDialog(this, "Usuário/Senha inválida.", "AVISO", JOptionPane.WARNING_MESSAGE); } } private void fechar() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja fechar o Programa?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { dispose(); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnFechar; private javax.swing.JLabel icon; private javax.swing.JLabel iconEntrar; private javax.swing.JLabel iconSair; private javax.swing.JTextField jtfLogin; private javax.swing.JPasswordField jtfSenha; private javax.swing.JLabel label1; private javax.swing.JLabel label2; private javax.swing.JLabel labelEntrar; private javax.swing.JLabel labelSair; private javax.swing.JPanel painel; private javax.swing.JPanel painel1; private javax.swing.JPanel painel2; private javax.swing.JPanel painel3; private javax.swing.JPanel painelEntrar; private javax.swing.JPanel painelSair; private javax.swing.JPanel painelTarefas; private javax.swing.JLabel title; // End of variables declaration//GEN-END:variables } <file_sep>package util; public abstract class FormatadorString { public static String format(Double _valor) { String valor = String.valueOf(_valor); int count1 = 0; int count2 = 0; for (int i = 0; i < valor.length(); i++) { if (valor.charAt(i) == '.') { count1++; } else if (count1 == 1) { count2++; } } if (count2 == 0) { valor += ",00"; } else if (count2 == 1) { valor += "0"; } return "R$ " + valor.replace(".", ","); } } <file_sep>package DAO; import model.ModelVendas; import conexoes.ConexaoMySql; import java.awt.Desktop; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JOptionPane; import net.sf.jasperreports.engine.JRResultSetDataSource; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import util.BLDatas; public class DAOVendas extends ConexaoMySql { public int salvarVendasDAO(ModelVendas pModelVendas) { try { this.conectar(); return this.insertSQL( "INSERT INTO tbl_vendas (" + "fk_cliente," + "ven_data_venda," + "ven_valor_liquido," + "ven_valor_bruto," + "ven_desconto" + ") VALUES (" + "'" + pModelVendas.getCliente() + "'," + "'" + pModelVendas.getVenDataVenda() + "'," + "'" + pModelVendas.getVenValorLiquido() + "'," + "'" + pModelVendas.getVenValorBruto() + "'," + "'" + pModelVendas.getVenDesconto() + "'" + ");"); } catch (Exception e) { e.printStackTrace(); return 0; } finally { this.fecharConexao(); } } public ModelVendas getVendasDAO(int pIdVenda) { ModelVendas modelVendas = new ModelVendas(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_id_venda," + "fk_cliente," + "fk_ven_data_venda," + "ven_valor_liquido," + "ven_valor_bruto," + "ven_desconto" + " FROM" + " tbl_vendas" + " WHERE" + " pk_id_vendas = '" + pIdVenda + "'" + ";"); while (this.getResultSet().next()) { modelVendas.setIdVenda(this.getResultSet().getInt(1)); modelVendas.setCliente(this.getResultSet().getInt(2)); modelVendas.setVenDataVenda(this.getResultSet().getDate(3)); modelVendas.setVenValorLiquido(this.getResultSet().getDouble(4)); modelVendas.setVenValorBruto(this.getResultSet().getDouble(5)); modelVendas.setVenDesconto(this.getResultSet().getDouble(6)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelVendas; } public ArrayList<ModelVendas> getListaVendasDAO() { ArrayList<ModelVendas> listamodelVendas = new ArrayList(); ModelVendas modelVendas = new ModelVendas(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_id_vendas," + "fk_cliente," + "fk_ven_data_venda," + "ven_valor_liquido," + "ven_valor_bruto," + "ven_desconto" + " FROM" + " tbl_vendas" + ";"); while (this.getResultSet().next()) { modelVendas = new ModelVendas(); modelVendas.setIdVenda(this.getResultSet().getInt(1)); modelVendas.setCliente(this.getResultSet().getInt(2)); modelVendas.setVenDataVenda(this.getResultSet().getDate(3)); modelVendas.setVenValorLiquido(this.getResultSet().getDouble(4)); modelVendas.setVenValorBruto(this.getResultSet().getDouble(5)); modelVendas.setVenDesconto(this.getResultSet().getDouble(6)); listamodelVendas.add(modelVendas); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return listamodelVendas; } public boolean atualizarVendasDAO(ModelVendas pModelVendas) { try { this.conectar(); return this.executarUpdateDeleteSQL( "UPDATE tbl_vendas SET " + "pk_id_vendas = '" + pModelVendas.getIdVenda() + "'," + "fk_cliente = '" + pModelVendas.getCliente() + "'," + "ven_data_venda = '" + pModelVendas.getVenDataVenda() + "'," + "ven_valor_liquido = '" + pModelVendas.getVenValorLiquido() + "'," + "ven_valor_bruto = '" + pModelVendas.getVenValorBruto() + "'," + "ven_desconto = '" + pModelVendas.getVenDesconto() + "'" + " WHERE " + "pk_id_vendas = '" + pModelVendas.getIdVenda() + "'" + ";"); } catch (Exception e) { e.printStackTrace(); return false; } finally { this.fecharConexao(); } } public boolean excluirVendasDAO(int pIdVenda) { try { this.conectar(); return this.executarUpdateDeleteSQL( "DELETE FROM tbl_vendas " + " WHERE " + "pk_id_vendas = '" + pIdVenda + "'" + ";"); } catch (Exception e) { e.printStackTrace(); return false; } finally { this.fecharConexao(); } } public boolean RelatorioVendaDAO(int codigoVenda) { try { this.conectar(); this.executarSQL( "SELECT * FROM" + " tbl_vendas tbl_vendas INNER JOIN tbl_vendas_produtos tbl_vendas_produtos ON tbl_vendas.pk_id_vendas = tbl_vendas_produtos.fk_vendas" + " INNER JOIN tbl_produto tbl_produto ON tbl_vendas_produtos.fk_produto = tbl_produto.pk_id_produto" + " INNER JOIN tbl_cliente tbl_cliente ON tbl_vendas.fk_cliente = tbl_cliente.pk_id_cliente " + "WHERE pk_id_vendas = '" + codigoVenda + "';" ); JRResultSetDataSource jrRS = new JRResultSetDataSource(getResultSet()); //caminho do relatório InputStream caminhoRelatorio = this.getClass().getClassLoader().getResourceAsStream("relatorios/Vendas.jasper"); JasperPrint jasperPrint = JasperFillManager.fillReport(caminhoRelatorio, new HashMap(), jrRS); JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/Relatorios/relVenda.pdf"); File file = new File("C:/Relatorios/relVenda.pdf"); try { Desktop.getDesktop().open(file); } catch (Exception e) { JOptionPane.showConfirmDialog(null, e); } file.deleteOnExit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { this.fecharConexao(); } } // public double retornarVendaDia() { // this.conectar(); // this.executarSQL("SELECT SUM(ven_valor_liquido) FROM tbl_vendas WHERE ven_data_venda =''"); // return 0; // } public ModelVendas retornarVendaDia() { ModelVendas modelVendas = new ModelVendas(); BLDatas bLDatas = new BLDatas(); String dataAtual = bLDatas.retornarData(); try { this.conectar(); this.executarSQL("SELECT SUM(ven_valor_liquido) FROM tbl_vendas WHERE ven_data_venda ='"+dataAtual+"'"); while (this.getResultSet().next()) { modelVendas.setValorVenDia(this.getResultSet().getDouble(1)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelVendas; } public ModelVendas retornarVendaSemana() { ModelVendas modelVendas = new ModelVendas(); try { this.conectar(); this.executarSQL( "SELECT SUM(ven_valor_liquido) FROM tbl_vendas WHERE yearweek(DATE(ven_data_venda), 1) = yearweek(curdate(), 1)"); while (this.getResultSet().next()) { modelVendas.setValorVenSemana(this.getResultSet().getDouble(1)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelVendas; } public ModelVendas retornarVendaMes() { ModelVendas modelVendas = new ModelVendas(); try { this.conectar(); this.executarSQL( "SELECT SUM(ven_valor_liquido) FROM tbl_vendas WHERE MONTH(ven_data_venda) = MONTH(CURRENT_DATE())"); while (this.getResultSet().next()) { modelVendas.setValorVenMes(this.getResultSet().getDouble(1)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelVendas; } } <file_sep>package model; public class ModelProdutos { private int idProduto; private int ProdutoiD; private String proNome; private Double proValor; private int proEstoque; public int getProdutoiD() { return ProdutoiD; } public void setProdutoiD(int ProdutoiD) { this.ProdutoiD = ProdutoiD; } public int getIdProduto() { return idProduto; } public void setIdProduto(int idProduto) { this.idProduto = idProduto; } public String getProNome() { return proNome; } public void setProNome(String proNome) { this.proNome = proNome; } public Double getProValor() { return proValor; } public void setProValor(Double proValor) { this.proValor = proValor; } public int getProEstoque() { return proEstoque; } public void setProEstoque(int proEstoque) { this.proEstoque = proEstoque; } } <file_sep># SistemaPdvWellsBurguer Sistema de PDV, controle de venda, controle finanças e relatórios em JAVA com Orientação a objetos, MVC, Banco de dados SQL. ![image](https://user-images.githubusercontent.com/48020517/65880832-d0299200-e368-11e9-8788-67296ce14f19.png) <file_sep>package view; import controller.ControllerProdutos; import controller.ControllerVendas; import controller.ControllerVendasProdutos; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.print.SimpleDoc; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.JobName; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.OrientationRequested; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import model.ModelProdutos; import model.ModelVendas; import model.ModelVendasProdutos; import util.BLDatas; import util.BLMascaras; public class ViewPDV extends javax.swing.JFrame { ControllerProdutos controllerProdutos = new ControllerProdutos(); ModelProdutos modelProdutos = new ModelProdutos(); ModelVendas modelVendas = new ModelVendas(); ModelVendasProdutos modelVendasProdutos = new ModelVendasProdutos(); ArrayList<ModelVendasProdutos> listaModelVendasProdutoses = new ArrayList<>(); ModelVendasProdutos modelVendasProdutos1 = new ModelVendasProdutos(); BLDatas bLDatas = new BLDatas(); ArrayList<ModelProdutos> listaModelProdutos = new ArrayList<>(); ControllerVendas controllerVendas = new ControllerVendas(); ControllerVendasProdutos controllerVendasProdutos = new ControllerVendasProdutos(); int quantidade; private ViewPagamentoPDV viewPagamentoPDV; BLMascaras bLMascaras = new BLMascaras(); public ViewPDV() { initComponents(); setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/imagens/icones/logo_lanche.jpg")).getImage()); quantidade = 1; limparTela(); jtfCodProduto.requestFocus(); alinharTabela(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel21 = new javax.swing.JLabel(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); jMenu3 = new javax.swing.JMenu(); jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jbExcluir = new javax.swing.JPanel(); labelVendas12 = new javax.swing.JLabel(); jbQuantidade = new javax.swing.JPanel(); labelVendas11 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jlStatus = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jtfValorTotal = new javax.swing.JTextField(); jbCancelar = new javax.swing.JPanel(); iconVendas8 = new javax.swing.JLabel(); labelVendas8 = new javax.swing.JLabel(); jbProdutos = new javax.swing.JPanel(); iconVendas9 = new javax.swing.JLabel(); labelVendas9 = new javax.swing.JLabel(); jbFinalizar = new javax.swing.JPanel(); iconVendas10 = new javax.swing.JLabel(); labelVendas10 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jtfValorBruto = new javax.swing.JTextField(); jtfDesconto = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtProdutos = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jtfCodProduto = new javax.swing.JFormattedTextField(); painelTarefas = new javax.swing.JPanel(); btnFechar = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu4 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jLabel21.setText("jLabel21"); jMenu1.setText("jMenu1"); jMenu2.setText("jMenu2"); jMenu3.setText("jMenu3"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBackground(new java.awt.Color(174, 232, 56)); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jbExcluir.setBackground(new java.awt.Color(132, 184, 38)); jbExcluir.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jbExcluir.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbExcluirMouseClicked(evt); } }); jbExcluir.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); labelVendas12.setBackground(new java.awt.Color(171, 219, 82)); labelVendas12.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N labelVendas12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); labelVendas12.setText("Excluir"); jbExcluir.add(labelVendas12, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 60, 28)); jPanel1.add(jbExcluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 460, 60, -1)); jbQuantidade.setBackground(new java.awt.Color(132, 184, 38)); jbQuantidade.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jbQuantidade.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbQuantidadeMouseClicked(evt); } }); jbQuantidade.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); labelVendas11.setBackground(new java.awt.Color(171, 219, 82)); labelVendas11.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N labelVendas11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); labelVendas11.setText("Quantidade"); jbQuantidade.add(labelVendas11, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 80, 28)); jPanel1.add(jbQuantidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 460, 79, -1)); jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel4.setBackground(new java.awt.Color(232, 232, 232)); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jlStatus.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jlStatus.setText("Funcionando"); jPanel4.add(jlStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(318, 42, -1, -1)); jLabel6.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel6.setText("Status:"); jPanel4.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(318, 11, -1, -1)); jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel3.setText("Operador:"); jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(165, 11, -1, -1)); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel5.setText("Administrador"); jPanel4.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(165, 42, -1, -1)); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel4.setText("Principal"); jPanel4.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 42, -1, -1)); jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel1.setText("Caixa:"); jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 11, -1, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 420, 70)); jPanel5.setBackground(new java.awt.Color(232, 232, 232)); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel8.setText("Valor Total:"); jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 10, -1, 38)); jtfValorTotal.setEditable(false); jtfValorTotal.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N jtfValorTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jPanel5.add(jtfValorTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 50, 120, 30)); jbCancelar.setBackground(new java.awt.Color(132, 184, 38)); jbCancelar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jbCancelar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbCancelarMouseClicked(evt); } }); jbCancelar.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); iconVendas8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); iconVendas8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/cancelar.png"))); // NOI18N iconVendas8.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jbCancelar.add(iconVendas8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 30, 28)); labelVendas8.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N labelVendas8.setText("Cancelar"); jbCancelar.add(labelVendas8, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 10, 60, 28)); jPanel5.add(jbCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 110, 120, 50)); jbProdutos.setBackground(new java.awt.Color(132, 184, 38)); jbProdutos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jbProdutos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbProdutosMouseClicked(evt); } }); jbProdutos.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); iconVendas9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); iconVendas9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/login (1).png"))); // NOI18N iconVendas9.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jbProdutos.add(iconVendas9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 30, 28)); labelVendas9.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N labelVendas9.setText("Produtos"); jbProdutos.add(labelVendas9, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 10, 70, 28)); jPanel5.add(jbProdutos, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 110, 120, 50)); jbFinalizar.setBackground(new java.awt.Color(132, 184, 38)); jbFinalizar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); jbFinalizar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbFinalizarMouseClicked(evt); } }); jbFinalizar.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); iconVendas10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); iconVendas10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/botoes/login (1).png"))); // NOI18N iconVendas10.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jbFinalizar.add(iconVendas10, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 30, 28)); labelVendas10.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N labelVendas10.setText("Finalizar"); jbFinalizar.add(labelVendas10, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 10, 60, 28)); jPanel5.add(jbFinalizar, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 110, 120, 50)); jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel9.setText("Valor Bruto:"); jPanel5.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 10, -1, 38)); jtfValorBruto.setEditable(false); jtfValorBruto.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jtfValorBruto.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jPanel5.add(jtfValorBruto, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 50, 120, -1)); jtfDesconto.setEditable(false); jtfDesconto.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jtfDesconto.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jPanel5.add(jtfDesconto, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 120, -1)); jLabel10.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel10.setText("Desconto:"); jPanel5.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, 38)); jPanel2.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 320, 420, 170)); jPanel6.setBackground(new java.awt.Color(232, 232, 232)); jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel7.setText("Comandos"); jPanel6.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 145, 45)); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel11.setText("Informar Quantidade"); jPanel6.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 60, -1, 14)); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel12.setText("Cancelar a Venda"); jPanel6.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 140, -1, -1)); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel13.setText("Excluir produto da Tabela de Vendas"); jPanel6.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 120, -1, -1)); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel14.setText("Tabela de produtos"); jPanel6.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 100, -1, -1)); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel15.setText("Finalizar a Venda"); jPanel6.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 80, -1, -1)); jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel16.setText("F3 "); jPanel6.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1)); jLabel17.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel17.setText("F7"); jPanel6.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, -1, -1)); jLabel19.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel19.setText("F5"); jPanel6.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, -1, -1)); jLabel20.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel20.setText("F4"); jPanel6.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, -1, -1)); jLabel22.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel22.setText("F6"); jPanel6.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1)); jPanel2.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, 420, 170)); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 10, 440, 500)); jtProdutos.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jtProdutos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Item", "Cod Iten", "Nome", "Quantidade", "Valor Unit.", "Valor Total" } ) { boolean[] canEdit = new boolean [] { false, false, true, false, true, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jtProdutos); if (jtProdutos.getColumnModel().getColumnCount() > 0) { jtProdutos.getColumnModel().getColumn(0).setResizable(false); jtProdutos.getColumnModel().getColumn(0).setPreferredWidth(20); jtProdutos.getColumnModel().getColumn(1).setResizable(false); jtProdutos.getColumnModel().getColumn(1).setPreferredWidth(20); jtProdutos.getColumnModel().getColumn(2).setResizable(false); jtProdutos.getColumnModel().getColumn(2).setPreferredWidth(250); jtProdutos.getColumnModel().getColumn(3).setResizable(false); jtProdutos.getColumnModel().getColumn(3).setPreferredWidth(35); jtProdutos.getColumnModel().getColumn(4).setResizable(false); jtProdutos.getColumnModel().getColumn(4).setPreferredWidth(40); jtProdutos.getColumnModel().getColumn(5).setResizable(false); jtProdutos.getColumnModel().getColumn(5).setPreferredWidth(40); } jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, 710, 250)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/logo_capaeditado.png"))); // NOI18N jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, -1)); jtfCodProduto.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); jtfCodProduto.setSelectionColor(new java.awt.Color(51, 153, 0)); jtfCodProduto.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jtfCodProdutoKeyPressed(evt); } }); jPanel1.add(jtfCodProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(109, 461, 550, 28)); jPanel3.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 1200, 520)); getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 25, 1220, 540)); painelTarefas.setBackground(new java.awt.Color(126, 178, 20)); painelTarefas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51))); painelTarefas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnFechar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icones/fechar2.png"))); // NOI18N btnFechar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnFecharMouseClicked(evt); } }); painelTarefas.add(btnFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(1195, 0, 25, 25)); getContentPane().add(painelTarefas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1220, 40)); jMenu4.setText("Comandos"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0)); jMenuItem1.setText("Infomar Quantidade"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu4.add(jMenuItem1); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0)); jMenuItem2.setText("Finalizar a Venda"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu4.add(jMenuItem2); jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0)); jMenuItem3.setText("Tabela de Produtos"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu4.add(jMenuItem3); jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0)); jMenuItem4.setText("Excluir Produto da Tabela"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu4.add(jMenuItem4); jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F7, 0)); jMenuItem5.setText("Cancelar a Venda"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu4.add(jMenuItem5); jMenuBar1.add(jMenu4); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents private void jbCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbCancelarMouseClicked cancelarMetodo(); }//GEN-LAST:event_jbCancelarMouseClicked private void jbProdutosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbProdutosMouseClicked produtosMetodo(); }//GEN-LAST:event_jbProdutosMouseClicked private void jbFinalizarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbFinalizarMouseClicked finalizarMetodo(); }//GEN-LAST:event_jbFinalizarMouseClicked private void jbQuantidadeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbQuantidadeMouseClicked quantidadeMetodo(); }//GEN-LAST:event_jbQuantidadeMouseClicked private void jbExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbExcluirMouseClicked excluirMetodo(); }//GEN-LAST:event_jbExcluirMouseClicked private void jtfCodProdutoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodProdutoKeyPressed pegarConteudo(evt); }//GEN-LAST:event_jtfCodProdutoKeyPressed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void btnFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFecharMouseClicked fechar(); }//GEN-LAST:event_btnFecharMouseClicked private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed produtosMetodo(); }//GEN-LAST:event_jMenuItem3ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed quantidadeMetodo(); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed finalizarMetodo(); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed excluirMetodo(); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed cancelarMetodo(); }//GEN-LAST:event_jMenuItem5ActionPerformed public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewPDV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewPDV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewPDV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewPDV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewPDV().setVisible(true); } }); } private void pegarConteudo(java.awt.event.KeyEvent e) { jlStatus.setText("Venda Aberta"); DefaultTableModel modelo = (DefaultTableModel) jtProdutos.getModel(); if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { try { modelProdutos = controllerProdutos.retornarProdutoController(Integer.parseInt(jtfCodProduto.getText())); modelo.addRow(new Object[]{ modelo.getRowCount() + 1, modelProdutos.getIdProduto(), modelProdutos.getProNome(), quantidade, modelProdutos.getProValor(), modelProdutos.getProValor() * quantidade }); String convertido = String.valueOf(somaValorTotal()); jtfValorBruto.setText(convertido); jtfCodProduto.setText(""); quantidade = 1; } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Você deve informar apenas numeros neste campo", "ERRO", JOptionPane.ERROR_MESSAGE); } } } private float somaValorTotal() { float soma = 0, valor = 0; int cont = jtProdutos.getRowCount(); for (int i = 0; i < cont; i++) { valor = Float.parseFloat(String.valueOf(jtProdutos.getValueAt(i, 5))); soma += valor; } return soma; } private void salvarVenda() { int cont; int codigoProduto = 0, codigoVenda = 0; modelVendas = new ModelVendas(); modelVendas.setCliente(1); try { modelVendas.setVenDataVenda(bLDatas.converterDataParaDateUS(new java.util.Date(System.currentTimeMillis()))); } catch (Exception ex) { Logger.getLogger(ViewPDV.class.getName()).log(Level.SEVERE, null, ex); } modelVendas.setVenValorBruto(Double.parseDouble(jtfValorBruto.getText())); modelVendas.setVenDesconto(viewPagamentoPDV.getDesconto()); modelVendas.setVenValorLiquido(bLMascaras.arredondamentoComPontoDuasCasasFDouble(viewPagamentoPDV.getValorTotal())); codigoVenda = controllerVendas.salvarVendasController(modelVendas); cont = jtProdutos.getRowCount(); for (int i = 0; i < cont; i++) { codigoProduto = (int) jtProdutos.getValueAt(i, 1); modelVendasProdutos = new ModelVendasProdutos(); modelProdutos = new ModelProdutos(); modelVendasProdutos.setProduto(codigoProduto); modelVendasProdutos.setVendas(codigoVenda); modelVendasProdutos.setVenProValor((double) jtProdutos.getValueAt(i, 4)); modelVendasProdutos.setNomeProduto(jtProdutos.getValueAt(i, 2).toString()); modelVendasProdutos.setVenProQuantidade(Integer.parseInt(jtProdutos.getValueAt(i, 3).toString())); modelProdutos.setIdProduto(codigoProduto); modelProdutos.setProEstoque(controllerProdutos.retornarProdutoController(codigoProduto).getProEstoque() - Integer.parseInt(jtProdutos.getValueAt(i, 3).toString())); listaModelVendasProdutoses.add(modelVendasProdutos); listaModelProdutos.add(modelProdutos); } if (controllerVendasProdutos.salvarVendasProdutosController(listaModelVendasProdutoses)) { controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos); JOptionPane.showMessageDialog(this, "Salvo com sucesso", "AVISO", JOptionPane.WARNING_MESSAGE); limparTela(); } else { JOptionPane.showMessageDialog(this, "Erro ao Salvar Produtos da venda", "ERRO", JOptionPane.ERROR_MESSAGE); } } private void imprimirCupom(ArrayList<ModelVendasProdutos> listaModelVendasProdutoses, ModelVendas modelVendas) { String dataF = "dd/MM/yyyy"; String horaF = "H:mm - a"; String data, hora; java.util.Date tempoAtual = new java.util.Date(); SimpleDateFormat formata = new SimpleDateFormat(dataF); data = formata.format(tempoAtual); formata = new SimpleDateFormat(horaF); hora = formata.format(tempoAtual); String conteudoImprimir = ""; for (int i = 0; i < listaModelVendasProdutoses.size(); i++) { conteudoImprimir += +listaModelVendasProdutoses.get(i).getVenProQuantidade() + " " + listaModelVendasProdutoses.get(i).getVenProValor() + " " + listaModelVendasProdutoses.get(i).getNomeProduto() + "\n\r"; } this.imprimir("Well's Burger\n\r" + "<NAME>,\n\r" + "553 Nova Odessa\n\r" + "--------------------------------\n\r" + " CUPOM NÃO FISCAL " + "--------------------------------\n\r" + "QT PRECO DESCRICAO\n\r" + conteudoImprimir + "" + "--------------------------------\n\r" + "VALOR BRUTO: " + modelVendas.getVenValorBruto() + "\n\r" + " DESCONTO: " + modelVendas.getVenDesconto() + "\n\r" + "VALOR TOTAL: " + modelVendas.getVenValorLiquido() + "\n\r" + "--------------------------------\n\r" + data + " - " + hora + "\n\r" + "\n\r \n\r" + " OBRIGADO E VOLTE SEMPRE\n\r " + "\n\r \n\r\f" ); } public void imprimir(String pTexto) { try { InputStream prin = new ByteArrayInputStream(pTexto.getBytes()); DocFlavor docFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE; SimpleDoc documentoTexto = new SimpleDoc(prin, docFlavor, null); PrintService impressora = PrintServiceLookup.lookupDefaultPrintService(); PrintRequestAttributeSet printerAttributes = new HashPrintRequestAttributeSet(); printerAttributes.add(new JobName("Impressao", null)); printerAttributes.add(OrientationRequested.PORTRAIT); printerAttributes.add(MediaSizeName.ISO_A4); DocPrintJob printJob = impressora.createPrintJob(); try { printJob.print(documentoTexto, (PrintRequestAttributeSet) printerAttributes); } catch (PrintException e) { JOptionPane.showMessageDialog(null, "Não foi possivel realizar a impressão!", "Erro", JOptionPane.ERROR_MESSAGE); } prin.close(); } catch (Exception e) { } } private void limparTela() { jtfValorBruto.setText(""); jtfDesconto.setText(""); jtfValorTotal.setText(""); DefaultTableModel modelo = (DefaultTableModel) jtProdutos.getModel(); modelo.setNumRows(0); jlStatus.setText("Caixa Livre"); } private void fechar() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja fechar o Programa?", "Encerrando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { dispose(); new ViewMenuPrincipal().setVisible(true); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } private void alinharTabela(){ DefaultTableCellRenderer esquerda = new DefaultTableCellRenderer(); DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer(); DefaultTableCellRenderer direita = new DefaultTableCellRenderer(); esquerda.setHorizontalAlignment(SwingConstants.LEFT); centralizado.setHorizontalAlignment(SwingConstants.CENTER); direita.setHorizontalAlignment(SwingConstants.RIGHT); jtProdutos.getColumnModel().getColumn(0).setCellRenderer(centralizado); jtProdutos.getColumnModel().getColumn(1).setCellRenderer(centralizado); jtProdutos.getColumnModel().getColumn(2).setCellRenderer(esquerda); jtProdutos.getColumnModel().getColumn(3).setCellRenderer(centralizado); jtProdutos.getColumnModel().getColumn(4).setCellRenderer(centralizado); jtProdutos.getColumnModel().getColumn(5).setCellRenderer(centralizado); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnFechar; private javax.swing.JLabel iconVendas10; private javax.swing.JLabel iconVendas8; private javax.swing.JLabel iconVendas9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel jbCancelar; private javax.swing.JPanel jbExcluir; private javax.swing.JPanel jbFinalizar; private javax.swing.JPanel jbProdutos; private javax.swing.JPanel jbQuantidade; private javax.swing.JLabel jlStatus; private javax.swing.JTable jtProdutos; private javax.swing.JFormattedTextField jtfCodProduto; private javax.swing.JTextField jtfDesconto; private javax.swing.JTextField jtfValorBruto; private javax.swing.JTextField jtfValorTotal; private javax.swing.JLabel labelVendas10; private javax.swing.JLabel labelVendas11; private javax.swing.JLabel labelVendas12; private javax.swing.JLabel labelVendas8; private javax.swing.JLabel labelVendas9; private javax.swing.JPanel painelTarefas; // End of variables declaration//GEN-END:variables private void quantidadeMetodo() { quantidade = Integer.parseInt(JOptionPane.showInputDialog("Informe a quantidade!")); } private void finalizarMetodo() { try { this.viewPagamentoPDV = new ViewPagamentoPDV(this, true); viewPagamentoPDV.setValorTotal(Float.parseFloat(jtfValorBruto.getText())); viewPagamentoPDV.setTextFieldValorTotal(); viewPagamentoPDV.setVisible(true); jtfValorTotal.setText(String.valueOf(viewPagamentoPDV.getValorTotal())); jtfDesconto.setText(String.valueOf(viewPagamentoPDV.getDesconto())); if (viewPagamentoPDV.isStatusVenda()) { salvarVenda(); } else { JOptionPane.showMessageDialog(this, "Pagamento cancelado!"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Você deve adicionar incluir um produto!"); } } private void produtosMetodo() { new ViewTabelaProdutos().setVisible(true); } private void excluirMetodo() { int quantLinha = jtProdutos.getRowCount(); if (quantLinha < 1) { JOptionPane.showMessageDialog(this, "Não existe itens para realizar a exclusão!"); } else { DefaultTableModel modelo = (DefaultTableModel) jtProdutos.getModel(); int linha = Integer.parseInt((JOptionPane.showInputDialog("Informe o item que deseja excluir"))); modelo.removeRow(linha - 1); String convertido = String.valueOf(somaValorTotal()); jtfValorBruto.setText(convertido); for (int i = 0; i < quantLinha; i++) { modelo.setValueAt(i + 1, i, 0); } } } private void cancelarMetodo() { int intOpcao = JOptionPane.showOptionDialog(null, "Deseja Cancelar a venda?", "Cancelando", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (intOpcao == 0) { limparTela(); } else { this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); } } }
b07866a01e31c47c953678685c41adf8af4acafe
[ "Markdown", "Java" ]
9
Java
igorcavichiolle/SistemaPdvWellsBurguer
6239867281d8da4dc6aa2c2043725b0cf7769557
9b5e4ccd698de6d04b1a27e0b30faba57b864e97
refs/heads/main
<repo_name>AlexDest-Dev/DE2020_CT1<file_sep>/README.md # DE2020_CT1 DE course 2020, Computational Task 1, <NAME>, BS19-03 <file_sep>/src/de_task/model/methods/ImprovedEulerMethod.java package de_task.model.methods; import de_task.model.base.NumericalMethod; public class ImprovedEulerMethod extends NumericalMethod { public ImprovedEulerMethod(){super();} public ImprovedEulerMethod(double x0, double y0, double X, int N) { super(x0, y0, X, N); } @Override public Double getFunctionResult(Double x, Double... y) { double step = this.getStep(); double interMainFunction = NumericalMethod.mainFunction.getFunctionResult(x, y[0]); return y[0] + (step / 2) * (interMainFunction + NumericalMethod.mainFunction.getFunctionResult(x + step, y[0] + step * interMainFunction)); } } <file_sep>/src/de_task/model/ExactFunction.java package de_task.model; import de_task.model.base.IFunction; import static java.lang.Math.sin; import static java.lang.Math.sqrt; public class ExactFunction implements IFunction<Double> { Double initX, initY, constant; public ExactFunction(Double initX, Double initY) { this.initX = initX; this.initY = initY; } public ExactFunction(){} @Override public Double getFunctionResult(Double x, Double... y) { constant = calculateConstant(initX, initY); return (sin(x) + constant)*(sin(x) + constant)/(x*x); } public void setInitialValues(Double initX, Double initY) { this.initX = initX; this.initY = initY; } private Double calculateConstant(Double x, Double y) { if(initX < 0) { return -1*sqrt(x*x*y) - sin(x); } return sqrt(x*x*y) - sin(x); } } <file_sep>/src/de_task/model/errors/GlobalTruncationErrors.java package de_task.model.errors; import de_task.model.base.Errors; import de_task.model.base.NumericalMethod; import de_task.model.base.Point; import javafx.scene.chart.XYChart; import java.util.Collections; import java.util.List; import static java.lang.Math.abs; public class GlobalTruncationErrors extends Errors { public GlobalTruncationErrors(){super();} @Override public void calculateErrors(NumericalMethod method) { this.getErrors().clear(); List<Point<Double>> methodPoints = method.getGrid(); //if (method.getX0() < 0) Collections.reverse(methodPoints); this.getErrors().add(new Point<>(methodPoints.get(0).getX(), 0.0)); for(int i = 1; i < methodPoints.size(); i++) { Double tempX = methodPoints.get(i).getX(); Double exactY = NumericalMethod.exactFunction.getFunctionResult(tempX); Double tempY = methodPoints.get(i).getY(); Point<Double> tempPoint = new Point<>(tempX, abs(exactY - tempY)); this.getErrors().add(tempPoint); } } } <file_sep>/src/de_task/model/base/Grid.java package de_task.model.base; import java.util.ArrayList; import java.util.List; public class Grid<T extends Number> { private List<Point<T>> grid; public Grid() { grid = new ArrayList<>(); } public void addPoint(T x, T y) { grid.add(new Point<>(x, y)); } public void addPoint(Point<T> point) { grid.add(point); } public List<Point<T>> getGrid() { return grid; } public Point<T> getPoint(int index) { return grid.get(index); } } <file_sep>/src/de_task/model/methods/RungeKutta.java package de_task.model.methods; import de_task.model.base.NumericalMethod; public class RungeKutta extends NumericalMethod { public RungeKutta(){super();} public RungeKutta(double x0, double y0, double X, int N) { super(x0, y0, X, N); } @Override public Double getFunctionResult(Double x, Double... y) { double step = this.getStep(); double k1 = mainFunction.getFunctionResult(x, y[0]); double k2 = mainFunction.getFunctionResult(x+step/2, y[0]+(step/2)*k1); double k3 = mainFunction.getFunctionResult(x+step/2, y[0]+(step/2)*k2); double k4 = mainFunction.getFunctionResult(x+step, y[0]+step*k3); return y[0] + (step/6)*(k1+2*k2+2*k3+k4); } } <file_sep>/src/de_task/model/errors/GlobalMethodsErrors.java package de_task.model.errors; import de_task.model.base.Errors; import de_task.model.base.NumericalMethod; import de_task.model.base.Point; import javafx.scene.chart.XYChart; import java.util.List; public class GlobalMethodsErrors extends Errors { private int n0, N; public GlobalMethodsErrors(){super();} public GlobalMethodsErrors(int n0, int N) { this.n0 = n0; this.N = N; } @Override public void calculateErrors(NumericalMethod method) { this.getErrors().clear(); GlobalTruncationErrors localErrors = new GlobalTruncationErrors(); for (Integer i = this.n0; i <= this.N; i++) { method.getSolution(method.getX0(), method.getY0(), method.getX(), i); localErrors.calculateErrors(method); List<Point<Double>> tempLocalErrors = localErrors.getErrors(); Point<Double> maxError = new Point<>(0.0, -1.0); for (int j = 0; j < tempLocalErrors.size(); j++) { if (tempLocalErrors.get(j).getY() > maxError.getY()) { maxError = tempLocalErrors.get(j); } } this.getErrors().add(new Point<Double>(Double.valueOf(i), maxError.getY())); } } public void setInitialValues(int n0, int N) { this.n0 = n0; this.N = N; } } <file_sep>/src/de_task/model/base/IFunction.java package de_task.model.base; public interface IFunction <T extends Number> { public T getFunctionResult(T x, T... y); }
65b7b1bf68e9aaaf00ca54a4ca924a874e499dc1
[ "Markdown", "Java" ]
8
Markdown
AlexDest-Dev/DE2020_CT1
112391298a16c827ba2b0ef966a3797659be0988
baa077011958c829808b44ee51008c683f9a46c5
refs/heads/master
<file_sep>rootProject.name='Db_T_2' include ':app' <file_sep># SQLite Database Example Android App by d4rk-lucif3r ![Google Phone](https://img.shields.io/badge/Android-Lollipop+-blue.svg?logo=google&longCache=true&style=flat-square) - This App uses the SQlite Database in Android. # Description - The main activity consists of: - 4 TextViews and 4 EditTexts for Name, Surname , Marks , And ID. - 4 Buttons for Adding, Showing, Deleting and Updating Data into Datadase. ## Usage **Sqlite Database** is a software library that provides a relational database management system. The lite in SQLite means light weight in terms of setup, database administration, and required resource. SQLite has the following noticeable features: self-contained, serverless, zero-configuration, transactional. ## Working - As soon as the app is installed it creates as database named as lucifer and a table named as Student containing 4 columns ID which is the primary key and of integer typr , Name string type , Surname String type , Marks Integer type. - Data is fed into the database through the Edittexts and then pressing **Add** Button. - Data is pulled from database by usimg **Show** button. - Data is deleted from Database using **Delete** Button. - To update data in Database, updated data is entered through edittexts and updated on the basis of ID usimg **update** Button. ## Screenshot ![Preview](https://github.com/arshanwar/SQLite-Database-Example-Android-App/blob/master/Preview.jpg) <file_sep>package com.lucifer.db_t_2; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Databasehelper mydb; EditText name,surname,marks,id; Button add,show,update,delete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb =new Databasehelper(this); name =(EditText) findViewById(R.id.NAME_EDIT); surname =(EditText) findViewById(R.id.SUR_EDIT); marks =(EditText) findViewById(R.id.MARKS_EDIT); id =(EditText) findViewById(R.id.id_edit); add =(Button)findViewById(R.id.add); update =(Button)findViewById(R.id.update); show =(Button)findViewById(R.id.show); delete =(Button)findViewById(R.id.delete); adddata(); viewall(); updatedata(); deletedata(); } public void adddata(){ add.setOnClickListener(new View.OnClickListener() { @SuppressLint("ShowToast") @Override public void onClick(View v) { boolean isInserted = mydb.insertData(name.getText().toString(),surname.getText().toString(),marks.getText().toString()); if(isInserted) Toast.makeText(MainActivity.this,"DATA INSERTED",Toast.LENGTH_SHORT); else Toast.makeText(MainActivity.this,"DATA Not INSERTED",Toast.LENGTH_SHORT); } }); } public void updatedata(){ update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean isupdate = mydb.updatedata(id.getText().toString(),name.getText().toString(),surname.getText().toString(),marks.getText().toString()); if(isupdate) Toast.makeText(MainActivity.this,"DATA updated",Toast.LENGTH_SHORT); else Toast.makeText(MainActivity.this,"DATA Not updated",Toast.LENGTH_SHORT); } }); } public void deletedata(){ delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Integer isdelete = mydb.deletedata(id.getText().toString()); if(isdelete>0) Toast.makeText(MainActivity.this,"DATA deleted",Toast.LENGTH_SHORT); else Toast.makeText(MainActivity.this,"DATA Not deleted",Toast.LENGTH_SHORT); } }); } public void viewall(){ show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor res = mydb.getalldata(); if(res.getCount() == 0){ showMessage("error","nothing found"); return; } StringBuffer buffer =new StringBuffer(); while(res.moveToNext()){ buffer.append("ID:"+res.getString(0)+"\n"); buffer.append("NAME:"+res.getString(1)+"\n"); buffer.append("SURNAME:"+res.getString(2)+"\n"); buffer.append("MARKS:"+res.getString(3)+"\n\n"); showMessage("Data",buffer.toString()); } } });} public void showMessage(String title, String Message) { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(Message); builder.show(); } }
2263fae242bcc5aaec52bbaa608b9d3db0eadb1b
[ "Markdown", "Java", "Gradle" ]
3
Gradle
d4rk-lucif3r/SQLite-Database-Example-Android-App
2876a962ce177e34a5d2e7989f5181533f4d2167
8a6c1fc5a4ac57370df35366694148ac553a3933
refs/heads/master
<repo_name>sgshy1995/static-server-nodejs<file_sep>/public/main.js console.log('这是一个静态页面,当你看到我时,说明你搭建成功啦!')<file_sep>/README.md ## 静态服务器 使用 Node.js 构建的静态服务器。 ### 使用环境 首先,保证你已安装 [Node.js](https://nodejs.org/zh-cn/download/),如已安装请忽略。 ### 创建静态资源目录 你的静态文件目录默认需要放在 `./public/`,你可以在 server.js 中做出设置。 ### 创建服务环境 指定端口(必须)。 ```sh # 标准命令格式 node server.js port ``` 在 8080 端口的示例: ```sh # 生产环境 node server.js 8080 ``` 如果是本地开发环境,推荐使用 [node-dev](https://www.npmjs.com/package/node-dev)。 ```sh # 开发环境 npm install -g node-dev node-dev server.js 8080 ``` ### 本地预览 如果按照示例方法使用服务器,现在你可以在本地预览你的静态页面了。 `http://localhost:8080` ### 关于服务器 现在服务器只支持下面几种文件: - html - css - js - json - jpg - jpeg - png - gif - mp3 如有需要,可以继续配置,添加 `pathStyle` 的内容即可。<file_sep>/server.js /* 初始化 */ var http = require('http') var fs = require('fs') var url = require('url') var port = process.argv[2] if (!port) { console.log('请指定端口号') process.exit(1) } var server = http.createServer(function (request, response) { var parsedUrl = url.parse(request.url, true) var pathWithQuery = request.url var queryString = '' if (pathWithQuery.indexOf('?') >= 0) { queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) } var path = parsedUrl.pathname var query = parsedUrl.query var method = request.method /* 服务器启动 */ console.log('总路径为:' + pathWithQuery) const userPath = path === '/' ? '/index.html' : path const index = path.lastIndexOf('.') const suffix = userPath.substr(index) const pathStyle = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'text/json', '.jpg': 'image/jpg', '.png': 'image/png', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.mp3': 'audio/mp3' } response.statusCode = 200 response.setHeader('Content-Type', `${pathStyle[suffix] || 'text/html'};charset=utf-8`) try { response.write(fs.readFileSync(`./public${userPath}`)) } catch (error) { response.statusCode = 404 response.write(fs.readFileSync(`./public/404.html`)) } response.end() }) /* 监听端口 */ server.listen(port) console.log('监听端口' + port + '成功') console.log('本地地址为 http://localhost:' + port)
0bf4e6056a6f84f3349a1005a51d060cb0d22806
[ "JavaScript", "Markdown" ]
3
JavaScript
sgshy1995/static-server-nodejs
d44addab753ae87c6de4de8489aaa91981b6c09b
6210e10780e2ad61e1dd448ea3a9390473fc104e
refs/heads/master
<repo_name>CwBear/web<file_sep>/Controlador/CProducto.php <?php include_once 'Modelo/Producto.php'; class CProducto { private $catalogo = []; private $carrito = []; public function getCatalogo() { return $this->catalogo; } public function getCarrito() { return $this->carrito; } public function agregarAlCatalogo(Producto $producto) { array_push($this->catalogo, $producto); } public function agregarAlCarrito(Producto $producto) { array_push($this->carrito, $producto); } } if(!(isset($_SESSION["CProducto"]))){ $cproducto = new CProducto(); $productoNuevo = new Producto(1, "Producto 1", 1000, 10); $cproducto->agregarAlCatalogo($productoNuevo); $_SESSION["catalogo"] = serialize($cproducto); $_SESSION["CProducto"] = "si"; } if(isset($_POST["idN"])){ $idPNuevo = $_POST["idN"]; $nombrePNuevo = $_POST["nombreN"]; $precioPNuevo = $_POST["precioN"]; $cantidadPNuevo = $_POST["cantidadN"]; $productoNuevo = new Producto($idPNuevo, $nombrePNuevo, $precioPNuevo, $cantidadPNuevo); $cproductoT = unserialize($_SESSION["catalogo"]); $cproductoT->agregarAlCatalogo($productoNuevo); $_SESSION["catalogo"] = serialize($cproductoT); } if(isset($_POST["idCarrito"])){ foreach (unserialize($_SESSION["catalogo"])->getCatalogo() as $prod){ if($prod->getId() == $_POST["idCarrito"]){ $cproductoT = unserialize($_SESSION["catalogo"]); $cproductoT->agregarAlCarrito($prod); $_SESSION["catalogo"] = serialize($cproductoT); break; } } }<file_sep>/index.php <!DOCTYPE html> <?php session_start(); include_once 'Modelo/Cliente.php'; include_once 'Controlador/CCliente.php'; include_once 'Controlador/CProducto.php'; ?> <html> <head> <meta charset="UTF-8"> <link href="css/Style.css" rel="stylesheet" type="text/css"/> <title>Storaged Gamin</title> <meta name="author" > </head> <style> body{ background-image: url( img/inicio.jpg ) } </style> <body> <h1 id="Titulonegro">Storaged Gaming</h1> <?php if(isset($_SESSION["user"])){?> <div><?php echo ("Bienvenido, ".unserialize($_SESSION["user"])->getNombre());?> </div> <br> <?php if(unserialize($_SESSION["user"])->getTelefono() == 123456789){?> <div> <a href="admin.php">Registrar producto</a> </div><br><?php } } if(!(isset($_SESSION["user"]))){?> <nav id="navegador"> <div > <a href="login.php" class="barra-usuario">Iniciar Sesión</a> </div> <br> <div> <a href="RegistrarUsuario.php" class="barra-usuario">Registrar Usuario</a> </div> </nav> <?php }else{?> <div> <a href="Controlador/LogOut.php" class="barra-usuario">Salir de la Sesión</a> </div> <?php }?> <br> <br> <div> <p id="parrafo">Su carro de compra:</p> </div> <br> <div><?php if(isset(unserialize($_SESSION["catalogo"])->getCarrito()[0])){ foreach(unserialize($_SESSION["catalogo"])->getCarrito() as $item){ ?> <div class="item"> <br><?php echo ($item->getNombre());?><br> <img src="Img/1.jpeg" alt="" width=100" height="100"/> <br> <?php echo ("Precio: $".$item->getPrecio());?> <br> <?php echo ("En stock: ".$item->getCantidad());?> </div> <?php } }else{ ?> <br> <div> <label>Su carrito está vacío.</label> </div> <br> <?php } ?> </div> <?php if(isset(unserialize($_SESSION["catalogo"])->getCarrito()[0])){ ?> <div> <a href="Compra.php" >Hacer Compra</a> </div> <?php } ?> <br> <div> <p id= "catalogo">Catálogo</p> </div> <br> <div><?php foreach (unserialize($_SESSION["catalogo"])->getCatalogo() as $prod){?> <div class="producto"> <br><?php echo ($prod->getNombre());?><br> <img src="img/1.jpeg" alt="" width=200" height="270"/> <br><?php echo ("Precio: $".$prod->getPrecio());?> <br> <?php echo ("En stock: ".$prod->getCantidad());?> <form action="index.php" method="POST"> <input type="hidden" name="idCarrito" value=<?php echo($prod->getId()); ?>><br> <input type="submit" value="Agregar al Carrito"> </form> <br> </div><?php }?> </div> </body> </html> <file_sep>/Controlador/CCliente.php <?php include_once 'Modelo/Cliente.php'; class CCliente { private $clientes = []; public function getClientes(){ return $this->clientes; } public function agregarCliente(Cliente $cliente) { array_push($this->clientes, $cliente); } } if(!(isset($_SESSION["instanciaCCliente"]))){ $ccliente = new CCliente(); $admin = new Cliente(123456789, "admin", "admin"); $ccliente->agregarCliente($admin); $_SESSION["clientes"] = serialize($ccliente); $_SESSION["instanciaCCliente"] = "si"; } if(isset($_POST["telefonoNuevo"])){ $idUnico = true; foreach (unserialize($_SESSION["clientes"])->getClientes() as $value){ if($value->getTelefono() == $_POST["telefonoNuevo"]){ $idUnico = false; break; } } if($idUnico){ if($_POST["passNuevo"] === $_POST["passNConfirm"]){ $telefonoNuevo = $_POST["telefonoNuevo"]; $nombreNuevo = $_POST["nombreNuevo"]; $passNueva = $_POST["<PASSWORD>"]; $clienteNuevo = new Cliente($telefonoNuevo, $nombreNuevo, $passNueva); $cclienteT = unserialize($_SESSION["clientes"]); $cclienteT->agregarCliente($clienteNuevo); $_SESSION["clientes"] = serialize($cclienteT); } } } if(isset($_POST["telefono"])){ foreach (unserialize($_SESSION["clientes"])->getClientes() as $value) { if($value->getTelefono() == $_POST["telefono"] && $value->getPass() == $_POST["pass"]){ $_SESSION["user"] = serialize($value); break; } } } <file_sep>/Compra.php <?php session_start(); include_once 'Modelo/Venta.php'; include_once 'Modelo/Cliente.php'; include_once 'Controlador/CProducto.php'; ?> <html> <head> <meta charset="UTF-8"> </head> <style> body{ background-image: url( img/money_dollar_bills-75751.jpg) } </style> <body> <?php if(isset($_SESSION["user"])){ $total = 0; foreach(unserialize($_SESSION["catalogo"])->getCarrito() as $item){ $total = $total + $item->getPrecio(); $fecha = date("jnY"); $idProducto = $item->getId(); $idCliente = unserialize($_SESSION["user"])->getTelefono(); $venta = new Venta($fecha, $idProducto, $idCliente); ?> <div> <div> <label> <?php echo ("ID del producto: ".$item->getId()); ?> </label> </div> <div> <label> <?php echo ($item->getNombre()); ?> </label> </div> <img src="img/1.jpeg" alt="" width=200" height="270"/> <div> <label> <?php echo ("Cantidad disponible: ".$item->getCantidad()); ?> </label> </div> <div> <label> <?php echo ("Precio: $".$item->getPrecio()); ?> </label> </div> </div> <?php } ?> <div> <label> <?php echo ("Total: $".$total); ?> </label> </div> <div> <a href="index.php">Volver</a> </div> <?php }else{ ?> <div> <label>Inicie sesión para poder comprar.</label> </div> <div> <a href="index.php" >Volver</a> </div> <?php } ?> </body> </html><file_sep>/Modelo/Cliente.php <?php class Cliente { private int $telefono; private string $nombre; private string $pass; public function __construct(int $telefono, string $nombre, string $pass) { $this->setTelefono($telefono); $this->setNombre($nombre); $this->setPass($pass); } public function getTelefono(){ return $this->telefono; } public function setTelefono(int $telefono){ $this->telefono = $telefono; } public function getNombre(){ return $this->nombre; } public function setNombre(string $nombre){ $this->nombre = $nombre; } public function getPass(){ return $this->pass; } public function setPass(string $pass){ $this->pass = $pass; } } <file_sep>/RegistrarUsuario.php <?php session_start(); ?> <html> <head> <meta charset="UTF-8"> <link href="css/Style.css" rel="stylesheet" type="text/css"/> </head> <style> body{ background-image: url( img/registro.jpg) } </style> <body> <h2 id="titulo-blanco">Registrar Usuario Nuevo</h2> <form class = "formulario" action="index.php" method="POST"> <div class="contenedor"> <div class="input-contenedor"> <label id="text-registro">Ingrese su número de teléfono:</label> <input type="number" name="telefonoNuevo" required maxlength="9"> </div> <div class="input-contenedor"> <label>Ingrese el nombre del usuario:</label> <input type="text" name="nombreNuevo" required maxlength="20"> </div> <div class="input-contenedor"> <label>Ingrese la contraseña:</label> <input type="<PASSWORD>" name="pass<PASSWORD>" required maxlength="20"> </div> <div class="input-contenedor"> <label>Ingrese de nuevo la contraseña:</label> <input type="<PASSWORD>" name="<PASSWORD>" required maxlength="20"> </div > <input type="submit" value="Registrarme"> </div> </form> <br> <div id="btnVolverRegistrarUsuario"> <a href="index.php">Volver al Inicio</a> </div> </body> </html><file_sep>/admin.php <?php session_start(); ?> <html> <head> <meta charset="UTF-8"> </head> <body> <h2>Registrar Producto Nuevo</h2> <form id="formRegistrarProducto" action="index.php" method="POST"> <label>Ingrese el número de identificación:</label> <input type="number" name="idN" required maxlength="9"> <br> <br> <label>Ingrese el nombre:</label> <input type="text" name="nombreN" required maxlength="30"> <br> <br> <label>Ingrese el precio:</label> <input type="number" name="precioN" required maxlength="7"> <br> <br> <label>Ingrese la cantidad disponible:</label> <input type="number" name="cantidadN" required maxlength="4"> <br> <br> <label>Ingrese caratula del video juego:</label> <input type="file" name="fotoN" multiple> <br> <br> <input type="submit" value="Registrar producto"> </form> <br> <div> <a href="index.php">Volver al Inicio</a> </div> </body> </html><file_sep>/login.php <?php session_start(); ?> <html> <head> <meta charset="UTF-8"> <link href="css/Style.css" rel="stylesheet" type="text/css"/> </head> <style> body{ background-image: url( img/iniciosesion.jpg) } </style> <body> <h2 id="titulo-blanco">Ingresar al Sistema</h2> <form class="formulario" action="index.php" method="POST"> <div class="contenedor"> <div class="input-contenedor"> <input type="number" name="telefono" placeholder="Ingrese su teléfono" required maxlength="9"> </div> <div class="input-contenedor"> <input type="<PASSWORD>" name="pass" placeholder="Ingrese su contraseña" required maxlength="20"> </div> <input type="submit" value="Iniciar Sesión"> </div> </form> <br> <div> <a href="index.php">Volver al Inicio</a> </div> </body> </html>
32dcc7fe1d97c92fa8dc9a8230a0cf160acc1ce1
[ "PHP" ]
8
PHP
CwBear/web
ddd041ffc658d9b1839639633d3818edc21e500f
40d00772d5de45e340368048f0f344553587b0cd
refs/heads/master
<repo_name>seunx/webdb-challenge<file_sep>/server/seeds/001-actions.js exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex("actions") .del() .then(function() { // Inserts seed entries return knex("actions").insert([ { id: 1, name: "Fork Project", description: "Clone the project then fork it", notes: "Add PM", completed: true, project: 1 }, { id: 2, name: "Complete Project", description: "Complete MVP", notes: "Meet all requirements", completed: false, project: 1 }, { id: 3, name: "Finish Stretch", description: "Complete all 3 stretch tasks", notes: "Mvp done, stretch next", completed: true, project: 2 }, { id: 4, name: "Study for Sprint", description: "Review WebDB-III/IV", notes: "Review difficult materials", completed: true, project: 2 } ]); }); }; <file_sep>/server/projects/index.js const express = require("express"); const db = require("../database/dbHelpers"); const router = express.Router(); /* Route: /api/projects Method: Get Returns: all projects in the database */ router.get("/", async (req, res) => { try { const data = await db.getProject(); res.status(200).json(data); } catch (err) { res.status(500).json({ err, message: "Internal Server Error!" }); } }); /* Route: /api/projects/id Method: GET Returns: project based on ID */ router.get("/:id", async (req, res) => { try { const data = await db.getProject(req.params.id); if (data.length === 0) { res.status(404).json({ message: "ID not found!" }); } res.status(200).json(data); } catch (err) { res.status(500).json({ err, message: "Internal Server Error!" }); } }); /* Route: /api/projects Method: Post Returns: Number of records inserted. Inserts a project into the database Parameters: *name: string, *description: string, *completed: boolean * required field */ router.post("/", async (req, res) => { try { const data = await db.addProject(req.body); res.status(201).json(data); } catch (err) { res.status(500).json({ err, message: "Internal Server Error!" }); } }); router.delete("/:id", async (req, res) => { try { const data = await db.delProject(req.params.id); if (!data) { res.status(404).json({ message: "ID not found!" }); } res.status(204).json(data); } catch (err) { res.status(500).json({ err, message: "Internal Server Error!" }); } }); router.put("/:id", async (req, res) => { try { const data = await db.updateProject(req.params.id, req.body); res.status(200).json(data); } catch (err) { res.status(500).json({ err, message: "Internal Server Error!" }); } }); module.exports = router; <file_sep>/server/database/dbHelpers.js const knex = require("knex"); const config = { client: "sqlite3", connection: { filename: "./database/dev.sqlite3" }, useNullAsDefault: true }; const db = knex(config); /* getProject takes optional parameter ID which would return a project based on that ID. !ID get project returns all projects in the database SQL SELECT * FROM projects || SELECT * FROM projects WHERE projects.id = ID */ const getProject = async id => { if (id) { const projects = await db("projects") .first() .where({ id }); const actions = await db("projects as p") .join("actions as a", "p.id", "a.project") .where({ "a.project": id }); const project = { ...projects, actions: actions }; return project; } return db("projects"); }; /* getAction takes optional parameter ID which would return the action related to the ID. !ID getAction returns all actions in the database SQL SELECT * FROM actions || SELECT * FROM actions WHERE actions.id = ID */ const getAction = id => { if (id) { return db("actions") .first() .where({ id }); } return db("actions"); }; /* addAction inserts a new action into the database. required fields: name, description, completed, project optional fields: notes SQL INSERT INTO actions (name, description, notes, completed, project) VALUES ("name", "description", "notes", "true/false", "project id") */ const addAction = action => { return db("actions").insert(action); }; const updateAction = (id, change) => { return db("actions") .where({ id }) .update(change); }; const delAction = id => { return db("actions") .where({ id }) .del(); }; /* addProject inserts a new project into the database. required fields: name, description, completed SQL INSERT INTO projects (name, description, completed) VALUES ("name", "description", "true/false",) */ const addProject = project => { return db("projects").insert(project); }; const delProject = id => { return db("projects") .where({ id }) .del(); }; const updateProject = (id, change) => { return db("projects") .where({ id }) .update(change); }; // Function to test db helper methods without endpoints async function execute() { try { const data = await getProject(2); console.log(data); } catch (err) { console.log(err); } } execute(); module.exports = { getProject, getAction, addAction, addProject, delProject, delAction, updateProject, updateAction };
707d2f4871411a7a5e4cefe5c3ac997099c62f60
[ "JavaScript" ]
3
JavaScript
seunx/webdb-challenge
9c56a066bb9b4bddd6e3c0bf1c6b894b00b93fe9
90a12cb3c87db0d248a00fe503f4f97522b1debd
refs/heads/master
<repo_name>AakashSharma01/AQI-Visualtion<file_sep>/Impact of COVID-19 on AQI.py #!/usr/bin/env python # coding: utf-8 import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.dates import DateFormatter import matplotlib.ticker as ticker get_ipython().run_line_magic('matplotlib', 'inline') Delhi = pd.read_csv(r'Delhi AQI 2020.csv') AnnArbor = pd.read_csv(r'ad_aqi_tracker_data.csv') Delhi['Date'] = pd.to_datetime(Delhi['Date'], format = '%m/%d/%Y') AnnArbor['Date'] = pd.to_datetime(AnnArbor['Date'], format = '%m/%d/%Y') AnnArbor.head() # Create figure and plot space fig, ax = plt.subplots(figsize=(8, 6)) # Add x-axis and y-axis ax.plot('Date', 'PM2.5', data=Delhi,color='lightcoral', linewidth=1) ax.plot('Date', 'PM2.5 AQI Value', data=AnnArbor,color='skyblue', linewidth=1) # Set title and labels for axes ax.set(xlabel="Date", ylabel="PM2.5 AQI Value", title="PM2.5 AQI Value in Delhi & Ann Arbour(2020)") plt.legend(['Delhi','Ann Arbor'],loc=0,frameon=False) # Define the date format date_form = DateFormatter("%m-%d-%y") ax.xaxis.set_major_formatter(date_form) # Ensure a major tick for each week using (interval=1) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) _=plt.xticks(rotation=90) plt.show()
3cb27b1aeffff7a9010fad6aae5dcf147f1b7873
[ "Python" ]
1
Python
AakashSharma01/AQI-Visualtion
c5340f6ccde7f2fb1f5494a10d9b2dedb162ed69
5a3012c57b3032ee6ecc33438c1a2b7319abe6d6
refs/heads/master
<repo_name>deviamsale/vue-iamsale<file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import { stat } from 'fs'; Vue.use( Vuex ) const createStore = () => { return new Vuex.Store({ state: { default_data : null, alias_data : {}, api : $('body').data('api'), domain : $('body').data('domain'), loading_alias : false, }, mutations: { }, actions: { /** Tải tài nguyên mặc định cho layout */ async loadDefaultResources({ state }){ $('#loading-box').removeClass('close'); var send_data = { resource_filters : [ "logo", "favicon", "default_meta", "header_text", "search_categories", "gov", "hotline", "email", "address", "copyright", "social", "feedback", "default_meta" ], prefix_resources : [ "menu", "footer", ] } var headers = { Domain : state.domain } /** home page */ const home_resources = [ "slider", "popularproduct", "adv", "full_adv", "hot_products", "policy", "banners", "tabproduct", "brand", ] const home_prefix = [ "home", "form_subscribe" ] home_resources.forEach((i)=>{ if( send_data.resource_filters.indexOf( i ) === -1 ){ send_data.resource_filters.push(i) } }) home_prefix.forEach((i)=>{ if( send_data.prefix_resources.indexOf( i ) === -1 ){ send_data.prefix_resources.push(i) } }) /** --- end home page ----*/ var res = await axios.post( state.api + 'page-data/resources', send_data, { headers : headers }) res = res.hasOwnProperty('data') ? res.data : {} if(res.success){ state.default_data = res.data ? res.data : {}; } setTimeout(()=>{ $('#loading-box').addClass('close'); $("html, body").animate({ scrollTop: 0 }, 500); }, 100) }, /** Tải tài nguyên cho trang */ async loadPageResource({state}, page){ var send_data = { resource_filters : [], prefix_resources : [] } switch ( page ){ /** load data trang chủ */ // case '' : // send_data.resource_filters = [ // "slider", // "popularproduct", // "adv", // "policy", // "banners", // "tabproduct", // "brand" // ]; // send_data.prefix_resources = [ // "home", // "form_subscribe" // ]; // break; default: break; } if( (send_data.resource_filters.length == 0 && send_data.prefix_resources == 0 ) && page === '' ){ return } send_data.alias = page var headers = { Domain : state.domain } $('#loading-box').removeClass('close'); state.loading_alias = true; if( page !== '' ){ var res = await axios.post( state.api + 'page-data/alias-resources', send_data, { headers : headers }) res = res.hasOwnProperty('data') ? res.data : {} if( res.success ){ state.alias_data = res.data } } state.loading_alias = false; setTimeout(()=>{ $('#loading-box').addClass('close'); $("html, body").animate({ scrollTop: 0 }, 500); }, 100) } } }) } export default createStore<file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HomePage from '@/pages/index' import AliasPage from '@/pages/alias' import CheckOut from '@/components/product/checkout' import Cart from '@/components/product/cart' import User from '@/components/user/index' import ChangePassword from '@/components/user/change-password' import Login from '@/components/user/login' import Register from '@/components/user/register' import Profile from '@/components/user/profile' import UserOrder from '@/components/user/order' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'HomePage', component: HomePage }, { path : '/check-out', name : 'checkout', component : CheckOut }, { path : '/login', name : 'Login', component : Login }, { path : '/register', name : 'Register', component : Register }, { path : '/dashboard', name : 'dashboard', component : User, children : [ { path : '/', name : 'profile', component : Profile }, { path : 'change-password', name : 'change-password', component : ChangePassword }, { path : 'orders', name : 'orders', component : UserOrder } ] }, { path : '/cart', name : 'cart', component : Cart }, { path: '/:alias', name : 'alias', component : AliasPage, }, ], mode: 'history', history: true , }) <file_sep>/src/plugins/helper.js const helper = { domain : $('body').data('domain'), page_structs : ['news', 'contact', 'about', 'product'], getSEOTitle( title, store ){ if( store.state.default_data.default_meta.title ){ return title + ' | ' + store.state.default_data.default_meta.title; } return title; }, alias( alias ){ if( alias.length ){ if( alias[0] == '/' ){ alias = alias.substring(1); } } if( alias != '' && alias != '#' ){ return {name: 'alias', params: {alias : alias } } } return alias; }, clone( object ){ try{ return JSON.parse( JSON.stringify( object ) ); }catch(e){ return null; } } } export default helper
e2cf43308670b1b6575eb10471289c50314a9ac8
[ "JavaScript" ]
3
JavaScript
deviamsale/vue-iamsale
a7fa350145387bd9a7924bd5a30cc9b6396d34b9
0728047aed20e5a864b3f38115c17d2667aedf81
refs/heads/master
<file_sep># Web_Spider_byPython 江南大学教务处课表爬虫 <file_sep># -*- coding:utf-8 -*- # author :Max import re import urllib import urllib2 import cookielib # 通过创建Spider类,用Spider类的两个方法来实现爬虫 class Spider: filename = 'cookie.txt' cookie = cookielib.MozillaCookieJar(filename) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) def __init__(self, url, account, password, xnd, xqd): self.url = url self.account = account self.password = <PASSWORD> self.xnd = xnd self.xqd = xqd def loginWeb(self): message = urllib2.urlopen(self.url).read() __ViewState = re.findall('<input type="hidden" name="__VIEWSTATE" value="(.*?)" />', message) if __ViewState == None: print 'no __VIewState' return headers = {'Connection': 'keep-alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;Miser Report)'} data = urllib.urlencode({ 'TextBox1': self.account, 'TextBox2': self.password, 'RadioButtonList1': 'ѧ��', 'Button1': '', '__VIEWSTATE': __ViewState[0]}) request = urllib2.Request(self.url, data, headers) try: response = Spider.opener.open(request).read().decode('gb2312').encode('utf-8') pattern = '<span id="xhxm">.*? (.*?)同学</span></em>' # name = re.findall(pattern, response) # return name except urllib2.HTTPError, e: print 'HTTPError = ' + e.code return 'Error' def timeTable(self): referer = 'http://jwxt.jiangnan.edu.cn/jndx/xs_main.aspx?xh=' + self.account url = 'http://jwxt.jiangnan.edu.cn/jndx/xskbcx.aspx?xh=' + self.account + '&xm=%D6%DC%BF%C6%D3%F0&gnmkdm=N121603' headers = {'Connection': 'keep-alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;Miser Report)', 'Referer': referer} request_test = urllib2.Request(url, headers=headers) message = Spider.opener.open(request_test).read().decode('gb2312', 'ignore').encode('utf-8') __ViewState = re.findall('<input type="hidden" name="__VIEWSTATE" value="(.*?)" />', message) # print __ViewState[0] # data = urllib.urlencode({'__EVENTTARGET':'xqd','__EVENTARGUMENT':'','__VIEWSTATE':__ViewState[0], # 'xnd':self.xnd,'xqd':self.xqd}) # # # request = urllib2.Request(url,data,headers) # response = Spider.opener.open(request).read().decode('gb2312','ignore').encode('utf-8') # print response lesson_message = [] lesson_table = []*12 for i in range(1,13): pattern = '第'+str(i)+'节(.*?)<td class="noprint" align="Center"' answer = re.findall(pattern,message) lesson_message.append(answer[0]) lesson_classroom = [] lesson_teacher = [] lesson_time = [] lesson_start = [] lesson_name = [] lesson_week = [] for i in range(0,12): pattern = '<td align="Center".*?>(.*?)</td>' lessons = re.findall(pattern,lesson_message[i]) week = 0 for lesson in lessons: week = week + 1 information = lesson.split('<br>') if len(lesson) <30: lesson_start.append(i + 1) lesson_name.append('null') lesson_time.append('null') lesson_classroom.append('null') lesson_teacher.append('null') lesson_week.append(week) continue if information.__len__() > 7: # 上课的名字、时间、教室分别储存在三个列表中 lesson_name.append(information[0]) lesson_time.append(information[2]) lesson_classroom.append(information[4]) lesson_teacher.append(information[3]) lesson_name.append(information[6]) lesson_time.append(information[8]) lesson_teacher.append(information[9]) lesson_classroom.append(information[10]) lesson_start.append(i+1) lesson_start.append(i + 1) lesson_week.append(week) lesson_week.append(week) else: lesson_name.append(information[0]) lesson_time.append(information[2]) lesson_classroom.append(information[4]) lesson_teacher.append(information[3]) lesson_start.append(i+1) lesson_week.append(week) #返回的课程信息储存到数组 lesson_WeekLength = [] lesson_length = [] lesson_Week_Odd_Even = []# Odd_Week or Even Week for i in lesson_time: print i if i == 'null': lesson_WeekLength.append([0,0]) lesson_Week_Odd_Even.append(0) lesson_length.append(0) else: pattern = '第(\d+-\d+)周' answer = re.findall(pattern,i) print answer information = answer[0].split('-') lesson_WeekLength.append([information[0],information[1]]) pattern = '\|(单|双)周' answer = re.search(pattern,i) if answer == None: lesson_Week_Odd_Even.append(0) else: if answer.group(1)=='单': lesson_Week_Odd_Even.append(1) elif answer.group(1) =='双': lesson_Week_Odd_Even.append(2) pattern = '(\d*,?\d*,?\d*,?\d+)节' answer = re.findall(pattern,i) lesson_length_deal = len(answer[0].split(',')) if lesson_length_deal > 1: lesson_length.append(lesson_length_deal) else: lesson_length.append(answer[0]) return lesson_name,lesson_time,lesson_classroom,lesson_teacher,lesson_start,lesson_week,lesson_length,lesson_WeekLength,lesson_Week_Odd_Even if __name__ == "__main__": print 'try spider' url = 'http://jwxt.jiangnan.edu.cn/jndx/default5.aspx' account = '' # 学号 password = '' # 密码 xnd = '2016-2017' # 学年 xqd = '2' # 学期 spider = Spider(url, account, password, xnd, xqd) name = spider.loginWeb() if name == 'Error': print 'Web Login Failed' else: print 'code right' spider.timeTable() print 'run over'
5bc28a9204f902d616c754e203589102b7e916a3
[ "Markdown", "Python" ]
2
Markdown
cheatcodezky/Web_Spider_byPython
593b53a044d928c154e71bd61ccaa7a42ea11a15
9d4c512df9f26ff40a28b6cd239784bb92c92128
refs/heads/master
<file_sep>use bucket_list; db.dropDatabase(); db.items.insertMany([ { item: "take a bubble bath with <NAME>", status: "false" }, { item: "drink a daiquiri in Harry's bar", status: "false" }, { item: "ride a wave", status: "true" }, { item: "fight a pig", status: "false" } ]); <file_sep>const express = require('express'); const createRouter = require('./helpers/router_helper.js'); const server = express(); const path = require('path'); const MongoClient = require('mongodb').MongoClient; const parser = require('body-parser'); const publicPath = path.join(__dirname, '../client/public'); server.use(express.static(publicPath)); server.use(parser.json()); MongoClient.connect('mongodb://localhost:27017') .then((client) => { const db = client.db('bucket_list'); const listItemCollection = db.collection('items'); const router = createRouter(listItemCollection); server.use('/api/list', router); }) .catch(console.error); server.listen(3000, function () { console.log(`Server running on port ${this.address().port}`); }) <file_sep>const PubSub = require('../helpers/pub_sub.js'); const Request = require('../helpers/request.js'); const BucketList = function () { this.url = 'http://localhost:3000/api/list'; this.request = new Request(this.url); }; BucketList.prototype.getData = function () { this.request.get().then( (list) => { PubSub.publish('BucketList:data-loaded', list) }) }; BucketList.prototype.bindEvents = function () { PubSub.subscribe('InputView:item-submitted', (event) => { this.request.post(event.detail).then( (list) => { PubSub.publish('BucketList:data-loaded', list) }) }) PubSub.subscribe('ContainerView:tick-clicked', (event) => { const id = event.detail; // this.request.show(id).then( (object) => { this.request.put(id).then( (list) => { PubSub.publish('BucketList:data-loaded', list) }) // }) }) }; module.exports = BucketList; <file_sep>const PubSub = require('../helpers/pub_sub.js'); const Request = require('../helpers/request.js'); const InputView = function (form) { this.form = form; } InputView.prototype.bindEvents = function () { this.form.addEventListener('submit', (event) => { this.submission(event); }) }; InputView.prototype.submission = function (event) { event.preventDefault(); const newItem = this.createItem(event.target); PubSub.publish('InputView:item-submitted', newItem); event.target.reset(); }; InputView.prototype.createItem = function (form) { const newItem = { item: form.item.value, status: false } return newItem; }; module.exports = InputView; <file_sep>const PubSub = require('../helpers/pub_sub.js'); const ContainerView = function (container) { this.container = container; } ContainerView.prototype.bindEvents = function () { PubSub.subscribe('BucketList:data-loaded', (event) => { this.render(event.detail); }) }; ContainerView.prototype.render = function (list) { this.container.innerHTML = ''; const target = document.querySelector('#list-container'); const bucketList = document.createElement('ul'); target.appendChild(bucketList); list.forEach( (item) => { const listItem = document.createElement('li'); listItem.textContent = `${item.item}`; if (item.status === "true" ){ listItem.classList.add('item-ticked'); } else { const tick = this.createTickButton(item._id); listItem.appendChild(tick); } bucketList.appendChild(listItem); }) }; ContainerView.prototype.createTickButton = function (itemId) { const tickButton = document.createElement('button') tickButton.classList.add('tick-button'); tickButton.textContent = '✓'; tickButton.value = itemId; tickButton.addEventListener('click', (event) => { PubSub.publish('ContainerView:tick-clicked', event.target.value) }) return tickButton; }; module.exports = ContainerView;
938a0b71a59b3627834c574c46eaab29ff42d064
[ "JavaScript" ]
5
JavaScript
MikeBlumenthal/lab_bucket_list
a4819553ddbf5af557a4ba0d8f1175a84e49ec84
c6e591774fb7fd58cc9a7ae898c12a48f88a45f6
refs/heads/master
<repo_name>codesquad-member-2020/photos-2<file_sep>/PhotosApp/PhotosApp/Model/ImageData.swift // // ImageData.swift // PhotosApp // // Created by delma on 2020/03/18. // Copyright © 2020 Codesquad. All rights reserved. // import Foundation struct ImageData { var title: String var image: String var date: String } <file_sep>/PhotosApp/PhotosApp/Controller/DoodleViewController.swift // // DoodleViewController.swift // PhotosApp // // Created by Viet on 2020/03/18. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit class DoodleViewController: UICollectionViewController { let defaultImage = #imageLiteral(resourceName: "defualtImage") var allImages: [UIImage] = [] private let reuseIdentifier = "doodleViewCell" let imageDownloader = ImageDownloader() override func viewDidLoad() { super.viewDidLoad() self.collectionView.backgroundColor = .darkGray self.navigationItem.title = "Doodles" self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(close)) getAllImages() addGestureRecognizerOnImage() } @objc func close() { self.dismiss(animated: true, completion: nil) } func getAllImages(){ imageDownloader.requestImage(handler: { (image) in guard let img = image else { return } self.allImages.append(img) DispatchQueue.main.async { self.collectionView.reloadData() } }) } private func inputImage(cell: UICollectionViewCell, indexPath: IndexPath) { if self.allImages.count != 0, indexPath.item < self.allImages.count { let image = self.allImages[indexPath.item] (cell as! DoodleViewCell).setImage(image) } } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.allImages.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) self.inputImage(cell: cell, indexPath: indexPath) return cell } // MARK: GestureRecognizer func addGestureRecognizerOnImage() { let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleGesture(gesture:))) gestureRecognizer.delegate = self print(gestureRecognizer.minimumPressDuration) collectionView.addGestureRecognizer(gestureRecognizer) } @objc func handleGesture(gesture: UIGestureRecognizer) { let point = gesture.location(in: collectionView) guard let indexPath = collectionView?.indexPathForItem(at: point) else { return } let cell = collectionView.cellForItem(at: indexPath) as! DoodleViewCell let menuItem = UIMenuItem(title: "Save", action: #selector(saveImage)) UIMenuController.shared.menuItems = [menuItem] UIMenuController.shared.showMenu(from: cell, rect: cell.contentView.frame) cell.becomeFirstResponder() } @objc func saveImage() { print("save image") } } extension DoodleViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let point = touch.location(in: collectionView) if let indexPath = collectionView.indexPathForItem(at: point), let _ = collectionView.cellForItem(at: indexPath) { return true } return false } } <file_sep>/PhotosApp/PhotosApp/View/DoodleViewCell.swift // // DoodleViewCell.swift // PhotosApp // // Created by Viet on 2020/03/18. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit class DoodleViewCell: UICollectionViewCell { @IBOutlet var doodleImageView: UIImageView! func setImage(_ image: UIImage) { DispatchQueue.main.async { self.doodleImageView.image = image } } override var canBecomeFirstResponder: Bool { return true } } <file_sep>/PhotosApp/PhotosApp/Model/PhotoLibraryManager.swift // // PhotoLibraryObserver.swift // PhotosApp // // Created by Viet on 2020/03/17. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit import Photos class PhotoLibraryManager: NSObject, PHPhotoLibraryChangeObserver { var allPhotos: PHFetchResult<PHAsset>? = PHAsset.fetchAssets(with: nil) let imageManager = PHCachingImageManager() let imageSize = CGSize(width: 100, height: 100) func requestImage(cell: CollectionViewCell, indexPath: IndexPath) { imageManager.requestImage(for: (allPhotos?[indexPath.row])!, targetSize: imageSize, contentMode: .aspectFill, options: nil) { (image, info) -> Void in if (image != nil) { cell.setImage(image!) } } } func photoLibraryDidChange(_ changeInstance: PHChange) { guard let changed = changeInstance.changeDetails(for: allPhotos!) else { return } allPhotos = changed.fetchResultAfterChanges NotificationCenter.default.post(name: .assetCollectionChanged, object: nil, userInfo: ["changed": changed]) } } <file_sep>/PhotosApp/PhotosApp/Controller/ViewController.swift // // ViewController.swift // PhotosApp // // Created by Viet on 2020/03/16. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit import Photos class ViewController: UIViewController { // MARK: Properties @IBOutlet weak var collectionView: UICollectionView! let dataSource = PhotosCollectionDataSource() private var photoLibraryManager: PhotoLibraryManager? // MARK: Methods override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self.dataSource self.photoLibraryManager = PhotoLibraryManager() setObserver() } func setObserver() { NotificationCenter.default.addObserver(self, selector: #selector(reloadCollectionViewData(_:)), name: .assetCollectionChanged, object: nil) } @IBAction func addButton(_ sender: UIBarButtonItem) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let doodleController = storyboard.instantiateViewController(withIdentifier: "Doodle") let navigationController = UINavigationController(rootViewController: doodleController) present(navigationController, animated: true, completion: nil) } @objc func reloadCollectionViewData(_ notification: Notification) { DispatchQueue.main.async { guard let collectionView = self.collectionView else { return } if let changes = notification.userInfo?["changed"] as? PHFetchResultChangeDetails<PHAsset> { if changes.hasIncrementalChanges { collectionView.performBatchUpdates({ if let removed = changes.removedIndexes, removed.count > 0 { collectionView.deleteItems(at: removed.map { IndexPath(item: $0, section:0) }) } if let inserted = changes.insertedIndexes, inserted.count > 0 { collectionView.insertItems(at: inserted.map { IndexPath(item: $0, section:0) }) } if let changed = changes.changedIndexes, changed.count > 0 { collectionView.reloadItems(at: changed.map { IndexPath(item: $0, section:0) }) } changes.enumerateMoves { fromIndex, toIndex in collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0), to: IndexPath(item: toIndex, section: 0)) } }) } else { collectionView.reloadData() } } } } deinit { NotificationCenter.default.removeObserver(self, name: .assetCollectionChanged, object: nil) } } <file_sep>/PhotosApp/PhotosApp/Network/NetworkConnector.swift // // NetworkConnector.swift // PhotosApp // // Created by delma on 2020/03/18. // Copyright © 2020 Codesquad. All rights reserved. // import Foundation import UIKit class NetworkConnector { var imageCollection: [ImageData] = [] enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } func request(url: String, methodType: HTTPMethod, body: Data? = nil) -> URLRequest? { guard let url = URL(string: url) else { return nil } var request = URLRequest(url: url) request.httpMethod = methodType.rawValue request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = body return request } } <file_sep>/PhotosApp/PhotosApp/PhotosCollectionDelegate.swift // // PhotosCollectionDelegate.swift // PhotosApp // // Created by delma on 2020/03/16. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit import Photos class PhotosCollectionDelegate: NSObject, UICollectionViewDelegate { var allPhotos: PHFetchResult<PHAsset>? = PHAsset.fetchAssets(with: nil) let imageManager = PHCachingImageManager() let imageSize = CGSize(width: 100, height: 100) func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.isSynchronous = false imageManager.requestImage(for: (allPhotos?[indexPath.row])!, targetSize: imageSize, contentMode: PHImageContentMode.aspectFill, options: options) { (image, info) -> Void in if (image != nil) { (cell as! CollectionViewCell).imageView.image = image } } } } <file_sep>/PhotosApp/PhotosApp/View/CollectionViewCell.swift // // CollectionViewCell.swift // PhotosApp // // Created by Viet on 2020/03/16. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! func setImage(_ image: UIImage) { imageView.image = image } } <file_sep>/PhotosApp/PhotosApp/Model/PhotosCollectionDataSource.swift // // PhotosCollectionDataSource.swift // PhotosApp // // Created by delma on 2020/03/16. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit import Photos class PhotosCollectionDataSource: NSObject, UICollectionViewDataSource { private let cellIdentifier = "collectionViewCell" private let photoLibraryManager = PhotoLibraryManager() override init() { super.init() PHPhotoLibrary.shared().register(photoLibraryManager) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photoLibraryManager.allPhotos!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) photoLibraryManager.requestImage(cell: cell as! CollectionViewCell, indexPath: indexPath) return cell } } <file_sep>/README.md # Photos App ### Members [delma](https://github.com/delmaSong), [모스](https://github.com/kjoonk) ## Ground Rules ### 매일 할일 - 기능구현 - 예습 위주 공부 - 스크럼 ### 매일 스크럼 시 공유할 내용 - 요구사항 분석 및 issue 생성 - 전날 공부한 것 공유 - 다음 날 공부해야 할 키워드 정리 <br> ## 브랜치 관리 - `master`: 온전한 개발 사항이 반영된 브랜치로 dev에서 merge함 - `dev`: PR 보내는 브랜치. - `feature/****`: 각 기능 담당 브랜치. dev로 PR 보냄. step별로 PR. - `feature/****/issue-number`: 각 step 밑에 issue 번호로 브랜치 만들어서 구현 <br> ## Coding Convention - [StyleShare/swift-style-guide: StyleShare에서 작성한 Swift 한국어 스타일 가이드](https://github.com/StyleShare/swift-style-guide) - [[Swift] Naming Convention for Swift - jinshine 기술 블로그 - Medium](https://medium.com/jinshine-%EA%B8%B0%EC%88%A0-%EB%B8%94%EB%A1%9C%EA%B7%B8/naming-convention-for-swift-fe15acf46a46) <br> ## 진행사항 ### Step 1. Collection View 2020.03.16 Mon **요구 사항** - 스토리보드 ViewController에 CollectionView를 추가하고 Safe 영역에 가득 채우도록 frame을 설정한다. - CollectionView Cell 크기를 80 x 80 로 지정한다. - UICollectionViewDataSource 프로토콜을 채택하고 40개 cell을 랜덤한 색상으로 채우도록 구현한다. <br> **실행 화면** <img src = "https://i.imgur.com/y3ey19t.png" width = "80%"/> <br> <br> ### Step 2. Photos 라이브러리 2020.03.17 Tue <br> **요구 사항** - UINavigationController를 Embed시키고, 타이틀을 'Photos'로 지정한다. - PHAsset 프레임워크를 사용해서 사진보관함에 있는 사진 이미지를 Cell에 표시한다. - CollectionView Cell 크기를 100 x 100 로 변경한다. - Cell을 처리하기 위한 커스텀 클래스를 만들어서 지정한다. - Cell을 가득 채우도록 UIImageView를 추가한다. - PHCachingImageManager 클래스를 활용해서 썸네일 이미지를 100 x 100 크기로 생성해서 Cell에 표시한다. - PHPhotoLibrary 클래스에 사진보관함이 변경되는지 여부를 옵저버로 등록한다. <br> **실행 화면** <img src = "https://i.imgur.com/U0xCF3M.png" width = "80%"/> <file_sep>/PhotosApp/PhotosApp/Extensions/ExtendedNotificationName.swift // // ExtendedNotificationName.swift // PhotosApp // // Created by delma on 2020/03/17. // Copyright © 2020 Codesquad. All rights reserved. // import Foundation extension Notification.Name { static let assetCollectionChanged = Notification.Name("assetCollectionChanged") } <file_sep>/PhotosApp/PhotosApp/Model/ImageDownloader.swift // // ImageDownloader.swift // PhotosApp // // Created by delma on 2020/03/20. // Copyright © 2020 Codesquad. All rights reserved. // import UIKit class ImageDownloader { func requestImage(handler: @escaping (UIImage?) -> ()) { let url = "https://public.codesquad.kr/jk/doodle.json" let request = NetworkConnector().request(url: url, methodType: .get) sessionDataTask(request: request!) { (image) in handler(image) } } func sessionDataTask(request: URLRequest, handler: @escaping (UIImage)->()) { let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) in guard error == nil else { return } do { let anyData = try JSONSerialization.jsonObject(with: data!, options: []) self.jsonConvertor(anyData: anyData) { (image) in handler(image) } } catch { } } task.resume() } func jsonConvertor(anyData: Any, handler: @escaping (UIImage)->()) { if let nsArray = anyData as? NSArray { for bundle in nsArray { if let nsDictionary = bundle as? NSDictionary { guard let imageString = nsDictionary["image"] as? String else { return } self.urlConvetor(imageString) { (image) in handler(image) } } } } } func urlConvetor(_ imageString: String, handler: @escaping (UIImage)->()) { DispatchQueue.global(qos: .background).async { do { let imageURL = URL(string: imageString)! let data = try Data(contentsOf: imageURL) let doodleImage = UIImage(data: data)! handler(doodleImage) } catch { } } } }
24f17efa1afe3e111d2a3079bf81e25b25339643
[ "Swift", "Markdown" ]
12
Swift
codesquad-member-2020/photos-2
3ab1436676c400f656b5cefcc63c0ae7ac2ddb14
3ca12a052ccf023d5cc3867ce7aa1b945742c501
refs/heads/master
<file_sep>module Types class RepoType < Types::BaseObject field :name, String, null: false end end <file_sep>module Types class UserType < Types::BaseObject field :login, String, null: false field :name, String, null: false field :repos, [RepoType], null: false end end <file_sep>module Types class QueryType < Types::BaseObject field :user, UserType, null: false do argument :login, String, required: true end def user(login: nil) user = User.find_by(login: login) if user user else search_api_user(login) User.find_by(login: login) end end private def search_api_user(login) search = Faraday.get("https://api.github.com/users/#{login}") result = JSON.parse(search.body) user = User.new(login: login, name: result["name"]) if user.save search_api_user_repos(login, user.id) else raise 'Incorrect login' end end def search_api_user_repos(login, user_id) search = Faraday.get("https://api.github.com/users/#{login}/repos") result = JSON.parse(search.body) result.each do |repo| @repo = Repo.new(name: repo["name"], user_id: user_id) @repo.save end end end end
68d94f0e892e239e2c93e2238faa085a1a39f81b
[ "Ruby" ]
3
Ruby
Onixikum/gitapi
ee95e7686a4a0cd306a927f4a80f0d2957dd6816
2fbce87b61985d817c85565e326c69801596ef96
refs/heads/master
<file_sep>package itcollege.team09.entities; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.tostring.RooToString; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.transaction.annotation.Transactional; @MappedSuperclass @RooToString @Transactional @RooEntity(mappedSuperclass = true) public abstract class Piirivalve { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Size(max=500) //@NotNull private String kommentaar; @Size(max=32) protected String avaja; @DateTimeFormat(style="M-") protected Date avatud; @Size(max=32) protected String muutja; @DateTimeFormat(style="M-") protected Date muudetud; @Size(max=32) protected String sulgeja; @DateTimeFormat(style="M-") protected Date suletud; public void setSuletud(Date suletud) { this.suletud = suletud; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getKommentaar() { return kommentaar; } public void setKommentaar(String kommentaar) { this.kommentaar = kommentaar; } @PrePersist public void recordCreated() { String user = GetUser(); this.avaja = user; this.muutja = user; this.sulgeja = user; this.avatud = new Date(); this.muudetud = new Date(); try { this.suletud = new SimpleDateFormat("yyyy-MM-dd").parse("9999-12-31"); } catch (ParseException e) { e.printStackTrace(); } } @PreUpdate public void recordModified() { this.muutja = GetUser(); this.muudetud = new Date(); } @PreRemove public void preventRemove() { throw new SecurityException("Removing of data is prohibited!"); } @Transactional public void remove() { this.sulgeja = GetUser(); this.suletud = new Date(); } private String GetUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return auth.getName(); } public Date getSuletud() { return suletud; } } <file_sep>package itcollege.team09.entities; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.tostring.RooToString; import itcollege.team09.entities.AdminYksuseLiik; import javax.persistence.ManyToOne; @Entity @RooToString @RooEntity public class VoimalikAlluvus extends Piirivalve implements Serializable { /** * */ private static final long serialVersionUID = 1L; @NotNull @DateTimeFormat(style="M-") private Date alates; @NotNull @DateTimeFormat(style="M-") private Date kuni; @ManyToOne private AdminYksuseLiik yksuseliik; @ManyToOne private AdminYksuseLiik alamyksus; public Date getAlates() { return alates; } public void setAlates(Date alates) { this.alates = alates; } public Date getKuni() { return kuni; } public void setKuni(Date kuni) { this.kuni = kuni; } public AdminYksuseLiik getYksuseliik() { return yksuseliik; } public void setYksuseliik(AdminYksuseLiik param) { this.yksuseliik = param; } public AdminYksuseLiik getAlamyksus() { return alamyksus; } public void setAlamyksus(AdminYksuseLiik param) { this.alamyksus = param; } public static List<VoimalikAlluvus> findAllVoimalikAlluvuses() { List<VoimalikAlluvus> items = entityManager().createQuery("SELECT o FROM VoimalikAlluvus o", VoimalikAlluvus.class).getResultList(); for (int i = items.size() - 1; i >= 0; i--) { VoimalikAlluvus item = (VoimalikAlluvus) items.get(i); if (!itcollege.team09.helpers.Helper.IsSurrogateDate(item.getSuletud())){ items.remove(i); } } return items; } } <file_sep>package itcollege.team09.entities; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.OneToMany; import javax.persistence.PersistenceContext; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.tostring.RooToString; import itcollege.team09.entities.VoimalikAlluvus; import java.util.Collection; import itcollege.team09.entities.AdminYksus; @Entity @RooToString @RooEntity public class AdminYksuseLiik extends Piirivalve implements Serializable { /** * */ private static final long serialVersionUID = 1L; @NotNull @Size(max=10) private String kood; @NotNull @Size(max=100) private String nimetus; @NotNull @DateTimeFormat(style="M-") private Date alates = new Date(); @NotNull @DateTimeFormat(style="M-") private Date kuni; @OneToMany(mappedBy = "yksuseliik") private Collection<VoimalikAlluvus> ylemyksused; @OneToMany(mappedBy = "alamyksus") private Collection<VoimalikAlluvus> alamyksused; @OneToMany(mappedBy = "adminYksuseLiik") private Collection<AdminYksus> adminyksused; public String getKood() { return kood; } public void setKood(String kood) { this.kood = kood; } public String getNimetus() { return nimetus; } public void setNimetus(String nimetus) { this.nimetus = nimetus; } public Date getAlates() { return alates; } public void setAlates(Date alates) { this.alates = alates; } public Date getKuni() { return kuni; } public void setKuni(Date kuni) { this.kuni = kuni; } public Collection<VoimalikAlluvus> getYlemyksused() { return ylemyksused; } public void setYlemyksused(Collection<VoimalikAlluvus> param) { this.ylemyksused = param; } public Collection<VoimalikAlluvus> getAlamyksused() { return alamyksused; } public void setAlamyksused(Collection<VoimalikAlluvus> param) { this.alamyksused = param; } public Collection<AdminYksus> getAdminyksused() { return adminyksused; } public void setAdminyksused(Collection<AdminYksus> param) { this.adminyksused = param; } public static List<AdminYksuseLiik> findAllAdminYksuseLiiks() { List<AdminYksuseLiik> items = entityManager().createQuery("SELECT o FROM AdminYksuseLiik o", AdminYksuseLiik.class).getResultList(); for (int i = items.size() - 1; i >= 0; i--) { AdminYksuseLiik item = (AdminYksuseLiik) items.get(i); if (!itcollege.team09.helpers.Helper.IsSurrogateDate(item.getSuletud())){ items.remove(i); } } return items; } } <file_sep>package itcollege.team09.entities; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.tostring.RooToString; import itcollege.team09.entities.Vaeosa; import javax.persistence.ManyToOne; @Entity @RooToString @RooEntity public class VaeosaAlluvus extends Piirivalve implements Serializable { /** * */ private static final long serialVersionUID = 1L; @NotNull @DateTimeFormat(style="M-") private Date alates; @NotNull @DateTimeFormat(style="M-") private Date kuni; @ManyToOne private Vaeosa vaeosa; @ManyToOne private Vaeosa alamvaeosa; public Date getAlates() { return alates; } public void setAlates(Date alates) { this.alates = alates; } public Date getKuni() { return kuni; } public void setKuni(Date kuni) { this.kuni = kuni; } public Vaeosa getVaeosa() { return vaeosa; } public void setVaeosa(Vaeosa param) { this.vaeosa = param; } public Vaeosa getAlamvaeosa() { return alamvaeosa; } public void setAlamvaeosa(Vaeosa param) { this.alamvaeosa = param; } public static List<VaeosaAlluvus> findAllVaeosaAlluvuses() { List<VaeosaAlluvus> items = entityManager().createQuery("SELECT o FROM VaeosaAlluvus o", VaeosaAlluvus.class).getResultList(); for (int i = items.size() - 1; i >= 0; i--) { VaeosaAlluvus item = (VaeosaAlluvus) items.get(i); if (!itcollege.team09.helpers.Helper.IsSurrogateDate(item.getSuletud())){ items.remove(i); } } return items; } }
116da5d7443027ec532939bea9157512529326fa
[ "Java" ]
4
Java
Mailis/Team09.BorderGuard
33816bdb279997f8e0e7441b1626830ed3e5d091
c756b1f21774d81f9f766670cc889fd1d69907cf
refs/heads/master
<repo_name>joel329/sound-project-challenge-2<file_sep>/main.ts while (true) { if (input.lightLevel() > 5) { light.setAll(color.rgb(255, 0, 0)) music.playMelody("E B C5 A B G A F ", 120) music.stopAllSounds() } } <file_sep>/main.py while True: if input.light_level() > 5: light.set_all(color.rgb(255, 0, 0)) music.play_melody("E B C5 A B G A F ", 120) music.stop_all_sounds()
ab83d563294e9c889efe91113ee9c3bd236c71f3
[ "Python", "TypeScript" ]
2
TypeScript
joel329/sound-project-challenge-2
9064157d28745310752e5b855812aa2a2906b703
1e50e1fe1738b27e98003ff018f385a29bf34373
refs/heads/main
<repo_name>SpookedByRoaches/Pico-HX8357-Parallel-Interface<file_sep>/README.md # HX8357 8-bit Parallel Pi Pico Interface - There is not much support for customizable parallel communication with the TFT driver chip: HX8357. Hopefully this helps others on their projects as much as it did for me - This is based on the Adafruit-GFX library and uses the same algorithms for drawing with some modifications to optimize for speed. - All of the geometric primitives are there and can be tested using the available test functions - Keep in mind there are many features that the GFX library has that this one does not ## Features not included in this library are 1- Custom fonts 2- PROGMEM bitmap drawing 3- Grayscale bitmap drawing 4- XBitMap drawing 5- AdafruitGFXButton 6- Reading GRAM data 7- Display inversion<file_sep>/include/HX8357_interface.h #ifndef _HX_8357_INTERFACE_ #define _HX_8357_INTERFACE_ #define FLIPPED_CONNECTIONS //In my setup the data connections are flipped //D7 -> GPIO2 //D6 -> GPIO3 .... //D0 -> GPIO10 //Comment out the defenition if the connections are not flipped on your setup #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <assert.h> #include <limits.h> #include <reent.h> #include <unistd.h> #include <fcntl.h> #include <ctype.h> #include <math.h> #include <time.h> #include "pico/config.h" #include "pico/stdlib.h" #include "pico/divider.h" #include "pico/bootrom.h" #include "pico/mutex.h" #include "pico/multicore.h" #include "hardware/flash.h" #include "hardware/adc.h" #include "hardware/pwm.h" #include "hardware/gpio.h" #include "hardware/uart.h" #include "hardware/i2c.h" #include "hardware/spi.h" #include "hardware/rtc.h" #include "hardware/divider.h" #include "hardware/clocks.h" #include "hardware/sync.h" #include "hardware/irq.h" #include "hardware/structs/systick.h" #include "glcdfont.c" #define LOW 0 #define HIGH 1 #define LOWER_BYTE(x) (uint8_t)(x & 0xFF) #define HIGHER_BYTE(x) (uint8_t)(x >> 8) #define HX8357_NOP 0x00 #define HX8357_SWRESET 0x01 #define HX8357_RDDID 0x04 #define HX8357_RDDST 0x09 #define HX8357_RDPOWMODE 0x0A #define HX8357_RDMADCTL 0x0B #define HX8357_RDCOLMOD 0x0C #define HX8357_RDDIM 0x0D #define HX8357_RDDSDR 0x0F #define HX8357_SLPIN 0x10 #define HX8357_SLPOUT 0x11 #define HX8357B_PTLON 0x12 #define HX8357B_NORON 0x13 #define HX8357_INVOFF 0x20 #define HX8357_INVON 0x21 #define HX8357_DISPOFF 0x28 #define HX8357_DISPON 0x29 #define HX8357_CASET 0x2A #define HX8357_PASET 0x2B #define HX8357_RAMWR 0x2C #define HX8357_RAMRD 0x2E #define HX8357B_PTLAR 0x30 #define HX8357_TEON 0x35 #define HX8357_TEARLINE 0x44 #define HX8357_MADCTL 0x36 #define HX8357_COLMOD 0x3A #define HX8357_SETOSC 0xB0 #define HX8357_SETPWR1 0xB1 #define HX8357B_SETDISPLAY 0xB2 #define HX8357_SETRGB 0xB3 #define HX8357D_SETCOM 0xB6 #define HX8357B_SETDISPMODE 0xB4 #define HX8357D_SETCYC 0xB4 #define HX8357B_SETOTP 0xB7 #define HX8357D_SETC 0xB9 #define HX8357B_SET_PANEL_DRIVING 0xC0 #define HX8357D_SETSTBA 0xC0 #define HX8357B_SETDGC 0xC1 #define HX8357B_SETID 0xC3 #define HX8357B_SETDDB 0xC4 #define HX8357B_SETDISPLAYFRAME 0xC5 #define HX8357B_GAMMASET 0xC8 #define HX8357B_SETCABC 0xC9 #define HX8357_SETPANEL 0xCC #define HX8357B_SETPOWER 0xD0 #define HX8357B_SETVCOM 0xD1 #define HX8357B_SETPWRNORMAL 0xD2 #define HX8357B_RDID1 0xDA #define HX8357B_RDID2 0xDB #define HX8357B_RDID3 0xDC #define HX8357B_RDID4 0xDD #define HX8357D_SETGAMMA 0xE0 #define HX8357B_SETGAMMA 0xC8 #define HX8357B_SETPANELRELATED 0xE9 #define MADCTL_MY 0x80 #define MADCTL_MX 0x40 #define MADCTL_MV 0x20 #define MADCTL_ML 0x10 #define MADCTL_RGB 0x00 #define MADCTL_BGR 0x08 #define MADCTL_SS 0x02 #define MADCTL_GS 0x01 #define TFT_WIDTH 320 #define TFT_HEIGHT 480 #define ROTATION_ZERO_RAD MADCTL_MX | MADCTL_BGR #define ROTATION_HALF_RAD MADCTL_MV | MADCTL_BGR #define ROTATION_ONE_RAD MADCTL_MY | MADCTL_BGR #define ROTATION_THREE_HALVES_RAD MADCTL_MX | MADCTL_MY | MADCTL_MV | MADCTL_BGR // Color definitions #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define PINK 0xEB3D #define DC_COMMAND 0 #define DC_DATA 1 #define WAIT_FOR_CHIP_US 1 template <class T> void swap( T& a, T& b ); class HX_8357_8Bit{ public: HX_8357_8Bit(int base_pin, int rst_pin, int rd_pin, int cs_pin, int wr_pin, int dc_pin, int width, int height); void init(), setDataBus(uint8_t val), fillScreen(uint16_t color), drawPixel(int16_t x, int16_t y, uint16_t color), drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color), drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), setRotation(uint8_t r), //invertDisplay(bool i), drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color), fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color), //drawEllipse(int16_t x0, int16_t y0, int16_t rx, int16_t ry, uint16_t color), //fillEllipse(int16_t x0, int16_t y0, int16_t rx, int16_t ry, uint16_t color), drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color, uint16_t bg), drawRGBBitmap(int16_t x, int16_t y, const uint16_t *bitmap, int16_t w, int16_t h), setCursor(int16_t x, int16_t y), setCursor(int16_t x, int16_t y, uint8_t font), setTextColor(uint16_t color), setTextColor(uint16_t fgcolor, uint16_t bgcolor), setTextSize(uint8_t size), setTextFont(uint8_t font), setTextWrap(bool wrap), //setTextDatum(uint8_t datum), //setTextPadding(uint16_t x_width), print(uint8_t *str), writeChar(uint8_t c); int getWidth(), getHeight(), getRotation(); uint8_t rotation; private: void drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size_x, uint8_t size_y), pushColors(uint16_t *data, uint8_t len), pushColors(uint8_t *data, uint32_t len), strobeColor(uint16_t color, uint16_t len), writecommand(uint8_t command), writedata(uint8_t data), setAddrWindow(uint16_t x0, uint16_t x1, uint16_t y0, uint16_t y1), pushColor(uint16_t color, uint32_t len); int base_pin, rst_pin, rd_pin, cs_pin, wr_pin, dc_pin, width, height; uint16_t textcolor, textbgcolor, cursor_x, cursor_y; uint8_t ptr_to_null[1], textsize_x, textsize_y; uint32_t data_bus_mask; }; #ifdef FLIPPED_CONNECTIONS const uint8_t reverse_lookup_table[256] = {0x0, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x8, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x4, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0xc, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x2, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0xa, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x6, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0xe, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x1, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x9, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x5, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0xd, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x3, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0xb, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x7, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0xf, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, }; #endif //FLIPPED_CONNECTIONS #endif //_HX_8357_INTERFACE_<file_sep>/src/main.cpp #include "main.h" HX_8357_8Bit tft(start_pin, RST_PIN, RD_PIN, CS_PIN, WR_PIN, DC_PIN, 320, 480); int main() { stdio_init_all(); gpio_init(button_pin); gpio_set_dir(button_pin, GPIO_IN); gpio_pull_down(button_pin); tft.init(); uint64_t begin_time = 0; uint64_t end_time = 0; long unsigned int time_elapsed = 0; tft.fillScreen(BLACK); uint8_t rot = 0; sleep_ms(2000); printf("Hello\n"); while(true){ drawGrid(); block(); tft.fillScreen(BLACK); block(); } } void fillSquares() { int x_val = 0; int y_val = 0; uint8_t curCol = 0; uint64_t begin_time = 0; uint64_t end_time = 0; long unsigned int time_elapsed = 0; for (int i = 0; i < 480*320/(20*20); i++){ tft.fillRect(x_val, y_val, 20, 20, colors[curCol]); curCol = (curCol+1)%7; if (x_val == tft.getWidth()-20){ x_val = 0; if (y_val == tft.getHeight() - 20) y_val = 0; else y_val += 20; } else{ x_val += 20; } } } void drawGrid() { int x_val = 0; int y_val = 0; for (int i = 0; i < tft.getWidth(); i += 20) tft.drawFastVLine(i, 0, tft.getHeight(), RED); for (int i = 0; i < tft.getHeight(); i += 20) tft.drawFastHLine(0, i, tft.getWidth(), RED); } void drawRays() { for (int i = 0; i <= tft.getWidth(); i += 20){ tft.drawLine(0, 0, i, tft.getHeight(), GREEN); } for (int i = 0; i <= tft.getHeight(); i += 20){ tft.drawLine(0, 0, tft.getWidth(), i, RED); } } void drawSquares() { int x_val = 0; int y_val = 0; uint8_t curCol = 0; for (int i = 0; i < 480*320/(20*20); i++){ tft.drawRect(x_val, y_val, 19, 19, colors[curCol]); curCol = (curCol+1)%7; if (x_val == tft.getWidth()-20){ x_val = 0; if (y_val == tft.getHeight() - 20) y_val = 0; else y_val += 20; } else{ x_val += 20; } } } void drawRoundSquares() { int x_val = 0; int y_val = 0; uint8_t curCol = 0; for (int i = 0; i < 480*320/(20*20); i++){ tft.drawRoundRect(x_val, y_val, 19, 19, 4,colors[curCol]); curCol = (curCol+1)%7; if (x_val == tft.getWidth()-20){ x_val = 0; if (y_val == tft.getHeight() - 20) y_val = 0; else y_val += 20; } else{ x_val += 20; } } } void fillRoundSquares() { int x_val = 0; int y_val = 0; uint8_t curCol = 0; for (int i = 0; i < 480*320/(20*20); i++){ tft.fillRoundRect(x_val, y_val, 19, 19, 4,colors[curCol]); curCol = (curCol+1)%7; if (x_val == tft.getWidth()-20){ x_val = 0; if (y_val == tft.getHeight() - 20) y_val = 0; else y_val += 20; } else{ x_val += 20; } } } void fillCircles() { int x_val = 10; int y_val = 10; uint8_t curCol = 0; for (int i = 10; i < 480*320/(20*20); i++){ tft.fillCircle(x_val, y_val, 9, colors[curCol]); curCol = (curCol+1)%7; if (x_val == (tft.getWidth()-10)){ x_val = 10; if (y_val == (tft.getHeight() - 10)) y_val = 10; else y_val += 20; } else{ x_val += 20; } } } void drawCircles() { int x_val = 10; int y_val = 10; uint8_t curCol = 0; for (int i = 10; i < 480*320/(20*20); i++){ tft.drawCircle(x_val, y_val, 9, colors[curCol]); curCol = (curCol+1)%7; if (x_val == (tft.getWidth()-10)){ x_val = 10; if (y_val == (tft.getHeight() - 10)) y_val = 10; else y_val += 20; } else{ x_val += 20; } } } void drawTriangles() { uint16_t x0 = 0, y0 = 0, x1 = 20, y1 = 0, x2 = 10, y2 = 20, curCol = 0; for (int i = 0; i < tft.getHeight(); i += 20){ for (int j = 0; j < tft.getWidth(); j += 20){ tft.drawTriangle(x0, y0, x1, y1, x2, y2, colors[curCol]); x0 += 20; x1 += 20; x2 += 20; curCol++; curCol %= 8; } x0 = 0; y0 += 20; x1 = x0 + 20; y1 = y0; x2 = x0 + 10; y2 = y1 + 20; curCol = 0; } } void fillTriangles() { uint16_t x0 = 0, y0 = 0, x1 = 20, y1 = 0, x2 = 10, y2 = 20, curCol = 0; for (int i = 0; i < tft.getHeight(); i += 20){ for (int j = 0; j < tft.getWidth(); j += 20){ tft.fillTriangle(x0, y0, x1, y1, x2, y2, colors[curCol]); x0 += 20; x1 += 20; x2 += 20; curCol++; curCol %= 8; } x0 = 0; y0 += 20; x1 = x0 + 20; y1 = y0; x2 = x0 + 10; y2 = y1 + 20; curCol = 0; } } void drawChars() { tft.setTextSize(2); for (int i = 0; i < 255; i++) { if (! (i%53)) tft.writeChar('\n'); tft.writeChar(i); } } void printText() { tft.setTextSize(2); uint8_t text[256]; for (int i = 0; i < 255; i++) text[i] = ((uint8_t)random()%80) + 33; text[255] = '\0'; tft.print(text); tft.setCursor(0, 0); } void block() { printf("Blocked\n"); while(gpio_get(button_pin)); sleep_ms(50); while(!gpio_get(button_pin)); } <file_sep>/src/HX8357_interface.cpp #include "HX8357_interface.h" HX_8357_8Bit::HX_8357_8Bit(int base_pin, int rst_pin, int rd_pin, int cs_pin, int wr_pin, int dc_pin, int width, int height): base_pin(base_pin), rst_pin(rst_pin), rd_pin(rd_pin), cs_pin(cs_pin), wr_pin(wr_pin), dc_pin(dc_pin), width(width), height(height) { *ptr_to_null = 0; data_bus_mask = (0xFFul) << base_pin; textsize_x = 1; textsize_y = 1; cursor_x = 0; cursor_y = 0; textcolor = 0xFFFF; textbgcolor = 0x0000; } /* * Function Name: init() * Description: */ void HX_8357_8Bit::init() { //This could be used in the future to take advantage of the PIO hardrware //As of now, just setting the GPIO mask is faster /*data_bus_io = pio0; offset = pio_add_program(data_bus_io, &output_program); sm = pio_claim_unused_sm(data_bus_io, true); output_program_init(data_bus_io, sm, offset, base_pin , 8); pio_sm_set_clkdiv(data_bus_io, sm, 1); */ uint32_t pins_mask = 0; pins_mask = (1ul << dc_pin) | (1ul << wr_pin) | (1ul << rd_pin) | (1ul << cs_pin) | (1ul << rst_pin) | (data_bus_mask); gpio_init_mask(pins_mask); gpio_set_dir_out_masked(pins_mask); gpio_put(dc_pin, HIGH); gpio_put(wr_pin, HIGH); gpio_put(rd_pin, HIGH); gpio_put(cs_pin, HIGH); gpio_put(rst_pin, HIGH); sleep_ms(50); gpio_put(rst_pin, LOW); sleep_ms(50); gpio_put(rst_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_SWRESET); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_SLPOUT); gpio_put(cs_pin, HIGH); sleep_ms(20); gpio_put(cs_pin, LOW); writecommand(HX8357B_SETPOWER); writedata(0x07); writedata(0x42); writedata(0x18); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357B_SETVCOM); writedata(0x00); writedata(0x07); writedata(0x10); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(0xD2); writedata(0x01); writedata(0x02); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357B_SETPWRNORMAL); writedata(0x10); writedata(0x3B); writedata(0x00); writedata(0x02); writedata(0x11); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357B_SETDISPLAYFRAME); writedata(0x08); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357B_GAMMASET); writedata(0x00); writedata(0x32); writedata(0x36); writedata(0x45); writedata(0x06); writedata(0x16); writedata(0x37); writedata(0x75); writedata(0x77); writedata(0x54); writedata(0x0C); writedata(0x00); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_MADCTL); writedata(ROTATION_ZERO_RAD); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_COLMOD); writedata(0x55); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_CASET); writedata(0x00); writedata(0x00); writedata(0x01); writedata(0x3F); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_PASET); writedata(0x00); writedata(0x00); writedata(0x01); writedata(0xDF); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_DISPON); gpio_put(cs_pin, HIGH); } /* * Function Name: setDataBus() * Description: Put the value of the command or data into the data bus for the * Driver to read * Params: * val: The actual byte */ void HX_8357_8Bit::setDataBus(uint8_t val) { uint32_t new_val = (uint32_t)val << base_pin; gpio_put_masked(data_bus_mask, new_val); } /* * Function Name: writecommand() * Description: Write a command to the Driver chip * Params: * command: command byte */ void HX_8357_8Bit::writecommand(uint8_t command) { gpio_put(dc_pin, DC_COMMAND); #ifdef FLIPPED_CONNECTIONS setDataBus(reverse_lookup_table[command]); #else setDataBus(command); #endif //FLIPPED_CONNECTIONS gpio_put(wr_pin, HIGH); gpio_put(wr_pin, LOW); } /* * Function Name: writedata() * Description: Write a byte of data to the Driver chip * Params: * data: data byte */ void HX_8357_8Bit::writedata(uint8_t data) { gpio_put(dc_pin, DC_DATA); #ifdef FLIPPED_CONNECTIONS setDataBus(reverse_lookup_table[data]); #else setDataBus(data); #endif //FLIPPED_CONNECTIONS gpio_put(wr_pin, HIGH); gpio_put(wr_pin, LOW); } /* * Function Name: setAddrWindow() * Description: Set the window frame for the driver to recieve color bytes * Params: * uint16_t x0: Starting column * uint16_t y0: Starting row * uint16_t x1: End column * uint16_t y1: End row */ void HX_8357_8Bit::setAddrWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { uint8_t columns[4] = {HIGHER_BYTE(x0), LOWER_BYTE(x0), HIGHER_BYTE(x1), LOWER_BYTE(x1)}; uint8_t pages[4] = {HIGHER_BYTE(y0), LOWER_BYTE(y0), HIGHER_BYTE(y1), LOWER_BYTE(y1)}; gpio_put(cs_pin, LOW); writecommand(HX8357_CASET); for (int i = 0; i < 4; i++) writedata(columns[i]); gpio_put(cs_pin, HIGH); gpio_put(cs_pin, LOW); writecommand(HX8357_PASET); for (int i = 0; i < 4; i++) writedata(pages[i]); gpio_put(cs_pin, HIGH); } /* * Function Name: pushColor() * Description: Write a color to the driver chip "len" times * This is without the assumption that the cs_pin is low or that * the chip received the RAMWR command * * Params: * uint16_t color: RGB565 color value * uint32_t len: Number of repetitions */ void HX_8357_8Bit::pushColor(uint16_t color, uint32_t len) { gpio_put(cs_pin, LOW); writecommand(HX8357_RAMWR); color = ~color; while(len--){ writedata(HIGHER_BYTE(color)); writedata(LOWER_BYTE(color)); } gpio_put(cs_pin, HIGH); } /* * Function Name: strobeColor() * Description: Write a color to the driver chip "len" times * This assumes that the cs_pin is low and * the RAMWR command has been received * Params: * uint16_t color: RGB565 color value * uint32_t len: Number of repetitions */ void HX_8357_8Bit::strobeColor(uint16_t color, uint16_t len) { color = ~color; while(len--){ writedata(HIGHER_BYTE(color)); writedata(LOWER_BYTE(color)); } } /* * Function Name: fillScreen() * Description: Fills the screen with a color * Params: * uint16_t color: RGB565 color */ void HX_8357_8Bit::fillScreen(uint16_t color) { fillRect(0, 0, width, height, color); } /* * Function Name: fillRect() * Description: Fills a rectangle at a certain location with a color * Params: * int16_t x: Starting column * int16_t y: Starting row * int16_t w: Rectangle width * int16_t h: Rectangle height * uint16_t color: RGB565 color */ void HX_8357_8Bit::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if ((x > width) || (y > height) || (w == 0) || (h == 0)) return; if ((x + w - 1) > width) w = width - x; if ((y + h - 1) > height) h = height - y; setAddrWindow(x, y, x + w - 1, y + h - 1); pushColor(color, w*h); } /* * Function Name: drawPixel() * Description: Draw a single pixel at a certain location * Params: * int16_t x: Column * int16_t y: Row * uint16_t color: color */ void HX_8357_8Bit::drawPixel(int16_t x, int16_t y, uint16_t color) { if ((x >= width) || (y >= height)) return; setAddrWindow(x, y, x, y); pushColor(color, 1); } /* * Function Name: drawFastVLine() * Description: Draw a vertical line optimized for speed * Params: * int16_t x: column * int16_t y: row * int16_t h: height * uint16_t color: color */ void HX_8357_8Bit::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if ((x >= width) || (y >= height)) return; if ((y + h - 1) >= height) h = height - y; setAddrWindow(x, y, x, y + h - 1); pushColor(color, h); } /* * Function Name: drawFastHLine() * Description: Draw a horizontal line optimized for speed * Params: * int16_t x: column * int16_t y: row * int16_t w: width * uint16_t color: color */ void HX_8357_8Bit::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { if ((x >= width) || (y >= height)) return; if ((x + w - 1) > width) w = width - x; setAddrWindow(x, y, x + w - 1 , y); pushColor(color, w); } /* * Function Name: drawLine() * Description: Draw a line from any point to another using the bresenham * algorithm * Params: * int16_t x0: First points column * int16_t y0: First points row * int16_t x1: Second points column * int16_t y1: Second points row * uint16_t color: color */ void HX_8357_8Bit::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color) { bool steep = abs(y1 - y0) > abs(x1 - x0); if (steep){ swap(x0, y0); swap(x1, y1); } if (x0 > x1){ swap(x0, x1); swap(y0, y1); } int16_t dx = x1 - x0; int16_t dy = abs(y1 - y0); int16_t err = dx >> 1; int16_t ystep; int16_t xs = x0; int16_t dlen = 0; if (y0 < y1) ystep = 1; else ystep = -1; for (; x0 <= x1; x0++){ if (steep) drawPixel(y0, x0, color); else drawPixel(x0, y0, color); err -= dy; if (err < 0){ y0 += ystep; err += dx; } } } /* * Function Name: setRotation() * Description: Set the rotation of the screen * ROTATION_ZERO_RAD makes the top-left corner the * starting point * The rotations are anti-clockwise * Params: * uint8_t m: Rotation value where each integer corresponds to a half radian rotation */ void HX_8357_8Bit::setRotation(uint8_t m) { gpio_put(cs_pin, LOW); writecommand(HX8357_MADCTL); rotation = m % 4; if (rotation%2) { width = TFT_HEIGHT; height = TFT_WIDTH; } else { width = TFT_WIDTH; height = TFT_HEIGHT; } switch (rotation){ case 0: // Portrait writedata(ROTATION_ZERO_RAD); break; case 1: // Landscape (Portrait + 90) writedata(ROTATION_HALF_RAD); break; case 2: // Inverter portrait writedata(ROTATION_ONE_RAD); break; case 3: // Inverted landscape writedata(ROTATION_THREE_HALVES_RAD); break; } gpio_put(cs_pin, HIGH); } /* * Function Name: drawRect() * Description: Same as fillrect but only draws the outline * Params: (int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) */ void HX_8357_8Bit::drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if ((x > width) || (y > height) || (w == 0) || (h == 0)) return; if ((x + w - 1) > width) w = width - x; if ((y + h - 1) > height) h = height - y; drawFastVLine(x, y, h, color); drawFastVLine(x + w, y, h, color); drawFastHLine(x, y, w, color); drawFastHLine(x, y + h, w, color); } /* * Function Name: fillCircleHelper() * Description: Fills a quarter circle to help fillCircle and fillRoundRect * Params: * int16_t x0: center point column * int16_t y0: center point row * int16_t r: circle radius * uint8_t cornername: The quadrant of the circle to draw * int16_t delta: Offset from center-point, used for round-rects * uint16_t color: color */ void HX_8357_8Bit::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -r*2; int16_t x = 0; int16_t y = r; int16_t px = x; int16_t py = y; delta++; while (x < y){ if (f >= 0){ y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (x < (y + 1)){ if (cornername & 1) drawFastVLine(x0 + x, y0 - y, 2 * y + delta, color); if (cornername & 2) drawFastVLine(x0 - x, y0 - y, 2 * y + delta, color); } if (y != py) { if (cornername & 1) drawFastVLine(x0 + py, y0 - px, 2 * px + delta, color); if (cornername & 2) drawFastVLine(x0 - py, y0 - px, 2 * px + delta, color); py = y; } px = x; } } /* * Function Name: drawCircleHelper() * Description: * Params: * int16_t x0: center point column * int16_t y0: center point row * int16_t r: circle radius * uint8_t cornername: The quadrant of the circle to draw * uint16_t color: color */ void HX_8357_8Bit::drawCircleHelper( int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x < y){ if (f >= 0){ y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4){ drawPixel(x0 + x, y0 + y, color); drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2){ drawPixel(x0 + x, y0 - y, color); drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8){ drawPixel(x0 - y, y0 + x, color); drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1){ drawPixel(x0 - y, y0 - x, color); drawPixel(x0 - x, y0 - y, color); } } } /* * Function Name: fillCircle() * Description: Draw a filled circle * Params: * int16_t x0: center point column * int16_t y0: center point row * int16_t r: circle radius * uint16_t color: color */ void HX_8357_8Bit::fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { drawFastVLine(x0, y0 - r, r*2 + 1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } /* * Function Name: drawCircle() * Description: Draw a non-filled circle * Params: * int16_t x0: center point column * int16_t y0: center point row * int16_t r: circle radius * uint16_t color: color */ void HX_8357_8Bit::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; drawPixel(x0, y0 + r, color); drawPixel(x0, y0 - r, color); drawPixel(x0 + r, y0, color); drawPixel(x0 - r, y0, color); while (x < y){ if (f >= 0){ y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } /* * Function Name: drawRoundRect() * Description: Draw a rounded rectangle * Params: * int16_t x: Top left corner x coordinate * int16_t y: Top left corner y coordinate * int16_t w: Width in pixels * int16_t h: Height in pixels * int16_t r: Radius of corner rounding * uint16_t color: color */ void HX_8357_8Bit::drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { int16_t max_radius = ((w < h) ? w : h) / 2; // 1/2 minor axis if (r > max_radius) r = max_radius; // smarter version drawFastHLine(x + r, y, w - 2 * r, color); // Top drawFastHLine(x + r, y + h - 1, w - 2 * r, color); // Bottom drawFastVLine(x, y + r, h - 2 * r, color); // Left drawFastVLine(x + w - 1, y + r, h - 2 * r, color); // Right // draw four corners drawCircleHelper(x + r, y + r, r, 1, color); drawCircleHelper(x + w - r - 1, y + r, r, 2, color); drawCircleHelper(x + w - r - 1, y + h - r - 1, r, 4, color); drawCircleHelper(x + r, y + h - r - 1, r, 8, color); } /* * Function Name: fillRoundRect() * Description: Fill a rounded rectangle * Params: * int16_t x: Top left corner x coordinate * int16_t y: Top left corner y coordinate * int16_t w: Width in pixels * int16_t h: Height in pixels * int16_t r: Radius of corner rounding * uint16_t color: color */ void HX_8357_8Bit::fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { int16_t max_radius = ((w < h) ? w : h) / 2; // 1/2 minor axis if (r > max_radius) r = max_radius; // smarter version fillRect(x + r, y, w - 2 * r, h, color); // draw four corners fillCircleHelper(x + w - r - 1, y + r, r, 1, h - 2 * r - 1, color); fillCircleHelper(x + r, y + r, r, 2, h - 2 * r - 1, color); } /* * Function Name: drawTriangle() * Description: Draw a triangle with the 3 provided corners * Params: * int16_t x0: First corner column * int16_t y0: First corner row * int16_t x1: Second corner column * int16_t y1: Second corner row * int16_t x2: Third corner column * int16_t y2: Third corner row */ void HX_8357_8Bit::drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { drawLine(x0, y0, x1, y1, color); drawLine(x1, y1, x2, y2, color); drawLine(x2, y2, x0, y0, color); } /* * Function Name: fillTriangle() * Description: Fill a triangle with the 3 provided corners * Params: * int16_t x0: First corner column * int16_t y0: First corner row * int16_t x1: Second corner column * int16_t y1: Second corner row * int16_t x2: Third corner column * int16_t y2: Third corner row */ void HX_8357_8Bit::fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1){ swap(y0, y1); swap(x0, x1); } if (y1 > y2){ swap(y2, y1); swap(x2, x1); } if (y0 > y1){ swap(y0, y1); swap(x0, x1); } if (y0 == y2){ a = b = x0; if (x1 < a) a = x1; else if (x1 > b) b = x1; if (x2 < a) a = x2; else if (x2 > b) b = x2; drawFastHLine(a, y0, b - a + 1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1; int32_t sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if (y1 == y2) last = y1; // Include y1 scanline else last = y1 - 1; // Skip it for (y = y0; y <= last; y++){ a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; if (a > b) swap(a, b); drawFastHLine(a, y, b - a + 1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = (int32_t)dx12 * (y - y1); sb = (int32_t)dx02 * (y - y0); for (; y <= y2; y++){ a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; if (a > b) swap(a, b); drawFastHLine(a, y, b - a + 1, color); } } /* * Function Name: drawBitmap() * Description: Draw a monochrome bitmap with the provided background and foreground * colors * Params: * int16_t x: Starting column * int16_t y: Starting row * const uint8_t *bitmap: bitmap array pointer * int16_t w: width of photo * int16_t h: height of photo * uint16_t color: foreground color * uint16_t bg: background color */ void HX_8357_8Bit::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color, uint16_t bg) { if (((w + x) > width) | ((h + y) > height)) return; int16_t byteWidth = (w + 7) / 8; // Bitmap scanline pad = whole byte uint8_t byte = 0; setAddrWindow(x, y, x + w - 1 , y + h - 1); gpio_put(cs_pin, LOW); writecommand(HX8357_RAMWR); for (int16_t j = 0; j < h; j++, y++){ for (int16_t i = 0; i < w; i++){ if (i & 7) byte <<= 1; else byte = bitmap[j * byteWidth + i / 8]; strobeColor((byte & 0x80) ? color : bg, 1); } } gpio_put(cs_pin, HIGH); } /* * Function Name: drawRGBBitmap() * Description: Draw a bitmap with the provided array colors * Params: * int16_t x: Starting column * int16_t y: Starting row * const uint16_t *bitmap: bitmap array pointer * int16_t w: width of photo * int16_t h: height of photo */ void HX_8357_8Bit::drawRGBBitmap(int16_t x, int16_t y, const uint16_t *bitmap, int16_t w, int16_t h) { if (((w + x) > width) | ((h + y) > height)) return; setAddrWindow(x, y, x + w - 1, y + h - 1); gpio_put(cs_pin, LOW); writecommand(HX8357_RAMWR); for (int16_t j = 0; j < h; j++){ for (int16_t i = 0; i < w; i++){ strobeColor(bitmap[j * w + i], 1); } } gpio_put(cs_pin, HIGH); } /* * Get the screen height */ int HX_8357_8Bit::getHeight() { return height; } /* * Get the screen width */ int HX_8357_8Bit::getWidth() { return width; } /* * Get the screen rotation */ int HX_8357_8Bit::getRotation() { return rotation; } /* * Function Name: drawChar() * Description: Draws a character into the screen without updating the cursor * Params: * int16_t x: Starting column * int16_t y: Starting row * unsigned char c: Actual character * uint16_t color: foreground color * uint16_t bg: background color * uint8_t size_x: magnification of the font horizontally * uint8_t size_y: magnification of the font vertically */ void HX_8357_8Bit::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size_x, uint8_t size_y) { if ((x >= width) || // Clip right (y >= width) || // Clip bottom ((x + 6 * size_x - 1) < 0) || // Clip left ((y + 8 * size_y - 1) < 0)) // Clip top return; if ((c >= 176)) c++; // Handle 'classic' charset behavior for (int8_t i = 0; i < 5; i++) { // Char bitmap = 5 columns uint8_t line = font[c * 5 + i]; for (int8_t j = 0; j < 8; j++, line >>= 1) { if (line & 1) { if (size_x == 1 && size_y == 1) drawPixel(x + i, y + j, color); else fillRect(x + i * size_x, y + j * size_y, size_x, size_y, color); } else if (bg != color) { if (size_x == 1 && size_y == 1) drawPixel(x + i, y + j, bg); else fillRect(x + i * size_x, y + j * size_y, size_x, size_y, bg); } } } if (bg != color) { // If opaque, draw vertical line for last column if (size_x == 1 && size_y == 1) drawFastVLine(x + 5, y, 8, bg); else fillRect(x + 5 * size_x, y, size_x, 8 * size_y, bg); } } /* * Function Name: setCursor() * Description: Sets where characters would be written to the screen * Params: * int16_t x: column * int16_t y: row */ void HX_8357_8Bit::setCursor(int16_t x, int16_t y) { cursor_x = x; cursor_y = y; } /* * Function Name: setTextSize() * Description: Sets the magnification of the font * Params: * uint8_t size: value of the magnification */ void HX_8357_8Bit::setTextSize(uint8_t size) { textsize_x = size; textsize_y = size; } /* * Function Name: setTextColor() * Description: Set the foreground text color * Params: * uint16_t color */ void HX_8357_8Bit::setTextColor(uint16_t color) { textcolor = color; } /* * Function Name: setTextColor() * Description: Sets the foreground and background color of the text * Params: * uint16_t fgcolor: foreground color * uint16_t bgcolor: background color */ void HX_8357_8Bit::setTextColor(uint16_t fgcolor, uint16_t bgcolor) { textcolor = fgcolor; textbgcolor = bgcolor; } /* * Function Name: writeChar() * Description: writes a character to the screen based on the parameters * set previously and are in the object attributes. It also * changes the cursor value for the next character to be written * Params: * uint8_t c: Character */ void HX_8357_8Bit::writeChar(uint8_t c) { if (c == '\n') { cursor_x = 0; cursor_y += textsize_y * 8; } else if (c != '\r') { if ((cursor_x + textsize_x * 6) > width) { cursor_x = 0; cursor_y += textsize_y * 8; } drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize_x, textsize_y); cursor_x += textsize_x * 6; } } /* * Function Name: print() * Description: similar to writeChar but with a null-terminated string * Params: * uint8_t *str: null-terminated string (VERY IMPORTANT TO HAVE IT NULL TERMINATED) */ void HX_8357_8Bit::print(uint8_t *str) { uint8_t curChar; for (int i = 0; str[i] != '\0'; i++){ writeChar(str[i]); } } template <class T> void swap( T& a, T& b ){ T c(a); a=b; b=c; }<file_sep>/include/main.h /* * A program to test the features of the interface */ #include "HX8357_interface.h" #include "SSL.h" #define start_pin 2 //The base pin where it and 7 others are to be used as the data pins //e.g. if it's pin 2 the data pins are 2 to 10. They have to be contiguous #define RD_PIN 11 #define RST_PIN 10 #define CS_PIN 12 #define button_pin 15 #define WR_PIN 27 #define DC_PIN 26 // AKA RS pin void block(); void fillSquares(); void drawGrid(); void drawRays(); void drawSquares(); void fillCircles(); void drawCircles(); void drawRoundSquares(); void fillRoundSquares(); void drawTriangles(); void fillTriangles(); void drawChars(); void printText(); uint16_t colors[8] = {BLUE, RED, CYAN, GREEN, PINK, WHITE, YELLOW};
eb60f03a4fa6fdec61273fbd5abd91396f45930a
[ "Markdown", "C", "C++" ]
5
Markdown
SpookedByRoaches/Pico-HX8357-Parallel-Interface
c2575ea7c1db99f259d7272e392e6b5e618c77d3
a705048c1c82629591e463b3e3ec4ad8ffdec2d1
refs/heads/master
<file_sep>class Committee < ActiveRecord::Base include ScrapedModel validates_presence_of :title, :url, :uid, :council_id validates_uniqueness_of :title, :scope => :council_id belongs_to :council has_many :meetings has_many :memberships, :primary_key => :uid has_many :members, :through => :memberships, :extend => UidAssociationExtension delegate :uids, :to => :members, :prefix => "member" delegate :uids=, :to => :members, :prefix => "member" end <file_sep>class InfoScraper < Scraper def process(options={}) @related_objects = [options[:objects]].flatten if options[:objects] related_objects.each do |obj| raw_results = parser.process(_data(obj.url), self).results update_with_results(raw_results, obj, options) end update_last_scraped if options[:save_results]&&parser.errors.empty? mark_as_problematic unless parser.errors.empty? self rescue ScraperError => e logger.debug { "*******#{e.message} while processing #{self.inspect}" } errors.add_to_base(e.message) mark_as_problematic self end def related_objects @related_objects ||= result_model.constantize.find(:all, :conditions => { :council_id => council_id }) end def scraping_for "info on #{result_model}s" end protected # overrides method in standard scraper def update_with_results(res, obj=nil, options={}) unless res.blank? obj.attributes = res.first options[:save_results] ? obj.save : obj.valid? results << obj end end end<file_sep>class ItemScraper < Scraper # validates_presence_of :url, :if => Proc.new { |i| i.related_model.blank? } def process(options={}) if related_model.blank? super else related_objects.each do |obj| target_url = url.blank? ? obj.url : obj.instance_eval("\"" + url + "\"") # if we have url evaluate it AS A STRING in context of related object (which allows us to interpolate uid etc), otherwise just use related object's url raw_results = parser.process(_data(target_url), self).results logger.debug { "\n\n**************RESULTS from parsing #{target_url}:\n#{raw_results.inspect}" } update_with_results(raw_results.collect{ |r| r.merge("#{obj.class.to_s.downcase}_id".to_sym => obj.id) }, options) unless raw_results.blank? end update_last_scraped if options[:save_results]&&parser.errors.empty? mark_as_problematic unless parser.errors.empty? self end rescue ScraperError => e logger.debug { "*******#{e.message} while processing #{self.inspect}" } errors.add_to_base(e.message) mark_as_problematic self end def related_objects @related_objects ||= related_model.constantize.find(:all, :conditions => { :council_id => council_id }) end def scraping_for "#{result_model}s from #{url}" end end<file_sep>module Gla class Scraper BASE_URL = "http://www.london.gov.uk/assembly/" def initialize(params={}) @target_page = params[:target_page] end def base_url BASE_URL end def response @base_response = Hpricot(_http_get(base_url + target_page.to_s)) end def target_page @target_page || (self.class.const_defined?(:TARGET_PAGE) ? self.class::TARGET_PAGE : nil) end protected def _http_get(url) open(url) end end class MembersScraper < Scraper TARGET_PAGE = "lams_facts_cont.jsp" def response super members = [] member_tables = @base_response.search("table table") constituency_members = member_tables.first.search("tr")[1..-1] london_wide_members = member_tables.last.search("tr")[1..-1] members += constituency_members.collect{ |m| { :full_name => m.at("td[2]").inner_text.strip, :constituency => m.at("td[1]").inner_text.strip, :party => m.at("td[3]").inner_text.strip, :url => m.at("a")[:href] } } members += london_wide_members.collect{ |m| { :full_name => m.at("td[1]").inner_text.strip, :party => m.at("td[2]").inner_text.strip, :url => m.at("a")[:href] } } end end class MemberScraper < Scraper def response super email_node = @base_response.at("table a[@href^=mailto]") email = email_node[:href].sub('mailto:','') telephone = email_node.parent.children.first.inner_text.scan(/[\d\s]+/).first member = Member.new(:email => email, :telephone => telephone.strip) end end class CommitteesScraper < Scraper def response super current_committees = @base_response.search('table ul li') current_committees.collect{ |c| Committee.new( :title => c.at("a").inner_text, :url => c.at("a")[:href] ) } end end class CommitteeScraper < Scraper def response super committee = Committee.new end end end<file_sep>require 'test_helper' class MeetingTest < ActiveSupport::TestCase context "The Meeting Class" do setup do @committee = Committee.create!(:title => "Audit Group", :url => "some.url", :uid => 33, :council_id => 1) @meeting = Meeting.create!(:date_held => "6 November 2008 7:30pm", :committee => @committee, :uid => 22, :council_id => @committee.council_id) end should_belong_to :committee should_belong_to :council # think about meeting should belong to council through committee should_validate_presence_of :date_held should_validate_presence_of :committee_id should_validate_presence_of :uid should_validate_uniqueness_of :uid, :scoped_to => :council_id should_have_one :minutes # no shoulda macro for polymorphic stuff so tested below should_have_db_columns :venue should "include ScraperModel mixin" do assert Meeting.respond_to?(:find_existing) end end context "A Meeting instance" do setup do @committee = Committee.create!(:title => "Audit Group", :url => "some.url", :uid => 33, :council_id => 1) @meeting = Meeting.create!(:date_held => "6 November 2008 7:30pm", :committee => @committee, :uid => 22, :council_id => @committee.council_id, :url => "http//council.gov.uk/meeting/22") end should "convert date string to date" do assert_equal DateTime.new(2008, 11, 6, 19, 30), @meeting.date_held end should "return committee name and date as title" do assert_equal "Audit Group meeting, November 6 2008, 7.30PM", @meeting.title end should "have polymorphic document as minutes" do doc = Factory(:document, :title => "minutes of some meeting") @meeting.minutes = doc assert_equal @meeting.id, doc.document_owner_id assert_equal "Meeting", doc.document_owner_type end context "when calling minutes_body setter" do setup do @meeting.minutes_body = "some document text" end should "create new minutes document" do assert_kind_of Document, @meeting.minutes end should "save new minutes document" do assert !@meeting.minutes.new_record? end should "store passed value in document body" do assert_equal "some document text", @meeting.minutes.body end should "save meeting url as document url" do assert_equal "http//council.gov.uk/meeting/22", @meeting.minutes.url end should "set document type to be 'Minutes'" do assert_equal "Minutes", @meeting.minutes.document_type end end context "when calling minutes_body setter and meeting has existing minutes" do setup do @existing_minutes = Factory(:document) @meeting.minutes = @existing_minutes @existing_minutes.save! @meeting.minutes_body = "some document text" end should "not replace minutes" do assert_equal @existing_minutes.id, @meeting.minutes.id end should "update existing minutes body" do assert_equal "some document text", @existing_minutes.reload.body end should "set document_type to be 'Minutes'" do assert_equal "Minutes", @meeting.minutes.document_type end end end private def new_meeting(options={}) Meeting.new({:date_held => 5.days.ago}.merge(options)) end end <file_sep>require File.dirname(__FILE__) + '/helper' class ConfigurationTest < Test::Unit::TestCase context "HoptoadNotifier configuration" do setup do @controller = HoptoadController.new class ::HoptoadController include HoptoadNotifier::Catcher def rescue_action e rescue_action_in_public e end end assert @controller.methods.include?("notify_hoptoad") end should "be done with a block" do HoptoadNotifier.configure do |config| config.host = "host" config.port = 3333 config.secure = true config.api_key = "<KEY>" config.ignore << [ RuntimeError ] config.ignore_user_agent << 'UserAgentString' config.ignore_user_agent << /UserAgentRegexp/ config.proxy_host = 'proxyhost1' config.proxy_port = '80' config.proxy_user = 'user' config.proxy_pass = '<PASSWORD>' config.http_open_timeout = 2 config.http_read_timeout = 5 end assert_equal "host", HoptoadNotifier.host assert_equal 3333, HoptoadNotifier.port assert_equal true, HoptoadNotifier.secure assert_equal "<KEY>", HoptoadNotifier.api_key assert_equal 'proxyhost1', HoptoadNotifier.proxy_host assert_equal '80', HoptoadNotifier.proxy_port assert_equal 'user', HoptoadNotifier.proxy_user assert_equal 'secret', HoptoadNotifier.proxy_pass assert_equal 2, HoptoadNotifier.http_open_timeout assert_equal 5, HoptoadNotifier.http_read_timeout assert_equal HoptoadNotifier::IGNORE_USER_AGENT_DEFAULT + ['UserAgentString', /UserAgentRegexp/], HoptoadNotifier.ignore_user_agent assert_equal HoptoadNotifier::IGNORE_DEFAULT + [RuntimeError], HoptoadNotifier.ignore end should "set a default host" do HoptoadNotifier.instance_variable_set("@host",nil) assert_equal "hoptoadapp.com", HoptoadNotifier.host end [File.open(__FILE__), Proc.new { puts "boo!" }, Module.new].each do |object| should "convert #{object.class} to a string when cleaning environment" do HoptoadNotifier.configure {} notice = @controller.send(:normalize_notice, {}) notice[:environment][:strange_object] = object filtered_notice = @controller.send(:clean_non_serializable_data, notice) assert_equal object.to_s, filtered_notice[:environment][:strange_object] end end [123, "string", 123_456_789_123_456_789, [:a, :b], {:a => 1}, HashWithIndifferentAccess.new].each do |object| should "not remove #{object.class} when cleaning environment" do HoptoadNotifier.configure {} notice = @controller.send(:normalize_notice, {}) notice[:environment][:strange_object] = object assert_equal object, @controller.send(:clean_non_serializable_data, notice)[:environment][:strange_object] end end should "remove notifier trace when cleaning backtrace" do HoptoadNotifier.configure {} notice = @controller.send(:normalize_notice, {}) assert notice[:backtrace].grep(%r{lib/hoptoad_notifier.rb}).any?, notice[:backtrace].inspect dirty_backtrace = @controller.send(:clean_hoptoad_backtrace, notice[:backtrace]) dirty_backtrace.each do |line| assert_no_match %r{lib/hoptoad_notifier.rb}, line end end should "add filters to the backtrace_filters" do assert_difference "HoptoadNotifier.backtrace_filters.length", 5 do HoptoadNotifier.configure do |config| config.filter_backtrace do |line| line = "1234" end end end assert_equal %w( 1234 1234 ), @controller.send(:clean_hoptoad_backtrace, %w( foo bar )) end should "use standard rails logging filters on params and env" do ::HoptoadController.class_eval do filter_parameter_logging :ghi end expected = {"notice" => {"request" => {"params" => {"abc" => "123", "def" => "456", "ghi" => "[FILTERED]"}}, "environment" => {"abc" => "123", "ghi" => "[FILTERED]"}}} notice = {"notice" => {"request" => {"params" => {"abc" => "123", "def" => "456", "ghi" => "789"}}, "environment" => {"abc" => "123", "ghi" => "789"}}} assert @controller.respond_to?(:filter_parameters) assert_equal( expected[:notice], @controller.send(:clean_notice, notice)[:notice] ) end should "add filters to the params filters" do assert_difference "HoptoadNotifier.params_filters.length", 2 do HoptoadNotifier.configure do |config| config.params_filters << "abc" config.params_filters << "def" end end assert HoptoadNotifier.params_filters.include?( "abc" ) assert HoptoadNotifier.params_filters.include?( "def" ) assert_equal( {:abc => "[FILTERED]", :def => "[FILTERED]", :ghi => "789"}, @controller.send(:clean_hoptoad_params, :abc => "123", :def => "456", :ghi => "789" ) ) end should "add filters to the environment filters" do assert_difference "HoptoadNotifier.environment_filters.length", 2 do HoptoadNotifier.configure do |config| config.environment_filters << "secret" config.environment_filters << "supersecret" end end assert HoptoadNotifier.environment_filters.include?( "secret" ) assert HoptoadNotifier.environment_filters.include?( "supersecret" ) assert_equal( {:secret => "[FILTERED]", :supersecret => "[FILTERED]", :ghi => "789"}, @controller.send(:clean_hoptoad_environment, :secret => "123", :supersecret => "456", :ghi => "789" ) ) end should "have at default ignored exceptions" do assert HoptoadNotifier::IGNORE_DEFAULT.any? end end end <file_sep>require 'test_helper' class PortalSystemsHelperTest < ActionView::TestCase end <file_sep>require 'test_helper' class GlaScraperTest < Test::Unit::TestCase context "A Gla scraper" do setup do @scraper = Gla::Scraper.new(:target_page => "lams_facts_cont.jsp") end should "have a base url" do assert_equal "http://www.london.gov.uk/assembly/", @scraper.base_url end should "use target page given" do assert_equal "lams_facts_cont.jsp", @scraper.target_page end should "return nil_for target page if none given and TARGET_PAGE not defined" do assert_nil Gla::Scraper.new.target_page end should "get response to using base_url and target page" do @scraper.expects(:_http_get).with("http://www.london.gov.uk/assembly/lams_facts_cont.jsp").returns("some response") @scraper.response end should "return Hpricot Doc object as response" do @scraper.stubs(:_http_get).with("http://www.london.gov.uk/assembly/lams_facts_cont.jsp").returns("some response") assert_kind_of Hpricot::Doc, @scraper.response end end context "A GlaMembersScraper" do setup do @members_scraper = Gla::MembersScraper.new Gla::MembersScraper.any_instance.stubs(:_http_get).returns(dummy_response(:members_list)) end should "use target page defined as constant" do assert_equal Gla::MembersScraper::TARGET_PAGE, Gla::MembersScraper.new.target_page end should "inherit from Gla scraper" do assert_equal Gla::Scraper, @members_scraper.class.superclass end should "return array from response" do assert_kind_of Array, @members_scraper.response end should "return array with same number of elements as number of members" do assert_equal 25, @members_scraper.response.size end context "response array element" do setup do @response_element = @members_scraper.response.first end should "be a Hash" do assert_kind_of Hash, @response_element end should "have parsed members name" do assert_equal "<NAME>", @response_element[:full_name] end should "have parsed members constituency" do assert_equal "Barnet & Camden", @response_element[:constituency] end should "have parsed members party" do assert_equal "Conservative", @response_element[:party] end should "have parsed members url" do assert_equal "members/colemanb.jsp", @response_element[:url] end # should "be a Member" do # assert_kind_of Member, @response_element # end # # should "have parsed members name" do # assert_equal "<NAME>", @response_element.full_name # end # # should "have parsed members constituency" do # assert_equal "Barnet & Camden", @response_element.constituency # end # # should "have parsed members party" do # assert_equal "Conservative", @response_element.party # end # # should "have parsed members url" do # assert_equal "members/colemanb.jsp", @response_element.url # end end context "response array element without constituency" do setup do @response_element = @members_scraper.response.last end should "be a Member" do assert_kind_of Hash, @response_element end should "have parsed members name" do assert_equal "<NAME>", @response_element[:full_name] end should "have parsed members constituency" do assert_nil @response_element[:constituency] end should "have parsed members party" do assert_equal "Liberal Democrat", @response_element[:party] end should "have parsed members url" do assert_equal "members/tuffreym.jsp", @response_element[:url] end end end context "A GlaMemberScraper" do setup do @member_scraper = Gla::MemberScraper.new(:target_page => "malthousek.jsp") Gla::MemberScraper.any_instance.stubs(:_http_get).returns(dummy_response(:member_details)) end should "inherit from Gla scraper" do assert_equal Gla::Scraper, @member_scraper.class.superclass end context "response" do setup do @response = @member_scraper.response end should "be a Member" do assert_kind_of Member, @response end should "have parsed email address" do assert_equal "<EMAIL>", @response.email end should "have parsed telephone" do assert_equal "020 7983 4099", @response.telephone end end end context "A GlaCommitteesScraper" do setup do @committee_scraper = Gla::CommitteesScraper.new(:target_page => "malthousek.jsp") Gla::CommitteesScraper.any_instance.stubs(:_http_get).returns(dummy_response(:committees_list)) end should "inherit from Gla scraper" do assert_equal Gla::Scraper, @committee_scraper.class.superclass end should "return array from response" do assert_kind_of Array, @committee_scraper.response end should "return array with same number of elements as number of committees" do assert_equal 16, @committee_scraper.response.size end context "response" do setup do @response_element = @committee_scraper.response.first end should "be a Committee" do assert_kind_of Committee, @response_element end should "have parsed title" do assert_equal "Audit Panel", @response_element.title end should "have parsed url" do assert_equal "audit_panel_mtgs/index.jsp", @response_element.url end end end context "A GlaCommitteeScraper" do setup do @committee_scraper = Gla::CommitteeScraper.new(:target_page => "malthousek.jsp") Gla::CommitteeScraper.any_instance.stubs(:_http_get).returns(dummy_response(:committee_details)) end should "inherit from Gla scraper" do assert_equal Gla::Scraper, @committee_scraper.class.superclass end context "response" do setup do @response = @committee_scraper.response end should "be a Committee" do assert_kind_of Committee, @response end # should "have parsed description" do # expected_description = "Agendas, minutes and other papers for meetings of this committee may be accessed below. This committee - formerly the Budget Committee - was renamed the Budget and Performance Committee in July 2008. (Note: Budget Monitoring Sub-Committee meetings are listed separately.) " # assert_equal expected_description, @response.description # end # should "have parsed telephone" do # assert_equal "020 7983 4099", @response.telephone # end end end private def dummy_response(response_name) IO.read(File.join([RAILS_ROOT + "/test/fixtures/dummy_responses/#{response_name.to_s}.html"])) end end <file_sep>require 'test_helper' class DatapointTest < ActiveSupport::TestCase context "The Datapoint class" do should_have_db_columns :data should_validate_presence_of :data, :dataset_id, :council_id should_belong_to :council should_belong_to :dataset end context "A Dataset instance" do setup do @datapoint = Factory.create(:datapoint, :data => [["heading_1", "heading_2"],["data_1", "data_2"]]) end should "serialize data" do assert_equal [["heading_1", "heading_2"],["data_1", "data_2"]], @datapoint.reload.data end context "with dataset with summary column" do setup do @datapoint.dataset.update_attribute(:summary_column, 1) end should "delegate summary_column to associated dataset" do assert_equal 1, @datapoint.summary_column end should "return summary for associated dataset" do assert_equal ["heading_2", "data_2"], @datapoint.summary end end context "with dataset with no summary column" do should "return nil for summary" do assert_nil @datapoint.summary end end end end <file_sep># This module should be included in associations to allow relationships to be # set given just a collection of uids. So if we have in the Committee model: # # has_many :members, :through => :memberships, :extend => UidAssociationExtension # this will add: members.uids and members.uids= methods. For convenience these can # be rewritten as members_uids and members_uids= using :delegate e.g. # # delegate :uids, :to => :members, :prefix => "member" # which delegates the member_uids method to the uids method of the members # association. # See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html # for more details module UidAssociationExtension def add_or_update(members) # not yet done end def uids=(uid_array) uid_members = proxy_reflection.source_reflection.klass.find_all_by_uid_and_council_id(uid_array, proxy_owner.council_id) proxy_owner.send("#{proxy_reflection.name}=",uid_members) end def uids collect(&:uid) end end<file_sep>module AcceptsNestedAttributesForMacros def should_accept_nested_attributes_for(*attr_names) klass = self.name.gsub(/Test$/, '').constantize context "#{klass}" do attr_names.each do |association_name| should "accept nested attrs for #{association_name}" do assert klass.instance_methods.include?("#{association_name}_attributes="), "#{klass} does not accept nested attributes for #{association_name}" end end end end end class ActiveSupport::TestCase extend AcceptsNestedAttributesForMacros end<file_sep>class MembersController < ApplicationController def show @member = Member.find(params[:id]) @council = @member.council @committees = @member.committees @title = @member.full_name respond_to do |format| format.html format.xml { render :xml => @member.to_xml } format.json { render :xml => @member.to_json } end end end <file_sep>require 'test_helper' class ItemScraperTest < ActiveSupport::TestCase context "The ItemScraper class" do should "be subclass of Scraper class" do assert_equal Scraper, ItemScraper.superclass end end context "an ItemScraper instance" do setup do @scraper = Factory(:item_scraper) @scraper.parser.update_attribute(:result_model, "Meeting") end should "return what it is scraping for" do assert_equal "Meetings from http://www.anytown.gov.uk/members", @scraper.scraping_for end context "with related model" do setup do @scraper.parser.update_attribute(:related_model, "Committee") end should "return related model" do assert_equal "Committee", @scraper.related_model end should "get related objects from related model" do Committee.expects(:find).with(:all, :conditions => {:council_id => @scraper.council_id}).returns("related_objects") assert_equal "related_objects", @scraper.related_objects end should "not search related model for related_objects when already exist" do @scraper.instance_variable_set(:@related_objects, "foo") Committee.expects(:find).never assert_equal "foo", @scraper.related_objects end end context "when processing" do setup do @parser = @scraper.parser @parser.stubs(:results).returns([{ :uid => 456 }, { :uid => 457 }] ).then.returns(nil) #second time around finds no results @scraper.stubs(:_data).returns("something") end context "item_scraper with url" do should "get data from url" do # This behaviour is inherited from parent Scraper class, so this is (poss unnecessary) sanity check @scraper.expects(:_data).with("http://www.anytown.gov.uk/members") @scraper.process end should "pass self to associated parser" do @parser.expects(:process).with(anything, @scraper).returns(stub_everything(:results => [])) @scraper.process end should "not update last_scraped attribute if not saving results" do assert_nil @scraper.process.last_scraped end should "update last_scraped attribute if saving results" do @scraper.process(:save_results => true) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end should "not update last_scraped if problem parsing" do @parser.stubs(:errors => stub(:empty? => false)) @scraper.process(:save_results => true) assert_nil @scraper.reload.last_scraped end should "not mark scraper as problematic" do @scraper.process assert !@scraper.reload.problematic? end end context "and problem getting data" do setup do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") end should "not raise exception" do assert_nothing_raised(Exception) { @scraper.process } end should "store error in scraper" do @scraper.process assert_equal "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found", @scraper.errors[:base] end should "return self" do assert_equal @scraper, @scraper.process end should "not update last_scraped attribute when saving results" do assert_nil @scraper.process(:save_results => true).last_scraped end should "mark scraper as problematic" do @scraper.process assert @scraper.reload.problematic? end end context "item_scraper with related_model" do setup do @scraper.parser.update_attribute(:related_model, "Committee") @committee_1 = Factory(:committee, :council => @scraper.council) @committee_2 = Factory(:committee, :council => @scraper.council, :title => "Another Committee", :url => "http://www.anytown.gov.uk/committee/78", :uid => 78) dummy_related_objects = [@committee_1, @committee_2] @scraper.stubs(:related_objects).returns(dummy_related_objects) @scraper.stubs(:_data).returns("something") end context "and url" do should "get data from scraper url" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/members").twice #once for each related object @scraper.process end end context "and url with related object in it" do setup do @scraper.update_attribute(:url, 'http://www.anytown.gov.uk/meetings?ctte_id=#{uid}') end should "get data from url interpolated with related object" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/meetings?ctte_id=77") @scraper.expects(:_data).with("http://www.anytown.gov.uk/meetings?ctte_id=78") @scraper.process end should "pass self to associated parser" do @parser.expects(:process).twice.with(anything, @scraper).returns(stub_everything(:results => [])) @scraper.process end should "not update last_scraped attribute if not saving results" do assert_nil @scraper.process.last_scraped end should "update last_scraped attribute if saving results" do @scraper.process(:save_results => true) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end should "not update last_scraped if problem parsing" do @parser.stubs(:errors => stub(:empty? => false)) @scraper.process(:save_results => true) assert_nil @scraper.reload.last_scraped end end context "and no url" do setup do @scraper.update_attribute(:url, nil) end should "get data from each related_object's url" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/committee/77") @scraper.expects(:_data).with("http://www.anytown.gov.uk/committee/78") @scraper.process end should "update result model with each result and related object details" do @scraper.expects(:update_with_results).with([{ :committee_id => @committee_1.id, :uid => 456 }, { :committee_id => @committee_1.id, :uid => 457 }], anything) @scraper.process end should "update result model passing on any options" do @scraper.expects(:update_with_results).with(anything, {:foo => "bar"}) @scraper.process({:foo => "bar"}) end should "not update last_scraped attribute if not saving results" do assert_nil @scraper.process.last_scraped end should "update last_scraped attribute if saving results" do @scraper.process(:save_results => true) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end should "not mark scraper as problematic" do @scraper.process assert !@scraper.reload.problematic? end context "and problem parsing" do setup do @parser.stubs(:errors => stub(:empty? => false)) @scraper.process(:save_results => true) end should "not update last_scraped if problem parsing" do assert_nil @scraper.reload.last_scraped end should "mark scraper as problematic" do @scraper.process assert @scraper.reload.problematic? end end end context "and problem getting data" do setup do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") end should "not raise exception" do assert_nothing_raised(Exception) { @scraper.process } end should "store error in scraper" do @scraper.process assert_equal "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found", @scraper.errors[:base] end should "return self" do assert_equal @scraper, @scraper.process end should "mark scraper as problematic" do @scraper.process assert @scraper.reload.problematic? end end end end end end <file_sep>class AddAttributesToCouncils < ActiveRecord::Migration def self.up add_column :councils, :base_url, :string add_column :councils, :telephone, :string add_column :councils, :address, :text add_column :councils, :authority_type, :string end def self.down remove_column :councils, :authority_type remove_column :councils, :address remove_column :councils, :telephone remove_column :councils, :base_url end end <file_sep>require 'test_helper' class ParserTest < Test::Unit::TestCase context "The Parser class" do should_have_many :scrapers should_belong_to :portal_system should_validate_presence_of :result_model should_validate_presence_of :scraper_type should_allow_values_for :result_model, "Member", "Committee", "Meeting" should_not_allow_values_for :result_model, "foo", "User" should_allow_values_for :scraper_type, "InfoScraper", "ItemScraper" should_not_allow_values_for :scraper_type, "foo", "OtherScraper" should_have_db_column :path should "serialize attribute_parser" do parser = Parser.create!(:description => "description of parser", :item_parser => "foo", :scraper_type => "ItemScraper", :attribute_parser => {:foo => "\"bar\"", :foo2 => "nil"}, :result_model => "Member") assert_equal({:foo => "\"bar\"", :foo2 => "nil"}, parser.reload.attribute_parser) end end context "A Parser instance" do setup do PortalSystem.delete_all # some reason not getting rid of old records -- poss 2.3.2 bug (see Caboose blog) @parser = Factory(:parser) @parser.item_parser.taint # as it's been submitted by form rails will have tainted it end context "in general" do should "have results accessor" do @parser.instance_variable_set(:@results, "foo") assert_equal "foo", @parser.results end should "return details as title" do assert_equal "Member item parser for single scraper only", @parser.title end should "return details as title when new parser" do assert_equal "Committee item parser for single scraper only", Parser.new(:result_model => "Committee", :scraper_type => "ItemScraper").title end end context "that is associated with portal system" do setup do @portal_system_for_parser = Factory(:portal_system, :name => "Portal for Parser") @parser.update_attribute(:portal_system_id, @portal_system_for_parser.id) end should "return details of portal_system in title" do assert_equal "Member item parser for Portal for Parser", @parser.title end end context "with attribute_parser has attribute_parser_object which" do setup do @attribute_parser_object = @parser.attribute_parser_object end should "be an Array" do assert_kind_of Array, @attribute_parser_object end should "be same size as attribute_parser" do assert_equal @parser.attribute_parser.keys.size, @attribute_parser_object.size end context "has elements which" do setup do @first_attrib = @attribute_parser_object.first end should "are Structs" do assert_kind_of Struct, @first_attrib end should "make attribute_parser_key accessible as attrib_name" do assert_equal "foo", @first_attrib.attrib_name end should "make attribute_parser_value accessible as parsing_code" do assert_equal "\"bar\"", @first_attrib.parsing_code end end context "when attribute_parser is blank" do setup do @empty_attribute_parser_object = Parser.new.attribute_parser_object end should "be an Array" do assert_kind_of Array, @empty_attribute_parser_object end should "with one element" do assert_equal 1, @empty_attribute_parser_object.size end should "is an empty Struct" do assert_equal Parser::AttribObject.new, @empty_attribute_parser_object.first end end end context "when given attribute_parser info from form params" do should "convert to attribute_parser hash" do @parser.attribute_parser_object = [{ "attrib_name" => "title", "parsing_code" => "parsing code for title"}, { "attrib_name" => "description", "parsing_code" => "parsing code for description"}] assert_equal({ :title => "parsing code for title", :description => "parsing code for description" }, @parser.attribute_parser) end should "set attribute_parser to empty hash if no form_params" do @parser.attribute_parser_object = [] assert_equal({}, @parser.attribute_parser) end end context "when evaluating parsing code" do should "evaluate code" do assert_equal "bar", @parser.send(:eval_parsing_code, code_to_parse("foo='bar'")) end should "raise execption if problem evaluating code" do assert_raise(NameError) { @parser.send(:eval_parsing_code, code_to_parse("foo")) } end should "make given object available as 'item' local variable" do given_obj = stub assert_nothing_raised(Exception) { @parser.send(:eval_parsing_code, code_to_parse, given_obj) } # will raise exception unless item local variable exists end should "not raise exception if duped item is changed by code" do given_obj = "hello world" assert_nothing_raised(Exception) { @parser.send(:eval_parsing_code, code_to_parse("item.to_sym"), given_obj) } end should "make current_scraper base_url available as 'base_url' local variable" do scraper = stub(:base_url => "http://base.url") @parser.instance_variable_set(:@current_scraper, scraper) assert_equal "http://base.url", @parser.send(:eval_parsing_code, "base_url") # will raise exception unless base_url local variable exists end end context "when processing" do context "in general" do setup do @dummy_hpricot = stub_everything @parser.stubs(:eval_parsing_code) end should "return self" do assert_equal @parser, @parser.process(@dummy_hpricot) end should "save given scraper in instance variable" do scraper = stub assert_equal scraper, @parser.process(@dummy_hpricot, scraper).instance_variable_get(:@current_scraper) end should "eval item_parser code on hpricot doc" do @parser.expects(:eval_parsing_code).with('foo="bar"', @dummy_hpricot ) @parser.process(@dummy_hpricot) end should "eval attribute_parser code on hpricot doc if no item_parser" do no_item_parser_parser = Factory.build(:parser, :item_parser => nil) dummy_hpricot = mock no_item_parser_parser.expects(:eval_parsing_code).with(){ |code, item| (code =~ /bar/) && (item == dummy_hpricot) } no_item_parser_parser.process(dummy_hpricot) end end context "and single item is returned" do setup do @dummy_item = stub @dummy_hpricot = stub @parser.stubs(:eval_parsing_code).with(@parser.item_parser, @dummy_hpricot).returns(@dummy_item) end should "evaluate each attribute_parser on item" do @parser.expects(:eval_parsing_code).twice.with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item) } @parser.process(@dummy_hpricot) end should "store result of attribute_parser as hash using attribute_parser keys" do @parser.expects(:eval_parsing_code).twice.with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item) }.returns("some value") assert_equal ([{:foo => "some value", :foo1 => "some value"}]), @parser.process(@dummy_hpricot).results end end context "and array of items is returned" do setup do @dummy_item_1, @dummy_item_2 = stub, stub @dummy_hpricot = stub @parser.stubs(:eval_parsing_code).with(@parser.item_parser, @dummy_hpricot).returns([@dummy_item_1, @dummy_item_2]) end should "evaluate each attribute_parser value on item" do @parser.expects(:eval_parsing_code).twice.with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item_1) } @parser.expects(:eval_parsing_code).twice.with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item_2) } @parser.process(@dummy_hpricot) end should "store result of attribute_parser as hash using attribute_parser keys" do @parser.stubs(:eval_parsing_code).with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item_1) }.returns("some value") @parser.stubs(:eval_parsing_code).with(){ |code, item| (code =~ /bar/)&&(item == @dummy_item_2) }.returns("another value") assert_equal ([{ :foo => "some value", :foo1 => "some value" }, { :foo => "another value", :foo1 => "another value" }]), @parser.process(@dummy_hpricot).results end end context "and array of items returned includes nil" do setup do @dummy_item_1 = stub @dummy_hpricot = stub @parser.stubs(:eval_parsing_code).with(@parser.item_parser, @dummy_hpricot).returns([@dummy_item_1, nil]) end should "evaluate each attribute_parser on non-nil items only" do @parser.stubs(:eval_parsing_code).with(){ |code, item| item == @dummy_item_1 } @parser.expects(:eval_parsing_code).never.with(){ |code, item| (code == "\"bar1\"")&&item.nil? } assert @parser.process(@dummy_hpricot).errors.empty? # failing expectation will raise exception, which will get caught and added to errors. Maybe move functionality into own method, but for the moment this works end should "return no results for nil item" do @parser.stubs(:eval_parsing_code).with(anything, @dummy_item_1).returns("some value") assert_equal ([{ :foo => "some value", :foo1 => "some value" }]), @parser.process(@dummy_hpricot).results end end context "and problems occur when parsing items" do setup do @dummy_hpricot_for_problem_parser = Hpricot("some text") @problem_parser = Parser.new(:item_parser => "foo + bar") @problem_parser.instance_eval("@results='foo'") # doesn't like instance_variable_set end should "not raise exception" do assert_nothing_raised() { @problem_parser.process(@dummy_hpricot_for_problem_parser) } end should "return self" do assert_equal @problem_parser, @problem_parser.process(@dummy_hpricot_for_problem_parser) end should "store errors in parser" do errors = @problem_parser.process(@dummy_hpricot_for_problem_parser).errors[:base] assert_match /Exception raised.+parsing items/, errors assert_match /Problem .+parsing code.+foo \+ bar/m, errors assert_match /Hpricot.+#{@dummy_hpricot_for_problem_parser.inspect}/m, errors end should "wipe previous results variable" do assert_nil @problem_parser.process(@dummy_hpricot_for_problem_parser).results end end context "and problems occur when parsing attributes" do setup do @dummy_item_1, @dummy_item_2 = "String_1", "String_2" @dummy_hpricot_for_attrib_prob = stub @problem_parser = Parser.new(:item_parser => "#nothing here", :attribute_parser => {:full_name => "foobar"}) # => unknown local variable @problem_parser.stubs(:eval_parsing_code).with("#nothing here", @dummy_hpricot_for_attrib_prob).returns([@dummy_item_1, @dummy_item_2]) end should "not raise exception" do assert_nothing_raised() { @problem_parser.process(@dummy_hpricot_for_attrib_prob) } end should "return self" do assert_equal @problem_parser, @problem_parser.process(@dummy_hpricot_for_attrib_prob) end should "store errors in parser" do errors = @problem_parser.process(@dummy_hpricot_for_attrib_prob).errors[:base] assert_match /Exception raised.+parsing attributes/, errors assert_match /Problem .+parsing code.+foobar/m, errors assert_match /Hpricot.+#{@dummy_item_1.inspect}/m, errors end end end end private def dummy_response(response_name) IO.read(File.join([RAILS_ROOT + "/test/fixtures/dummy_responses/#{response_name.to_s}.html"])) end def code_to_parse(some_code="item") some_code.taint end end <file_sep>require 'net/http' require 'net/https' require 'rubygems' require 'active_support' # Plugin for applications to automatically post errors to the Hoptoad of their choice. module HoptoadNotifier IGNORE_DEFAULT = ['ActiveRecord::RecordNotFound', 'ActionController::RoutingError', 'ActionController::InvalidAuthenticityToken', 'CGI::Session::CookieStore::TamperedWithCookie', 'ActionController::UnknownAction'] # Some of these don't exist for Rails 1.2.*, so we have to consider that. IGNORE_DEFAULT.map!{|e| eval(e) rescue nil }.compact! IGNORE_DEFAULT.freeze IGNORE_USER_AGENT_DEFAULT = [] VERSION = "1.2.2" LOG_PREFIX = "** [Hoptoad] " class << self attr_accessor :host, :port, :secure, :api_key, :http_open_timeout, :http_read_timeout, :proxy_host, :proxy_port, :proxy_user, :proxy_pass, :output def backtrace_filters @backtrace_filters ||= [] end def ignore_by_filters @ignore_by_filters ||= [] end # Takes a block and adds it to the list of ignore filters. When the filters # run, the block will be handed the exception. If the block yields a value # equivalent to "true," the exception will be ignored, otherwise it will be # processed by hoptoad. def ignore_by_filter &block self.ignore_by_filters << block end # Takes a block and adds it to the list of backtrace filters. When the filters # run, the block will be handed each line of the backtrace and can modify # it as necessary. For example, by default a path matching the RAILS_ROOT # constant will be transformed into "[RAILS_ROOT]" def filter_backtrace &block self.backtrace_filters << block end # The port on which your Hoptoad server runs. def port @port || (secure ? 443 : 80) end # The host to connect to. def host @host ||= 'hoptoad<EMAIL>' end # The HTTP open timeout (defaults to 2 seconds). def http_open_timeout @http_open_timeout ||= 2 end # The HTTP read timeout (defaults to 5 seconds). def http_read_timeout @http_read_timeout ||= 5 end # Returns the list of errors that are being ignored. The array can be appended to. def ignore @ignore ||= (HoptoadNotifier::IGNORE_DEFAULT.dup) @ignore.flatten! @ignore end # Sets the list of ignored errors to only what is passed in here. This method # can be passed a single error or a list of errors. def ignore_only=(names) @ignore = [names].flatten end # Returns the list of user agents that are being ignored. The array can be appended to. def ignore_user_agent @ignore_user_agent ||= (HoptoadNotifier::IGNORE_USER_AGENT_DEFAULT.dup) @ignore_user_agent.flatten! @ignore_user_agent end # Sets the list of ignored user agents to only what is passed in here. This method # can be passed a single user agent or a list of user agents. def ignore_user_agent_only=(names) @ignore_user_agent = [names].flatten end # Returns a list of parameters that should be filtered out of what is sent to Hoptoad. # By default, all "password" attributes will have their contents replaced. def params_filters @params_filters ||= %w(password) end def environment_filters @environment_filters ||= %w() end def report_ready write_verbose_log("Notifier #{VERSION} ready to catch errors") end def report_environment_info write_verbose_log("Environment Info: #{environment_info}") end def report_response_body(response) write_verbose_log("Response from Hoptoad: \n#{response}") end def environment_info info = "[Ruby: #{RUBY_VERSION}]" info << " [Rails: #{::Rails::VERSION::STRING}] [RailsEnv: #{RAILS_ENV}]" if defined?(Rails) end def write_verbose_log(message) logger.info LOG_PREFIX + message if logger end # Checking for the logger in hopes we can get rid of the ugly syntax someday def logger if defined?(Rails.logger) Rails.logger elsif defined?(RAILS_DEFAULT_LOGGER) RAILS_DEFAULT_LOGGER end end # Call this method to modify defaults in your initializers. # # HoptoadNotifier.configure do |config| # config.api_key = '<KEY>' # config.secure = false # end # # NOTE: secure connections are not yet supported. def configure add_default_filters yield self if defined?(ActionController::Base) && !ActionController::Base.include?(HoptoadNotifier::Catcher) ActionController::Base.send(:include, HoptoadNotifier::Catcher) end report_ready end def protocol #:nodoc: secure ? "https" : "http" end def url #:nodoc: URI.parse("#{protocol}://#{host}:#{port}/notices/") end def default_notice_options #:nodoc: { :api_key => HoptoadNotifier.api_key, :error_message => 'Notification', :backtrace => caller, :request => {}, :session => {}, :environment => ENV.to_hash } end # You can send an exception manually using this method, even when you are not in a # controller. You can pass an exception or a hash that contains the attributes that # would be sent to Hoptoad: # * api_key: The API key for this project. The API key is a unique identifier that Hoptoad # uses for identification. # * error_message: The error returned by the exception (or the message you want to log). # * backtrace: A backtrace, usually obtained with +caller+. # * request: The controller's request object. # * session: The contents of the user's session. # * environment: ENV merged with the contents of the request's environment. def notify notice = {} Sender.new.notify_hoptoad( notice ) end def add_default_filters self.backtrace_filters.clear filter_backtrace do |line| line.gsub(/#{RAILS_ROOT}/, "[RAILS_ROOT]") end filter_backtrace do |line| line.gsub(/^\.\//, "") end filter_backtrace do |line| if defined?(Gem) Gem.path.inject(line) do |line, path| line.gsub(/#{path}/, "[GEM_ROOT]") end end end filter_backtrace do |line| line if line !~ /lib\/#{File.basename(__FILE__)}/ end end end # Include this module in Controllers in which you want to be notified of errors. module Catcher def self.included(base) #:nodoc: if base.instance_methods.include? 'rescue_action_in_public' and !base.instance_methods.include? 'rescue_action_in_public_without_hoptoad' base.send(:alias_method, :rescue_action_in_public_without_hoptoad, :rescue_action_in_public) base.send(:alias_method, :rescue_action_in_public, :rescue_action_in_public_with_hoptoad) end end # Overrides the rescue_action method in ActionController::Base, but does not inhibit # any custom processing that is defined with Rails 2's exception helpers. def rescue_action_in_public_with_hoptoad exception notify_hoptoad(exception) unless ignore?(exception) || ignore_user_agent? rescue_action_in_public_without_hoptoad(exception) end # This method should be used for sending manual notifications while you are still # inside the controller. Otherwise it works like HoptoadNotifier.notify. def notify_hoptoad hash_or_exception if public_environment? notice = normalize_notice(hash_or_exception) notice = clean_notice(notice) send_to_hoptoad(:notice => notice) end end # Returns the default logger or a logger that prints to STDOUT. Necessary for manual # notifications outside of controllers. def logger ActiveRecord::Base.logger rescue @logger ||= Logger.new(STDERR) end private def public_environment? #nodoc: defined?(RAILS_ENV) and !['development', 'test'].include?(RAILS_ENV) end def ignore?(exception) #:nodoc: ignore_these = HoptoadNotifier.ignore.flatten ignore_these.include?(exception.class) || ignore_these.include?(exception.class.name) || HoptoadNotifier.ignore_by_filters.find {|filter| filter.call(exception_to_data(exception))} end def ignore_user_agent? #:nodoc: # Rails 1.2.6 doesn't have request.user_agent, so check for it here user_agent = request.respond_to?(:user_agent) ? request.user_agent : request.env["HTTP_USER_AGENT"] HoptoadNotifier.ignore_user_agent.flatten.any? { |ua| ua === user_agent } end def exception_to_data exception #:nodoc: data = { :api_key => HoptoadNotifier.api_key, :error_class => exception.class.name, :error_message => "#{exception.class.name}: #{exception.message}", :backtrace => exception.backtrace, :environment => ENV.to_hash } if self.respond_to? :request data[:request] = { :params => request.parameters.to_hash, :rails_root => File.expand_path(RAILS_ROOT), :url => "#{request.protocol}#{request.host}#{request.request_uri}" } data[:environment].merge!(request.env.to_hash) end if self.respond_to? :session data[:session] = { :key => session.instance_variable_get("@session_id"), :data => session.respond_to?(:to_hash) ? session.to_hash : session.instance_variable_get("@data") } end data end def normalize_notice(notice) #:nodoc: case notice when Hash HoptoadNotifier.default_notice_options.merge(notice) when Exception HoptoadNotifier.default_notice_options.merge(exception_to_data(notice)) end end def clean_notice(notice) #:nodoc: notice[:backtrace] = clean_hoptoad_backtrace(notice[:backtrace]) if notice[:request].is_a?(Hash) && notice[:request][:params].is_a?(Hash) notice[:request][:params] = filter_parameters(notice[:request][:params]) if respond_to?(:filter_parameters) notice[:request][:params] = clean_hoptoad_params(notice[:request][:params]) end if notice[:environment].is_a?(Hash) notice[:environment] = filter_parameters(notice[:environment]) if respond_to?(:filter_parameters) notice[:environment] = clean_hoptoad_environment(notice[:environment]) end clean_non_serializable_data(notice) end def log(level, message, response = nil) logger.send level, LOG_PREFIX + message if logger HoptoadNotifier.report_environment_info HoptoadNotifier.report_response_body(response.body) if response && response.respond_to?(:body) end def send_to_hoptoad data #:nodoc: headers = { 'Content-type' => 'application/x-yaml', 'Accept' => 'text/xml, application/xml' } url = HoptoadNotifier.url http = Net::HTTP::Proxy(HoptoadNotifier.proxy_host, HoptoadNotifier.proxy_port, HoptoadNotifier.proxy_user, HoptoadNotifier.proxy_pass).new(url.host, url.port) http.use_ssl = true http.read_timeout = HoptoadNotifier.http_read_timeout http.open_timeout = HoptoadNotifier.http_open_timeout http.use_ssl = !!HoptoadNotifier.secure response = begin http.post(url.path, stringify_keys(data).to_yaml, headers) rescue TimeoutError => e log :error, "Timeout while contacting the Hoptoad server." nil end case response when Net::HTTPSuccess then log :info, "Success: #{response.class}", response else log :error, "Failure: #{response.class}", response end end def clean_hoptoad_backtrace backtrace #:nodoc: if backtrace.to_a.size == 1 backtrace = backtrace.to_a.first.split(/\n\s*/) end filtered = backtrace.to_a.map do |line| HoptoadNotifier.backtrace_filters.inject(line) do |line, proc| proc.call(line) end end filtered.compact end def clean_hoptoad_params params #:nodoc: params.each do |k, v| params[k] = "[FILTERED]" if HoptoadNotifier.params_filters.any? do |filter| k.to_s.match(/#{filter}/) end end end def clean_hoptoad_environment env #:nodoc: env.each do |k, v| env[k] = "[FILTERED]" if HoptoadNotifier.environment_filters.any? do |filter| k.to_s.match(/#{filter}/) end end end def clean_non_serializable_data(data) #:nodoc: case data when Hash data.inject({}) do |result, (key, value)| result.update(key => clean_non_serializable_data(value)) end when Fixnum, Array, String, Bignum data else data.to_s end end def stringify_keys(hash) #:nodoc: hash.inject({}) do |h, pair| h[pair.first.to_s] = pair.last.is_a?(Hash) ? stringify_keys(pair.last) : pair.last h end end end # A dummy class for sending notifications manually outside of a controller. class Sender def rescue_action_in_public(exception) end include HoptoadNotifier::Catcher end end <file_sep>require 'test_helper' class PortalSystemTest < ActiveSupport::TestCase context "The PortalSystem class" do setup do @existing_portal = Factory.create(:portal_system) end should_validate_presence_of :name should_validate_uniqueness_of :name should_have_many :councils should_have_many :parsers end context "A PortalSystem instance" do setup do @existing_portal = Factory.create(:portal_system) end should "alias name as title" do assert_equal @existing_portal.name, @existing_portal.title end end end <file_sep>module ScrapedModel module ClassMethods # default find_existing. Overwrite in models that include this mixin if necessary def find_existing(params) find_by_council_id_and_uid(params[:council_id], params[:uid]) end def build_or_update(params) existing_record = find_existing(params) existing_record.attributes = params if existing_record existing_record || self.new(params) end def create_or_update_and_save(params) updated_record = self.build_or_update(params) updated_record.save_without_losing_dirty updated_record end def create_or_update_and_save!(params) updated_record = build_or_update(params) updated_record.save_without_losing_dirty || raise(ActiveRecord::RecordNotSaved) updated_record end end module InstanceMethods def save_without_losing_dirty ch_attributes = changed_attributes.clone success = save # this clears changed attributes changed_attributes.update(ch_attributes) # so merge them back in success # return result of saving end def new_record_before_save? instance_variable_get(:@new_record_before_save) end protected # Updates timestamp of council when member details are updated, new member is added or deleted def mark_council_as_updated council.update_attribute(:updated_at, Time.now) if council end end def self.included(i_class) i_class.extend ClassMethods i_class.send :include, InstanceMethods i_class.after_save :mark_council_as_updated i_class.after_destroy :mark_council_as_updated end end<file_sep>Factory.define :scraper, :class => :item_scraper do |s| s.url 'http://www.anytown.gov.uk/members/bob' s.association :parser s.association :council end Factory.define :item_scraper, :class => :item_scraper do |s| s.url 'http://www.anytown.gov.uk/members' s.association :parser s.association :council, :factory => :tricky_council end Factory.define :info_scraper, :class => :info_scraper do |s| s.association :parser, :factory => :another_parser s.association :council, :factory => :another_council end Factory.define :parser do |f| f.description 'description of dummy parser' f.item_parser 'foo="bar"' f.result_model 'Member' f.scraper_type 'ItemScraper' f.attribute_parser({:foo => "\"bar\"", :foo1 => "\"bar1\""}) end Factory.define :another_parser, :parent => :parser do |f| f.description 'another dummy parser' f.scraper_type 'InfoScraper' end Factory.define :council do |f| f.name 'Anytown' f.url 'http://www.anytown.gov.uk' end Factory.define :another_council, :class => :council do |f| f.name 'Anothertown' f.url 'http://www.anothertown.gov.uk' end Factory.define :tricky_council, :class => :council do |f| f.name 'Tricky Town' f.url 'http://www.trickytown.gov.uk' end Factory.define :member do |f| f.full_name "<NAME>" f.uid 99 f.url "http://www.anytown.gov.uk/members/bob" f.association :council end Factory.define :old_member, :class => :member do |f| f.full_name "<NAME>" f.uid 88 f.url "http://www.anytown.gov.uk/members/yeller" f.date_left 6.months.ago f.association :council end Factory.define :committee do |f| f.uid 77 f.association :council f.title 'Ways and Means' f.url "http://www.anytown.gov.uk/committee/77" end Factory.define :meeting do |f| f.uid 123 f.association :council f.association :committee f.date_held 2.weeks.ago f.url "http://www.anytown.gov.uk/meeting/123" end Factory.define :portal_system do |f| f.name 'SuperPortal' f.url "http://www.superportal.com" end Factory.define :document do |f| f.url "http://www.council.gov.uk/document/33" f.body "This is a document" end Factory.define :dataset do |f| f.key "abc123" f.title "Dummy dataset" f.query "some query" end Factory.define :datapoint do |f| f.association :council f.association :dataset f.data "some data" end<file_sep>require 'test_helper' class CouncilsControllerTest < ActionController::TestCase def setup @member = Factory(:member) @council = @member.council @old_member = Factory(:old_member, :council => @council) @another_council = Factory(:another_council) @committee = Factory(:committee, :council => @council) end # index test context "on GET to :index" do context "with basic request" do setup do get :index end should_assign_to(:councils) { [@council]} # only parsed councils should_respond_with :success should_render_template :index end context "including unparsed councils" do setup do get :index, :include_unparsed => true end should_assign_to(:councils) { Council.find(:all, :order => "name")} # all councils should_respond_with :success should_render_template :index should "class unparsed councils as unparsed" do assert_select "#councils .unparsed", @another_council.name end should "class parsed councils as parsed" do assert_select "#councils .parsed", @council.name end end context "with xml requested" do setup do get :index, :format => "xml" end should_assign_to(:councils) { [@council]} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :index, :format => "json" end should_assign_to(:councils) { [@council]} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end # show test context "on GET to :show " do context "with basic request" do setup do get :show, :id => @council.id end should_assign_to(:council) { @council} should_respond_with :success should_render_template :show should_assign_to(:members) { @council.members.current } should "list all members" do assert_select "#members li", @council.members.current.size end should "list all committees" do assert_select "#committees li", @council.committees.size end end context "with xml requested" do setup do get :show, :id => @council.id, :format => "xml" end should_assign_to(:council) { @council} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :show, :id => @council.id, :format => "json" end should_assign_to(:council) { @council} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end context "when council has datapoints" do setup do @datapoint = Factory(:datapoint, :council => @council) @dataset = @datapoint.dataset Council.any_instance.stubs(:datapoints).returns([@datapoint, @datapoint]) end context "with summary" do setup do @datapoint.stubs(:summary => ["heading_1", "data_1"]) get :show, :id => @council.id end should_assign_to :datapoints should "show datapoint data" do assert_select "#datapoints" do assert_select ".datapoint", 2 do assert_select "div", /data_1/ end end end should "show links to full datapoint data" do assert_select "#datapoints" do assert_select "a.more_info[href*='datasets/#{@dataset.id}/data']" end end end context "without summary" do setup do @datapoint.stubs(:summary) get :show, :id => @council.id end should_assign_to(:datapoints) {[]} should "not show datapoint data" do assert_select "#datapoints", false end end context "with xml requested" do setup do @datapoint.stubs(:summary => ["heading_1", "data_1"]) get :show, :id => @council.id, :format => "xml" end should "show associated datasets" do assert_select "council>datasets>dataset>id", @datapoint.dataset.id end end context "with json requested" do setup do @datapoint.stubs(:summary => ["heading_1", "data_1"]) get :show, :id => @council.id, :format => "json" end should "show associated datasets" do assert_match /dataset.+#{@datapoint.dataset.title}/, @response.body end end end end # new test context "on GET to :new without auth" do setup do get :new end should_respond_with 401 end context "on GET to :new" do setup do stub_authentication get :new end should_assign_to(:council) should_respond_with :success should_render_template :new should "show form" do assert_select "form#new_council" end should "show possible portal_systems in form" do assert_select "select#council_portal_system_id" end end # create test context "on POST to :create" do setup do @council_params = { :name => "Some Council", :url => "http://somecouncil.gov.uk"} end context "description" do setup do post :create, :council => @council_params end should_respond_with 401 end context "with valid params" do setup do stub_authentication post :create, :council => @council_params end should_change "Council.count", :by => 1 should_assign_to :council should_redirect_to( "the show page for council") { council_path(assigns(:council)) } should_set_the_flash_to "Successfully created council" end context "with invalid params" do setup do stub_authentication post :create, :council => @council_params.except(:name) end should_not_change "Council.count" should_assign_to :council should_render_template :new should_not_set_the_flash end end # edit test context "on GET to :edit without auth" do setup do get :edit, :id => @council end should_respond_with 401 end context "on GET to :edit with existing record" do setup do stub_authentication get :edit, :id => @council end should_assign_to(:council) should_respond_with :success should_render_template :edit should "show form" do assert_select "form#edit_council_#{@council.id}" end end # update test context "on PUT to :update" do setup do @council_params = { :name => "<NAME> SomeCouncil", :url => "http://somecouncil.gov.uk/new"} end context "without auth" do setup do put :update, :id => @council.id, :council => @council_params end should_respond_with 401 end context "with valid params" do setup do stub_authentication put :update, :id => @council.id, :council => @council_params end should_not_change "Council.count" should_change "@council.reload.name", :to => "New Name for SomeCouncil" should_change "@council.reload.url", :to => "http://somecouncil.gov.uk/new" should_assign_to :council should_redirect_to( "the show page for council") { council_path(assigns(:council)) } should_set_the_flash_to "Successfully updated council" end context "with invalid params" do setup do stub_authentication put :update, :id => @council.id, :council => {:name => ""} end should_not_change "Council.count" should_not_change "@council.reload.name" should_assign_to :council should_render_template :edit should_not_set_the_flash end end end <file_sep>class AddWikipediaUrlToCouncils < ActiveRecord::Migration def self.up add_column :councils, :wikipedia_url, :string add_column :councils, :ons_url, :string end def self.down remove_column :councils, :ons_url remove_column :councils, :wikipedia_url end end <file_sep>require 'test_helper' class PortalSystemsControllerTest < ActionController::TestCase def setup @portal = Factory(:portal_system) end # index test context "on GET to :index without auth" do setup do get :index end should_respond_with 401 end context "on GET to :index" do setup do stub_authentication get :index end should_assign_to(:portal_systems) { PortalSystem.find(:all)} should_respond_with :success should_render_template :index should "list portal systems" do assert_select "li a", @portal.name end should "not show share block" do assert_select "#share_block", false end end # show test context "on GET to :show without auth" do setup do get :show, :id => @portal.id end should_respond_with 401 end context "on GET to :show for first record" do setup do @council = Factory(:council, :portal_system_id => @portal.id) @parser = Factory(:parser, :portal_system => @portal) stub_authentication get :show, :id => @portal.id end should_assign_to(:portal_system) { @portal} should_respond_with :success should_render_template :show should_assign_to(:councils) { @portal.councils } should "list all councils" do assert_select "#councils li", @portal.councils.size do assert_select "a", @council.title end end should "list all parsers" do assert_select "#parsers li" do assert_select "a", @parser.title end end should "not show share block" do assert_select "#share_block", false end end # new test context "on GET to :new without auth" do setup do get :new end should_respond_with 401 end context "on GET to :new" do setup do stub_authentication get :new end should_assign_to(:portal_system) should_respond_with :success should_render_template :new should "show form" do assert_select "form#new_portal_system" end end # create test context "on POST to :create" do context "without auth" do setup do post :create, :portal_system => {:name => "New Portal", :url => "http:://new_portal.com"} end should_respond_with 401 end context "with valid params" do setup do stub_authentication post :create, :portal_system => {:name => "New Portal", :url => "http:://new_portal.com"} end should_change "PortalSystem.count", :by => 1 should_assign_to :portal_system should_redirect_to( "the show page for portal_system") { portal_system_path(assigns(:portal_system)) } should_set_the_flash_to "Successfully created portal system" end context "with invalid params" do setup do stub_authentication post :create, :portal_system => {:url => "http:://new_portal.com"} end should_not_change "PortalSystem.count" should_assign_to :portal_system should_render_template :new should_not_set_the_flash end end # edit test context "on GET to :edit without auth" do setup do get :edit, :id => @portal end should_respond_with 401 end context "on GET to :edit with existing record" do setup do stub_authentication get :edit, :id => @portal end should_assign_to(:portal_system) should_respond_with :success should_render_template :edit should "show form" do assert_select "form#edit_portal_system_#{@portal.id}" end end # update test context "on PUT to :update" do context "without auth" do setup do put :update, :id => @portal.id, :portal_system => { :name => "New Name", :url => "http://new.name.com"} end should_respond_with 401 end context "with valid params" do setup do stub_authentication put :update, :id => @portal.id, :portal_system => { :name => "<NAME>", :url => "http://new.name.com"} end should_not_change "PortalSystem.count" should_change "@portal.reload.name", :to => "New Name" should_change "@portal.reload.url", :to => "http://new.name.com" should_assign_to :portal_system should_redirect_to( "the show page for portal system") { portal_system_path(assigns(:portal_system)) } should_set_the_flash_to "Successfully updated portal system" end context "with invalid params" do setup do stub_authentication put :update, :id => @portal.id, :portal_system => {:name => ""} end should_not_change "PortalSystem.count" should_not_change "@portal.reload.name" should_assign_to :portal_system should_render_template :edit should_not_set_the_flash end end end <file_sep>class AddPathToParser < ActiveRecord::Migration def self.up add_column :parsers, :path, :string end def self.down remove_column :parsers, :path end end <file_sep>class AddDefaultToProblematic < ActiveRecord::Migration def self.up change_column_default :scrapers, :problematic, false Scraper.update_all(:problematic => false) end def self.down end end <file_sep>class AddRawBodyToDocuments < ActiveRecord::Migration def self.up add_column :documents, :raw_body, :text end def self.down remove_column :documents, :raw_body end end <file_sep>require 'net/http' require 'uri' require 'active_support' module HoptoadTasks def self.deploy(opts = {}) if HoptoadNotifier.api_key.blank? puts "I don't seem to be configured with an API key. Please check your configuration." return false end if opts[:rails_env].blank? puts "I don't know to which Rails environment you are deploying (use the TO=production option)." return false end params = {:api_key => HoptoadNotifier.api_key} opts.each {|k,v| params["deploy[#{k}]"] = v } url = URI.parse("http://#{HoptoadNotifier.host}/deploys.txt") response = Net::HTTP.post_form(url, params) puts response.body return Net::HTTPSuccess === response end end <file_sep>class ParsersController < ApplicationController before_filter :authenticate skip_before_filter :share_this def show @parser = Parser.find(params[:id]) @scrapers = @parser.scrapers end def new raise ArgumentError unless params[:portal_system_id]&&params[:scraper_type] @parser = PortalSystem.find(params[:portal_system_id]).parsers.build(:result_model => params[:result_model], :scraper_type => params[:scraper_type]) end def edit @parser = Parser.find(params[:id]) end def create @parser = Parser.new(params[:parser]) @parser.save! flash[:notice] = "Successfully created parser" redirect_to parser_path(@parser) rescue render :action => "new" end def update @parser = Parser.find(params[:id]) @parser.update_attributes!(params[:parser]) flash[:notice] = "Successfully updated parser" redirect_to parser_url(@parser) rescue render :action => "edit" end end <file_sep>require 'test_helper' class ScrapersControllerTest < ActionController::TestCase # index test context "on GET to :index without auth" do setup do Factory(:scraper) get :index end should_respond_with 401 end context "on GET to :index" do setup do stub_authentication @scraper1 = Factory(:scraper) @portal_system = Factory(:portal_system) @council2 = Factory(:another_council, :portal_system => @portal_system) @scraper2 = Factory(:info_scraper, :council => @council2) get :index end should_assign_to :councils should_respond_with :success should_render_template :index should_not_set_the_flash should "list all councils" do assert_select "#councils" do assert_select ".council", 2 do assert_select "h3 a", @scraper1.council.name end end end should "show title" do assert_select "title", /All scrapers/ end should "list scrapers for each council" do assert_select "#council_#{@scraper1.council.id}" do assert_select "li a", @scraper1.title end end should "link to portal system if council has portal system" do assert_select "#council_#{@scraper2.council.id}" do assert_select "a", @portal_system.name end end should "not show share block" do assert_select "#share_block", false end end # show test context "on GET to :show for first record without auth" do setup do @scraper = Factory(:scraper) get :show, :id => @scraper.id end should_respond_with 401 end context "on GET to :show for first record" do setup do @scraper = Factory(:scraper) @scraper.class.any_instance.expects(:test).never stub_authentication get :show, :id => @scraper.id end should_assign_to :scraper should_respond_with :success should_render_template :show should "show scraper title in page title" do assert_select "title", /#{@scraper.title}/ end should "show link to perform dry run" do assert_select "#scraper a", /perform test scrape/ end should "show link to perform edit" do assert_select "#scraper a", /edit/ end should "not show share block" do assert_select "#share_block", false end end context "on GET to :show with :dry_run" do setup do @scraper = Factory(:scraper) end should "run process scraper" do @scraper.class.any_instance.expects(:process).returns(stub_everything) stub_authentication get :show, :id => @scraper.id, :dry_run => true end end context "on GET to :show with successful :dry_run" do setup do @scraper = Factory(:scraper) @member = Factory(:member, :council => @scraper.council) @member.save # otherwise looks like new_before_save @new_member = Member.new(:full_name => "<NAME>", :uid => 55) @scraper.class.any_instance.stubs(:process).returns(@scraper) @scraper.stubs(:results).returns([@member, @new_member]) stub_authentication get :show, :id => @scraper.id, :dry_run => true end should_assign_to :scraper, :results should_respond_with :success should "show summary of successful results" do assert_select "#results" do assert_select "div.member", 2 do assert_select "h4", /#{@member.full_name}/ assert_select "div.new", 1 do assert_select "h4", /<NAME>/ end end end end should "not show summary of problems" do assert_select "div.errorExplanation", false end end context "on GET to :show with :dry_run with request error" do setup do @scraper = Factory(:scraper) @scraper.class.any_instance.stubs(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") parser = @scraper.parser Scraper.expects(:find).returns(@scraper) stub_authentication get :show, :id => @scraper.id, :dry_run => true end should_assign_to :scraper should_respond_with :success should "show summary of problems" do assert_select "div.errorExplanation" do assert_select "li", /Problem getting data/ end end end context "on GET to :show with :dry_run with parsing problems" do setup do @scraper = Factory(:scraper) @scraper.class.any_instance.stubs(:_data).returns(stub_everything) parser = @scraper.parser parser.stubs(:results) # pretend there are no results parser.errors.add_to_base("problems ahoy") Scraper.expects(:find).returns(@scraper) stub_authentication get :show, :id => @scraper.id, :dry_run => true end should_assign_to :scraper, :results should_respond_with :success should "show summary of problems" do assert_select "div.errorExplanation" do assert_select "li", "problems ahoy" end end end context "on GET to :show with :process" do setup do @scraper = Factory(:scraper) end should "run test on scraper" do @scraper.class.any_instance.expects(:process).with(:save_results => true).returns(stub_everything) stub_authentication get :show, :id => @scraper.id, :process => true end end context "on GET to :show with successful :process" do setup do @scraper = Factory(:scraper) @scraper.class.any_instance.stubs(:_data).returns(stub_everything) @scraper.class.any_instance.stubs(:parsing_results).returns([{ :full_name => "<NAME>", :uid => 1, :url => "http://www.anytown.gov.uk/members/fred" }] ) stub_authentication get :show, :id => @scraper.id, :process => true end should_assign_to :scraper, :results should_respond_with :success should_change "Member.count", :by => 1 should "show summary of successful results" do assert_select "#results" do assert_select "div.member" do assert_select "h4", /<NAME>/ end end end should "not show summary of problems" do assert_select "div.errorExplanation", false end end context "on GET to :show with unsuccesful :process due to failed validation" do setup do @scraper = Factory(:scraper) @scraper.class.any_instance.stubs(:_data).returns(stub_everything) @scraper.class.any_instance.stubs(:parsing_results).returns([{ :full_name => "<NAME>", :uid => 1, :url => "http://www.anytown.gov.uk/members/fred" }, { :full_name => "<NAME>"}] ) stub_authentication get :show, :id => @scraper.id, :process => true end should_assign_to :scraper, :results should_change "Member.count", :by => 1 # => Not two should_respond_with :success should "show summary of problems" do assert_select "div.member div.errorExplanation" do assert_select "li", "Url can't be blank" end end should "highlight member with error" do assert_select "div.member", :count => 2 do assert_select "div.error", :count => 1 do # only one of which hs error class assert_select "div.member div.errorExplanation" #...and that has error explanation in it end end end end # new test context "on GET to :new without auth" do setup do @council = Factory(:council) get :new, :type => "InfoScraper", :council_id => @council.id end should_respond_with 401 end context "on GET to :new with no scraper type given" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :new } end end context "on GET to :new with bad scraper type" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :new, :type => "Member" } end end context "on GET to :new with no given council" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :new, :type => "InfoScraper" } end end context "on GET to :new" do setup do @council = Factory(:council) end context "for basic scraper" do setup do stub_authentication get :new, :type => "InfoScraper", :council_id => @council.id end should_assign_to :scraper should_respond_with :success should_render_template :new should_not_set_the_flash should_render_a_form should "assign given type of scraper" do assert_kind_of InfoScraper, assigns(:scraper) end should "build parser from params" do assert assigns(:scraper).parser.new_record? assert_equal "InfoScraper", assigns(:scraper).parser.scraper_type end should "show nested form for parser" do assert_select "textarea#scraper_parser_attributes_item_parser" assert_select "input#scraper_parser_attributes_attribute_parser_object__attrib_name" assert_select "input#scraper_parser_attributes_attribute_parser_object__parsing_code" end should "include scraper type in hidden field" do assert_select "input#type[type=hidden][value=InfoScraper]" end should "include council in hidden field" do assert_select "input#scraper_council_id[type=hidden][value=#{@council.id}]" end should "not show select box for possible_parsers" do assert_select "select#scraper_parser_id", false end should "not show related_model select_box for info scraper" do assert_select "select#scraper_parser_attributes_related_model", false end should "not have hidden parser details form" do assert_select "fieldset#parser_details[style='display:none']", false end should "not have link to show parser form" do assert_select "form a", :text => /use dedicated parser/i, :count => 0 end should "show hidden field with parser scraper_type" do assert_select "input#scraper_parser_attributes_scraper_type[type=hidden][value=InfoScraper]" end end context "for basic scraper with given result model" do setup do Factory(:parser, :result_model => "Committee", :scraper_type => "InfoScraper") # make sure there's at least one parser already in db with this result model stub_authentication get :new, :type => "InfoScraper", :council_id => @council.id, :result_model => "Committee" end should "build parser from params" do assert assigns(:scraper).parser.new_record? assert_equal "Committee", assigns(:scraper).result_model assert_equal "InfoScraper", assigns(:scraper).parser.scraper_type end should "show result_model select box in form" do assert_select "select#scraper_parser_attributes_result_model" do assert_select "option[value='Committee'][selected='selected']" end end end context "for basic item_scraper" do setup do stub_authentication get :new, :type => "ItemScraper", :council_id => @council.id end should_assign_to :scraper should_respond_with :success should_render_template :new should_not_set_the_flash should_render_a_form should "assign given type of scraper" do assert_kind_of ItemScraper, assigns(:scraper) assert assigns(:scraper).new_record? end should "not show related_model select_box for info scraper" do assert_select "select#scraper_parser_attributes_related_model" end end context "when scraper council has portal system" do setup do @portal_system = Factory(:portal_system, :name => "Some Portal for Councils") @portal_system.parsers << @parser = Factory(:another_parser) # add a parser to portal_system... @council.update_attribute(:portal_system_id, @portal_system.id)# .. and associate portal_system to council @parser = Factory(:parser, :portal_system => @portal_system) stub_authentication get :new, :type => "ItemScraper", :result_model => @parser.result_model, :council_id => @council.id end should_assign_to :scraper should_respond_with :success should_render_template :new should_not_set_the_flash should_render_a_form should "assign appropriate parser to scraper" do assert_equal @parser, assigns(:scraper).parser end should "show text box for url" do assert_select "input#scraper_url" end should "show hidden field with parser details" do assert_select "input#scraper_parser_id[type=hidden][value=#{@parser.id}]" end should "not show parser_details form" do assert_select "fieldset#parser_details", false end # should "have hidden parser details form" do # assert_select "fieldset#parser_details[style='display:none']" # end # # should "not use parser in parser details form" do # assert_select "fieldset#parser_details input#scraper_parser_attributes_description[value='#{@parser.description}']", false # end # # should "show result_model in parser details form" do # assert_select "select#scraper_parser_attributes_result_model option[selected='selected'][value='#{@parser.result_model}']" # end # # should "not show parser attribute_parser details in parser form" do # assert_select "input#scraper_parser_attributes_attribute_parser_object__attrib_name[value='#{@parser.attribute_parser.keys.first}']", false # end # # should "show hidden field with parser scraper_type" do # assert_select "input#scraper_parser_attributes_scraper_type[type=hidden][value=ItemScraper]" # end should "show parser details" do assert_select "div#parser_#{@parser.id}" end should "have link to show parser form" do assert_select "form a", /use dedicated parser/i end end context "when scraper council has portal system but dedicated parser specified" do setup do @portal_system = Factory(:portal_system, :name => "Some Portal for Councils") @portal_system.parsers << @parser = Factory(:another_parser) # add a parser to portal_system... @council.update_attribute(:portal_system_id, @portal_system.id)# .. and associate portal_system to council @parser = Factory(:parser, :portal_system => @portal_system) stub_authentication get :new, :type => "ItemScraper", :result_model => @parser.result_model, :council_id => @council.id, :dedicated_parser => true end should_assign_to :scraper should_respond_with :success should_render_template :new should_not_set_the_flash should_render_a_form should "assign appropriate parser to scraper" do assert_equal @parser, assigns(:scraper).parser end should "show text box for url" do assert_select "input#scraper_url" end should "show parser_details form" do assert_select "fieldset#parser_details" end should "show not show hidden field with parser details" do assert_select "input#scraper_parser_id[type=hidden][value=#{@parser.id}]", false end # should "have hidden parser details form" do # assert_select "fieldset#parser_details[style='display:none']" # end # # should "not use parser in parser details form" do # assert_select "fieldset#parser_details input#scraper_parser_attributes_description[value='#{@parser.description}']", false # end # # should "show result_model in parser details form" do # assert_select "select#scraper_parser_attributes_result_model option[selected='selected'][value='#{@parser.result_model}']" # end # # should "not show parser attribute_parser details in parser form" do # assert_select "input#scraper_parser_attributes_attribute_parser_object__attrib_name[value='#{@parser.attribute_parser.keys.first}']", false # end # # should "show hidden field with parser scraper_type" do # assert_select "input#scraper_parser_attributes_scraper_type[type=hidden][value=ItemScraper]" # end # should "show parser details" do # assert_select "div#parser_#{@parser.id}" # end # # should "have link to show parser form" do # assert_select "form a", /use dedicated parser/i # end end context "when scraper council has portal system but parser does not exist" do setup do @portal_system = Factory(:portal_system, :name => "Some Portal for Councils") @portal_system.parsers << @parser = Factory(:another_parser) # add a parser to portal_system... @council.update_attribute(:portal_system_id, @portal_system.id)# .. and associate portal_system to council @parser = Factory(:parser, :portal_system => @portal_system) stub_authentication get :new, :type => "ItemScraper", :result_model => "Meeting", :council_id => @council.id end should_assign_to :scraper should_respond_with :success should_render_template :new should_not_set_the_flash should_render_a_form should "assign appropriate fresh parser to scraper" do assert assigns(:scraper).parser.new_record? end should "show text box for url" do assert_select "input#scraper_url" end should "show parser details form" do assert_select "fieldset#parser_details" end should "show link to add new parser for portal_system" do assert_select "form p.alert", /no parser/i do assert_select "a", /add new/i end end end end # create tests context "on POST to :create" do setup do @council = Factory(:council) @portal_system = Factory(:portal_system, :name => "Another portal system") @existing_parser = Factory(:parser, :portal_system => @portal_system, :description => "existing parser") @scraper_params = { :council_id => @council.id, :url => "http://anytown.com/committees", :parser_attributes => { :description => "new parser", :result_model => "Committee", :scraper_type => "InfoScraper", :item_parser => "some code", :attribute_parser_object => [{:attrib_name => "foo", :parsing_code => "bar"}] }} @exist_scraper_params = { :council_id => @council.id, :url => "http://anytown.com/committees", :parser_id => @existing_parser.id } end context "without auth" do setup do post :create, { :type => "InfoScraper", :scraper => @scraper_params } end should_respond_with 401 end context "with no scraper type given" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { post :create, { :scraper => @scraper_params } } end end context "with bad scraper type" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :create, { :type => "Member", :scraper => @scraper_params } } end end context "with scraper type" do context "and new parser" do setup do stub_authentication post :create, { :type => "InfoScraper", :scraper => @scraper_params } end should_change "Scraper.count", :by => 1 should_assign_to :scraper should_redirect_to( "the show page for scraper") { scraper_path(assigns(:scraper)) } should_set_the_flash_to "Successfully created scraper" should "save as given scraper type" do assert_kind_of InfoScraper, assigns(:scraper) end should_change "Parser.count", :by => 1 should "save parser description" do assert_equal "new parser", assigns(:scraper).parser.description end should "save parser item_parser" do assert_equal "some code", assigns(:scraper).parser.item_parser end should "save parser attribute_parser" do assert_equal({:foo => "bar"}, assigns(:scraper).parser.attribute_parser) end end context "and existing parser" do setup do stub_authentication post :create, { :type => "InfoScraper", :scraper => @exist_scraper_params } end should_change "Scraper.count", :by => 1 should_assign_to :scraper should_redirect_to( "the show page for scraper") { scraper_path(assigns(:scraper)) } should_set_the_flash_to "Successfully created scraper" should "save as given scraper type" do assert_kind_of InfoScraper, assigns(:scraper) end should_not_change "Parser.count" should "associate existing parser to scraper " do assert_equal @existing_parser, assigns(:scraper).parser end end context "and new parser and existing parser details both given" do setup do stub_authentication post :create, { :type => "InfoScraper", :scraper => @scraper_params.merge(:parser_id => @existing_parser.id ) } end should_change "Scraper.count", :by => 1 should_change "Parser.count", :by => 1 should_assign_to :scraper should_redirect_to( "the show page for scraper") { scraper_path(assigns(:scraper)) } should_set_the_flash_to "Successfully created scraper" should "save parser description from new details" do assert_equal "new parser", assigns(:scraper).parser.description end end end end # edit tests context "on get to :edit a scraper without auth" do setup do @scraper = Factory(:scraper) get :edit, :id => @scraper.id end should_respond_with 401 end context "on get to :edit a scraper" do setup do @scraper = Factory(:scraper) stub_authentication get :edit, :id => @scraper.id end should_assign_to :scraper should_respond_with :success should_render_template :edit should_not_set_the_flash should_render_a_form should "show nested form for parser " do assert_select "input[type=hidden][value=?]#scraper_parser_attributes_id", @scraper.parser.id end end # update tests context "on PUT to :update without auth" do setup do @scraper = Factory(:scraper) put :update, { :id => @scraper.id, :scraper => { :council_id => @scraper.council_id, :result_model => "Committee", :url => "http://anytown.com/new_committees", :parser_attributes => { :id => @scraper.parser.id, :description => "new parsing description", :item_parser => "some code" }}} end should_respond_with 401 end context "on PUT to :update" do setup do @scraper = Factory(:scraper) stub_authentication put :update, { :id => @scraper.id, :scraper => { :council_id => @scraper.council_id, :url => "http://anytown.com/new_committees", :parser_attributes => { :id => @scraper.parser.id, :description => "new parsing description", :item_parser => "some code" }}} end should_assign_to :scraper should_redirect_to( "the show page for scraper") { scraper_path(@scraper) } should_set_the_flash_to "Successfully updated scraper" should "update scraper" do assert_equal "http://anytown.com/new_committees", @scraper.reload.url end should "update scraper parser" do assert_equal "new parsing description", @scraper.parser.reload.description end end # delete tests context "on delete to :destroy a scraper without auth" do setup do @scraper = Factory(:scraper) delete :destroy, :id => @scraper.id end should_respond_with 401 end context "on delete to :destroy a scraper" do setup do @scraper = Factory(:scraper) stub_authentication delete :destroy, :id => @scraper.id end should "destroy scraper" do assert_nil Scraper.find_by_id(@scraper.id) end should_redirect_to ( "the scrapers page") { scrapers_url(:anchor => "council_#{@scraper.council_id}") } should_set_the_flash_to "Successfully destroyed scraper" end end <file_sep>class ScrapersController < ApplicationController before_filter :authenticate skip_before_filter :share_this def index @councils = Council.find(:all, :include => :scrapers, :order => "name") @title = "All scrapers" end def show @scraper = Scraper.find(params[:id]) @title = @scraper.title if params[:dry_run] @results = @scraper.process.results elsif params[:process] @results = @scraper.process(:save_results => true).results end @parser = @scraper.parser end def new raise ArgumentError unless Scraper::SCRAPER_TYPES.include?(params[:type]) && params[:council_id] @council = Council.find(params[:council_id]) @scraper = params[:type].constantize.new(:council_id => @council.id) parser = @council.portal_system_id ? Parser.find_by_portal_system_id_and_result_model_and_scraper_type(@council.portal_system_id, params[:result_model], params[:type]) : nil parser ? (@scraper.parser = parser) : @scraper.build_parser(:result_model => params[:result_model], :scraper_type => params[:type]) end def create raise ArgumentError unless Scraper::SCRAPER_TYPES.include?(params[:type]) @scraper = params[:type].constantize.new(params[:scraper]) @scraper.save! flash[:notice] = "Successfully created scraper" redirect_to scraper_url(@scraper) end def edit @scraper = Scraper.find(params[:id]) end def update @scraper = Scraper.find(params[:id]) @scraper.update_attributes!(params[:scraper]) flash[:notice] = "Successfully updated scraper" redirect_to scraper_url(@scraper) end def destroy @scraper = Scraper.find(params[:id]) @scraper.destroy flash[:notice] = "Successfully destroyed scraper" redirect_to scrapers_url(:anchor => "council_#{@scraper.council_id}") end end <file_sep>class CreateDatasets < ActiveRecord::Migration def self.up create_table :datasets do |t| t.string :title t.string :key t.string :source t.string :query t.timestamps end end def self.down drop_table :datasets end end <file_sep>require 'test_helper' class ScrapersHelperTest < ActionView::TestCase include ApplicationHelper include ScrapersHelper context "class_for_result helper method" do should "return empty string by default" do assert_equal "unchanged", class_for_result(stub_everything(:errors => [])) end should "return new when record is new" do assert_equal "new", class_for_result(stub_everything(:new_record? => true, :errors => [])) end should "return new when record was new before saving" do assert_equal "new", class_for_result(stub_everything(:new_record_before_save? => true, :errors => [])) end should "return error when record has errors" do assert_equal "unchanged error", class_for_result(stub_everything(:errors => ["foo"])) end should "return changed when record has changed" do assert_equal "changed", class_for_result(stub_everything(:changed? => true, :errors => [])) end should "return just new when record is new and has changed" do assert_equal "new", class_for_result(stub_everything(:changed? => true, :new_record? => true, :errors => [])) end should "return multiple class when record is new and has errors" do assert_equal "new error", class_for_result(stub_everything(:errors => ["foo"], :new_record? => true)) end end context "flash_for_result helper method" do should "return empty string by default" do assert_nil flash_for_result(stub_everything(:errors => [])) end should "return new when record is new" do assert_dom_equal "<span class='new flash'>new</span>", flash_for_result(stub_everything(:new_record? => true, :errors => [])) end should "return new when record was new before saving" do assert_dom_equal "<span class='new flash'>new</span>", flash_for_result(stub_everything(:new_record_before_save? => true, :errors => [])) end should "return error when record has errors" do assert_dom_equal "<span class='unchanged error flash'>unchanged error</span>", flash_for_result(stub_everything(:errors => ["foo"])) end should "return changed when record has changed" do assert_dom_equal "<span class='changed flash'>changed</span>", flash_for_result(stub_everything(:changed? => true, :errors => [])) end should "return just new when record is new and has changed" do assert_dom_equal "<span class='new flash'>new</span>", flash_for_result(stub_everything(:changed? => true, :new_record? => true, :errors => [])) end should "return mutiple class when record is new and has errors" do assert_dom_equal "<span class='new error flash'>new error</span>", flash_for_result(stub_everything(:errors => ["foo"], :new_record? => true)) end end context "changed_attributes helper method" do setup do @member = Factory.create(:member) @member.save # save again so record is not newly created end should "show message if no changed attributes" do assert_dom_equal content_tag(:div, "Record is unchanged"), changed_attributes_list(@member) end should "list only attributes that have changed" do @member.first_name = "Pete" @member.telephone = "0123 456 789" assert_dom_equal content_tag(:div, content_tag(:ul, content_tag(:li, "first_name <strong>Pete</strong> (was Bob)") + content_tag(:li, "telephone <strong>0123 456 789</strong> (was empty)")), :class => "changed_attributes"), changed_attributes_list(@member) end end context "scraper_links_for_council helper method" do setup do @scraper = Factory(:scraper, :last_scraped => 2.days.ago) @council = @scraper.council end should "return array" do assert_kind_of Array, scraper_links_for_council(@council) end should "return array of links for council's scrapers" do assert_equal link_for(@scraper), scraper_links_for_council(@council).first end should "return links for all possible scrapers" do assert_equal Scraper::SCRAPER_TYPES.size*Parser::ALLOWED_RESULT_CLASSES.size, scraper_links_for_council(@council).size end should "class as problem if scraper is problematic" do @scraper.class.any_instance.stubs(:problematic?).returns(true) assert_equal link_for(@scraper, :class => "problem"), scraper_links_for_council(@council).first end should "class as stale if scraper is stale" do @scraper.class.any_instance.stubs(:stale?).returns(true) assert_equal link_for(@scraper, :class => "stale"), scraper_links_for_council(@council).first end should "class as problem and stale if scraper is problematic and stale" do @scraper.class.any_instance.stubs(:stale?).returns(true) @scraper.class.any_instance.stubs(:problematic?).returns(true) assert_equal link_for(@scraper, :class => "problem stale"), scraper_links_for_council(@council).first end should "return links for not yet created scrapers" do links = scraper_links_for_council(@council) assert links.include?(link_to("Add Committee item scraper for #{@council.name} council", new_scraper_path(:council_id => @council.id, :result_model => "Committee", :type => "ItemScraper"), :class => "new_scraper_link")) end end end<file_sep>class CreateMeetings < ActiveRecord::Migration def self.up create_table :meetings do |t| t.date :date_held t.string :agenda_url t.string :minutes_pdf t.string :minutes_rtf t.timestamps end end def self.down drop_table :meetings end end <file_sep>class ChangeMeetingHeldAtToDateTime < ActiveRecord::Migration def self.up change_column :meetings, :date_held, :datetime end def self.down change_column :meetings, :date_held, :date end end <file_sep>class Membership < ActiveRecord::Base belongs_to :member # belongs_to :uid_member, :foreign_key => :member_uid, :conditions => ?? belongs_to :committee # belongs_to :council validates_presence_of :member_id validates_presence_of :committee_id end <file_sep>class CouncilsController < ApplicationController before_filter :authenticate, :except => [:index, :show] def index @councils = params[:include_unparsed] ? Council.find(:all, :order => "name") : Council.parsed @title = "All Councils" respond_to do |format| format.html format.xml { render :xml => @councils.to_xml } format.json { render :json => @councils.to_json } end end def show @council = Council.find(params[:id]) @members = @council.members.current @datapoints = @council.datapoints.select{ |d| d.summary } respond_to do |format| format.html format.xml { render :xml => @council.to_xml(:include => :datasets) } format.json { render :json => @council.to_json(:include => :datasets) } end end def new @council = Council.new end def create @council = Council.new(params[:council]) @council.save! flash[:notice] = "Successfully created council" redirect_to council_path(@council) rescue render :action => "new" end def edit @council = Council.find(params[:id]) end def update @council = Council.find(params[:id]) @council.update_attributes!(params[:council]) flash[:notice] = "Successfully updated council" redirect_to council_path(@council) rescue render :action => "edit" end end <file_sep>require File.dirname(__FILE__) + '/helper' class LoggerTest < Test::Unit::TestCase class ::LoggerController < ::ActionController::Base include HoptoadNotifier::Catcher include TestMethods def rescue_action e rescue_action_in_public e end end def stub_http(response) @http = stub(:post => response, :read_timeout= => nil, :open_timeout= => nil, :use_ssl= => nil) Net::HTTP.stubs(:new).returns(@http) end def stub_controller ::ActionController::Base.logger = Logger.new(StringIO.new) @controller = ::LoggerController.new @controller.stubs(:public_environment?).returns(true) @controller.stubs(:rescue_action_in_public_without_hoptoad) HoptoadNotifier.stubs(:environment_info) end context "notifier is configured normally" do before_should "report that notifier is ready" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Notifier (.*) ready/ } end setup do HoptoadNotifier.configure { } end context "controller is hooked up to the notifier" do setup do stub_controller end context "expection is raised and notification is successful" do before_should "print environment info" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Environment Info:/ } end setup do stub_http(Net::HTTPSuccess) request("do_raise") end end context "exception is raised and notification fails" do before_should "print environment info" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Environment Info:/ } end setup do stub_http(Net::HTTPError) request("do_raise") end end context "exception is raised and notification fails with response body" do before_should "print environment info and response" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Environment Info:/ } HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Response from Hoptoad:/ } end setup do response = Net::HTTPSuccess.new(nil, nil, nil) response.stubs(:body => "test") stub_http(response) request("do_raise") end end end end context "verbose logging is on" do setup do stub_controller end context "exception is raised and notification succeeds" do before_should "print environment info and response body" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Environment Info:/ } HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Response from Hoptoad:/ } end setup do response = Net::HTTPSuccess.new(nil, nil, nil) response.stubs(:body => "test") stub_http(response) request("do_raise") end end context "exception is raised and notification fails" do before_should "print environment info and response body" do HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Environment Info:/ } HoptoadNotifier.expects(:write_verbose_log).with { |message| message =~ /Response from Hoptoad:/ } end setup do response = Net::HTTPError.new(nil, nil) response.stubs(:body => "test") stub_http(response) request("do_raise") end end end end <file_sep>class Meeting < ActiveRecord::Base include ScrapedModel belongs_to :committee belongs_to :council has_one :minutes, :class_name => "Document", :as => "document_owner" validates_presence_of :date_held, :committee_id, :uid, :council_id validates_uniqueness_of :uid, :scope => :council_id def title "#{committee.title} meeting, #{date_held.to_s(:event_date).squish}" end def minutes_body=(doc_body=nil) minutes ? minutes.update_attributes(:body => doc_body, :document_type => "Minutes") : create_minutes(:body => doc_body, :url => url, :document_type => "Minutes") end end <file_sep>require 'test_helper' class MeetingsControllerTest < ActionController::TestCase def setup @committee = Factory(:committee) @council = @committee.council @member = Factory(:member, :council => @council) @meeting = Factory(:meeting, :council => @council, :committee => @committee) @another_meeting = Factory(:meeting, :date_held => 3.days.from_now.to_date, :council => @council, :committee => @committee, :uid => @meeting.uid+1) @committee.members << @member end # index tests context "on GET to :index for council" do context "with basic request" do setup do get :index, :council_id => @council.id end should_assign_to(:council) { @council } should_assign_to(:meetings) { [@another_meeting, @meeting] } # most recent first should_respond_with :success should_render_template :index should_respond_with_content_type 'text/html' should "list meetings" do assert_select "#meetings ul a", @meeting.title end should "have title" do assert_select "title", /Committee meetings :: #{@council.title}/ end end context "with xml requested" do setup do get :index, :council_id => @council.id, :format => "xml" end should_assign_to(:council) { @council } should_assign_to(:meetings) { [@another_meeting, @meeting]} # most recent first should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :index, :council_id => @council.id, :format => "json" end should_assign_to(:council) { @council } should_assign_to(:meetings) { [@another_meeting, @meeting]} # most recent first should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end # show tests context "on GET to :show" do context "with basic request" do setup do get :show, :id => @meeting.id end should_assign_to :meeting, :committee should_respond_with :success should_render_template :show should "show committee in title" do assert_select "title", /#{@committee.title}/ end should "show meeting date in title" do assert_select "title", /#{@meeting.date_held.to_s(:event_date).squish}/ end should "list members" do assert_select "#members ul a", @member.title end should "list other meetings" do assert_select "#meetings ul a", @another_meeting.title assert_select "#meetings ul a", :text => @meeting.title, :count => 0 end end context "when meeting has minutes" do setup do @document = Factory(:document, :document_owner => @meeting) get :show, :id => @meeting.id # p @meeting.minutes end should "show link to minutes" do assert_select "a", /minutes/i end end context "with xml request" do setup do get :show, :id => @meeting.id, :format => "xml" end should_assign_to :meeting should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json request" do setup do get :show, :id => @meeting.id, :format => "json" end should_assign_to :meeting should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end end <file_sep>class AddVenueToMeetings < ActiveRecord::Migration def self.up add_column :meetings, :venue, :text remove_column :meetings, :minutes_rtf remove_column :meetings, :minutes_pdf remove_column :meetings, :agenda_url end def self.down add_column :meetings, :agenda_url, :string add_column :meetings, :minutes_pdf, :string add_column :meetings, :minutes_rtf, :string remove_column :meetings, :venue end end <file_sep>class MainController < ApplicationController caches_action :index def index @councils = Council.parsed.find(:all, :order => "councils.updated_at DESC", :limit => 10) end end <file_sep>require 'test_helper' class AdminControllerTest < ActionController::TestCase context "on GET to :index" do context "with authentication" do setup do stub_authentication get :index end should_respond_with :success should_render_template :index should_not_set_the_flash should "show admin in title" do assert_select "title", /admin/i end end context "without authentication" do setup do get :index end should_respond_with 401 end end end <file_sep>class AddUidEtcToMeetings < ActiveRecord::Migration def self.up add_column :meetings, :uid, :integer add_column :meetings, :council_id, :integer add_column :meetings, :url, :string end def self.down remove_column :meetings, :council_id remove_column :meetings, :uid end end <file_sep>require 'test_helper' class CouncilTest < ActiveSupport::TestCase context "The Council class" do setup do @council = Factory(:council) end should_validate_presence_of :name should_validate_uniqueness_of :name should_have_many :members should_have_many :committees should_have_many :scrapers should_have_many :meetings should_have_many :datapoints should_belong_to :portal_system should_have_db_column :notes should_have_db_column :wikipedia_url should_have_db_column :ons_url should_have_db_column :egr_id should_have_db_column :wdtk_name should "have parser named_scope" do expected_options = { :conditions => "members.council_id = councils.id", :joins => "INNER JOIN members", :group => "councils.id" } assert_equal expected_options, Council.parsed.proxy_options end should "return councils with members as parsed" do @another_council = Factory(:another_council) @member = Factory(:member, :council => @another_council) @another_member = Factory(:old_member, :council => @another_council) # add two members to @another council, @council has none assert_equal [@another_council], Council.parsed end should "have many datasets through datapoints" do @datapoint = Factory(:datapoint, :council => @council) assert_equal [@datapoint.dataset], @council.datasets end end context "A Council instance" do setup do @council = Factory(:council) end should "alias name as title" do assert_equal @council.name, @council.title end should "return url as base_url if base_url is not set" do assert_equal @council.url, @council.base_url end should "return base_url as base_url if base_url is set" do council = Factory(:another_council, :base_url => "another.url") assert_equal "another.url", council.base_url end should "be considered parsed if it has members" do Factory(:member, :council => @council) assert @council.parsed? end should "be considered unparsed if it has no members" do assert !@council.parsed? end should "return name without Borough etc as short_name" do assert_equal "Brent", Council.new(:name => "London Borough of Brent").short_name assert_equal "Westminster", Council.new(:name => "City of Westminster").short_name assert_equal "Kingston upon Thames", Council.new(:name => "Royal Borough of Kingston upon Thames").short_name end end end <file_sep>require 'test_helper' class MemberTest < ActiveSupport::TestCase should_validate_presence_of :last_name, :url, :council_id should_belong_to :council should_have_many :memberships should_have_many :committees, :through => :memberships should_have_named_scope :current, :conditions => "date_left IS NULL" context "The Member class" do setup do @existing_member = Factory.create(:member) @params = {:full_name => "<NAME>", :uid => 2, :council_id => 2, :party => "Independent", :url => "http:/some.url"} # uid and council_id can be anything as we stub finding of existing member end should_validate_uniqueness_of :uid, :scoped_to => :council_id should_validate_presence_of :uid should "include ScraperModel mixin" do assert Member.respond_to?(:find_existing) end end context "A Member instance" do setup do NameParser.stubs(:parse).returns(:first_name => "Fred", :last_name => "Scuttle", :name_title => "Prof", :qualifications => "PhD") @member = new_member(:full_name => "<NAME>") end should "return full name" do assert_equal "<NAME>", @member.full_name end should "should extract first name from full name" do assert_equal "Fred", @member.first_name end should "extract last name from full name" do assert_equal "Scuttle", @member.last_name end should "extract name_title from full name" do assert_equal "Prof", @member.name_title end should "extract qualifications from full name" do assert_equal "PhD", @member.qualifications end should "alias full_name as title" do assert_equal @member.full_name, @member.title end should "be ex_member if has left office" do assert new_member(:date_left => 5.months.ago).ex_member? end should "not be ex_member if has not left office" do assert !new_member.ex_member? end should "store party attribute" do assert_equal "Conservative", new_member(:party => "Conservative").party end should "discard 'Party' from given party name" do assert_equal "Conservative", new_member(:party => "Conservative Party").party assert_equal "Conservative", new_member(:party => "Conservative party").party end should "strip extraneous spaces from given party name" do assert_equal "Conservative", new_member(:party => " Conservative ").party end should "strip extraneous spaces and 'Party' from given party name" do assert_equal "Liberal Democrat", new_member(:party => " Liberal Democrat Party ").party end context "with committees" do # this part is really just testing inclusion of uid_association extension in committees association setup do @member = Factory(:member) @council = @member.council @another_council = Factory(:another_council) @old_committee = Factory(:committee, :council => @council) @new_committee = Factory(:committee, :council => @council, :uid => @old_committee.uid+1, :title => "new committee") @another_council_committee = Factory(:committee, :council => @another_council, :uid => 999, :title => "another council committee") @member.committees << @old_committee end should "return committee uids" do assert_equal [@old_committee.uid], @member.committee_uids end should "replace existing committees with ones with given uids" do @member.committee_uids = [@new_committee.uid] assert_equal [@new_committee], @member.committees end should "not add committees with that don't exist for council" do @member.committee_uids = [@another_council_committee.uid] assert_equal [], @member.committees end end context "with council" do setup do @member = Factory(:member) @council = @member.council Council.record_timestamps = false # update timestamp without triggering callbacks @council.update_attributes(:updated_at => 2.days.ago) #... though thought from Rails 2.3 you could do this without turning off timestamps Council.record_timestamps = true end context "when member is updated" do setup do @member.update_attribute(:last_name, "Wilson") end should "mark council as updated" do assert_in_delta Time.now, @council.updated_at, 2 end end context "when member is deleted" do setup do @member.destroy end should "mark council as updated" do assert_in_delta Time.now, @council.updated_at, 2 end end end end private def new_member(options={}) Member.new(options) end end <file_sep>module ScrapersHelper def class_for_result(res) css_class = case when res.new_record? || res.new_record_before_save? "new" when res.changed? "changed" else "unchanged" end css_class += " error" unless res.errors.empty? css_class end def changed_attributes_list(record) return content_tag(:div, "Record is unchanged") unless record.changed? || record.new_record_before_save? attrib_list = record.changes.collect{ |attrib_name, changes| content_tag(:li, "#{attrib_name} <strong>#{changes.last}</strong> (was #{changes.first || 'empty'})") } content_tag(:div, content_tag(:ul, attrib_list), :class => "changed_attributes") end def flash_for_result(res) css_classes = class_for_result(res) return if css_classes.blank? || css_classes == "unchanged" "<span class='#{css_classes} flash'>#{css_classes}</span>" end def scraper_links_for_council(council) existing_scraper_links, new_scraper_links = [], [] scrapers = council.scrapers Parser::ALLOWED_RESULT_CLASSES.each do |r| Scraper::SCRAPER_TYPES.each do |st| if es = scrapers.detect{ |s| s.type == st && s.result_model == r } css_classes = [] << (es.problematic? ? "problem" : nil ) css_classes << (es.stale? ? "stale" : nil ) css_classes = css_classes.compact.blank? ? nil : css_classes.compact.join(" ") existing_scraper_links << link_for(es, :class => css_classes) else new_scraper_links << link_to("Add #{r} #{st.sub('Scraper', '').downcase} scraper for #{council.name} council", new_scraper_path(:council_id => council.id, :result_model => r, :type => st), :class => "new_scraper_link") end end end existing_scraper_links + new_scraper_links end end <file_sep>require 'rake' require 'rake/testtask' require 'rake/rdoctask' desc 'Default: run unit tests.' task :default => :test desc 'Test the hoptoad_notifier plugin.' Rake::TestTask.new(:test) do |t| t.libs << 'lib' t.pattern = 'test/**/*_test.rb' t.verbose = true end desc 'Generate documentation for the hoptoad_notifier plugin.' Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'HoptoadNotifier' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/**/*.rb') end desc 'Run ginger tests' task :ginger do $LOAD_PATH << File.join(*%w[vendor ginger lib]) ARGV.clear ARGV << 'test' load File.join(*%w[vendor ginger bin ginger]) end <file_sep>require 'test_helper' class MembersControllerTest < ActionController::TestCase # show test context "on GET to :show" do setup do @member = Factory(:member) @council = @member.council @committee = Factory(:committee, :council => @council) @member.committees << @committee end context "with basic request" do setup do get :show, :id => @member.id end should_assign_to(:member) { @member } should_assign_to(:council) { @council } should_assign_to :committees should_respond_with :success should_render_template :show should_respond_with_content_type 'text/html' should "list committee memberships" do assert_select "#committees ul a", @committee.title end should "show member name in title" do assert_select "title", /#{@member.full_name}/ end end context "with xml requested" do setup do get :show, :id => @member.id, :format => "xml" end should_assign_to(:member) { @member } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :show, :id => @member.id, :format => "json" end should_assign_to(:member) { @member } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end end <file_sep>require 'test_helper' class DocumentsControllerTest < ActionController::TestCase context "on GET to :show" do setup do #set up doc owner @committee = Factory(:committee) @council = @committee.council @doc_owner = Factory(:meeting, :council => @committee.council, :committee => @committee) @document = Factory(:document, :document_owner => @doc_owner) get :show, :id => @document.id end should_assign_to(:document) { @document} should_respond_with :success should_render_template :show should_assign_to(:council) { @council } should "show document title in title" do assert_select "title", /#{@document.title}/ end should "show body of document" do assert_select "#document_body", @document.body end # should "list all parsers" do # assert_select "ul#parsers li" do # assert_select "a", @parser.title # end # end end end <file_sep>class MoveScraperAttribsToParser < ActiveRecord::Migration def self.up rename_column :parsers, :title, :description add_column :parsers, :result_model, :string add_column :parsers, :related_model, :string Scraper.find(:all).each { |s| s.parser.update_attributes(:result_model => s.result_model, :related_model => s.related_model) } end def self.down Scraper.find(:all).each { |s| s.update_attributes(:result_model => s.parser.result_model, :related_model => s.parser.related_model) } remove_column :parsers, :related_model remove_column :parsers, :result_model rename_column :parsers, :description, :title end end <file_sep>class AddExpectedsToScraper < ActiveRecord::Migration def self.up add_column :scrapers, :expected_result_class, :string add_column :scrapers, :expected_result_size, :integer add_column :scrapers, :expected_result_attributes, :text end def self.down remove_column :scrapers, :expected_result_attributes remove_column :scrapers, :expected_result_size remove_column :scrapers, :expected_result_class end end <file_sep>class DocumentsController < ApplicationController def show @document = Document.find(params[:id]) @council = @document.document_owner.council @title = @document.title end end <file_sep>require 'test_helper' # Way of testing application controller stuff (though some of this can be # tested in unit test) and application layout stuff class GenericController < ApplicationController def index render :text => "index text", :layout => true end def show @council = Council.find(params[:council_id]) if params[:council_id] @title = "Foo Title" render :text => "show text", :layout => true end end class GenericControllerTest < ActionController::TestCase def setup ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' # add usual route for testing purposes end end # index tests context "on GET to :index" do setup do get :index end should "show title" do assert_select "title", "They Work For You Local" end end context "on GET to :show" do setup do @council = Factory(:council) get :show end should "show given title in title" do assert_select "title", "Foo Title :: They Work For You Local" end end context "on GET to :show with council instantiated" do setup do @council = Factory(:council) get :show, :council_id => @council.id end should "show council in title" do assert_select "title", "Foo Title :: #{@council.title} :: They Work For You Local" end end end<file_sep>class PortalSystemsController < ApplicationController before_filter :authenticate skip_before_filter :share_this def index @portal_systems = PortalSystem.find(:all) end def show @portal_system = PortalSystem.find(params[:id]) @councils = @portal_system.councils @parsers = @portal_system.parsers end def new @portal_system = PortalSystem.new end def create @portal_system = PortalSystem.new(params[:portal_system]) @portal_system.save! flash[:notice] = "Successfully created portal system" redirect_to portal_system_path(@portal_system) rescue render :action => "new" end def edit @portal_system = PortalSystem.find(params[:id]) end def update @portal_system = PortalSystem.find(params[:id]) @portal_system.update_attributes!(params[:portal_system]) flash[:notice] = "Successfully updated portal system" redirect_to portal_system_path(@portal_system) rescue render :action => "edit" end end <file_sep>require 'test_helper' class NameParserTest < Test::Unit::TestCase OriginalNameAndParsedName = { "<NAME>" => {:first_name => "Fred", :last_name => "Flintstone"}, "<NAME>" => {:first_name => "<NAME>", :last_name => "Flintstone"}, "Fred-<NAME>" => {:first_name => "Fred-Bob", :last_name => "Flintstone"}, "<NAME>" => {:first_name => "Fred", :last_name => "Flintstone-May"}, "<NAME>" => {:first_name => "<NAME>", :last_name => "Flintstone"}, "Councillor <NAME>" => {:first_name => "Fred", :last_name => "Flintstone"}, "Mr <NAME>" => {:name_title => "Mr", :first_name => "Fred", :last_name => "Flintstone"}, "Mr <NAME>" => {:name_title => "Mr", :first_name => "Fred", :last_name => "McFlintstone"}, "Prof Dr <NAME>" => {:name_title => "Prof Dr", :first_name => "Fred", :last_name => "Flintstone"}, "Dr <NAME>" => {:name_title => "Dr", :first_name => "Fred", :last_name => "Flintstone"}, "Dr. <NAME>" => {:name_title => "Dr", :first_name => "Fred", :last_name => "Flintstone"}, "Councillor Mrs <NAME>" => {:name_title => "Mrs", :first_name => "Wilma", :last_name => "Flintstone"}, "Councillor Mrs. <NAME>" => {:name_title => "Mrs", :first_name => "Wilma", :last_name => "Flintstone"}, "Councillor Mrs. Flintstone" => {:name_title => "Mrs", :first_name => "", :last_name => "Flintstone"}, "<NAME>" => {:first_name => "", :last_name => "Flintstone"}, "Cllr <NAME>" => {:first_name => "Fred", :last_name => "Flintstone"}, "Professor <NAME>" => {:name_title => "Professor", :first_name => "<NAME>", :last_name => "Flintstone"}, "<NAME> BSc" => {:first_name => "Fred", :last_name => "Flintstone", :qualifications => "BSc"}, "<NAME> BSc, PhD" => {:first_name => "Fred", :last_name => "Flintstone", :qualifications => "BSc PhD"}, "<NAME> BSc, MRTPI(Rtd)" => {:first_name => "Fred", :last_name => "Flintstone", :qualifications => "BSc"}, "<NAME> (nee Allen)" => {:first_name => "<NAME>", :last_name => "Wilson"} } context "The NameParser module" do should "parse first name and last name from name" do OriginalNameAndParsedName.each do |orig_name, parsed_values| assert_equal parsed_values, NameParser.parse(orig_name) end end end end <file_sep># attributes: url wikipedia_url location website_generator class Council < ActiveRecord::Base has_many :members has_many :committees has_many :scrapers has_many :meetings has_many :datapoints has_many :datasets, :through => :datapoints#, :source => :join_association_table_foreign_key_to_datasets_table belongs_to :portal_system validates_presence_of :name validates_uniqueness_of :name named_scope :parsed, :conditions => "members.council_id = councils.id", :joins => "INNER JOIN members", :group => "councils.id" default_scope :order => "name" alias_attribute :title, :name def base_url read_attribute(:base_url) || url end def parsed? !members.blank? end def short_name name.gsub(/Borough|City|Royal|London|of/, '').strip end end <file_sep>class MeetingsController < ApplicationController def index @council = Council.find(params[:council_id]) @title = "Committee meetings" @meetings = @council.meetings.find(:all, :order => "date_held DESC") respond_to do |format| format.html format.xml { render :xml => @meetings.to_xml } format.json { render :xml => @meetings.to_json } end end def show @meeting = Meeting.find(params[:id]) @council = @meeting.council @committee = @meeting.committee @other_meetings = @committee.meetings - [@meeting] @title = "#{@meeting.title}" respond_to do |format| format.html format.xml { render :xml => @meeting.to_xml } format.json { render :json => @meeting.to_json } end end end <file_sep>module NameParser extend self Titles = %w(Mr Dr Mrs Miss Professor Prof Doctor Ms) Qualifications = %w(BSc BA PhD DPhil) def parse(fn) titles, qualifications, result_hash = [], [], {} names = fn.sub(/Councillor|Cllr/, '').gsub(/([.,])/, '').gsub(/\([\w ]+\)/, '').gsub(/[A-Z]{3,}/, '').split(" ") names.delete_if{ |n| Titles.include?(n) ? titles << n : (Qualifications.include?(n) ? qualifications << n : false)} result_hash[:first_name] = names[0..-2].join(" ") result_hash[:last_name] = names.last result_hash[:name_title] = titles.join(" ") unless titles.empty? result_hash[:qualifications] = qualifications.join(" ") unless qualifications.empty? result_hash end end<file_sep>class RenameMembersTitleAsNameTitle < ActiveRecord::Migration def self.up rename_column :members, :title, :name_title end def self.down rename_column :members, :name_title, :title end end <file_sep>class CreateDatapoints < ActiveRecord::Migration def self.up create_table :datapoints do |t| t.string :data_summary t.text :data t.integer :council_id t.integer :dataset_id t.timestamps end end def self.down drop_table :datapoints end end <file_sep>require 'test_helper' class MainControllerTest < ActionController::TestCase context "on GET to :index" do setup do @council1 = Factory(:council) @council2 = Factory(:another_council) @member = Factory(:member, :council => @council1) get :index end should_assign_to :councils should_respond_with :success should_render_template :index should_not_set_the_flash should "list latest parsed councils" do assert_select "#latest_councils" do assert_select "li", 1 do # only #council1 has members and therefore is considered parsed assert_select "a", @council1.title end end end end end <file_sep>require 'test_helper' class CommitteesHelperTest < ActionView::TestCase end <file_sep>require 'test_helper' class ScraperMailerTest < ActionMailer::TestCase context "A ScraperMailer auto_scraping_report email" do setup do @report_text = "auto_scraping_report body text" @report = ScraperMailer.create_auto_scraping_report(:report => @report_text, :summary => "3 successes") end should "be sent from countculture" do assert_equal "<EMAIL>", @report.from[0] end should "be sent to countculture" do assert_equal "<EMAIL>", @report.to[0] end should "include summary in subject" do assert_match /3 successes/, @report.subject end should "include report text in body" do assert_match /#{@report_text}/, @report.body end end end <file_sep>require 'test_helper' class CommitteesControllerTest < ActionController::TestCase # show test context "on GET to :show" do setup do @committee = Factory(:committee) @member = Factory(:member, :council => @committee.council) @meeting = Factory(:meeting, :council => @committee.council, :committee => @committee) @committee.members << @member end context "with basic request" do setup do get :show, :id => @committee.id end should_assign_to :committee should_respond_with :success should_render_template :show should "show committee in title" do assert_select "title", /#{@committee.title}/ end should "show council in title" do assert_select "title", /#{@committee.council.title}/ end should "list members" do assert_select "div#members li a", @member.title end should "list meetings" do assert_select "div#meetings li a", @meeting.title end end context "with xml request" do setup do get :show, :id => @committee.id, :format => "xml" end should_assign_to :committee should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' should "include members in response" do assert_select "committee member" end should "include meetings in response" do assert_select "committee meeting" end end context "with json request" do setup do get :show, :id => @committee.id, :format => "json" end should_assign_to :committee should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' should "include members in response" do assert_match /committee\":.+members\":/, @response.body end should "include meetings in response" do assert_match /committee\":.+meetings\":/, @response.body end end end # index test context "on GET to :index with council_id" do setup do @committee = Factory(:committee) @council = @committee.council Factory.create(:committee, :council_id => @council.id, :uid =>@committee.uid+1, :title => "another committee", :url => "http://foo.com" ) Factory.create(:committee, :council_id => Factory(:another_council).id, :uid => @committee.uid+1, :title => "another council's committee", :url => "http://foo.com" ) end context "with basic request" do setup do get :index, :council_id => @council.id end should_assign_to :committees should_assign_to(:council) { @council } should_respond_with :success should_render_template :index should "show council in title" do assert_select "title", /#{@council.title}/ end should "should list committees for council" do assert_select "#committees li", 2 do assert_select "a", @committee.title end end end context "with xml requested" do setup do get :index, :council_id => @council.id, :format => "xml" end should_assign_to :committees should_assign_to(:council) { @council } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :index, :council_id => @council.id, :format => "json" end should_assign_to :committees should_assign_to(:council) { @council } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end context "on GET to :index without council_id" do setup do @committee = Factory(:committee) end # should_respond_with :failure should "raise an exception" do assert_raise(ActiveRecord::RecordNotFound) { get :index } end end end <file_sep>require 'test/unit' require 'rubygems' require 'mocha' gem 'thoughtbot-shoulda', ">= 2.0.0" require 'shoulda' $LOAD_PATH << File.join(File.dirname(__FILE__), *%w[.. vendor ginger lib]) require 'ginger' require 'action_controller' require 'action_controller/test_process' require 'active_record' require 'active_record/base' require 'active_support' require File.join(File.dirname(__FILE__), "..", "lib", "hoptoad_notifier") RAILS_ROOT = File.join( File.dirname(__FILE__), "rails_root" ) RAILS_ENV = "test" begin require 'redgreen'; rescue LoadError; end module TestMethods def rescue_action e raise e end def do_raise raise "Hoptoad" end def do_not_raise render :text => "Success" end def do_raise_ignored raise ActiveRecord::RecordNotFound.new("404") end def do_raise_not_ignored raise ActiveRecord::StatementInvalid.new("Statement invalid") end def manual_notify notify_hoptoad(Exception.new) render :text => "Success" end def manual_notify_ignored notify_hoptoad(ActiveRecord::RecordNotFound.new("404")) render :text => "Success" end end class HoptoadController < ActionController::Base include TestMethods end class Test::Unit::TestCase def request(action = nil, method = :get, user_agent = nil, params = {}) @request = ActionController::TestRequest.new @request.action = action ? action.to_s : "" if user_agent if @request.respond_to?(:user_agent=) @request.user_agent = user_agent else @request.env["HTTP_USER_AGENT"] = user_agent end end @request.query_parameters = @request.query_parameters.merge(params) @response = ActionController::TestResponse.new @controller.process(@request, @response) end # Borrowed from ActiveSupport 2.3.2 def assert_difference(expression, difference = 1, message = nil, &block) b = block.send(:binding) exps = Array.wrap(expression) before = exps.map { |e| eval(e, b) } yield exps.each_with_index do |e, i| error = "#{e.inspect} didn't change by #{difference}" error = "#{message}.\n#{error}" if message assert_equal(before[i] + difference, eval(e, b), error) end end def assert_no_difference(expression, message = nil, &block) assert_difference expression, 0, message, &block end end # Also stolen from AS 2.3.2 class Array # Wraps the object in an Array unless it's an Array. Converts the # object to an Array using #to_ary if it implements that. def self.wrap(object) case object when nil [] when self object else if object.respond_to?(:to_ary) object.to_ary else [object] end end end end <file_sep>desc "Quick and dirty scraper to get basic info about councils from eGR page" task :scrape_egr_for_councils => :environment do BASE_URL = "http://www.brent.gov.uk" require 'hpricot' require 'open-uri' puts "Please enter eGR url to be scraped for councils: " url = $stdin.gets.chomp puts "Please enter global values (e.g attrib1=val1, attrib2=val2): " default_values = $stdin.gets.chomp default_hash = default_values.blank? ? {} : Hash[*default_values.split(",").collect{|ap| ap.split("=")}.flatten] doc = Hpricot(open(url)) council_data = doc.search("#viewZone tr")[1..-2] council_data.each do |council_datum| council_link = council_datum.at("a[@href*='egr.nsf/LAs'") short_title = council_link.inner_text council = Council.find(:first, :conditions => ["name LIKE ?", "%#{short_title}%"]) || Council.new council.attributes = default_hash egr_url = BASE_URL + council_link[:href] council.authority_type ||= council_datum.search("td")[2].at("font").inner_text.strip puts "About to scrape eGR page for #{short_title} (#{egr_url})" detailed_data = Hpricot(open(egr_url)) values = detailed_data.search("#main tr") council.name ||= values.at("td[text()*='Full Name']").next_sibling.inner_text.strip council.telephone ||= values.at("td[text()*='Telephone']").next_sibling.inner_text.strip council.url ||= values.at("td[text()*='Website']").next_sibling.inner_text.strip council.address ||= values.at("td[text()*='Address']").next_sibling.inner_text.strip council.ons_url ||= values.at("td[text()*='Nat Statistics']").next_sibling.at("a")[:href] council.wikipedia_url ||= values.at("td[text()*='Wikipedia']").next_sibling.inner_text.strip council.egr_id ||= values.at("td[text()*='eGR ID']").next_sibling.at("font").inner_text.strip begin council.save! p council.attributes, "____________" rescue Exception => e puts "Problem saving #{council.name}: #{e.message}" end end end desc "Scraper WhatDoTheyKnow.com to get WDTK name" task :scrape_wdtk_for_names => :environment do require 'hpricot' require 'open-uri' url = "http://www.whatdotheyknow.com/body/list/local_council" doc = Hpricot(open(url)) wdtk_councils = doc.search("#body_list .body_listing span.head") Council.find(:all, :conditions => 'wdtk_name IS NULL').each do |council| wdtk_council = wdtk_councils.at("a[text()*='#{council.short_name}']") if wdtk_council wdtk_name = wdtk_council[:href].gsub('/body/', '') council.update_attribute(:wdtk_name, wdtk_name) puts "Added WDTK name (#{wdtk_name}) to #{council.name} record\n____________" else puts "Failed to find entry for #{council.name}" end end end <file_sep>class ScraperMailer < ActionMailer::Base def auto_scraping_report(report_hash) subject "TWFY Local :: Auto Scraping Report :: #{report_hash[:summary]}" recipients '<EMAIL>' from '<EMAIL>' sent_on Time.now body :report => report_hash[:report] end end <file_sep>require 'test_helper' class DatasetTest < ActiveSupport::TestCase context "The Dataset class" do should_have_db_columns :title, :source, :key, :query, :description, :originator, :originator_url, :summary_column, :last_checked should_validate_presence_of :title, :key, :query should_have_many :datapoints should "have base_url" do assert_match /spreadsheets.google/, Dataset::BASE_URL end should "should return stale datasets" do @never_checked_dataset = Factory(:dataset) @fresh_dataset = Factory(:dataset, :key => "foo123", :last_checked => 6.days.ago) @stale_dataset = Factory(:dataset, :key => "bar456", :last_checked => 8.days.ago) stale_datasets = Dataset.stale assert_equal 2, stale_datasets.size assert stale_datasets.include?(@stale_dataset) assert stale_datasets.include?(@never_checked_dataset) assert !stale_datasets.include?(@fresh_dataset) end end context "A Dataset instance" do setup do @dataset = Factory.create(:dataset, :query => "select A,B,C,D,E,F,G") @council = Factory(:council) @another_council = Factory(:another_council) end should_validate_uniqueness_of :key should "constuct public_url from key" do assert_equal "http://spreadsheets.google.com/pub?key=abc123", @dataset.public_url end should "build query_url from query, key when no council given" do @council.stubs(:short_name).returns("Foo bar") assert_equal 'http://spreadsheets.google.com/tq?tqx=out:csv&tq=select+A%2CB%2CC%2CD%2CE%2CF%2CG&key=abc123', @dataset.query_url end should "build query_url from query, key and council short title" do @council.stubs(:short_name).returns("Foo bar") assert_equal 'http://spreadsheets.google.com/tq?tqx=out:csv&tq=select+A%2CB%2CC%2CD%2CE%2CF%2CG+where+A+contains+%27Foo+bar%27&key=abc123', @dataset.query_url(@council) end context "when processing" do setup do @csv_response = "\"LOCAL AUTHORITY\",\"Authority Type\"\n\"Bristol City \",\"UA\"\n\"Anytown Council\",\"LB\"" @dataset.stubs(:query_url).returns("some_url") @dataset.stubs(:_http_get).returns(@csv_response) end should "build query_url" do @dataset.expects(:query_url) @dataset.process end should "get data from query_url" do @dataset.expects(:_http_get).with("some_url").returns(@csv_response) @dataset.process end should "parse csv data" do FasterCSV.expects(:parse).with(@csv_response, anything).returns([["LOCAL AUTHORITY"],["Anytown Council"]]) @dataset.process end should "return nil if no data found" do @dataset.expects(:_http_get).returns(nil) # using expects overrides stubbing assert_nil @dataset.process end should "save data as datapoints for matching councils" do old_count = Datapoint.count @dataset.process assert_equal old_count+1, Datapoint.count end should "associate datapoint with council" do @dataset.process assert_equal @council, Datapoint.find(:first, :order => "id DESC").council end should "associate datapoint with dataset" do @dataset.process assert_equal @dataset, Datapoint.find(:first, :order => "id DESC").dataset end should "save data as datapoint data for council" do @dataset.process assert_equal [["LOCAL AUTHORITY", "Authority Type"], ["Anytown Council", "LB"]], @council.datapoints.find(:first, :order => "id DESC").data end should "update last_checked timestamp" do @dataset.process assert_in_delta Time.now, @dataset.last_checked, 2 end context "and datapoint already exists for council and dataset" do setup do @old_datapoint = Factory(:datapoint, :council => @council, :dataset => @dataset) end should "not create new datapoint" do old_count = Datapoint.count @dataset.process assert_equal old_count, Datapoint.count end should "update data for datapoint" do @dataset.process assert_equal [["LOCAL AUTHORITY", "Authority Type"], ["Anytown Council", "LB"]], @old_datapoint.reload.data end end end context "when getting data for council" do setup do @csv_response = "\"LOCAL AUTHORITY\",\"Authority Type\"\n\"Bristol City \",\"UA\"" @dataset.stubs(:query_url).returns("some_url") @dataset.stubs(:_http_get).returns(@csv_response) end should "build query_url using council" do @dataset.expects(:query_url).with(@council) @dataset.data_for(@council) end should "get data from query_url" do @dataset.expects(:_http_get).with("some_url").returns(@csv_response) @dataset.data_for(@council) end should "parse csv data into ruby array" do parsed_response = [["LOCAL AUTHORITY", "Bristol City "], ["Authority Type", "UA"]] assert_equal parsed_response, @dataset.data_for(@council) end should "return nil if no data found" do @dataset.expects(:_http_get).returns(nil) # using expects overrides stubbing assert_nil @dataset.data_for(@council) end end end end <file_sep>class RenameMemberidToUid < ActiveRecord::Migration def self.up rename_column :members, :member_id, :uid end def self.down rename_column :members, :uid, :member_id end end <file_sep># Methods added to this helper will be available to all templates in the application. module ApplicationHelper def council_page_for(obj) link_to("council page", obj.url, :class => "council_page_link external") end def link_for(obj=nil, options={}) return if obj.blank? freshness = obj.created_at > 7.days.ago ? "new" : (obj.updated_at > 7.days.ago ? "updated" : nil) css_class = ["#{obj.class.to_s.downcase}_link", options.delete(:class), freshness].compact.join(" ") link_to(h(obj.title), obj, { :class => css_class }.merge(options)) end def link_to_api_url(response_type) link_to(response_type, params.merge(:format => response_type), :class => "api_link") end def list_all(coll=nil) if coll.blank? "<p class='no_results'>No results</p>" else coll = coll.is_a?(Array) ? coll : [coll] content_tag(:ul, coll.collect{ |i| (content_tag(:li, link_for(i))) }.join) end end end <file_sep>#attributes: uri class MemberScraper < ActiveRecord::Base belongs_to :parser belongs_to :council def self.update doc = Hpricot(_http_get(uri)) results = parser.process(doc) Member.update_with(results) end end <file_sep>class CommitteesController < ApplicationController def index @council = Council.find(params[:council_id]) @committees = @council.committees @title = "Committees" respond_to do |format| format.html format.xml { render :xml => @committees.to_xml } format.json { render :json => @committees.to_json } end end def show @committee = Committee.find(params[:id]) @council = @committee.council @title = @committee.title respond_to do |format| format.html format.xml { render :xml => @committee.to_xml(:include => [:members, :meetings]) } format.json { render :json => @committee.to_json(:include => [:members, :meetings]) } end end end <file_sep>require File.dirname(__FILE__) + '/helper' class NotifierTest < Test::Unit::TestCase context "Sending a notice" do should "not fail without rails environment" do assert_nothing_raised do HoptoadNotifier.environment_info end end context "with an exception" do setup do @sender = HoptoadNotifier::Sender.new @backtrace = caller @exception = begin raise rescue => caught_exception caught_exception end @options = {:error_message => "123", :backtrace => @backtrace} HoptoadNotifier.instance_variable_set("@backtrace_filters", []) HoptoadNotifier::Sender.expects(:new).returns(@sender) @sender.stubs(:public_environment?).returns(true) HoptoadNotifier.stubs(:environment_info) end context "when using an HTTP Proxy" do setup do @body = 'body' @response = stub(:body => @body) @http = stub(:post => @response, :read_timeout= => nil, :open_timeout= => nil, :use_ssl= => nil) @sender.stubs(:logger).returns(stub(:error => nil, :info => nil)) @proxy = stub @proxy.stubs(:new).returns(@http) HoptoadNotifier.port = nil HoptoadNotifier.host = nil HoptoadNotifier.secure = false Net::HTTP.expects(:Proxy).with( HoptoadNotifier.proxy_host, HoptoadNotifier.proxy_port, HoptoadNotifier.proxy_user, HoptoadNotifier.proxy_pass ).returns(@proxy) end context "on notify" do setup { HoptoadNotifier.notify(@exception) } before_should "post to Hoptoad" do url = "http://hoptoadapp.com:80/notices/" uri = URI.parse(url) URI.expects(:parse).with(url).returns(uri) @http.expects(:post).with(uri.path, anything, anything).returns(@response) end end end context "when stubbing out Net::HTTP" do setup do @body = 'body' @response = stub(:body => @body) @http = stub(:post => @response, :read_timeout= => nil, :open_timeout= => nil, :use_ssl= => nil) @sender.stubs(:logger).returns(stub(:error => nil, :info => nil)) Net::HTTP.stubs(:new).returns(@http) HoptoadNotifier.port = nil HoptoadNotifier.host = nil HoptoadNotifier.proxy_host = nil end context "on notify" do setup { HoptoadNotifier.notify(@exception) } before_should "post to the right url for non-ssl" do HoptoadNotifier.secure = false url = "http://hoptoadapp.com:80/notices/" uri = URI.parse(url) URI.expects(:parse).with(url).returns(uri) @http.expects(:post).with(uri.path, anything, anything).returns(@response) end before_should "post to the right path" do @http.expects(:post).with("/notices/", anything, anything).returns(@response) end before_should "call send_to_hoptoad" do @sender.expects(:send_to_hoptoad) end before_should "default the open timeout to 2 seconds" do HoptoadNotifier.http_open_timeout = nil @http.expects(:open_timeout=).with(2) end before_should "default the read timeout to 5 seconds" do HoptoadNotifier.http_read_timeout = nil @http.expects(:read_timeout=).with(5) end before_should "allow override of the open timeout" do HoptoadNotifier.http_open_timeout = 4 @http.expects(:open_timeout=).with(4) end before_should "allow override of the read timeout" do HoptoadNotifier.http_read_timeout = 10 @http.expects(:read_timeout=).with(10) end before_should "connect to the right port for ssl" do HoptoadNotifier.secure = true Net::HTTP.expects(:new).with("hoptoadapp.com", 443).returns(@http) end before_should "connect to the right port for non-ssl" do HoptoadNotifier.secure = false Net::HTTP.expects(:new).with("hoptoadapp.com", 80).returns(@http) end before_should "use ssl if secure" do HoptoadNotifier.secure = true HoptoadNotifier.host = 'example.org' Net::HTTP.expects(:new).with('example.org', 443).returns(@http) end before_should "not use ssl if not secure" do HoptoadNotifier.secure = nil HoptoadNotifier.host = 'example.org' Net::HTTP.expects(:new).with('example.org', 80).returns(@http) end end end should "send as if it were a normally caught exception" do @sender.expects(:notify_hoptoad).with(@exception) HoptoadNotifier.notify(@exception) end should "make sure the exception is munged into a hash" do options = HoptoadNotifier.default_notice_options.merge({ :backtrace => @exception.backtrace, :environment => ENV.to_hash, :error_class => @exception.class.name, :error_message => "#{@exception.class.name}: #{@exception.message}", :api_key => HoptoadNotifier.api_key, }) @sender.expects(:send_to_hoptoad).with(:notice => options) HoptoadNotifier.notify(@exception) end should "parse massive one-line exceptions into multiple lines" do @original_backtrace = "one big line\n separated\n by new lines\nand some spaces" @expected_backtrace = ["one big line", "separated", "by new lines", "and some spaces"] @exception.set_backtrace [@original_backtrace] options = HoptoadNotifier.default_notice_options.merge({ :backtrace => @expected_backtrace, :environment => ENV.to_hash, :error_class => @exception.class.name, :error_message => "#{@exception.class.name}: #{@exception.message}", :api_key => HoptoadNotifier.api_key, }) @sender.expects(:send_to_hoptoad).with(:notice => options) HoptoadNotifier.notify(@exception) end end context "without an exception" do setup do @sender = HoptoadNotifier::Sender.new @backtrace = caller @options = {:error_message => "123", :backtrace => @backtrace} HoptoadNotifier::Sender.expects(:new).returns(@sender) end should "send sensible defaults" do @sender.expects(:notify_hoptoad).with(@options) HoptoadNotifier.notify(:error_message => "123", :backtrace => @backtrace) end end end end <file_sep>require "test_helper" class ScraperRunnerTest < ActiveSupport::TestCase context "A ScraperRunner instance" do setup do @runner = ScraperRunner.new(:email_results => true, :limit => 42) end should "set email_results reader from options" do assert @runner.email_results end should "set email_results reader to false by default" do assert !ScraperRunner.new.email_results end should "set limit reader from options" do assert_equal 42, @runner.limit end should "set limit to 5 by default" do assert_equal 5, ScraperRunner.new.limit end should "have result_output accessor" do @runner.result_output = "foo" assert_equal "foo", @runner.result_output end should "set result_output to be empty string by default" do assert_equal "", ScraperRunner.new.result_output end context "when refreshing stale scrapers" do setup do ActionMailer::Base.deliveries.clear @scraper = Factory(:scraper) Scraper.stubs(:find).returns([@scraper]) end should "find stale scrapers" do Scraper.expects(:find).returns([]) @runner.refresh_stale end should "process stale scrapers" do @scraper.expects(:process).returns(@scraper) @runner.refresh_stale end should "summarize results in summary" do Scraper.expects(:find).returns([@scraper]*3) @scraper.stubs(:process).returns(stub(:results => stub_everything)).then.returns(stub(:results => stub_everything)).then.returns(stub(:results)) @runner.refresh_stale assert_equal "3 scrapers processed, 1 problem(s)", @runner.instance_variable_get(:@summary) end should "email results if email_results is true" do @runner.result_output = "some output" @runner.refresh_stale assert_sent_email do |email| email.subject =~ /Auto Scraping Report/ && email.body =~ /some output/ end end should "use summary in email subject" do @scraper.stubs(:process).returns(stub(:results => stub_everything)) @runner.refresh_stale assert_sent_email do |email| email.subject =~ /1 scrapers processed/ end end should "not email results if email_results is not true" do ScraperRunner.new.refresh_stale assert_did_not_send_email end end end end <file_sep># attributes item_parser, title, attribute_parser class Parser < ActiveRecord::Base ALLOWED_RESULT_CLASSES = %w(Member Committee Meeting) AttribObject = Struct.new(:attrib_name, :parsing_code, :to_param) validates_presence_of :result_model validates_presence_of :scraper_type validates_inclusion_of :result_model, :in => ALLOWED_RESULT_CLASSES, :message => "is invalid" validates_inclusion_of :scraper_type, :in => Scraper::SCRAPER_TYPES, :message => "is invalid" has_many :scrapers belongs_to :portal_system serialize :attribute_parser attr_reader :results def attribute_parser_object return [AttribObject.new] if attribute_parser.blank? self.attribute_parser.collect { |k,v| AttribObject.new(k.to_s, v) }.sort{ |a,b| a.attrib_name <=> b.attrib_name } end def attribute_parser_object=(params) result_hash = {} params.each do |a| result_hash[a["attrib_name"].to_sym] = a["parsing_code"] end self.attribute_parser = result_hash end def process(doc, scraper=nil) @raw_response = doc @current_scraper = scraper @results = nil # wipe previous results if they exist (same parser instance may be called more than once by scraper) now_parsing = "items" parsing_code = item_parser object_to_be_parsed = doc items = item_parser.blank? ? doc : eval_parsing_code(item_parser, doc) now_parsing = "attributes" items = [items] unless items.is_a?(Array) @results = items.compact.collect do |item| # remove nil items result_hash = {} attribute_parser.each do |key, value| parsing_code = value object_to_be_parsed = item result_hash[key] = eval_parsing_code(value, item) end result_hash end self rescue Exception => e message = "Exception raised parsing #{now_parsing}: #{e.message}\n\n" + "Problem occurred using parsing code:\n#{parsing_code}\n\n on following Hpricot object:\n#{object_to_be_parsed.inspect}" logger.debug { message } logger.debug { "Backtrace:\n#{e.backtrace}" } errors.add_to_base(message) self end def title "#{result_model} #{scraper_type&&scraper_type.sub('Scraper','').downcase} parser for " + (portal_system ? portal_system.name : 'single scraper only') end protected def eval_parsing_code(code=nil, item=nil) base_url = @current_scraper.try(:base_url) # Wraps in new thread with higher $SAFE level as per Pickaxe, # ... poss investigate using proc as per http://www.davidflanagan.com/2008/11/safe-is-proc-lo.html code_to_eval = code.dup code_to_eval.untaint # like code it will tainted as it was submitted in form. Can't eval tainted string thread = Thread.start do $SAFE = 2 begin eval(code_to_eval) rescue Exception => e logger.debug { "********Exception raised in thread: #{e.message}\n#{e.backtrace}" } raise e end end thread.value # wait for the thread to finish and return value end end <file_sep>class PortalSystem < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name has_many :councils has_many :parsers alias_attribute :title, :name end <file_sep>require 'test_helper' class MembershipTest < ActiveSupport::TestCase context "The Membership Class" do setup do # @membership = Membership.create!(:title => "Some Committee", :url => "some.url", :uid => 44, :council_id => 1) end should_validate_presence_of :member_id, :committee_id should_belong_to :committee # should_belong_to :council should_belong_to :member # should_belong_to :uid_member end end <file_sep>require 'test_helper' class CouncilsHelperTest < ActionView::TestCase end <file_sep>class TweakDatapointsAndDatasets < ActiveRecord::Migration def self.up add_column :datasets, :last_checked, :datetime remove_column :datapoints, :data_summary end def self.down remove_column :datasets, :last_checked add_column :datapoints, :data_summary, :string end end <file_sep>desc "Finds stale scrapers and runs them" task :run_stale_scrapers => :environment do ScraperRunner.new(:limit => ENV["LIMIT"], :email_results => ENV["EMAIL_RESULTS"]).refresh_stale end <file_sep>require 'test_helper' class DatasetsControllerTest < ActionController::TestCase def setup @dataset = Factory(:dataset) end # index test context "on GET to :index" do context "with basic request" do setup do get :index end should_assign_to(:datasets) { Dataset.find(:all)} should_respond_with :success should_render_template :index should_respond_with_content_type 'text/html' should "list datasets" do assert_select "li a", @dataset.title end should "have title" do assert_select "title", /Datasets/ end end context "with xml requested" do setup do get :index, :format => "xml" end should_assign_to(:datasets) { Dataset.find(:all)} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :index, :format => "json" end should_assign_to(:datasets) { Dataset.find(:all)} should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end # show test context "on GET to :show" do context "with basic request" do setup do get :show, :id => @dataset.id end should_assign_to(:dataset) { @dataset } should_respond_with :success should_render_template :show should_respond_with_content_type 'text/html' should "show title" do assert_select "title", /#{@dataset.title}/ end end context "with xml requested" do setup do get :show, :id => @dataset.id, :format => "xml" end should_assign_to(:dataset) { @dataset } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/xml' end context "with json requested" do setup do get :show, :id => @dataset.id, :format => "json" end should_assign_to(:dataset) { @dataset } should_respond_with :success should_render_without_layout should_respond_with_content_type 'application/json' end end # new test context "on GET to :new without auth" do setup do get :new end should_respond_with 401 end context "on GET to :new" do setup do stub_authentication get :new end should_assign_to(:dataset) should_respond_with :success should_render_template :new should "show form" do assert_select "form#new_dataset" end end # create test context "on POST to :create" do context "without auth" do setup do post :create, :dataset => Factory.attributes_for(:dataset) end should_respond_with 401 end context "with valid params" do setup do stub_authentication post :create, :dataset => Factory.attributes_for(:dataset, :key => "foo123") end should_change "Dataset.count", :by => 1 should_assign_to :dataset should_redirect_to( "the show page for dataset") { dataset_url(assigns(:dataset)) } should_set_the_flash_to "Successfully created dataset" end context "with invalid params" do setup do stub_authentication post :create, :dataset => {:title => "Dataset title"} end should_not_change "Dataset.count" should_assign_to :dataset should_render_template :new should_not_set_the_flash end end # edit test context "on GET to :edit without auth" do setup do get :edit, :id => @dataset end should_respond_with 401 end context "on GET to :edit with existing record" do setup do stub_authentication get :edit, :id => @dataset end should_assign_to(:dataset) should_respond_with :success should_render_template :edit should "show form" do assert_select "form#edit_dataset_#{@dataset.id}" end end # update test context "on PUT to :update" do context "without auth" do setup do put :update, :id => @dataset.id, :dataset => { :title => "New title" } end should_respond_with 401 end context "with valid params" do setup do stub_authentication put :update, :id => @dataset.id, :dataset => { :title => "New title" } end should_not_change "Dataset.count" should_change "@dataset.reload.title", :to => "New title" should_assign_to :dataset should_redirect_to( "the show page for dataset") { dataset_path(assigns(:dataset)) } should_set_the_flash_to "Successfully updated dataset" end context "with invalid params" do setup do stub_authentication put :update, :id => @dataset.id, :dataset => {:title => ""} end should_not_change "Dataset.count" should_not_change "@dataset.reload.title" should_assign_to :dataset should_render_template :edit should_not_set_the_flash end end # data tests context "on GET to data with dataset and council" do setup do @council = Factory(:council) @datapoint = Factory(:datapoint, :data => [["LOCAL AUTHORITY", "% who are foo"], ["Some City ", "37"]], :council => @council, :dataset_id => @dataset.id) get :data, :id => @dataset.id, :council_id => @council.id end should_assign_to(:dataset) { @dataset } should_assign_to(:council) { @council } should_respond_with :success should_render_template :data should "show dataset in title" do assert_select "title", /#{@dataset.title}/ end should "show council in title" do assert_select "title", /#{@council.title}/ end should "show datapoint data in table" do assert_select "#dataset_data table th", 2 do assert_select "th", "% who are foo" end assert_select "#dataset_data table td", "37" end end context "on GET to data with no datapoint for dataset and council" do setup do @council = Factory(:council) get :data, :id => @dataset.id, :council_id => @council.id end should_assign_to(:dataset) { @dataset } should_assign_to(:council) { @council } should_respond_with :success should_render_template :data should "show dataset in title" do assert_select "title", /#{@dataset.title}/ end should "show message" do assert_select "p.alert", /no data/ end end end <file_sep>class DatasetsController < ApplicationController before_filter :authenticate, :except => [:index, :show, :data] def index @datasets = Dataset.find(:all) @title = "All Datasets" respond_to do |format| format.html format.xml { render :xml => @datasets.to_xml } format.json { render :xml => @datasets.to_json } end end def show @dataset = Dataset.find(params[:id]) @title = @dataset.title respond_to do |format| format.html format.xml { render :xml => @dataset.to_xml } format.json { render :xml => @dataset.to_json } end end def new @dataset = Dataset.new end def create @dataset = Dataset.new(params[:dataset]) @dataset.save! flash[:notice] = "Successfully created dataset" redirect_to dataset_path(@dataset) rescue render :action => "new" end def edit @dataset = Dataset.find(params[:id]) end def update @dataset = Dataset.find(params[:id]) @dataset.update_attributes!(params[:dataset]) flash[:notice] = "Successfully updated dataset" redirect_to dataset_url(@dataset) rescue render :action => "edit" end # returns data for given dataset def data @dataset = Dataset.find(params[:id]) @council = Council.find(params[:council_id]) @datapoint = Datapoint.find_by_council_id_and_dataset_id(@council.id, @dataset.id) @title = "Data for #{@dataset.title}" end end <file_sep>class Scraper < ActiveRecord::Base class ScraperError < StandardError; end class RequestError < ScraperError; end class ParsingError < ScraperError; end SCRAPER_TYPES = %w(InfoScraper ItemScraper) belongs_to :parser belongs_to :council validates_presence_of :council_id named_scope :stale, lambda { { :conditions => ["(last_scraped IS NULL) OR (last_scraped < ?)", 7.days.ago], :order => "last_scraped" } } named_scope :problematic, { :conditions => { :problematic => true } } named_scope :unproblematic, { :conditions => { :problematic => false } } accepts_nested_attributes_for :parser attr_accessor :related_objects, :parsing_results attr_protected :results delegate :result_model, :to => :parser delegate :related_model, :to => :parser delegate :portal_system, :to => :council delegate :base_url, :to => :council def validate errors.add(:parser, "can't be blank") unless parser end def computed_url !base_url.blank?&&!parser.path.blank? ? "#{base_url}#{parser.path}" : nil end def expected_result_attributes read_attribute(:expected_result_attributes) ? Hash.new.instance_eval("merge(#{read_attribute(:expected_result_attributes)})") : {} end def title getting = self.is_a?(InfoScraper) ? 'Info' : 'Items' "#{result_model} #{getting} scraper for #{council.name}" end def parsing_errors parser.errors end # Returns true if associated parser belongs to portal_system, false otherwise def portal_parser? !!parser.try(:portal_system) end def possible_parsers portal_system.parsers end def process(options={}) self.parsing_results = parser.process(_data(url), self).results update_with_results(parsing_results, options) update_last_scraped if options[:save_results]&&parser.errors.empty? mark_as_problematic unless parser.errors.empty? self rescue ScraperError => e logger.debug { "*******#{e.message} while processing #{self.inspect}" } errors.add_to_base(e.message) mark_as_problematic self end def results @results ||=[] end def stale? !last_scraped||(last_scraped < 7.days.ago) end # build url from council's base_url and parsers path unless url is set def url read_attribute(:url).blank? ? computed_url : read_attribute(:url) end protected def _data(target_url=nil) begin page_data = _http_get(target_url) rescue Exception => e error_message = "Problem getting data from #{target_url}: #{e.inspect}" logger.error { error_message } raise RequestError, error_message end begin Hpricot.parse(page_data, :fixup_tags => true) rescue Exception => e logger.error { "Problem with data returned from #{target_url}: #{e.inspect}" } raise ParsingError end end def _http_get(target_url) return false if RAILS_ENV=="test" # make sure we don't call make calls to external services in test environment. Mock this method to simulate response instead # response = nil # target_url = URI.parse(target_url) # request = Net::HTTP.new(target_url.host, target_url.port) # request.read_timeout = 5 # set timeout at 5 seconds # begin # response = request.get(target_url.request_uri) # raise RequestError, "Problem retrieving info from #{target_url}." unless response.is_a? Net::HTTPSuccess # rescue Timeout::Error # raise RequestError, "Timeout::Error retrieving info from #{target_url}." # end open(target_url).read # logger.debug "********Scraper response = #{response.body.inspect}" # response.body end # def match_attribute(result, key, value) # case value # when TrueClass # message = "weren't matched: :#{key} expected but was missing or nil" unless result[key] # when Class # message = "weren't matched: :#{key} expected to be #{value} but was #{result[key].class}" unless result[key].is_a?(value) # when Regexp # message = "weren't matched: :#{key} expected to match /#{value.source}/ but was '#{result[key]}'" unless result[key] =~ value # end # errors.add(:expected_result_attributes, message) if message # end def update_with_results(parsing_results, options={}) unless parsing_results.blank? parsing_results.each do |result| item = result_model.constantize.build_or_update(result.merge(:council_id => council.id)) options[:save_results] ? item.save_without_losing_dirty : item.valid? # we want to know what's changed and keep any errors, so run save_without_losing_dirty if we're saving, run validation to add errors to item otherwise results << item end end end private # marks as problematic without changing timestamps def mark_as_problematic self.class.update_all({ :problematic => true }, { :id => id }) end def update_last_scraped self.class.update_all({ :last_scraped => Time.zone.now }, { :id => id }) end end <file_sep>class AddTypeToScrapers < ActiveRecord::Migration def self.up add_column :scrapers, :type, :string Scraper.all{ |s| s.update_attribute(:type, "ItemScraper") } end def self.down remove_column :scrapers, :type end end <file_sep>class ScraperRunner attr_accessor :result_output attr_reader :email_results, :limit def initialize(args={}) @email_results = args[:email_results] @limit = args[:limit] || 5 @result_output = "" end def refresh_stale stale_scrapers = Scraper.unproblematic.stale.find(:all, :limit => limit) error_total = 0 output_result "About to run #{stale_scrapers.size} stale scrapers:\n" stale_scrapers.each do |scraper| output_result "\n\nRunning #{scraper.title}\n===========================================" results = scraper.process(:save_results => true).results if results.blank? output_result "No results" output_result "\n\nScraper Errors:\n* #{scraper.errors.full_messages.join("\n* ")}" output_result "\n\nParser Errors:\n* #{scraper.parser.errors.full_messages.join("\n* ")}" error_total +=1 else results.each do |result| output_result "\n*#{result.title}\nChanges: #{result.changes.inspect}" end end end @summary = "#{stale_scrapers.size} scrapers processed, " + (error_total > 0 ? "#{error_total} problem(s)" : "No problems") email_results ? ScraperMailer.deliver_auto_scraping_report!(:report => result_output, :summary => @summary) : output_result("*****"*10 + "\n" + @summary) end protected # outputs to screen or adds to result string def output_result(text) email_results ? (result_output << text) : RAILS_ENV!="test"&&puts(text) end end <file_sep>class Dataset < ActiveRecord::Base BASE_URL = 'http://spreadsheets.google.com/' has_many :datapoints validates_presence_of :title, :key, :query validates_uniqueness_of :key def data_for(council) raw_response = _http_get(query_url(council)) FasterCSV.parse(raw_response, :headers => true).by_col.collect{|c| c.flatten} unless raw_response.blank? end def process raw_response = _http_get(query_url) update_attribute(:last_checked, Time.now) return if raw_response.blank? rows = FasterCSV.parse(raw_response, :headers => true).to_a header_row = rows.shift all_councils = Council.find(:all) all_councils.each do |council| c_row = rows.detect { |row_data| row_data.first.match(council.short_name) } if c_row dp = council.datapoints.find_or_initialize_by_dataset_id(id) dp.update_attributes(:data => [header_row, c_row]) end end end def self.stale find(:all, :conditions => ["last_checked < ? OR last_checked IS NULL", 7.days.ago], :order => "last_checked ASC") end # This is the url where original datasheet in spreadsheet can be seen def public_url BASE_URL + "pub?key=#{key}" end # This is the url for make a query through google visualization api def query_url(council=nil) BASE_URL + 'tq?tqx=out:csv&tq=' + CGI.escape(query + (council ? " where A contains '#{council.short_name}'" : '')) + "&key=#{key}" end protected def _http_get(url) return false if RAILS_ENV=="test" # make sure we don't call make calls to external services in test environment. Mock this method to simulate response instead open(url) end end <file_sep>require 'test_helper' class ParsersControllerTest < ActionController::TestCase # show tests context "on GET to :show without auth" do setup do @parser = Factory(:parser) @scraper = Factory(:scraper, :parser => @parser) get :show, :id => @parser.id end should_respond_with 401 end context "on GET to :show" do setup do @parser = Factory(:parser) @scraper = Factory(:scraper, :parser => @parser) stub_authentication get :show, :id => @parser.id end should_assign_to :parser should_assign_to :scrapers should_respond_with :success should_render_template :show should "show link to perform edit" do assert_select ".parser a", /edit/ end should "list associated scrapers" do assert_select "#scrapers a", @scraper.title end should "show related model field" do assert_select ".parser strong", /related/i end should "not show share block" do assert_select "#share_block", false end end context "on GET to :show for InfoScraper parser" do setup do @parser = Factory(:another_parser) @scraper = Factory(:scraper, :parser => @parser) stub_authentication get :show, :id => @parser.id end should_assign_to :parser should_assign_to :scrapers should_respond_with :success should_render_template :show should "list associated scrapers" do assert_select "#scrapers a", @scraper.title end should "not show related model field" do assert_select ".parser strong", :text => /related/i, :count => 0 end end # new tests context "on GET to :new" do setup do @portal_system = Factory(:portal_system) end context "with no portal_system given" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :new, :result_model => "Member", :scraper_type => "ItemParser" } end end context "with no scraper_type given" do should "raise exception" do stub_authentication assert_raise(ArgumentError) { get :new, :portal_system_id => @portal_system.id, :result_model => "Member" } end end context "without auth" do setup do get :new, :portal_system_id => @portal_system.id, :result_model => "Member", :scraper_type => "ItemParser" end should_respond_with 401 end context "for basic parser" do setup do stub_authentication get :new, :portal_system_id => @portal_system.id, :result_model => "Member", :scraper_type => "ItemParser" end should_assign_to(:parser) should_respond_with :success should_render_template :new should "show form" do assert_select "form#new_parser" end should "include portal_system in hidden field" do assert_select "input#parser_portal_system_id[type=hidden][value=#{@portal_system.id}]" end should "include scraper_type in hidden field" do assert_select "input#parser_scraper_type[type=hidden][value='ItemParser']" end end end # create test context "on POST to :create" do setup do @portal_system = Factory(:portal_system) @parser_params = Factory.attributes_for(:parser, :portal_system => @portal_system) end context "without auth" do setup do post :create, :parser => @parser_params end should_respond_with 401 end context "with valid params" do setup do stub_authentication post :create, :parser => @parser_params end should_change "Parser.count", :by => 1 should_assign_to :parser should_redirect_to( "the show page for parser") { parser_path(assigns(:parser)) } should_set_the_flash_to "Successfully created parser" end context "with invalid params" do setup do stub_authentication post :create, :parser => @parser_params.except(:result_model) end should_not_change "Parser.count" should_assign_to :parser should_render_template :new should_not_set_the_flash end context "with no scraper_type" do setup do stub_authentication post :create, :parser => @parser_params.except(:scraper_type) end should_not_change "Parser.count" should_assign_to :parser should_render_template :new should_not_set_the_flash end end # edit tests context "on GET to :edit without auth" do setup do @portal_system = Factory(:portal_system) @parser = Factory(:parser, :portal_system => @portal_system) get :edit, :id => @parser.id end should_respond_with 401 end context "on GET to :edit" do setup do @portal_system = Factory(:portal_system) @parser = Factory(:parser, :portal_system => @portal_system) stub_authentication get :edit, :id => @parser.id end should_assign_to(:parser) should_respond_with :success should_render_template :edit should "show form" do assert_select "form#edit_parser_#{@parser.id}" end end # update test context "on PUT to :update" do setup do @portal_system = Factory(:portal_system) @parser = Factory(:parser, :portal_system => @portal_system) @parser_params = { :description => "New Description", :result_model => "Committee", :item_parser => "foo=\"new_bar\"", :attribute_parser_object => [{:attrib_name => "newfoo", :parsing_code => "barbar"}]} end context "wihtout auth" do setup do put :update, :id => @parser.id, :parser => @parser_params end should_respond_with 401 end context "with valid params" do setup do stub_authentication put :update, :id => @parser.id, :parser => @parser_params end should_not_change "Parser.count" should_change "@parser.reload.description", :to => "New Description" should_change "@parser.reload.result_model", :to => "Committee" should_change "@parser.reload.item_parser", :to => "foo=\"new_bar\"" should_change "@parser.reload.attribute_parser", :to => {:newfoo => "barbar"} should_assign_to :parser should_redirect_to( "the show page for parser") { parser_path(assigns(:parser)) } should_set_the_flash_to "Successfully updated parser" end context "with invalid params" do setup do stub_authentication put :update, :id => @parser.id, :parser => {:result_model => ""} end should_not_change "Parser.count" should_not_change "@parser.reload.result_model" should_assign_to :parser should_render_template :edit should_not_set_the_flash end end end <file_sep>class Document < ActiveRecord::Base validates_presence_of :body validates_presence_of :url validates_uniqueness_of :url belongs_to :document_owner, :polymorphic => true def body=(raw_text) self[:raw_body] = raw_text # save orig raw text write_attribute(:body, sanitize_body(raw_text))#self[:body] = sanitize_body(raw_text) end def document_type self[:document_type] || "Document" end def title self[:title] || "#{document_type} for #{document_owner.title}" end protected def sanitize_body(raw_text) return if raw_text.blank? sanitized_body = ActionController::Base.helpers.sanitize(raw_text) base_url = url&&url.sub(/\/[^\/]+$/,'/') doc = Hpricot(sanitized_body) doc.search("a[@href]").each do |link| link[:href].match(/^http:/) ? link : link.set_attribute(:href, "#{base_url}#{link[:href]}") link.set_attribute(:class, 'external') end doc.search('img').remove doc.to_html end end <file_sep>require 'test_helper' class DocumentTest < ActiveSupport::TestCase context "The Document class" do setup do @document = Factory(:document) end should_validate_presence_of :body, :url should_validate_uniqueness_of :url should_belong_to :document_owner should_have_db_column :raw_body end context "A Document instance" do context "in general" do setup do @committee = Factory(:committee) @council = @committee.council @doc_owner = Factory(:meeting, :council => @committee.council, :committee => @committee) @document = Factory(:document, :document_owner => @doc_owner) end should "return document type and document owner as title" do @document.stubs(:document_type).returns("FooDocument") assert_equal "FooDocument for #{@doc_owner.title}", @document.title end should "return title attribute if set" do @document.title = "new title" assert_equal "new title", @document.title end should "return 'Document' as document_type if not set" do assert_equal "Document", @document.document_type end should "return document_type if set" do @document.document_type = "Minutes" assert_equal "Minutes", @document.document_type end end context "when setting body" do setup do @document = Document.new end should "store raw text in raw_body" do assert_equal "raw <font='Helvetica'>text</font>", Document.new(:body => "raw <font='Helvetica'>text</font>").raw_body end should "sanitize raw text" do @document.expects(:sanitize_body).with("raw <font='Helvetica'>text</font>") @document.body = "raw <font='Helvetica'>text</font>" end should "store sanitized text in body" do @document.stubs(:sanitize_body).returns("sanitized text") @document.body = "raw text" assert_equal "sanitized text", @document.body end should "not raise exception when setting body to nil" do assert_nothing_raised(Exception) { @document.body = nil } end end context "when sanitizing body text" do setup do @raw_text = "some <font='Helvetica'>stylized text</font> with <a href='councillor22'>relative link</a> and an <a href='http://external.com/dummy'>absolute link</a>. Also <script> something dodgy</script> here" @document = Document.new(:url => "http://www.council.gov.uk/document/some_page.htm?q=something") end should "convert relative urls to absolute ones based on url" do assert_match /with <a href="http:\/\/www\.council\.gov\.uk\/document\/councillor22/, @document.send(:sanitize_body, @raw_text) end should "not change urls of absolute links" do assert_match /an <a href=\"http:\/\/external\.com\/dummy\"/, @document.send(:sanitize_body, @raw_text) end should "add external class to all links" do assert_match /councillor22\" class=\"external/, @document.send(:sanitize_body, @raw_text) assert_match /dummy\" class=\"external/, @document.send(:sanitize_body, @raw_text) end should "remove images" do assert_match /with image/, @document.send(:sanitize_body, "text with <img src='http://council.gov.uk/image' /> image") end end # should "delegate council to document_owner" do # assert_equal @doc_owner.council, @document.council # end end end <file_sep>require 'test_helper' class InfoScraperTest < ActiveSupport::TestCase context "The InfoScraper class" do setup do @scraper = InfoScraper.new() end should "not validate presence of :url" do @scraper.valid? # trigger validation assert_nil @scraper.errors[:url] end should "be subclass of Scraper class" do assert_equal Scraper, InfoScraper.superclass end end context "an InfoScraper instance" do setup do @scraper = Factory.create(:info_scraper) end should "return what it is scraping for" do assert_equal "info on Members", @scraper.scraping_for end should "search result model for related_objects when none exist" do Member.expects(:find).with(:all, :conditions => {:council_id => @scraper.council_id}).returns("related_objects") assert_equal "related_objects", @scraper.related_objects end should "not search result model for related_objects when already exist" do @scraper.instance_variable_set(:@related_objects, "foo") Member.expects(:find).never assert_equal "foo", @scraper.related_objects end context "when processing" do context "with single given object" do setup do @scraper.stubs(:_data).returns("something") @parser = @scraper.parser @parser.stubs(:results).returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/fred" }] ) @dummy_related_object = Member.new(:url => "http://www.anytown.gov.uk/members/fred") end should "get data from object's url" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/members/fred") @scraper.process(:objects => @dummy_related_object) end should "save in related_objects" do @scraper.process(:objects => @dummy_related_object) assert_equal [@dummy_related_object], @scraper.related_objects end should "return self" do assert_equal @scraper, @scraper.process(:objects => @dummy_related_object) end should "parse info returned from url" do @parser.expects(:process).with("something", anything).returns(stub_everything(:results => [])) @scraper.process(:objects => @dummy_related_object) end should "pass self to associated parser" do @parser.expects(:process).with(anything, @scraper).returns(stub_everything(:results => [])) @scraper.process(:objects => @dummy_related_object) end should "update existing instance of result_class" do @scraper.process(:objects => @dummy_related_object) assert_equal "<NAME>", @dummy_related_object.full_name end should "not build new or update existing instance of result_class" do Member.expects(:build_or_update).never @scraper.process(:objects => @dummy_related_object) end should "validate existing instance of result_class" do @scraper.process(:objects => @dummy_related_object) assert @dummy_related_object.errors[:uid] end should "not try to save existing instance of result_class" do @dummy_related_object.expects(:save).never @scraper.process(:objects => @dummy_related_object) end should "try to save existing instance of result_class" do @dummy_related_object.expects(:save) @scraper.process(:save_results => true, :objects => @dummy_related_object) end should "store updated existing instance in results" do assert_equal [@dummy_related_object], @scraper.process(:objects => @dummy_related_object).results end should "not update last_scraped attribute if not saving results" do assert_nil @scraper.process(:objects => @dummy_related_object).last_scraped end should "update last_scraped attribute when saving results" do @scraper.process(:save_results => true, :objects => @dummy_related_object) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end should "not mark scraper as problematic" do @scraper.process assert !@scraper.reload.problematic? end context "and problem parsing" do setup do @parser.stubs(:errors => stub(:empty? => false)) end should "not build or update instance of result_class if no results" do @parser.stubs(:results) # => returns nil Member.expects(:attributes=).never @scraper.process(:objects => @dummy_related_object) end should "not update last_scraped attribute" do @scraper.process(:objects => @dummy_related_object) assert_nil @scraper.reload.last_scraped end should "mark scraper as problematic" do @scraper.process(:objects => @dummy_related_object) assert @scraper.reload.problematic? end end context "and problem getting data" do setup do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") end should "not raise exception" do assert_nothing_raised(Exception) { @scraper.process(:objects => @dummy_related_object) } end should "store error in scraper" do @scraper.process(:objects => @dummy_related_object) assert_equal "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found", @scraper.errors[:base] end should "return self" do assert_equal @scraper, @scraper.process(:objects => @dummy_related_object) end should "mark scraper as problematic" do @scraper.process(:objects => @dummy_related_object) assert @scraper.reload.problematic? end end end context "with collection of given objects" do setup do @scraper.stubs(:_data).returns("something") @parser = @scraper.parser @dummy_object_1, @dummy_object_2 = Member.new(:url => "http://www.anytown.gov.uk/members/fred"), Member.new(:url => "http://www.anytown.gov.uk/members/bob") @dummy_collection = [@dummy_object_1, @dummy_object_2] @parser.stubs(:results).returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/fred" }] ).then.returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/barney" }]) end should "get data from objects' urls" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/members/fred").then.with("http://www.anytown.gov.uk/members/bob") @scraper.process(:objects => @dummy_collection) end should "save in related_objects" do @scraper.process(:objects => @dummy_collection) assert_equal @dummy_collection, @scraper.related_objects end should "parse info returned from url" do @parser.expects(:process).with("something", anything).twice.returns(stub_everything(:results => [])) @scraper.process(:objects => @dummy_collection) end should "pass self to associated parser" do @parser.expects(:process).with(anything, @scraper).twice.returns(stub_everything(:results => [])) @scraper.process(:objects => @dummy_collection) end should "return self" do assert_equal @scraper, @scraper.process(:objects => @dummy_collection) end should "update collection objects" do @scraper.process(:objects => @dummy_collection) assert_equal "<NAME>", @dummy_object_1.full_name assert_equal "<NAME>", @dummy_object_2.full_name end should "not build new or update existing instance of result_class" do Member.expects(:build_or_update).never @scraper.process(:objects => @dummy_collection) end should "validate existing instance of result_class" do @scraper.process(:objects => @dummy_collection) assert @dummy_object_1.errors[:uid] end should "store updated existing instance in results" do assert_equal @dummy_collection, @scraper.process(:objects => @dummy_collection).results end should "not mark scraper as problematic" do @scraper.process(:objects => @dummy_collection) assert !@scraper.reload.problematic? end should "not update last_scraped attribute when not saving" do @scraper.process(:objects => @dummy_collection) assert_nil @scraper.reload.last_scraped end should "update last_scraped attribute when saving" do @scraper.process(:save_results => true, :objects => @dummy_collection) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end context "and problem getting data" do setup do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") end should "not raise exception" do assert_nothing_raised(Exception) { @scraper.process(:objects => @dummy_collection) } end should "store error in scraper" do @scraper.process(:objects => @dummy_collection) assert_equal "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found", @scraper.errors[:base] end should "return self" do assert_equal @scraper, @scraper.process(:objects => @dummy_collection) end should "not update last_scraped attribute when saving" do @scraper.process(:save_results => true, :objects => @dummy_collection) assert_nil @scraper.reload.last_scraped end should "mark scraper as problematic" do @scraper.process(:save_results => true, :objects => @dummy_collection) assert @scraper.reload.problematic? end end end context "with no given objects" do setup do @member = Factory(:member) Member.stubs(:find).returns([@member]) @scraper.stubs(:_data).returns("something") @parser = @scraper.parser @dummy_object_1, @dummy_object_2 = Member.new, Member.new @dummy_collection = [@dummy_object_1, @dummy_object_2] @parser.stubs(:results).returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/fred" }] ).then.returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/barney" }]) end should "use default related_objects" do Member.expects(:find).returns([@member]) @scraper.process assert_equal [@member], @scraper.related_objects end should "not raise exception" do assert_nothing_raised() { @scraper.process } end should "update default related objects with parsed results" do @scraper.expects(:update_with_results).with(anything, @member, anything) @scraper.process end end end end end <file_sep>class AddScraperTypeToParsers < ActiveRecord::Migration def self.up add_column :parsers, :scraper_type, :string Parser.all.each { |p| p.update_attribute(:scraper_type, p.scrapers.first.class.to_s) } end def self.down remove_column :parsers, :scraper_type end end <file_sep>require File.dirname(__FILE__) + '/helper' def expect_session_data_for(controller) # NOTE: setting expectations on the controller is not a good idea here, # because the controller is the unit we're trying to test. However, as all # exception-related behavior is mixed into the controller itsef, we have # little choice. Delegating notifier methods from the controller to a # Sender could make this easier to maintain and test. @controller.expects(:send_to_hoptoad).with do |params| assert params.respond_to?(:to_hash), "The notifier needs a hash" notice = params[:notice] assert_not_nil notice, "No notice passed to the notifier" assert_not_nil notice[:session][:key], "No session key was set" assert_not_nil notice[:session][:data], "No session data was set" true end @controller.stubs(:rescue_action_in_public_without_hoptoad) end def should_notify_normally should "have inserted its methods into the controller" do assert @controller.methods.include?("notify_hoptoad") end should "prevent raises and send the error to hoptoad" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise") end end should "allow a non-raising action to complete" do assert_nothing_raised do request("do_not_raise") end end should "allow manual sending of exceptions" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad).never assert_nothing_raised do request("manual_notify") end end should "disable manual sending of exceptions in a non-public (development or test) environment" do @controller.stubs(:public_environment?).returns(false) @controller.expects(:send_to_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad).never assert_nothing_raised do request("manual_notify") end end should "send even ignored exceptions if told manually" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad).never assert_nothing_raised do request("manual_notify_ignored") end end should "ignore default exceptions" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise_ignored") end end should "convert non-serializable data to strings" do klass = Class.new File.open(__FILE__) do |file| data = { :ghi => "789", :klass => klass, :file => file } assert_equal({ :ghi => "789", :file => file.to_s, :klass => klass.to_s }, @controller.send(:clean_non_serializable_data, data)) end end should "apply all params, environment and technical filters" do params_hash = {:abc => 123} environment_hash = {:def => 456} backtrace_data = :backtrace_data raw_notice = {:request => {:params => params_hash}, :environment => environment_hash, :backtrace => backtrace_data} processed_notice = {:backtrace => :backtrace_data, :request => {:params => :params_data}, :environment => :environment_data} @controller.expects(:clean_hoptoad_backtrace).with(backtrace_data).returns(:backtrace_data) @controller.expects(:clean_hoptoad_params).with(params_hash).returns(:params_data) @controller.expects(:clean_hoptoad_environment).with(environment_hash).returns(:environment_data) @controller.expects(:clean_non_serializable_data).with(processed_notice).returns(:serializable_data) assert_equal(:serializable_data, @controller.send(:clean_notice, raw_notice)) end should "send session data to hoptoad when the session has @data" do expect_session_data_for(@controller) @request = ActionController::TestRequest.new @request.action = 'do_raise' @request.session.instance_variable_set("@data", { :message => 'Hello' }) @response = ActionController::TestResponse.new @controller.process(@request, @response) end should "send session data to hoptoad when the session responds to to_hash" do expect_session_data_for(@controller) @request = ActionController::TestRequest.new @request.action = 'do_raise' @request.session.stubs(:to_hash).returns(:message => 'Hello') @response = ActionController::TestResponse.new @controller.process(@request, @response) end end def should_auto_include_catcher should "auto-include for ApplicationController" do assert ApplicationController.include?(HoptoadNotifier::Catcher) end end class ControllerTest < Test::Unit::TestCase context "Hoptoad inclusion" do should "be able to occur even outside Rails controllers" do assert_nothing_raised do class MyHoptoad include HoptoadNotifier::Catcher end end my = MyHoptoad.new assert my.respond_to?(:notify_hoptoad) end context "when auto-included" do setup do class ::ApplicationController < ActionController::Base end class ::AutoIncludeController < ::ApplicationController include TestMethods def rescue_action e rescue_action_in_public e end end HoptoadNotifier.ignore_only = HoptoadNotifier::IGNORE_DEFAULT @controller = ::AutoIncludeController.new @controller.stubs(:public_environment?).returns(true) @controller.stubs(:send_to_hoptoad) HoptoadNotifier.configure do |config| config.api_key = "<KEY>" end end context "when included through the configure block" do should_auto_include_catcher should_notify_normally end context "when included both through configure and normally" do setup do class ::AutoIncludeController < ::ApplicationController include HoptoadNotifier::Catcher end end should_auto_include_catcher should_notify_normally end end end context "when the logger is overridden for an action" do setup do class ::IgnoreActionController < ::ActionController::Base include TestMethods include HoptoadNotifier::Catcher def rescue_action e rescue_action_in_public e end def logger super unless action_name == "do_raise" end end ::ActionController::Base.logger = Logger.new(STDOUT) @controller = ::IgnoreActionController.new @controller.stubs(:public_environment?).returns(true) @controller.stubs(:rescue_action_in_public_without_hoptoad) HoptoadNotifier.stubs(:environment_info) # stubbing out Net::HTTP as well @body = 'body' @http = stub(:post => @response, :read_timeout= => nil, :open_timeout= => nil, :use_ssl= => nil) Net::HTTP.stubs(:new).returns(@http) HoptoadNotifier.port = nil HoptoadNotifier.host = nil HoptoadNotifier.proxy_host = nil end should "work when action is called and request works" do @response = stub(:body => @body, :class => Net::HTTPSuccess) assert_nothing_raised do request("do_raise") end end should "work when action is called and request doesn't work" do @response = stub(:body => @body, :class => Net::HTTPError) assert_nothing_raised do request("do_raise") end end should "work when action is called and hoptoad times out" do @http.stubs(:post).raises(TimeoutError) assert_nothing_raised do request("do_raise") end end end context "The hoptoad test controller" do setup do @controller = ::HoptoadController.new class ::HoptoadController def rescue_action e raise e end end end context "with no notifier catcher" do should "not prevent raises" do assert_raises RuntimeError do request("do_raise") end end should "allow a non-raising action to complete" do assert_nothing_raised do request("do_not_raise") end end end context "with the notifier installed" do setup do class ::HoptoadController include HoptoadNotifier::Catcher def rescue_action e rescue_action_in_public e end end HoptoadNotifier.ignore_only = HoptoadNotifier::IGNORE_DEFAULT @controller.stubs(:public_environment?).returns(true) @controller.stubs(:send_to_hoptoad) end should_notify_normally context "and configured to ignore_by_filter" do setup do HoptoadNotifier.configure do |config| config.ignore_by_filter do |exception_data| if exception_data[:error_class] == "RuntimeError" true if exception_data[:request][:params]['blah'] == 'skip' end end end end should "ignore exceptions based on param data" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise", "get", nil, :blah => 'skip') end end end context "and configured to ignore additional exceptions" do setup do HoptoadNotifier.ignore << ActiveRecord::StatementInvalid end should "still ignore default exceptions" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise_ignored") end end should "ignore specified exceptions" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise_not_ignored") end end should "not ignore unspecified, non-default exceptions" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise") end end end context "and configured to ignore only certain exceptions" do setup do HoptoadNotifier.ignore_only = [ActiveRecord::StatementInvalid] end should "no longer ignore default exceptions" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise_ignored") end end should "ignore specified exceptions" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise_not_ignored") end end should "not ignore unspecified, non-default exceptions" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise") end end end context "and configured to ignore certain user agents" do setup do HoptoadNotifier.ignore_user_agent << /Ignored/ HoptoadNotifier.ignore_user_agent << 'IgnoredUserAgent' end should "ignore exceptions when user agent is being ignored" do @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise", :get, 'IgnoredUserAgent') end end should "ignore exceptions when user agent is being ignored (regexp)" do HoptoadNotifier.ignore_user_agent_only = [/Ignored/] @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise", :get, 'IgnoredUserAgent') end end should "ignore exceptions when user agent is being ignored (string)" do HoptoadNotifier.ignore_user_agent_only = ['IgnoredUserAgent'] @controller.expects(:notify_hoptoad).never @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise", :get, 'IgnoredUserAgent') end end should "not ignore exceptions when user agent is not being ignored" do @controller.expects(:notify_hoptoad) @controller.expects(:rescue_action_in_public_without_hoptoad) assert_nothing_raised do request("do_raise") end end end end end end <file_sep>require "test_helper" class TestModel <ActiveRecord::Base attr_accessor :council include ScrapedModel set_table_name "members" end class ScrapedModelTest < ActiveSupport::TestCase context "A class that includes ScrapedModel mixin" do setup do TestModel.delete_all # doesn't seem to delete old records !?! @test_model = TestModel.create!(:uid => 33, :council_id => 99) @params = {:uid => 2, :council_id => 2, :party => "Independent", :url => "http:/some.url"} # uid and council_id can be anything as we stub finding of existing member end context "when finding existing member from params" do should "should return member which has given uid and council" do assert_equal @test_model, TestModel.find_existing(:uid => @test_model.uid, :council_id => @test_model.council_id) end should "should return nil when no record with given uid and council" do assert_nil TestModel.find_existing(:uid => @test_model.uid, :council_id => 42) end end context "when building_or_updating from params" do setup do end should "should use existing record if it exists" do TestModel.expects(:find_existing).returns(@test_model) TestModel.build_or_update(@params) end should "return existing record if it exists" do TestModel.stubs(:find_existing).returns(@test_model) rekord = TestModel.build_or_update(@params) assert_equal @test_model, rekord end should "update existing record" do TestModel.stubs(:find_existing).returns(@test_model) rekord = TestModel.build_or_update(@params) assert_equal 2, rekord.council_id assert_equal "Independent", rekord.party end should "should build with attributes for new member when existing not found" do TestModel.stubs(:find_existing) # => returns nil TestModel.expects(:new).with(@params) TestModel.build_or_update(@params) end should "should return new record when existing not found" do TestModel.stubs(:find_existing) # => returns nil dummy_new_record = stub TestModel.stubs(:new).returns(dummy_new_record) assert_equal dummy_new_record, TestModel.build_or_update(@params) end end context "when creating_or_update_and_saving from params" do context "with existing record" do setup do @dummy_record = stub_everything end should "build_or_update on class" do TestModel.expects(:build_or_update).with(@params).returns(@dummy_record) TestModel.create_or_update_and_save(@params) end should "save_without_losing_dirty on record built or updated" do TestModel.stubs(:build_or_update).returns(@dummy_record) @dummy_record.expects(:save_without_losing_dirty) TestModel.create_or_update_and_save(@params) end should "return updated record" do TestModel.stubs(:build_or_update).returns(@dummy_record) assert_equal @dummy_record, TestModel.create_or_update_and_save(@params) end should "not raise exception if saving fails" do TestModel.stubs(:build_or_update).returns(@dummy_record) @dummy_record.stubs(:save_without_losing_dirty) assert_nothing_raised() { TestModel.create_or_update_and_save(@params) } end end end context "when creating_or_update_and_saving! from params" do setup do @dummy_record = stub_everything @dummy_record.stubs(:save_without_losing_dirty).returns(true) end should "build_or_update on class" do TestModel.expects(:build_or_update).with(@params).returns(@dummy_record) TestModel.create_or_update_and_save!(@params) end should "save_without_losing_dirty on record built or updated" do TestModel.stubs(:build_or_update).returns(@dummy_record) @dummy_record.expects(:save_without_losing_dirty).returns(true) TestModel.create_or_update_and_save!(@params) end should "return updated record" do TestModel.stubs(:build_or_update).returns(@dummy_record) assert_equal @dummy_record, TestModel.create_or_update_and_save!(@params) end should "raise exception if saving fails" do TestModel.stubs(:build_or_update).returns(@dummy_record) @dummy_record.stubs(:save_without_losing_dirty) assert_raise(ActiveRecord::RecordNotSaved) { TestModel.create_or_update_and_save!(@params) } end end end context "An instance of a class that includes ScrapedModel mixin" do setup do @test_model = TestModel.new(:uid => 42) end should "provide access to new_record_before_save instance variable" do @test_model.instance_variable_set(:@new_record_before_save, true) assert @test_model.new_record_before_save? end should "save_without_losing_dirty" do assert @test_model.respond_to?(:save_without_losing_dirty) end context "when saving_without_losing_dirty" do setup do @test_model.save_without_losing_dirty end should_change "TestModel.count", :by => 1 should "save record" do assert !@test_model.new_record? end should "keep record of new attributes" do assert_equal [nil, 42], @test_model.changes['uid'] end should "return true if successfully saves" do @test_model.expects(:save).returns(true) assert @test_model.save_without_losing_dirty end should "return false if does not successfully save" do @test_model.expects(:save).returns(false) assert !@test_model.save_without_losing_dirty end end context "with an associated council" do setup do @council = Factory(:council) @test_model.council = @council Council.record_timestamps = false # update timestamp without triggering callbacks @council.update_attributes(:updated_at => 2.days.ago) #... though thought from Rails 2.3 you could do this without turning off timestamps Council.record_timestamps = true end should "mark council as updated when member is updated" do @test_model.update_attribute(:last_name, "Wilson") assert_in_delta Time.now, @council.updated_at, 2 end should "mark council as updated when member is deleted" do @test_model.destroy assert_in_delta Time.now, @council.updated_at, 2 end end end end<file_sep>class AdminController < ApplicationController before_filter :authenticate def index @title = 'Admin' end end <file_sep>#atttributes url, constituency, party class Member < ActiveRecord::Base include ScrapedModel validates_presence_of :last_name, :url, :uid, :council_id validates_uniqueness_of :uid, :scope => :council_id # uid is unique id number assigned by council. It's possible that some councils may not assign them (e.g. GLA), but cross that bridge... has_many :memberships, :primary_key => :id has_many :committees, :through => :memberships, :extend => UidAssociationExtension belongs_to :council named_scope :current, :conditions => "date_left IS NULL" alias_attribute :title, :full_name delegate :uids, :to => :committees, :prefix => "committee" delegate :uids=, :to => :committees, :prefix => "committee" def full_name=(full_name) names_hash = NameParser.parse(full_name) %w(first_name last_name name_title qualifications).each do |a| self.send("#{a}=", names_hash[a.to_sym]) end end def full_name "#{first_name} #{last_name}" end def ex_member? date_left end def party=(party_name) self[:party] = party_name.gsub(/party/i, '').strip end end <file_sep>require 'test_helper' # TO DO: Sort out testing and behavious of #process method. At the # moment Scraper#process method is never called directly, only via # a super in a single case of ItemScraper. So tests are being # duplicated, as is code, and since we enver have an instance of the base # Scraper model, prob shouldn't be testing it, rather should test a # basic scraper that inherits from it. class ScraperTest < ActiveSupport::TestCase should_belong_to :parser should_belong_to :council should_validate_presence_of :council_id should_accept_nested_attributes_for :parser context "The Scraper class" do should "define ScraperError as child of StandardError" do assert_equal StandardError, Scraper::ScraperError.superclass end should "define RequestError as child of ScraperError" do assert_equal Scraper::ScraperError, Scraper::RequestError.superclass end should "define ParsingError as child of ScraperError" do assert_equal Scraper::ScraperError, Scraper::ParsingError.superclass end should "have stale named_scope" do expected_options = { :conditions => ["(last_scraped IS NULL) OR (last_scraped < ?)", 7.days.ago], :order => "last_scraped" } actual_options = Scraper.stale.proxy_options assert_equal expected_options[:conditions].first, actual_options[:conditions].first assert_in_delta expected_options[:conditions].last, actual_options[:conditions].last, 2 assert_equal expected_options[:order], actual_options[:order] end should "return stale scrapers" do # just checking... fresh_scraper = Factory(:scraper, :last_scraped => 6.days.ago) stale_scraper = Factory(:item_scraper, :last_scraped => 8.days.ago) never_used_scraper = Factory(:info_scraper) assert_equal [never_used_scraper, stale_scraper], Scraper.stale end should "have problematic named_scope" do expected_options = { :conditions => { :problematic => true } } actual_options = Scraper.problematic.proxy_options assert_equal expected_options, actual_options end should "have unproblematic named_scope" do expected_options = { :conditions => { :problematic => false } } actual_options = Scraper.unproblematic.proxy_options assert_equal expected_options, actual_options end # context "when finding all by type" do # setup do # # end # # should "return all with given result model" do # find_by_result_model # end # # should "return all with given scraper type" do # # end # end end context "A Scraper instance" do setup do @scraper = Factory.create(:scraper) @council = @scraper.council @parser = @scraper.parser end should "not save unless there is an associated parser" do s = Scraper.new(:council => @council) assert !s.save assert_equal "can't be blank", s.errors[:parser] end should "save if there is an associated parser set via parser_id" do # just checking... s = Scraper.new(:council => @council, :parser_id => @parser.id) assert s.save end should "be stale if last_scraped more than 1 week ago" do @scraper.update_attribute(:last_scraped, 8.days.ago) assert @scraper.stale? end should "not be stale if last_scraped less than 1 week ago" do @scraper.update_attribute(:last_scraped, 6.days.ago) assert !@scraper.stale? end should "be stale if last_scraped nil" do assert @scraper.stale? end should "not be problematic by default" do assert !@scraper.problematic? end should "delegate result_model to parser" do @parser.expects(:result_model).returns("result_model") assert_equal "result_model", @scraper.result_model end should "delegate related_model to parser" do @parser.expects(:related_model).returns("related_model") assert_equal "related_model", @scraper.related_model end should "delegate portal_system to council" do @council.expects(:portal_system).returns("portal_system") assert_equal "portal_system", @scraper.portal_system end should "delegate base_url to council" do @council.expects(:base_url).returns("http://some.council.com/democracy") assert_equal "http://some.council.com/democracy", @scraper.base_url end should "have results accessor" do @scraper.instance_variable_set(:@results, "foo") assert_equal "foo", @scraper.results end should "return empty array as results if not set" do assert_equal [], @scraper.results end should "set empty array as results if not set" do @scraper.results assert_equal [], @scraper.instance_variable_get(:@results) end should_not_allow_mass_assignment_of :results should "have parsing_results accessor" do @scraper.instance_variable_set(:@parsing_results, "foo") assert_equal "foo", @scraper.parsing_results end should "have related_objects accessor" do @scraper.instance_variable_set(:@related_objects, "foo") assert_equal "foo", @scraper.related_objects end should "build title from council name result class and scraper type when ItemScraper" do assert_equal "Member Items scraper for Anytown", @scraper.title end should "build title from council name result class and scraper type when InfoScraper" do assert_equal "Member Info scraper for Anothertown", Factory.build(:info_scraper).title end should "return errors in parser as parsing errors" do @parser.errors.add_to_base("some error") assert_equal "some error", @scraper.parsing_errors[:base] end should "update last_scraped attribute without changing updated_at timestamp" do ItemScraper.record_timestamps = false # update timestamp without triggering callbacks @scraper.update_attributes(:updated_at => 2.days.ago) #... though thought from Rails 2.3 you could do this turning off timestamps ItemScraper.record_timestamps = true @scraper.send(:update_last_scraped) assert_in_delta 2.days.ago, @scraper.reload.updated_at, 2 # check timestamp hasn't changed... assert_in_delta Time.now, @scraper.last_scraped, 2 #...but last_scraped has end should "mark as problematic without changing updated_at timestamp" do ItemScraper.record_timestamps = false # update timestamp without triggering callbacks @scraper.update_attributes(:updated_at => 2.days.ago) #... though thought from Rails 2.3 you could do this without turning off timestamps ItemScraper.record_timestamps = true @scraper.send(:mark_as_problematic) assert_in_delta 2.days.ago, @scraper.reload.updated_at, 2 # check timestamp hasn't changed... assert @scraper.problematic? end context "if scraper has url attribute" do should "return url attribute as url" do assert_equal 'http://www.anytown.gov.uk/members/bob', @scraper.url end should "ignore base_url and parser path when returning url" do @scraper.parser.expects(:path).never @scraper.expects(:base_url).never assert_equal 'http://www.anytown.gov.uk/members/bob', @scraper.url end end context "if url attribute is nil" do setup do @scraper.url = nil end should "use computed_url for url" do @scraper.expects(:computed_url).returns("http://council.gov.uk/computed_url/") assert_equal "http://council.gov.uk/computed_url/", @scraper.url end end context "if url attribute is blank" do setup do @scraper.url = "" end should "use computed_url for url" do @scraper.expects(:computed_url).returns("http://council.gov.uk/computed_url/") assert_equal "http://council.gov.uk/computed_url/", @scraper.url end end context "for computed url" do should "combine base_url and parser path" do @scraper.stubs(:base_url).returns("http://council.gov.uk/democracy/") @scraper.parser.stubs(:path).returns("path/to/councillors") assert_equal 'http://council.gov.uk/democracy/path/to/councillors', @scraper.computed_url end should "return nil if base_url is nil" do @scraper.stubs(:base_url) # => nil @scraper.parser.stubs(:path).returns("path/to/councillors") assert_nil @scraper.computed_url end should "return nil if parser path is nil" do @scraper.stubs(:base_url).returns("http://council.gov.uk/democracy/") @scraper.parser.stubs(:path) # => nil assert_nil @scraper.computed_url end end context "that belongs to council with portal system" do setup do @portal_system = Factory(:portal_system, :name => "Big Portal System") @portal_system.parsers << @parser = Factory(:another_parser) @council.portal_system = @portal_system end should "return council's portal system" do assert_equal @portal_system, @scraper.portal_system end should "return portal system's parsers as possible parsers" do assert_equal [@parser], @scraper.possible_parsers end end context "has portal_parser? method which" do should "return true for if parser has associated portal system" do @scraper.parser.portal_system = Factory(:portal_system) assert @scraper.portal_parser? end should "return false if parser does not have associated portal system" do assert !@scraper.portal_parser? end should "return false if no parser" do assert !Scraper.new.portal_parser? end end context "when getting data" do should "get given url" do @scraper.expects(:_http_get).with('http://another.url').returns("something") @scraper.send(:_data, 'http://another.url') end should "return data as Hpricot Doc" do @scraper.stubs(:_http_get).returns("something") assert_kind_of Hpricot::Doc, @scraper.send(:_data) end should "raise ParsingError when problem processing page with Hpricot" do Hpricot.expects(:parse).raises assert_raise(Scraper::ParsingError) {@scraper.send(:_data)} end should "raise RequestError when problem getting page" do @scraper.expects(:_http_get).raises(OpenURI::HTTPError, "404 Not Found") assert_raise(Scraper::RequestError) {@scraper.send(:_data)} end end context "when processing" do setup do @parser = @scraper.parser @parser.stubs(:results).returns([{ :full_name => "<NAME>", :url => "http://www.anytown.gov.uk/members/fred" }] ) @scraper.stubs(:_data).returns("something") end should "get data from url" do @scraper.expects(:_data).with("http://www.anytown.gov.uk/members/bob") @scraper.process end should "pass data to associated parser" do @parser.expects(:process).with("something", anything).returns(stub_everything) @scraper.process end should "pass self to associated parser" do @parser.expects(:process).with(anything, @scraper).returns(stub_everything) @scraper.process end should "return self" do assert_equal @scraper, @scraper.process end should "build new or update existing instance of result_class with parser results and scraper council" do dummy_new_member = Member.new Member.expects(:build_or_update).with(:full_name => "<NAME>", :council_id => @council.id, :url => "http://www.anytown.gov.uk/members/fred").returns(dummy_new_member) dummy_new_member.expects(:save).never @scraper.process end should "validate instances of result_class" do Member.any_instance.expects(:valid?) @scraper.process end should "store instances of result class in results" do dummy_member = Member.new Member.stubs(:build_or_update).returns(dummy_member) assert_equal [dummy_member], @scraper.process.results end should "not update last_scraped attribute" do @scraper.process assert_nil @scraper.reload.last_scraped end should "not mark scraper as problematic" do @scraper.process assert !@scraper.reload.problematic? end context "and problem parsing" do setup do @parser.stubs(:results) # => returns nil @parser.stubs(:errors => stub(:empty? => false)) end should "not build or update instance of result_class if no results" do Member.expects(:build_or_update).never end should "mark scraper as problematic" do @scraper.process assert @scraper.reload.problematic? end end context "and problem getting data" do setup do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") end should "not raise exception" do assert_nothing_raised(Exception) { @scraper.process } end should "store error in scraper" do @scraper.process assert_equal "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found", @scraper.errors[:base] end should "return self" do assert_equal @scraper, @scraper.process end should "mark as problematic when problem getting page" do @scraper.process assert @scraper.reload.problematic? end end context "and saving results" do should "return self" do assert_equal @scraper, @scraper.process(:save_results => true) end should "create new or update and save existing instance of result_class with parser results and scraper council" do dummy_new_member = Member.new Member.expects(:build_or_update).with(:full_name => "<NAME>", :council_id => @council.id, :url => "http://www.anytown.gov.uk/members/fred").returns(dummy_new_member) @scraper.process(:save_results => true) end should "save record using save_without_losing_dirty" do dummy_new_member = Member.new Member.stubs(:build_or_update).returns(dummy_new_member) dummy_new_member.expects(:save_without_losing_dirty) @scraper.process(:save_results => true) end should "store instances of result class in results" do dummy_member = Member.new Member.stubs(:build_or_update).returns(dummy_member) assert_equal [dummy_member], @scraper.process(:save_results => true).results end should "update last_scraped attribute" do @scraper.process(:save_results => true) assert_in_delta(Time.now, @scraper.reload.last_scraped, 2) end should "not update last_scraped result attribute when problem getting data" do @scraper.expects(:_data).raises(Scraper::RequestError, "Problem getting data from http://problem.url.com: OpenURI::HTTPError: 404 Not Found") @scraper.process(:save_results => true) assert_nil @scraper.reload.last_scraped end should "not update last_scraped result attribute when problem parsing" do @parser.stubs(:errors => stub(:empty? => false)) @scraper.process(:save_results => true) assert_nil @scraper.reload.last_scraped end end end end private def new_scraper(options={}) Scraper.new(options) end end <file_sep>class Datapoint < ActiveRecord::Base belongs_to :council belongs_to :dataset validates_presence_of :data, :council_id, :dataset_id serialize :data delegate :summary_column, :to => :dataset def summary data.collect{ |d| d[summary_column] } if summary_column end end <file_sep>class RenameParsingCodeAsItemParser < ActiveRecord::Migration def self.up rename_column :parsers, :parsing_code, :item_parser add_column :parsers, :attribute_parser, :text end def self.down remove_column :parsers, :attribute_parser rename_column :parsers, :item_parser, :parsing_code end end <file_sep>class AddDatesToMembers < ActiveRecord::Migration def self.up add_column :members, :date_elected, :date add_column :members, :date_left, :date end def self.down remove_column :members, :date_left remove_column :members, :date_elected end end <file_sep>require 'test_helper' class CommitteeTest < ActiveSupport::TestCase context "The Committee Class" do setup do @committee = Committee.create!(:title => "Some Committee", :url => "some.url", :uid => 44, :council_id => 1) end should_validate_presence_of :title, :url, :uid, :council_id should_validate_uniqueness_of :title, :scoped_to => :council_id should_have_many :meetings should_have_many :memberships should_have_many :members, :through => :memberships should_belong_to :council should "include ScraperModel mixin" do assert Committee.respond_to?(:find_existing) end end context "A Committee instance" do setup do @council, @another_council = Factory(:council), Factory(:another_council) @committee = Committee.new(:title => "Some Committee", :url => "some.url", :council_id => @council.id) end context "with members" do # this part is really just testing inclusion of uid_association extension in members association setup do @member = Factory(:member, :council => @council) @old_member = Factory(:old_member, :council => @council) @another_council_member = Factory(:member, :council => @another_council, :uid => 999) @committee.members << @old_member end should "return member uids" do assert_equal [@old_member.uid], @committee.member_uids end should "replace existing members with ones with given uids" do @committee.member_uids = [@member.uid] assert_equal [@member], @committee.members end should "not add members that don't exist for council" do @committee.member_uids = [@another_council_member.uid] assert_equal [], @committee.members end end end private def new_committee(options={}) Committee.new({:title => "Some Title"}.merge(options)) end end <file_sep>require 'test_helper' class ApplicationHelperTest < ActionView::TestCase context "link_for helper method" do should "return nil by default" do assert_nil link_for end should "return link for item with object title for link text" do obj = stale_factory_object(:committee) # poss better way of testing this. obj can be any ActiveRecord obj assert_dom_equal link_to(obj.title, obj, :class => "committee_link"), link_for(obj) end should "escape object's title" do obj = stale_factory_object(:committee, :title => "something & nothing... which <needs> escaping" ) assert_dom_equal link_to(h(obj.title), obj, :class => "committee_link"), link_for(obj) end should "pass on options" do obj = stale_factory_object(:committee, :title => "something & nothing... which <needs> escaping" ) assert_dom_equal link_to(h(obj.title), obj, :foo => "bar", :class => "committee_link"), link_for(obj, :foo => "bar") end should "add given class to object class" do obj = stale_factory_object(:committee, :title => "something & nothing... which <needs> escaping" ) assert_dom_equal link_to(h(obj.title), obj, :class => "committee_link bar"), link_for(obj, :class => "bar") end should "add new class if it has recently been created" do obj = Factory(:committee) assert_dom_equal link_to(obj.title, obj, :class => "committee_link new"), link_for(obj) end should "add updated class if it is not new but has recently been updated" do obj = Factory(:committee) obj.stubs(:created_at => 8.days.ago) assert_dom_equal link_to(obj.title, obj, :class => "committee_link updated"), link_for(obj) end end context "council_page_for helper method" do should "return link based on url" do obj = stub(:url => "http://somecouncil/meeting") assert_dom_equal link_to("council page", "http://somecouncil/meeting", :class => "council_page_link external"), council_page_for(obj) end end context "link_to_api_url" do setup do @controller = TestController.new self.stubs(:params).returns(:controller => "councils", :action => "index") end should "should return xml link when xml requested" do assert_equal link_to("xml", { :controller => "councils", :action => "index", :format => "xml" }, :class => "api_link"), link_to_api_url("xml") end should "should return js link when json requested" do assert_equal link_to("json", { :controller => "councils", :action => "index", :format => "json" }, :class => "api_link"), link_to_api_url("json") end end context "list_all helper method" do setup do @obj1 = Factory(:committee ) @obj2 = Factory(:another_council) end should "return message if no object given" do assert_dom_equal "<p class='no_results'>No results</p>", list_all end should "return message if empty_array given" do assert_dom_equal "<p class='no_results'>No results</p>", list_all([]) end should "return message if nil given" do assert_dom_equal "<p class='no_results'>No results</p>", list_all(nil) end should "return unordered list of objects using link_for helper method" do assert_dom_equal "<ul><li>#{link_for(@obj1)}</li><li>#{link_for(@obj2)}</li></ul>", list_all([@obj1,@obj2]) end should "return unordered list of single object" do assert_dom_equal "<ul><li>#{link_for(@obj1)}</li></ul>", list_all(@obj1) end end private def stale_factory_object(name, options={}) obj = Factory(name, options) obj.stubs(:created_at => 8.days.ago, :updated_at => 8.days.ago) obj end end
be021236db78cd0ba9f564bdb8f35ce7e95c71d4
[ "Ruby" ]
100
Ruby
CountCulture/twfy_local_parser
8d4c9d9ab9c42be623c9a2974b5926de9f3222bc
37c14c2b9415c2c41ccb92a0e739cc5c36df2782
refs/heads/master
<file_sep><?php class DB_Functions { private $db; //put your code here // constructor function __construct() { include_once './db_connect.php'; include_once '../../config.php'; // connecting to database $this->db = new DB_Connect(); $this->db->connect(); } // destructor function __destruct() { } /** * Storing new asset * returns asset details */ public function addAsset($asset_id='',$name='',$description='',$created_at='',$updated_at='',$deleted='',$latitude='',$longitude='',$images='',$locations=null) { // Insert user into database //$timestamp = time(); //$deleted = 0; $assetQuery = "INSERT INTO assets ("._ASSETS_COLUMN_ASSET_ID.", " ._ASSETS_COLUMN_ASSET_NAME.", " ._ASSETS_COLUMN_ASSET_DESCRIPTION.", " ._ASSETS_COLUMN_CREATED_AT.", " ._ASSETS_COLUMN_UPDATED_AT.", " ._ASSETS_COLUMN_DELETED.") VALUES('$asset_id','$name','$description','$created_at','$updated_at','$deleted')"; //if the location array is empty, just insert the one location if($locations == null) { $locationQuery = "INSERT INTO " ._LOCATIONS_TABLE. " ("._LOCATIONS_COLUMN_ASSET_ID.", " ._LOCATIONS_COLUMN_LATITUDE.", " ._LOCATIONS_COLUMN_LONGITUDE.") VALUES('$asset_id','$latitude','$longitude')"; } else { $locationQuery = "INSERT INTO " ._LOCATIONS_TABLE. " ("._LOCATIONS_COLUMN_ASSET_ID.", " ._LOCATIONS_COLUMN_LATITUDE.", " ._LOCATIONS_COLUMN_LONGITUDE.") VALUES"; $insertData = array(); foreach ($locations as $location) { $insertData[] = "("; $insertData[] = $asset_id.","; $insertData[] = $location['latitude'].","; $insertData[] = $location['longitude']; $insertData[] = "),"; } if (!empty($insertData)) { $locationQuery .= implode('', $insertData); $locationQuery = trim($locationQuery, ","); } } $mediaQuery = "INSERT INTO " ._MEDIA_TABLE. " ("._MEDIA_COLUMN_ASSET_ID.", " ._MEDIA_COLUMN_IMAGES.") VALUES('$asset_id','$images')"; $assetResult = mysql_query($assetQuery); if($assetResult) { $locationResult = mysql_query($locationQuery); $mediaResult = mysql_query($mediaQuery); } //error_log($assetQuery); if ($assetResult && $locationResult && $mediaResult) { return true; } else { if( mysql_errno() == 1062) { // Duplicate key - Primary Key Violation return true; } else { // For other errors return false; } } } /** * Mark asset as deleted * */ public function deleteAsset($asset_id, $updated_at) { //Insert user into database //$timestamp = time(); $deleted = 1; $result = mysql_query("UPDATE assets SET deleted = '$deleted' , updated_at = '$updated_at' WHERE asset_id = '$asset_id' "); if ($result) { return true; } else { if( mysql_errno() == 1062) { // Duplicate key - Primary Key Violation return true; } else { // For other errors return false; } } } /** * Mark asset as deleted * */ public function updateAsset($asset_id='',$name='',$description='',$created_at='',$updated_at='',$deleted='',$latitude='',$longitude='',$images='',$locations=null) { //Insert user into database //$timestamp = time(); $assetQuery = "UPDATE assets SET " ._ASSETS_COLUMN_ASSET_NAME. " = '$name'," ._ASSETS_COLUMN_ASSET_DESCRIPTION. " = '$description'," ._ASSETS_COLUMN_CREATED_AT. "= '$created_at'," ._ASSETS_COLUMN_UPDATED_AT. "= '$updated_at'," ._ASSETS_COLUMN_DELETED. "= '$deleted' WHERE " ._ASSETS_COLUMN_ASSET_ID. "= '$asset_id' "; //if the location array is empty, just insert the one location if($locations == null) { $locationQuery = "UPDATE "._LOCATIONS_TABLE." SET " ._LOCATIONS_COLUMN_LATITUDE. " = '$latitude'," ._LOCATIONS_COLUMN_LONGITUDE. "= '$longitude' WHERE " ._LOCATIONS_COLUMN_ASSET_ID. "= '$asset_id' "; } else { //delete the locations assosiated with the asset before updating $deleteLocations = "DELETE FROM " ._LOCATIONS_TABLE. " WHERE " ._LOCATIONS_COLUMN_ASSET_ID. "=" .$asset_id; mysql_query($deleteLocations); $locationQuery = "INSERT INTO " ._LOCATIONS_TABLE. " ("._LOCATIONS_COLUMN_ASSET_ID.", " ._LOCATIONS_COLUMN_LATITUDE.", " ._LOCATIONS_COLUMN_LONGITUDE.") VALUES"; $insertData = array(); foreach ($locations as $location) { $insertData[] = "("; $insertData[] = $asset_id.","; $insertData[] = $location['latitude'].","; $insertData[] = $location['longitude']; $insertData[] = "),"; } if (!empty($insertData)) { $locationQuery .= implode('', $insertData); $locationQuery = trim($locationQuery, ","); } } $mediaQuery = "UPDATE "._MEDIA_TABLE." SET " ._MEDIA_COLUMN_IMAGES. " = '$images' WHERE " ._MEDIA_COLUMN_ASSET_ID. "= '$asset_id' "; //error_log($query); $assetResult = mysql_query($assetQuery); if ($assetResult) { $locationResult = mysql_query($locationQuery); $mediaResult = mysql_query($mediaQuery); } if ($assetResult && $locationResult && $mediaResult) { return true; } else { if( mysql_errno() == 1062) { // Duplicate key - Primary Key Violation return true; } else { // For other errors return false; } } } /** * Getting all assets */ public function getAllAssets() { $sql = 'SELECT '._ASSETS_TABLE.'.*, '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LONGITUDE.', '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LATITUDE.', '._MEDIA_TABLE.'.'._MEDIA_COLUMN_IMAGES.' FROM '._ASSETS_TABLE.' LEFT JOIN '._LOCATIONS_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_ASSET_ID.' LEFT JOIN '._MEDIA_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._MEDIA_TABLE.'.'._MEDIA_COLUMN_ASSET_ID.' ORDER BY ' ._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID; $result = mysql_query($sql); return $result; } /** * Get location */ public function getLocationsByAssetId($asset_id) { $query = 'SELECT '._LOCATIONS_COLUMN_LONGITUDE.', '._LOCATIONS_COLUMN_LATITUDE.' FROM '._LOCATIONS_TABLE.' WHERE '._ASSETS_COLUMN_ASSET_ID.' = '.$asset_id.' ORDER BY '._LOCATIONS_COLUMN_LOCATION_ID.' ASC' ; $result = mysql_query($query); return $result; } /** * Execute SQL Query */ public function executeSqlQuery($query) { $result = mysql_query($query) or die(mysql_error()); return $result; } /** * Getting asset by id */ public function getAssetById($asset_id) { $sql = 'SELECT '._ASSETS_TABLE.'.*, '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LONGITUDE.', '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LATITUDE.', '._MEDIA_TABLE.'.'._MEDIA_COLUMN_IMAGES.' FROM '._ASSETS_TABLE.' LEFT JOIN '._LOCATIONS_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_ASSET_ID.' LEFT JOIN '._MEDIA_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._MEDIA_TABLE.'.'._MEDIA_COLUMN_ASSET_ID.' WHERE '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '.$asset_id; $result = mysql_query($sql); return $result; } /** * Getting all active assets */ public function getAllActiveAssets() { $sql = 'SELECT '._ASSETS_TABLE.'.*, '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LONGITUDE.', '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_LATITUDE.', '._MEDIA_TABLE.'.'._MEDIA_COLUMN_IMAGES.' FROM '._ASSETS_TABLE.' LEFT JOIN '._LOCATIONS_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._LOCATIONS_TABLE.'.'._LOCATIONS_COLUMN_ASSET_ID.' LEFT JOIN '._MEDIA_TABLE.' ON '._ASSETS_TABLE.'.'._ASSETS_COLUMN_ASSET_ID.' = '._MEDIA_TABLE.'.'._MEDIA_COLUMN_ASSET_ID. ' WHERE '._ASSETS_COLUMN_DELETED. ' = 0 ORDER BY '._ASSETS_COLUMN_ASSET_ID.' DESC'; $result = mysql_query($sql); return $result; } } ?><file_sep><?php /** * DB configuration variables */ define("DB_HOST", "mysql"); define("DB_USER", "root"); define("DB_PASSWORD", $_ENV["MYSQL_ROOT_PASSWORD"]); define("DB_DATABASE", "tams"); # DO NOT TOUCH ANYTHING BELLOW THIS LINE # -------------------------------------# // Tables define("_ASSETS_TABLE", "assets"); define("_LOCATIONS_TABLE", "locations"); define("_MEDIA_TABLE", "media"); define("_ATTRIBUTES_TABLE", "attributes"); define("_ATTRIBUTES_INDEXES_TABLE", "attributes_indexes"); define("_ATTRIBUTES_VALUES_TABLE", "attributes_values"); define("_ASSET_TYPES_TABLE", "asset_types_table"); define("_API_AUTH_TABLE", "api_auth"); // Table columns //Asset table columns define("_ASSETS_COLUMN_ASSET_ID", "asset_id"); define("_ASSETS_COLUMN_CREATED_AT", "created_at"); define("_ASSETS_COLUMN_UPDATED_AT", "updated_at"); define("_ASSETS_COLUMN_ASSET_NAME", "name"); define("_ASSETS_COLUMN_ASSET_DESCRIPTION", "description"); define("_ASSETS_COLUMN_NEEDSSYNC", "needsSync"); //used in app only define("_ASSETS_COLUMN_DELETED", "deleted"); define("_ASSETS_COLUMN_ISNEW", "isNew"); //used in app only - keeps track if the asset is brand new - useful for server function call //Locations table columns define("_LOCATIONS_COLUMN_LOCATION_ID", "location_id"); define("_LOCATIONS_COLUMN_ASSET_ID", "asset_id"); define("_LOCATIONS_COLUMN_LONGITUDE", "longitude"); define("_LOCATIONS_COLUMN_LATITUDE", "latitude"); //Media table columns define("_MEDIA_COLUMN_MEDIA_ID", "media_id"); define("_MEDIA_COLUMN_ASSET_ID", "asset_id"); define("_MEDIA_COLUMN_IMAGES", "images"); define("_MEDIA_COLUMN_VOICE_MEMO", "voice_memo"); //Asset types table columns define("_ASSET_TYPES_ASSET_TYPE_ID", "asset_type_id"); define("_ASSET_TYPES_TYPE_VALUE", "type_value"); //Attributes table columns define("_ATTRIBUTES_ATTRIBUTE_ID", "attribute_id"); define("_ATTRIBUTES_ATTRIBUTE_LABEL", "attribute_label"); //Attributes indexes columns define("_ATTRIBUTES_INDEXES_ATTRIBUTE_INDEX_ID", "attribute_index_id"); define("_ATTRIBUTES_INDEXES_ASSET_ID", "asset_id"); define("_ATTRIBUTES_INDEXES_ATTRIBUTE_ID", "attrubute_id"); define("_ATTRIBUTES_INDEXES_ATTRIBUTE_VALUE_ID", "attribute_value_id"); //Atributes values columns define("_ATTRIBUTES_VALUES_ATTRIBUTE_VALUE_ID", "attribute_value_id"); define("_ATTRIBUTES_VALUES_ATTRIBUTE_VALUE", "attribute_value"); define("_ATTRIBUTES_VALUES_ATTRIBUTE_ID", "attribute_id"); //Api Auth columns define("_API_AUTH_API_AUTH_ID","api_auth_id"); define("_API_AUTH_KEY","key"); define("_API_AUTH_PRACTICE","practice"); //post requests define("_API_AUTH_POST", "apiAuth"); define("_ASSETS_JSON_POST", "asset"); /* Skin */ if (!defined ('skin')) { define('skin', '../skin/default/'); } ?> <file_sep><?php include_once './db_functions.php'; include_once '../../config.php'; class GetAsset { public function processGetAsset($asset_id = null) { error_log("GET STARTED"); //Create Object for DB_Functions clas $db = new DB_Functions(); //Util arrays to create response JSON $a=array(); $b=array(); $parent = array(); $purgeAllAssets = 0; //purge all if ($purgeAllAssets) { $b["purgeAllAssets"] = $purgeAllAssets; array_push($a,$b); return $a; } if ($asset_id == null) { $assets = $db->getAllAssets(); } else { $assets = $db->getAssetById($asset_id); } while($row = mysql_fetch_assoc($assets)) { //$parent[$row['asset_id']]= array("asset_id"=>$row['asset_id'],"name"=>$row['name']); $parent = $row; $parent[_ASSETS_COLUMN_NEEDSSYNC] = 0; $parent[_ASSETS_COLUMN_ISNEW] = 0; $parent["purgeAllAssets"] = $purgeAllAssets; $result1 = $db->getLocationsByAssetId($row[_ASSETS_COLUMN_ASSET_ID]); while($row1 = mysql_fetch_array($result1)) { $parent["locations"][] = array(_LOCATIONS_COLUMN_LATITUDE=>$row1[_LOCATIONS_COLUMN_LATITUDE], _LOCATIONS_COLUMN_LONGITUDE=>$row1[_LOCATIONS_COLUMN_LONGITUDE]); } array_push($a, $parent); } error_log("GET ENDED"); return $a; } } ?> <file_sep><?php include '../config.php'; include 'db_functions.php'; if ( !empty($_GET['asset_id'])) { $asset_id = $_REQUEST['asset_id']; } if ( !isset($asset_id) ) { header("Location: index.php"); } else { $db = new DB_Functions(); $asset = $db->getAssetById($asset_id); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo skin;?>css/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo skin;?>css/styles.css" rel="stylesheet" > <script src="../js/jquery-1.11.2.min.js"> </script> <script src="../js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="span10 offset1"> <div class="row" style="margin-left:15px; margin-right: 15px;"> <div class="form-actions" style="float:right;padding-top: 10px;"> <a class="btn btn-default" href="home.php">Back</a> </div> <h3><?php echo $asset['name'];?> - ID:<?php echo $asset['asset_id'];?></h3> </div> <div class="col-lg-6"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Image</h3> </div> <div class="panel-body"> <img class="asset-image" src="data:image/png;base64,<?php echo $asset['images'];?>" /> </div> </div> </div> <div class="col-lg-6"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Information</h3> </div> <div class="panel-body"> <div class="control-group"> <label class="control-label">Description:</label> <?php echo $asset['description'];?> </div> <div class="control-group"> <label class="control-label">Location:</label> Lat:<?php echo $asset['latitude'];?> Long:<?php echo $asset['longitude'];?> </div> <div class="control-group"> <label class="control-label">Created by:</label> <?php echo $asset['username'];?> </div> <!--<div class="control-group"> <?php foreach ($asset as $row): ?> <br> <?php echo '<strong>' . $row['attribute_label'] .':</strong> '. $row['attribute_value'];?> <?php endforeach;?> </div>--> </div> </div> </div> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Map</h3> </div> <div class="panel-body"> <iframe frameborder="0" style="border:0; width:100%; height:300px" src="https://www.google.com/maps/embed/v1/search?key=<KEY>&q=<?php echo $asset['latitude'];?>,<?php echo $asset['longitude'];?>"> </iframe> </div> </div> </div> </div> </div> <!-- /container --> </body> </html> <file_sep>// // AssetTableViewCellView.swift // TAMS // // Created by arash on 8/25/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit public class AssetTableViewCellView : UITableViewCell { } <file_sep><?php require_once 'API.abstract.class.php'; require_once 'GetAsset.class.php'; require_once 'DeleteAsset.class.php'; require_once 'CreateAsset.class.php'; require_once 'UpdateAsset.class.php'; class API extends AbstractAPI { protected $User; public function __construct($request, $origin) { parent::__construct($request); // Abstracted out for example /*$APIKey = new Models\APIKey(); $User = new Models\User(); if (!array_key_exists('apiKey', $this->request)) { throw new Exception('No API Key provided'); } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) { throw new Exception('Invalid API Key'); } else if (array_key_exists('token', $this->request) && !$User->get('token', $this->request['token'])) { throw new Exception('Invalid User Token'); } $this->User = $User;*/ } /** * Get Assets Endpoint */ protected function asset() { if ($this->method == 'GET') { $asset = new GetAsset(); if ($this->verb == 'get') { if ($this->args[0] == null) return "Asset ID is required"; else return $asset->processGetAsset($this->args[0]); } elseif ($this->verb == 'list') { return $asset->processGetAsset(); } else { return "Unknown Operation"; } } elseif ($this->method == 'POST') { if ($this->verb == 'create') { $create = new CreateAsset(); parse_str($this->file, $post); //error_log($post['assets']); return $create->processCreate(json_decode($post['assets'])); } elseif ($this->verb == 'update') { $update = new UpdateAsset(); parse_str($this->file, $post); return $update->processUpdate(json_decode($post['assets'])); } else { return "Unknown Operation"; } } elseif ($this->method == 'PUT') { $delete = new DeleteAsset(); if ($this->verb == 'delete') { parse_str($this->file, $post); return $delete->processDeleteAsset(json_decode($post['assets'])); } else { return "Unknown Operation"; } } else { return "Only accepts GET/POST/PUT requests"; } } } <file_sep>// // AssetAttribute.swift // TAMS // // Created by arash on 8/30/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import CoreData class AssetAttributeEntity: NSManagedObject { @NSManaged var attributeData: String @NSManaged var attributeName: String @NSManaged var asset: AssetEntity } <file_sep>// // Asset.swift // TAMS // // Created by arash on 8/31/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit class Asset : NSObject{ var image: NSData = UIImageJPEGRepresentation(UIImage(named: "Camera.png")!,2) ?? NSData() var audio: NSData = NSData() var date: NSDate = NSDate() var latitude: Double = 0.0 var longitude: Double = 0.0 var title: String = "" var attributes: [AssetAttribute] = [] }<file_sep># Backend Server --- ## Prerequisites - Docker - **Linux**: https://docs.docker.com/engine/installation/ - **OSX**: docker on OSX is more difficult than in linux. Dont use the recommended method for installation, its flawed. OSX tries to make you use a VM for all of this kind of stuff. Do the following for OSX: - Install Homebrew - `brew install docker` - `brew install dlite` - `sudo dlite install` - `dlite start` - Use docker normally... - Docker-compose - **Linux**: `sudo apt-get install docker-compose` - **OSX**: It should come pre-installed when you `brew install docker` ## Why Docker? Docker is pretty great. As an example, lets discuss PHP. To install and run PHP locally, you need to install Apachi, PHP, and Mysql then configure them all manually so that they work together. If you change machines, rinse and repeat. Docker allows developers to configure the server once, then deploy it on many machines. It utilizes virtual containers to house the applications. Because of this, once the container is running, you can ssh into it, ping it, etc. The server configuration settings carry over to each machine. After the initial setup, to deploy and run on another server requires 1 line of code, assuming Docker is already installed. ## Installation Navigate to this folder and type: ``` MYSQLPASS=somepass docker-compose up -d ``` Replace `<PASSWORD>pass` with the password you would like to use for the mysql instance Then give it a minute for the server to come up, then navigate to: http://ip-address/app/install.php ### View It Use `docker ps` to find the ip address of the web server. Note that 0.0.0.0 and 127.0.0.1 is localhost. ## Rebuild With New Code There is another way... I can setup a volume so that rebuilding is not necessary. I will look into this.. later. **If you used the automatic install method:** ``` docker-compose build && MYSQLPASS=somepass docker-compose up -d ``` Replace `<PASSWORD>pass` with the password you would like to use for the mysql instance ## Stop & Remove the container **!!!IMPORTANT!!!** Because the mysql server utilizes a volume so that things can be stopped, started, updated, etc, it is imperitive that you do NOT use `docker-compose kill` OR `docker kill`. This WILL cause **corruption** on the database. **If you used the automatic install method:** ```bash docker-compose down ``` ## Other Docker Commands ``` docker ps # view containers docker images # view images docker rmi image-label # remove image docker rm container-label # remove container docker inspect container-label # container properties ```<file_sep>// // AnnotationView.swift // TAMS // // Created by arash on 8/24/15. // Copyright (c) 2015 arash. All rights reserved. // import MapKit import UIKit class AnnotationView: NSObject, MKAnnotation { let title: String? let subTitle: String let coordinate: CLLocationCoordinate2D let imagedata : NSData var asset = Asset() init(asset : Asset) { self.title = asset.title self.subTitle = "\(asset.latitude),\(asset.longitude)" self.coordinate = CLLocationCoordinate2D(latitude: asset.latitude, longitude: asset.longitude) self.imagedata = asset.image self.asset = asset super.init() } }<file_sep><?php include "../config.php"; include "db_functions.php"; session_start(); if(empty($_SESSION['login_user'])) { header('Location: index.php'); } ?> <script src="../js/jquery-1.11.2.min.js"></script> <script src="../js/tablefilter/tablefilter.js"></script> <script type="text/javascript"> $(function() { populateAssets(); }); function loadingImg () { $('#assets_table table > tbody:first').html("<img style='width:30px;' src='../skin/default/img/loading.gif'/>"); } //pull the table body function populateAssets() { $('#top-bar-deleted').hide(); $('#top-bar').show(); $('#active-assets').addClass('active'); $('#deleted-assets').removeClass('active'); $.ajax({ type: "GET", // HTTP method POST or GET url: "assets_table.php", //Where to make Ajax calls //dataType:"text", // Data type, HTML, json etc. dataType: 'html', /*data: { name: $('#name').val(), address: $('#address').val(), city: $('#city').val() },*/ success: function(data) { $('#assets_table table > tbody:first').html(data); //alert(data); }, error: function(xhr, ajaxOptions, thrownError) { //On error, we alert user //alert(thrownError); }, complete: function() { d = new Date(); $('#last_refreshed').html("Last Refreshed:<br>" + d.toLocaleString()); $("#mobile-assets-table").html(""); $("#mobile-assets-table").html($(".list-group-item")); reloadTableFilter(); } }); } //pull the table body function populateDeletedAssets() { $('#top-bar').hide(); $('#top-bar-deleted').show(); $('#active-assets').removeClass('active'); $('#deleted-assets').addClass('active'); $.ajax({ type: "GET", // HTTP method POST or GET url: "deleted_assets_table.php", //Where to make Ajax calls //dataType:"text", // Data type, HTML, json etc. dataType: 'html', /*data: { name: $('#name').val(), address: $('#address').val(), city: $('#city').val() },*/ success: function(data) { $('#assets_table table > tbody:first').html(data); //alert(data); }, error: function(xhr, ajaxOptions, thrownError) { //On error, we alert user //alert(thrownError); }, complete: function() { d = new Date(); $('#last_refreshed').html("Last Refreshed:<br>" + d.toLocaleString()); $("#mobile-assets-table").html(""); $("#mobile-assets-table").html($(".list-group-item")); reloadTableFilter(); } }); } var interval; // refresh the table every x seconds function timedRefresh(timeoutPeriod) { clearInterval(interval); interval=0; if (timeoutPeriod != 0) { interval = setInterval(populateAssets, timeoutPeriod); } } function refreshOnChange(thisObj) { timedRefresh(thisObj.val()); } var tf = null; var filtersConfig = null; function reloadTableFilter() { if (tf != null) { tf.destroy(); tf = null; filtersConfig = null; } //Table Filter filtersConfig = { base_path: '/js/tablefilter/', paging: true, results_per_page: ['Records: ', [10,25,50,100]], remember_page_number: true, remember_page_length: true, alternate_rows: true, highlight_keywords: true, auto_filter: true, auto_filter_delay: 500, //milliseconds filters_row_index: 1, remember_grid_values: true, alternate_rows: true, rows_counter: true, rows_counter_text: "Rows: ", btn_reset: true, status_bar: true, msg_filter: 'Filtering...', col_9: 'none', col_10: 'none', col_11: 'none', }; tf = new TableFilter('assets-table', filtersConfig); tf.init(); } </script> <?php include_once 'header.php'; ?> <div class="container" id="assets_table"> <div class="row"> <div id="top-bar"> <div id="left" class="column"> <a href="create.php" class="btn btn-large btn-primary"><i class="glyphicon glyphicon-plus"></i> &nbsp; Add Asset</a> </div> <div id="center" class="column"> <span id="last_refreshed"></span> </div> <!--<div id="right" class="column"> <select id="refresh_rate" class="form-control" onchange="refreshOnChange($(this));"> <option value="0">No Refresh</option> <option value="1000">Every 1 sec</option> <option value="5000">Every 5 sec</option> <option value="10000">Every 10 sec</option> <option value="30000">Every 30 sec</option> </select> </div>--> </div> <div id="top-bar-deleted"> <div class="column deleted-assets-bar" >DELETED ASSETS</div> </div> </div> <div class="row"> <span id="mobile-assets-table"></span> <table class="table table-striped table-bordered" id="assets-table"> <thead> <tr> <th>Image</th> <th>AssetId</th> <th>Name</th> <th>Description</th> <th>Type</th> <th>Latitude</th> <th>Longitude</th> <th>Created By</th> <th>Update At</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td colspan="12">LOADING DATA...</td> </tr> </tbody> </table> </div> </div> <!-- /container --> <script type="text/javascript"> </script> <?php include_once 'footer.php'; ?> <file_sep><?php include 'db_connect.php'; $pdo = DB_Connect::connect(); $count = 0; session_start(); if (isset($_POST['username']) && isset($_POST['password'])) { // username and password sent from Form $username = $_POST['username']; //$password=md5($_POST['password']); $password = $_POST['password']; $sql = "SELECT user_id, password FROM users WHERE username='$username'"; foreach ($pdo->query($sql) as $row) { if (!password_verify($password, $row['password'])) exit(); $count++; // If result matched $myusername and $mypassword, table row must be 1 row if ($count == 1) { $_SESSION['login_user'] = $row['user_id']; echo $row['user_id']; } } } ?><file_sep><?php include "../config.php"; include "db_functions.php"; session_start(); if(empty($_SESSION['login_user'])) { header('Location: index.php'); } ?> <?php $temp_assets = array(); $db = new DB_Functions(); $assets = $db->getDeletedAssets(); ?> <?php foreach ($assets as $asset):?> <?php //check for unique results if (!in_array($asset['asset_id'], $temp_assets)) { $temp_assets[] = $asset['asset_id']; } ?> <a href="read.php?asset_id=<?php print($asset['asset_id'])?>" class="list-group-item"> <?php if ($asset['images']): ?> <img class="asset-image-table asset-image-table-mobile" src="data:image/png;base64,<?php print($asset['images']) ?>"/> <?php endif; ?> <div class="asset-mobile-description"> <h4 class="list-group-item-heading"> <?php print($asset['name']); ?> </h4> <p class="list-group-item-text"> <?php print($asset['description'])?> </p> </div> </a> <tr> <td> <?php if ($asset['images']): ?> <img class="asset-image-table" src="data:image/png;base64,<?php print($asset['images'])?>"/> <?php endif; ?> </td> <td><?php print($asset['asset_id'])?></td> <td><?php print($asset['name'])?></td> <td><?php print($asset['description'])?></td> <td><?php print($asset['type_value'])?></td> <td><?php print($asset['latitude'])?></td> <td><?php print($asset['longitude'])?></td> <td><?php print($asset['created_by'])?></td> <td><?php print(date('Y-m-d h:i:s',$asset['updated_at']))?></td> <td align="center"> <a href="read.php?asset_id=<?php print($asset['asset_id'])?>"><i class="glyphicon glyphicon-eye-open"></i></a> </td> <td align="center"> <a href="undelete.php?asset_id=<?php print($asset['asset_id'])?>"><i class="glyphicon glyphicon-ok-circle"></i></a> </td> <td align="center"> <a href="purge.php?asset_id=<?php print($asset['asset_id'])?>"><i class="glyphicon glyphicon-ban-circle"></i></a> </td> </tr> <?php endforeach ?><file_sep><script> $(function() { validateFields(); }); function checkPass() { //Store the password field objects into variables ... var pass1 = document.getElementById('password'); var pass2 = document.getElementById('confirm-password'); //Store the Confimation Message Object ... var message = document.getElementById('confirmMessage'); //Set the colors we will be using ... var goodColor = "#66cc66"; var badColor = "#ff6666"; //Compare the values in the password field //and the confirmation field if(pass1.value == pass2.value){ //The passwords match. //Set the color to the good color and inform //the user that they have entered the correct password pass2.style.backgroundColor = goodColor; message.style.color = goodColor; message.innerHTML = "Passwords Match!" }else{ //The passwords do not match. //Set the color to the bad color and //notify the user. pass2.style.backgroundColor = badColor; message.style.color = badColor; message.innerHTML = "Passwords Do Not Match!" } } function validateFields() { document.getElementById("create-btn").disabled = true; var password = document.getElementById('password').value; var confirmPasswod = document.getElementById('confirm-password').value; var firstname = document.getElementById('firstname').value; var username = document.getElementById('username').value; if (password != "" && firstname != "" && username != "" && password == <PASSWORD>) { document.getElementById("create-btn").disabled = false; } } </script> <script type="text/javascript"> jQuery(document).ready(function($) { $('.search-input').keyup(function(){ makeAjaxRequest(); }); function makeAjaxRequest() { $.ajax({ url: 'search.php', type: 'get', data: {search: $('input#search').val()}, success: function(response) { //if(screen.width > 767) $('table#assets-table tbody').html(response); //else $('#mobile-assets-table').html(response); } }); } }); </script> </body> </html><file_sep><?php class DB_Functions { private static $pdo = null; // constructor function __construct() { require_once 'db_connect.php'; require_once '../config.php'; // connecting to database self::$pdo = DB_Connect::connect(); self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // destructor function __destruct() { DB_Connect::disconnect(); } /** * Storing new asset */ public function addAsset($name='',$description='',$latitude='',$longitude='',$images='') { //ASSET $assetSql = "INSERT INTO assets (asset_id,name,description,created_at,updated_at) values(?, ?, ?, ?, ?)"; $assetQuery = self::$pdo->prepare($assetSql); $assetQuery->execute(array(time(),$name,$description,time(),time())); //LOCATION /* get last inserted auto_increment id */ $asset_id = self::$pdo->lastInsertId(); $locationSql = "INSERT INTO locations (asset_id, latitude, longitude) values(?, ?, ?)"; $locationQuery = self::$pdo->prepare($locationSql); $locationQuery->execute(array($asset_id, $latitude, $longitude)); //MEDIA $mediaSql = "INSERT INTO media (asset_id, images, voice_memo) values(?, ?, ?)"; $mediaQuery = self::$pdo->prepare($mediaSql); $mediaQuery->execute(array($asset_id, $images, $voice_memo)); } /** * Mark asset as deleted * */ public function deleteAsset($asset_id) { // delete data $sql = "UPDATE assets SET deleted = 1, updated_at = ".time()." WHERE asset_id = ?"; $q = self::$pdo->prepare($sql); $q->execute(array($asset_id)); } /** * Undelete asset * */ public function undeleteAsset($asset_id) { // delete data $sql = "UPDATE assets SET deleted = 0, updated_at = ".time()." WHERE asset_id = ?"; $q = self::$pdo->prepare($sql); $q->execute(array($asset_id)); } /** * Purge User */ public function purgeAsset($asset_id) { $sql = "DELETE FROM assets WHERE asset_id = ?"; $q = self::$pdo->prepare($sql); $q->execute(array($asset_id)); } /** * Update Asset */ public function updateAsset($asset_id,$name, $description) { $sql = "UPDATE assets set name = ?, description = ?, updated_at = ? WHERE asset_id = ?"; $q = self::$pdo->prepare($sql); $q->execute(array($name,$description,time(),$asset_id)); } /** * Getting all active assets */ public function getActiveAssets() { $sql = 'SELECT assets.*, locations.longitude, locations.latitude, asset_types.type_value, media.images FROM assets LEFT JOIN asset_types ON assets.type_id = asset_types.asset_type_id LEFT JOIN media ON assets.asset_id = media.asset_id LEFT JOIN locations ON assets.asset_id = locations.asset_id WHERE deleted = 0 ORDER BY assets.asset_id DESC'; return self::$pdo->query($sql); } /** * Getting all active assets */ public function getDeletedAssets() { $sql = 'SELECT assets.*, locations.longitude, locations.latitude, asset_types.type_value, media.images FROM assets LEFT JOIN asset_types ON assets.type_id = asset_types.asset_type_id LEFT JOIN media ON assets.asset_id = media.asset_id LEFT JOIN locations ON assets.asset_id = locations.asset_id WHERE deleted = 1 ORDER BY assets.asset_id DESC'; return self::$pdo->query($sql); } /** * Getting asset by id */ public function getAssetById($asset_id) { $sql = 'SELECT assets.*, attributes.attribute_label, attributes_values.attribute_value, locations.longitude, locations.latitude, asset_types.type_value, media.images, media.voice_memo FROM assets LEFT JOIN asset_types ON assets.type_id = asset_types.asset_type_id LEFT JOIN attributes_indexes ON assets.asset_id = attributes_indexes.asset_id LEFT JOIN attributes ON attributes_indexes.attribute_id = attributes.attribute_id LEFT JOIN attributes_values ON attributes_indexes.attribute_value_id = attributes_values.attribute_value_id LEFT JOIN media ON assets.asset_id = media.asset_id LEFT JOIN locations ON assets.asset_id = locations.asset_id WHERE (assets.asset_id = ?)'; $q = self::$pdo->prepare($sql); $q->execute(array($asset_id)); return $q->fetch(PDO::FETCH_ASSOC); } /** * Delete User */ public function deleteUser($user_id) { $sql = "DELETE FROM users WHERE user_id = ?"; $q = self::$pdo->prepare($sql); $q->execute(array($user_id)); } /** * Get All Users */ public function getAllUsers() { $sql = 'SELECT * FROM users ORDER BY user_id DESC'; return self::$pdo->query($sql); } // Start Paging public function paging($query,$records_per_page) { $starting_position=0; if(isset($_GET["page_no"])) { $starting_position=($_GET["page_no"]-1)*$records_per_page; } $sql=$query." limit $starting_position,$records_per_page"; return $sql; } public function paginglink($query,$records_per_page) { $self = $_SERVER['PHP_SELF']; $stmt = $this->db->prepare($query); $stmt->execute(); $total_no_of_records = $stmt->rowCount(); if($total_no_of_records > 0) { ?><ul class="pagination"><?php $total_no_of_pages=ceil($total_no_of_records/$records_per_page); $current_page=1; if(isset($_GET["page_no"])) { $current_page=$_GET["page_no"]; } if($current_page!=1) { $previous =$current_page-1; echo "<li><a href='".$self."?page_no=1'>First</a></li>"; echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>"; } for($i=1;$i<=$total_no_of_pages;$i++) { if($i==$current_page) { echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>"; } else { echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>"; } } if($current_page!=$total_no_of_pages) { $next=$current_page+1; echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>"; echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>"; } ?></ul><?php } } // End Paging } ?><file_sep>// // AssetAttributeAddCellView.swift // TAMS // // Created by arash on 9/6/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit class AssetAttributeAddCellView: UITableViewCell { @IBOutlet weak var attributeName: UITextField! @IBOutlet weak var attributeValue: UITextField! @IBOutlet weak var attributeAddButton: UIButton! } <file_sep>// // TableViewControllerNodesTableViewController.swift // TAMS // // Created by arash on 8/17/15. // Copyright (c) 2015 arash. All rights reserved. // import UIKit import MapKit class TableViewController: UITableViewController { @IBOutlet var assetTableView: UITableView! let allassets: [Asset] = Assets.sharedInstance.retriveAllAsets() var regin : MKCoordinateRegion = MKCoordinateRegion() var allassetsAtRegion : [Asset] { get { return Assets.sharedInstance.retriveAllAsets() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidLoad() { tableView.delegate = self tableView.dataSource = self self.clearsSelectionOnViewWillAppear = true self.navigationItem.rightBarButtonItem = self.editButtonItem() super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allassets.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TheCell", forIndexPath: indexPath) as UITableViewCell // let row = indexPath.row if let c = (cell as? TableViewCellView) { let ass = allassets[indexPath.row] c.cellViewImage?.image = UIImage( data: allassets[indexPath.row].image) c.cellViewTitle?.text = allassets[indexPath.row].title c.cellViewSubtitle?.text = "\(ass.latitude),\(ass.longitude),\(ass.date)" c.asset = allassets[indexPath.row] } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let c = (tableView.cellForRowAtIndexPath(indexPath) as? TableViewCellView){ print(c.cellViewSubtitle.text!) performSegueWithIdentifier("TableViewToAssetView", sender: c) tableView.deselectRowAtIndexPath(indexPath, animated: true) } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "TableViewToAssetView"{ let assetVC = segue.destinationViewController as! AssetViewController let thecell = sender as! TableViewCellView assetVC.asset = thecell.asset } } } <file_sep>#!/usr/bin/env bash echo " " echo "Pulling Latest Changes" ssh $DEPLOY_USER@$DEPLOY_HOST "cd ~/Class/csc190/main; git reset --hard HEAD; git pull --rebase origin master" echo " " echo "Docker-compose pulling" ssh $DEPLOY_USER@$DEPLOY_HOST "cd ~/Class/csc190/main/source/backend; docker-compose pull" echo " " echo "Docker-compose running" ssh $DEPLOY_USER@$DEPLOY_HOST "cd ~/Class/csc190/main/source/backend; docker-compose build; MYSQLPASS=$DEPLOY_MYSQL_PASS docker-compose up -d"<file_sep><?php // namespace libs\mysql; require_once '../config.php'; $pdo = null; $dbname = "tams"; $sqlschema = "../db/schema.sql"; $password = $_POST['pw']; // One connection through whole application try { $pdo = new PDO( "mysql:host=".DB_HOST, DB_USER, DB_PASSWORD); } catch(PDOException $e) { die($e->getMessage()); } //----------------------------------------------------------- //---- CHECK INSTALLATION ----------------------------------- //----------------------------------------------------------- $stmt = $pdo->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '".$dbname."'"); $exists = (bool) $stmt->fetchColumn(); if($exists) { echo "<div style=\"text-align:center\"><br><br><br>Database Already Exists. <br>Setup Not Requried.<br><br></div>"; exit(1); } if( !isset($_POST['pw'])) { echo "<div style=\"text-align:center\"><br><br><br>Please Enter An Admin Password:<br><form action=\"./install.php\" method=\"POST\"><input type='text' name='pw'><input type='submit' value='Create!'></form><br></div>"; exit(0); } echo "<div style=\"text-align:center;\"><br><br><br>Installing....!<br><br></div>"; //----------------------------------------------------------- //---- CREATE DATABSASE ------------------------------------- //----------------------------------------------------------- $pdo->exec("CREATE DATABASE `$dbname`;") or die(print_r($dbo->errorInfo(), true)); //----------------------------------------------------------- //---- INSTALL SCHEMA --------------------------------------- //----------------------------------------------------------- $keywords = array( 'ALTER', 'CREATE', 'DELETE', 'DROP', 'INSERT', 'REPLACE', 'SELECT', 'SET', 'TRUNCATE', 'UPDATE', 'USE', 'DELIMITER', 'END' ); # read file into array $file = file($sqlschema); # import file line by line # and filter (remove) those lines, beginning with an sql comment token $file = array_filter($file, create_function('$line', 'return strpos(ltrim($line), "--") !== 0;')); # and filter (remove) those lines, beginning with an sql notes token $file = array_filter($file, create_function('$line', 'return strpos(ltrim($line), "/*") !== 0;')); $sql = ""; $del_num = false; foreach($file as $line){ $query = trim($line); try { $delimiter = is_int(strpos($query, "DELIMITER")); if($delimiter || $del_num){ if($delimiter && !$del_num ){ $sql = ""; $sql = $query."; "; echo "OK"; echo "<br/>"; echo "---"; echo "<br/>"; $del_num = true; }else if($delimiter && $del_num){ $sql .= $query." "; $del_num = false; echo $sql; echo "<br/>"; echo "do---do"; echo "<br/>"; $pdo->exec($sql); $sql = ""; }else{ $sql .= $query."; "; } }else{ $delimiter = is_int(strpos($query, ";")); if($delimiter){ $pdo->exec("$sql $query"); echo "$sql $query"; echo "<br/>"; echo "---"; echo "<br/>"; $sql = ""; }else{ $sql .= " $query"; } } } catch (\Exception $e){ echo $e->getMessage() . "<br /> <p>The sql is: $query</p>"; } } //----------------------------------------------------------- //---- INSERT USER ------------------------------------------ //----------------------------------------------------------- //Insert User $firstname = "admin"; $lastname = "admin"; $username = "admin"; $email = "<EMAIL>"; $role = 0; //admin $password = password_hash($password, PASSWORD_DEFAULT); $assetSql = "INSERT INTO users (firstname,username, lastname, email, role, password) values(?, ?, ?, ?, ?, ?)"; $assetQuery = $pdo->prepare($assetSql); $assetQuery->execute(array($firstname,$username, $lastname, $email, $role, $password)); echo "<div style=\"text-align:center;\"><br><br><br>Install Completed Successfully!<br><br> Exiting...</div>"; exit(0); ?><file_sep>// // AssetAttribute.swift // TAMS // // Created by arash on 8/31/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation class AssetAttribute : NSObject{ var attributeData: String = "" var attributeName: String = "" }<file_sep>// // TableViewCellView.swift // TAMS // // Created by arash on 8/26/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit public class TableViewCellView : UITableViewCell { @IBOutlet weak var cellViewImage: UIImageView! @IBOutlet weak var cellViewTitle: UILabel! @IBOutlet weak var cellViewSubtitle: UILabel! @IBOutlet weak var cellViewDescription: UILabel! var asset = Asset() } <file_sep>// // Nodes.swift // TAMS // // Created by arash on 8/18/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit import MapKit import CoreData class Assets { static let sharedInstance = Assets() var assets = [Asset]() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext func addAsset(asset : Asset) { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let entityDescription = NSEntityDescription.entityForName("AssetsTable",inManagedObjectContext:managedObjectContext!) let ass = AssetEntity(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) ass.image = asset.image ass.audio = asset.audio ass.latitude = asset.latitude ass.longitude = asset.longitude ass.title = asset.title ass.date = asset.date ass.attributes.setByAddingObjectsFromArray(asset.attributes as [AnyObject]) } func addAsset(latitude : Double, longitude: Double, title: String) { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let entityDescription = NSEntityDescription.entityForName("AssetsTable",inManagedObjectContext:managedObjectContext!) let ass = AssetEntity(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) //ass.image = NSData() //ass.audio = NSData() ass.latitude = latitude ass.longitude = longitude ass.title = title ass.date = NSDate() //ass.attributes = nil } // func editAsset(location:CLLocation, title: String?=nil,subtitle:String?=nil, Attributes : [AssetAttribute]? = nil ) { // //assets[location.description] = Asset(location: location, title: title!, subtitle: subtitle!,Attributes : Attributes!) // } // func removeAsset(location:CLLocation, title: String?=nil,subtitle:String?=nil) { // //assets.removeValueForKey(location.description) // } func retriveAllAsets() -> [Asset] { var asset = [Asset]() let entityDescription = NSEntityDescription.entityForName("AssetsTable", inManagedObjectContext: managedObjectContext!) let request = NSFetchRequest() request.entity = entityDescription let pred = NSPredicate(value: true) request.predicate = pred var error: NSError? var objects = try? managedObjectContext?.executeFetchRequest(request) as? [AssetEntity] ?? [] for obj in objects ?? [] { let ass : Asset = Asset() ass.image = obj.image ass.audio = obj.audio ass.title = obj.title ass.latitude = obj.latitude.doubleValue ass.longitude = obj.longitude.doubleValue ass.date = obj.date for objatt in obj.attributes { let assatt = AssetAttribute() assatt.attributeName = (objatt as! AssetAttributeEntity).attributeName assatt.attributeData = (objatt as! AssetAttributeEntity).attributeData ass.attributes.append(assatt) } asset.append(ass) } return asset } // func retriveAssetsAtRegin(regin : MKCoordinateRegion )->[Asset]{ // // let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext // let entityDescription = NSEntityDescription.entityForName("Assets",inManagedObjectContext: managedObjectContext!) // let asset = Asset(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) // let request = NSFetchRequest() // request.entity = entityDescription // let pred = NSPredicate(format: "(title = %@)", "<NAME>") // request.predicate = pred // // var error: NSError? // var results = managedObjectContext?.executeFetchRequest(request, error: &error) // // let radious = sqrt( pow(regin.span.latitudeDelta,2) + pow(regin.span.longitudeDelta ,2 )) // let center = CLLocation(latitude: regin.center.latitude, longitude: regin.center.longitude) // var assetsInRegin = [Asset]() // //for ass in retriveAllAsets() { // //if ass.location.distanceFromLocation(center) < radious {assetsInRegin.append(ass) } // //} // return assetsInRegin // } func count() -> Int{ return assets.count } }<file_sep>// // ViewController.swift // TAMS // // Created by arash on 8/16/15. // Copyright (c) 2015 arash. All rights reserved. // import UIKit import MapKit import CoreData import ImageIO import AVFoundation class MapViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate,UIGestureRecognizerDelegate { @IBOutlet weak var MapView: MKMapView! let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let centerLocation = CLLocationCoordinate2D( latitude : 38.560884, longitude : -121.422357 ) let radious = 0.1 var locations : [CLLocationCoordinate2D]=[] var annotations:[AnnotationView] = [] let clusteringManager = FBClusteringManager() var imagearray = [UIImage]() // random generator override func viewDidLoad() { MapView.delegate = self removeAnnotations() makeAnnotationsFromAssets() // gesture and bottons setup var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:") uilpgr.minimumPressDuration = 1.0 MapView.addGestureRecognizer(uilpgr) uilpgr.delegate = self var rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "LIST", style: UIBarButtonItemStyle.Plain, target: self, action: "listTapped:") var rightSearchBarButtonItem:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchTapped:") self.navigationItem.setRightBarButtonItems([rightAddBarButtonItem,rightSearchBarButtonItem], animated: true) //add annotations to map MapView.addAnnotations(annotations) MapView.showAnnotations(annotations, animated: true) let span = MKCoordinateSpanMake(radious, radious) let region = MKCoordinateRegion(center: centerLocation, span: span) MapView.setRegion(region, animated: true) // add annotation cluster control clusteringManager.addAnnotations(annotations) //POLY LINE var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.001, longitude: -121.422357 + 0.001)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.002, longitude: -121.422357 + 0.001)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.001, longitude: -121.422357 + 0.002)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.003, longitude: -121.422357 + 0.003)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.005, longitude: -121.422357 + 0.003)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.003, longitude: -121.422357 + 0.006)) points.append(CLLocationCoordinate2D(latitude: 38.560884 - 0.003, longitude: -121.422357 - 0.003)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.001, longitude: -121.422357 + 0.001)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.002, longitude: -121.422357 + 0.001)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.001, longitude: -121.422357 + 0.002)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.003, longitude: -121.422357 + 0.003)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.005, longitude: -121.422357 + 0.003)) points.append(CLLocationCoordinate2D(latitude: 38.560884 + 0.003, longitude: -121.422357 + 0.006)) var polyline = MKPolyline(coordinates: &points, count: points.count) MapView.addOverlay(polyline) MapView.mapType = MKMapType.Standard MapView.pitchEnabled = true MapView.camera.centerCoordinate = centerLocation MapView.camera.pitch = 45; MapView.camera.altitude = 5000; MapView.camera.heading = 45; // // let userCoordinate = CLLocationCoordinate2D(latitude: 58.592725, longitude: 16.185962) // let eyeCoordinate = CLLocationCoordinate2D(latitude: 58.571647, longitude: 16.234660) // let mapCamera = MKMapCamera(lookingAtCenterCoordinate: userCoordinate, fromEyeCoordinate: eyeCoordinate, eyeAltitude: 400.0) // MapView.setCamera(mapCamera, animated: true) // super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func mapType(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { MapView.mapType = MKMapType.Standard MapView.removeAnnotations(annotations) MapView.addAnnotations(annotations) } else { MapView.mapType = MKMapType.Hybrid MapView.removeAnnotations(annotations) MapView.addAnnotations(annotations) } } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { var reuseId = "" if annotation.isKindOfClass(FBAnnotationCluster) { reuseId = "Cluster" var clusterView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) clusterView = FBAnnotationClusterView(annotation: annotation, reuseIdentifier: reuseId) return clusterView } else { let annotation = annotation as? AnnotationView var view: MKPinAnnotationView let identifier = "pin" view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) let theimage = UIImage(data:annotation!.imagedata) let size = CGSizeApplyAffineTransform(theimage!.size, CGAffineTransformMakeScale(0.5, 0.5)) let hasAlpha = false let scale: CGFloat = 0.0 // Automatically use scale factor of main screen UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale) theimage!.drawInRect(CGRect(origin: CGPointZero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() view.image = scaledImage view.canShowCallout = true view.calloutOffset = CGPoint(x: 0, y: 0) view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) return view } } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { let v = view.annotation as! AnnotationView performSegueWithIdentifier("MapToAssetView", sender: v) } func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) { NSOperationQueue().addOperationWithBlock({ let mapBoundsWidth = Double(self.MapView.bounds.size.width) let mapRectWidth:Double = self.MapView.visibleMapRect.size.width let scale:Double = mapBoundsWidth / mapRectWidth let annotationArray = self.clusteringManager.clusteredAnnotationsWithinMapRect(self.MapView.visibleMapRect, withZoomScale:scale) self.clusteringManager.displayAnnotations(annotationArray, onMapView:self.MapView) }) } func mapView(mapView: MKMapView!, regionWillChangeAnimated animated: Bool) { } //MARK:- MapViewDelegate methods func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if overlay is MKPolyline { var polylineRenderer = MKPolylineRenderer(overlay: overlay) polylineRenderer.strokeColor = UIColor.blueColor() polylineRenderer.lineWidth = 5 return polylineRenderer } return nil } func action(gestureRecognizer:UIGestureRecognizer) { print("long press detected ") var touchPoint = gestureRecognizer.locationInView(self.MapView) var newCoordinate:CLLocationCoordinate2D = MapView.convertPoint(touchPoint, toCoordinateFromView: self.MapView) let ass = Asset() ass.title = "New Asset" ass.latitude = newCoordinate.latitude ass.longitude = newCoordinate.longitude let ann = AnnotationView(asset: ass) MapView.addAnnotation(ann) MapView.showAnnotations([ann], animated: true) Assets.sharedInstance.addAsset(newCoordinate.latitude, longitude: newCoordinate.longitude, title: "NEW ASSET") performSegueWithIdentifier("MapToAssetView", sender: ann) } func searchTapped(sender:UIButton) { print("search pressed") for i in 0...10{ print("adding asset:\(i)") addRandomAsset("Asset \(i)") } clusteringManager.addAnnotations(annotations) MapView.addAnnotations(annotations) MapView.showAnnotations(annotations, animated: true) } func listTapped (sender:UIButton) { print("list pressed") performSegueWithIdentifier("TableView", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "MapToAssetView"{ let assetVC = segue.destinationViewController as! AssetViewController assetVC.asset = (sender as! AnnotationView).asset } else if segue.identifier == "TableView"{ let TableVC = segue.destinationViewController as! TableViewController } } func makeRand(latlong: String) -> Double{ //Latitude: -85 to +85 (actually -85.05115 for some reason) //Longitude: -180 to +180 var r : Double = 0 if (latlong == "latitude") { let lower : UInt32 = 0 let upper : UInt32 = 85*2 r = (Double(upper)/2) - Double(arc4random_uniform(upper)) } else if (latlong == "longitude"){ let lower : UInt32 = 0 let upper : UInt32 = 180*2 r = (Double(upper)/2) - Double(arc4random_uniform(upper)) } let randomfloat = CGFloat( (Float(arc4random()) / Float(UINT32_MAX)) ) r = r + Double(randomfloat) r=r/1000 print(r) return r } func removeAnnotations(){ MapView.removeAnnotations(annotations) annotations.removeAll(keepCapacity: false) } func makeAnnotationsFromAssets(){ let assets = Assets.sharedInstance.retriveAllAsets() for ass in assets { let ann = AnnotationView(asset: ass) annotations.append(ann) } } func addRandomAsset(title:String){ if imagearray.count == 0{ makeImageArray()} let entityDescription = NSEntityDescription.entityForName("AssetsTable",inManagedObjectContext: managedObjectContext!) let ass = AssetEntity(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) ass.latitude = 38.560884 + makeRand("latitude") ass.longitude = -121.422357 + makeRand("longitude") ass.title = title ass.date = NSDate() var rand = Int(arc4random_uniform(UInt32(imagearray.count))) ass.image = UIImagePNGRepresentation(imagearray[rand]) ?? NSData() var audiourl = NSURL(string: "http://www.noiseaddicts.com/samples_1w72b820/280.mp3" )! ass.audio = NSData(contentsOfURL: audiourl)! for i in 0...10{ var att = NSEntityDescription.insertNewObjectForEntityForName("Attributes", inManagedObjectContext: self.managedObjectContext!) as! AssetAttributeEntity att.attributeName = "att \(i)" att.attributeData = "data \(i)" att.asset = ass } try? managedObjectContext?.save() let asset : Asset = Asset() asset.latitude = ass.latitude.doubleValue asset.longitude = ass.longitude.doubleValue asset.image = ass.image asset.audio = ass.audio asset.title = ass.title let ann = AnnotationView(asset: asset) annotations.append(ann) } func makeImageArray(){ for x in 1...80{ let urlstring = String(stringLiteral:"http://www.streetsignpictures.com/images/225_traffic\(x).jpg") let imageurl = NSURL(string: urlstring)! if let imagedata = NSData(contentsOfURL: imageurl) { let d : [NSObject:AnyObject] = [ kCGImageSourceCreateThumbnailFromImageIfAbsent: true, //kCGImageSourceShouldAllowFloat : true, kCGImageSourceCreateThumbnailWithTransform: true, //kCGImageSourceCreateThumbnailFromImageAlways: false, kCGImageSourceThumbnailMaxPixelSize: 100 ] let cgimagesource = CGImageSourceCreateWithData(imagedata, d) let imref = CGImageSourceCreateThumbnailAtIndex(cgimagesource!, 0, d) let im = UIImage(CGImage:imref!, scale:0.2, orientation:.Up) //let image = UIImage(data:imagedata)! //CGImageSourceCreateThumbnailAtIndex(image.CGImage, , ) //imagearray.append(image) //} imagearray.append(im) } } } } <file_sep>package com.imihov.tamssql; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; import com.imihov.tamssql.Variables; public class MainActivity extends ActionBarActivity { // DB Class to perform DB related operations DBController controller = new DBController(this); // Progress Dialog Object ProgressDialog prgDialog; HashMap<String, String> queryValues; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get User records from SQLite DB ArrayList<HashMap<String, String>> userList = controller.getAllUsers(); // If users exists in SQLite DB /*if (userList.size() != 0) { // Set the User Array list in ListView ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.view_user_entry, new String[] { "assetId", "name" }, new int[] { R.id.assetId, R.id.name }); ListView myList = (ListView) findViewById(android.R.id.list); myList.setAdapter(adapter); }*/ if(userList.size()!=0){ //Set the User Array list in ListView ListAdapter adapter = new SimpleAdapter( MainActivity.this,userList, R.layout.view_user_entry, new String[] { "assetId","name"}, new int[] {R.id.assetId, R.id.name}); ListView myList=(ListView)findViewById(android.R.id.list); myList.setAdapter(adapter); //Display Sync status of SQLite DB Toast.makeText(getApplicationContext(), controller.getSyncStatus(), Toast.LENGTH_LONG).show(); } // Initialize Progress Dialog properties prgDialog = new ProgressDialog(this); prgDialog.setMessage("Syncing... Please wait..."); prgDialog.setCancelable(false); // BroadCase Receiver Intent Object Intent alarmIntent = new Intent(getApplicationContext(), SampleBC.class); // Pending Intent Object PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Alarm Manager Object AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); // Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in // Remote MySQL DB alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent); } // Options Menu (ActionBar Menu) @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } // When Options Menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //When Sync action button is clicked if (id == R.id.refresh) { //Sync SQLite DB data to remote MySQL DB insertSQLitetoMySQL(); insertMySQLtoSQLite(); return true; } return super.onOptionsItemSelected(item); } //Add User method getting called on clicking (+) button public void addUser(View view) { Intent objIntent = new Intent(getApplicationContext(), NewUser.class); startActivity(objIntent); } // Method to Sync MySQL to SQLite DB public void insertMySQLtoSQLite() { // Create AsycHttpClient object AsyncHttpClient client = new AsyncHttpClient(); // Http Request Params Object RequestParams params = new RequestParams(); // Show ProgressBar prgDialog.show(); // Make Http call to getusers.php client.post(Variables._IPADDRESS + "/mysqlsqlitesync/getusers.php", params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { // Hide ProgressBar prgDialog.hide(); // Update SQLite DB with response sent by getusers.php updateSQLite(response); } // When error occured @Override public void onFailure(int statusCode, Header[] headers, String content, Throwable error) { // TODO Auto-generated method stub // Hide ProgressBar prgDialog.hide(); if (statusCode == 404) { Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show(); } else if (statusCode == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show(); } } }); } // Method to Sync SQLite to MySQL DB public void insertSQLitetoMySQL(){ //Create AsycHttpClient object AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); ArrayList<HashMap<String, String>> userList = controller.getAllUsers(); if(userList.size()!=0){ if(controller.dbSyncCount() != 0){ prgDialog.show(); params.put("usersJSON", controller.composeJSONfromSQLite()); System.out.println("Params:"+params); client.post(Variables._IPADDRESS + "/sqlitemysqlsync/insertuser.php",params ,new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { System.out.println(response); System.out.println("TESTINGGGG"); prgDialog.hide(); try { JSONArray arr = new JSONArray(response); System.out.println(arr.length()); for(int i=0; i<arr.length();i++){ JSONObject obj = (JSONObject)arr.get(i); System.out.println(obj.get("id")); System.out.println("ASSET Sync: "+obj.get("needsSync")); controller.updateSyncStatus(obj.get("id").toString(),obj.get("needsSync").toString()); } Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show(); } catch (JSONException e) { // TODO Auto-generated catch block Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String content, Throwable error) { // TODO Auto-generated method stub prgDialog.hide(); if(statusCode == 404){ Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show(); }else if(statusCode == 500){ Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show(); } } }); }else{ Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show(); } }else{ Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show(); } } public void updateSQLite(String response){ //long time_stamp = System.currentTimeMillis() / 1000L; ArrayList<HashMap<String, String>> usersynclist; usersynclist = new ArrayList<HashMap<String, String>>(); // Create GSON object Gson gson = new GsonBuilder().create(); try { // Extract JSON array from the response JSONArray arr = new JSONArray(response); System.out.println(arr.length()); // If no of array elements is not zero if(arr.length() != 0){ // Loop through each array element, get JSON object which has assetid and username for (int i = 0; i < arr.length(); i++) { JSONObject obj = (JSONObject) arr.get(i); System.out.println("Asset exist: " + controller.hasAsset(obj.get("assetId").toString())); System.out.println("Local timestamp: "+controller.getAssetTimestamp(obj.get("assetId").toString())); System.out.println("Remote timestamp" +Double.parseDouble(obj.get("last_timestamp").toString())); //server return list of assets //ensure that asset is not present on the device or //if it is, the version on the server is newer //TODO: THIS inserts new record if it find that timestamp on server is newer -> change it to update existing record // Split into two if's one creates new record if doesnt exist, the other updates an existing record // when downloading data from server set the time stamp that is stored on the server, do not create a new one if (!controller.hasAsset((String)obj.get("assetId"))){ // Get JSON object System.out.println(obj.get("assetId")); System.out.println(obj.get("name")); System.out.println("Asset exist: " + controller.hasAsset(obj.get("assetId").toString())); System.out.println("Local timestamp: "+controller.getAssetTimestamp(obj.get("assetId").toString())); System.out.println("Remote timestamp" +Integer.parseInt(obj.get("last_timestamp").toString())); // DB QueryValues Object to insert into SQLite queryValues = new HashMap<String, String>(); // Add assetID extracted from Object queryValues.put("assetId", obj.get("assetId").toString()); // Add userName extracted from Object queryValues.put("name", obj.get("name").toString()); queryValues.put("last_timestamp", obj.get("last_timestamp").toString()); queryValues.put("needsSync", "0"); // Insert User into SQLite DB controller.insertRemoteUser(queryValues); HashMap<String, String> map = new HashMap<String, String>(); // Add status for each User in Hashmap map.put("id", obj.get("assetId").toString()); //map.put("last_timestamp", String.valueOf(time_stamp)); map.put("last_timestamp", obj.get("last_timestamp").toString()); map.put("needsSync", "0"); usersynclist.add(map); } else if(controller.hasAsset(obj.get("assetId").toString()) && controller.getAssetTimestamp(obj.get("assetId").toString())<Integer.parseInt(obj.get("last_timestamp").toString())){ // DB QueryValues Object to insert into SQLite queryValues = new HashMap<String, String>(); // Add assetID extracted from Object queryValues.put("assetId", obj.get("assetId").toString()); // Add userName extracted from Object queryValues.put("name", obj.get("name").toString()); queryValues.put("last_timestamp", obj.get("last_timestamp").toString()); queryValues.put("needsSync", "0"); // Insert User into SQLite DB controller.updateRemoteUser(queryValues); HashMap<String, String> map = new HashMap<String, String>(); // Add status for each User in Hashmap map.put("id", obj.get("assetId").toString()); //map.put("last_timestamp", String.valueOf(time_stamp)); map.put("last_timestamp", obj.get("last_timestamp").toString()); map.put("needsSync", "0"); usersynclist.add(map); } else if (controller.remoteAssetDeleted(arr)){ Toast.makeText(getApplicationContext(), "Nothing to update", Toast.LENGTH_LONG).show(); } controller.remoteAssetDeleted(arr); } // Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users //updateMySQLSyncSts(gson.toJson(usersynclist)); // Reload the Main Activity reloadActivity(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Method to inform remote MySQL DB about completion of Sync activity /*public void updateMySQLSyncSts(String json) { System.out.println(json); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("last_timestamp", json); // Make Http call to updatesyncsts.php with JSON parameter which has Sync statuses of Users client.post("http://10.117.243.22:8888/mysqlsqlitesync/updatesyncsts.php", params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, String content, Throwable error) { Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_LONG).show(); } }); }*/ // Reload MainActivity public void reloadActivity() { Intent objIntent = new Intent(getApplicationContext(), MainActivity.class); startActivity(objIntent); } }<file_sep><?php include '../config.php'; include 'db_functions.php'; if ( !empty($_POST)) { // keep track validation errors $nameError = null; $descriptionError = null; // keep track post values $name = $_POST['name']; $description = $_POST['description']; $longitude = $_POST['longitude']; $latitude = $_POST['latitude']; $images = $_POST['images']; $voice_memo = $_POST['voice_memo']; // validate input $valid = true; if (empty($name)) { $nameError = 'Please enter Name'; $valid = false; } if (empty($description)) { $descriptionError = 'Please enter Description'; $valid = false; } // insert data if ($valid) { //Create Object for DB_Functions clas $db = new DB_Functions(); $db->addAsset($name, $description, $latitude, $longitude, $images); header("Location: index.php"); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <!--<script src="../js/jquery-1.11.2.min.js"></script>--> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="../js/dropzone.js"></script> <link href="<?php echo skin;?>css/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo skin;?>css/styles.css" rel="stylesheet" > <script src="../js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="span10 offset1"> <div class="row"> <h3>Create an Asset</h3> </div> <form id="form1" enctype="multipart/form-data" method="post" action="Upload.php"> <div id="draghere"> <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();uploadFile();" accept="image/*" capture="camera"/> </div> <div id="details"></div> <div id="progress"></div> </form> <form class="form-horizontal" action="create.php" method="post"> <div class="form-group <?php echo !empty($nameError)?'has-error':'';?>"> <label class="control-label" for="inputDefault">Name</label> <input name="name" type="text" placeholder="Name" value="<?php echo !empty($name)?$name:'';?>" type="text" class="form-control" id="<?php echo !empty($nameError)?'inputError':'inputDefault';?>"> <?php if (!empty($nameError)): ?> <span class="help-inline"><?php echo $nameError;?></span> <?php endif;?> </div> <input name="images" type="hidden" value="test" id="image-file"> <div class="form-group <?php echo !empty($descriptionError)?'has-error':'';?>"> <label class="control-label" for="inputDefault">Description</label> <input name="description" type="text" placeholder="Description" value="<?php echo !empty($description)?$description:'';?>" type="text" class="form-control" id="<?php echo !empty($descriptionError)?'inputError':'inputDefault';?>"> <?php if (!empty($descriptionError)): ?> <span class="help-inline"><?php echo $descriptionError;?></span> <?php endif;?> </div> <div class="form-group"> <label class="control-label">Coordinates <img src="<?php echo skin;?>img/loading.gif" class="loading" id="spinner"/></label> <div class="input-group"> <span class="input-group-addon">Lat:</span> <input name="latitude" type="text" id="lat" class="form-control" placeholder="Latitude" value="<?php echo !empty($latitude)?$latitude:'';?>"> <span class="input-group-addon">Long:</span> <input name="longitude" type="text" id="lon" class="form-control" placeholder="Longitude" value="<?php echo !empty($longitude)?$longitude:'';?>"> </div> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-success">Create</button> <a class="btn btn-default" href="home.php">Back</a> </div> </form> </div> <!-- Get Location --> <script> $(function() { document.getElementById("spinner").style.display = "-webkit-inline-box"; var lat = document.getElementById("lat"); var lon = document.getElementById("lon"); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } }); function showPosition(position) { lat.value = position.coords.latitude; lon.value = position.coords.longitude; document.getElementById("spinner").style.display = "none"; } </script> <!-- /Get Location --> <!-- File Upload --> <script type="text/javascript"> function fileSelected() { var count = document.getElementById('fileToUpload').files.length; document.getElementById('details').innerHTML = ""; for (var index = 0; index < count; index ++) { var file = document.getElementById('fileToUpload').files[index]; var fileSize = 0; if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; //document.getElementById('details').innerHTML += 'Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type; //document.getElementById('details').innerHTML += '<p>'; document.getElementById('image-file').value = '../media/' + file.name; } } function uploadFile() { var fd = new FormData(); var count = document.getElementById('fileToUpload').files.length; var file = ""; for (var index = 0; index < count; index ++) { file = document.getElementById('fileToUpload').files[index]; fd.append('myFile', file); } var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.addEventListener("load", uploadComplete.bind(null, file), false); xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); xhr.open("POST", "savetofile.php"); xhr.send(fd); } function uploadProgress(evt) { if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); document.getElementById('progress').innerHTML = percentComplete.toString() + '%'; } else { document.getElementById('progress').innerHTML = 'unable to compute'; } } function uploadComplete(file, evt) { /* This event is raised when the server send back a response */ document.getElementById('draghere').innerHTML = '<img id="image-placeholder" src="' + '../media/' + file.name + '"/>'; } function uploadFailed(evt) { alert("There was an error attempting to upload the file."); } function uploadCanceled(evt) { alert("The upload has been canceled by the user or the browser dropped the connection."); } </script> <!-- /File Upload --> </div> <!-- /container --> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <title>TAMS</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo skin;?>css/bootstrap.min.css" rel="stylesheet" > <link href="<?php echo skin;?>css/styles.css" rel="stylesheet" > <script src="../js/jquery-1.11.2.min.js"> </script> <script src="../js/bootstrap.min.js" ></script> <!--Export--> <script type="text/javascript" src="export/tableExport.js" > </script> <script type="text/javascript" src="export/jquery.base64.js" ></script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="home.php">TAMS</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <!--<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li>--> <li id="active-assets"><a href="home.php" onclick="loadingImg();populateAssets()">Active Assets <span class="sr-only">(current)</span></a></li> <li id="deleted-assets"><a href="#" onclick="loadingImg();populateDeletedAssets()">Deleted Assets <span class="sr-only">(current)</span></a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Export <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a onClick ="$('#assets-table').tableExport({type:'csv',escape:'false',ignoreColumn:'[0,9,10,11]'});">CSV</a></li> </ul> </li> </ul> <ul class="nav navbar-nav navbar-right navbar-settings"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <img id="settings-icon" src="<?php echo skin;?>img/gear-icon.png"/><span class="settings-label">Settings<span class="caret"></span></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">My Account</a></li> <li class="divider"></li> <li><a href="accounts.php">Manage Accounts</a></li> <li class="divider"></li> <li><a href="logout.php">Logout</a></li> </ul> </li> </ul> </div> </div> </nav><file_sep>package com.imihov.tamssql; /** * Created by imihov on 8/26/15. */ public class Variables { //define table columns public static String _TABLE = "assets"; public static String _ASSETID = "assetId"; public static String _TIMESTAMP = "last_timestamp"; public static String _ASSETNAME = "name"; public static String _NEEDSSYNC = "needsSync"; public static String _IPADDRESS = "http://tams.imihov.com"; } <file_sep>// // Asset.swift // TAMS // // Created by arash on 8/31/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import CoreData class AssetEntity: NSManagedObject { @NSManaged var image: NSData @NSManaged var audio: NSData @NSManaged var date: NSDate @NSManaged var latitude: NSNumber @NSManaged var longitude: NSNumber @NSManaged var title: String @NSManaged var attributes: NSSet } <file_sep><?php //if password is test use test db //send password only first, after success send the data include_once './db_functions.php'; include_once '../../config.php'; class UpdateAsset { public function processUpdate($data) { error_log("UPDATE STARTED"); //Create Object for DB_Functions clas $db = new DB_Functions(); //Get JSON posted by Android Application //$jsonAssets = $_POST[_ASSETS_JSON_POST]; //$apiPassword = $_POST[_API_AUTH_POST]; //Remove Slashes //$jsonAssets = stripslashes($jsonAssets); //Decode JSON into an Array //$data = json_decode($jsonAssets); //error_log("PUSH SERVER RECEIVED: ".$jsonAssets,0); //error_log($apiPassword,0); //Util arrays to create response JSON $a=array(); $b=array(); $locations = array(); $purgeAsset = 0; //Loop through an Array and insert data read from JSON into MySQL DB for($i=0; $i<count($data) ; $i++) { $asset_id = $asset_name = $asset_description = $asset_created_at = $asset_updated_at = ""; $asset_deleted = $asset_latitude = $asset_longitude = $asset_images= ""; if (isset($data[$i]->asset_id)) $asset_id = $data[$i]->asset_id; if (isset($data[$i]->name)) $asset_name = $data[$i]->name; if (isset($data[$i]->description)) $asset_description = $data[$i]->description; if (isset($data[$i]->created_at)) $asset_created_at = $data[$i]->created_at; if (isset($data[$i]->updated_at)) $asset_updated_at = $data[$i]->updated_at; if (isset($data[$i]->deleted)) $asset_deleted = $data[$i]->deleted; if (isset($data[$i]->latitude)) $asset_latitude = $data[$i]->latitude; if (isset($data[$i]->longitude)) $asset_longitude = $data[$i]->longitude; if (isset($data[$i]->images)) $asset_images = $data[$i]->images; if ($data[$i]->isNew == 0) { //get all locations for the asset and push them into array foreach ($data[$i]->locations as $location) { array_push($locations, (array)$location); } //Store Asset into MySQL DB $query = $db->updateAsset($asset_id, $asset_name, $asset_description, $asset_created_at, $asset_updated_at, $asset_deleted, $asset_latitude, $asset_longitude, $asset_images, $locations); //send the timestamp to compare } else { return "Asset is new"; } //Based on inserttion, create JSON response to set the asset flags if($query) { //if success $b[_ASSETS_COLUMN_ASSET_ID] = $data[$i]->asset_id; $b[_ASSETS_COLUMN_NEEDSSYNC] = 0; //asset does not need sync any more $b["error"] = 0; //return 0 if success array_push($a,$b); } else { //if insert failed $b[_ASSETS_COLUMN_ASSET_ID] = $data[$i]->asset_id; $b[_ASSETS_COLUMN_NEEDSSYNC] = 1; $b["error"] = 1; //return 1 if fail array_push($a,$b); } } //Post JSON response back to Android Application error_log("UPDATE ENDED"); return $a; //error_log("PUSH SERVER RESPONSE: ".json_encode($a),0); } } ?> <file_sep>// // AssetViewCellView.swift // TAMS // // Created by arash on 8/27/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit public class AssetViewCellView : UITableViewCell { @IBOutlet weak var attribute: UILabel! @IBOutlet weak var value: UILabel! } <file_sep>Backend for TAMS ==================================== How to install the Backend -------------------------- This document goes over how we have set up the TAMS web application and API. **Assumptions** For a server set up, you can use this as a base, however, it might require a different approach unless you have complete control (i.e. you are root) on the server and can install all the dependencies, secure the machine, etc. So, use these instructions as a starting point rather than a definitive “this is the ultimate way” step-by-step guide. **Download** - Option 1: If you don’t have the version control system git you’ll need to install it. For Debian based system use: apt-get install git - Option 2: Copy the contets of the "Backend" folder into the machine. Install the Dependencies ------------------------ **We need the following bits and pieces** - Apache with the fillowing modules enabled: - rewrite - headers - php - PHP - Version >=5.5 - MySQL **For Debian based machines run the following commands to install the requirements:** ``` sudo apt-get install apache2 php5 php5-cli mysql-server libmysqlclient15-dev php5-mysql ``` ``` # Enable the apache modules a2enmod php a2enmod rewrite a2enmod headers service apache2 restart ``` **Moving the web application in the correct spot** ``` # For Debian mv Backend/* /var/www # This will overwrite anything in the www directory ``` MySQL ----- We now need to create a database in MySQL and load the schema. We assume that you have MySQL running and that your MySQL super user is root and the account has a password. Step one. Create the database. This is pretty simple: ``` mysqladmin -u root -p create tams Enter password: **** ``` Step two. Import the schema: ``` mysql -u root -p tams < Backend/db/schema.sql Enter password: **** ``` Configure the web application itself (If required) -------------------------------------------------- Edit the file "config.php" which should now reside in "/var/www/config.php" ``` # For Debian Based systems nano /var/www/config.php # Change the data base configuration to suit your setup ``` Look at the result ------------------ You should now be able to view the results at your webserver URL Hopefully, you should see a working version of TAMS but without any data in it. This is because we haven’t loaded anything into the database yet. <file_sep>// // AssetViewController.swift // TAMS // // Created by arash on 8/23/15. // Copyright (c) 2015 arash. All rights reserved. // import Foundation import UIKit import MapKit import MobileCoreServices import AVFoundation class AssetViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,AVAudioPlayerDelegate,AVAudioRecorderDelegate{ var asset = Asset() var newMedia: Bool? var audioPlayer: AVAudioPlayer! var audioRecorder: AVAudioRecorder! var updater : CADisplayLink! = nil @IBOutlet weak var image: UIImageView! @IBOutlet weak var smallMap: MKMapView! @IBOutlet weak var assetTitleLabel: UITextField! @IBOutlet weak var assetTableView: UITableView! @IBOutlet weak var audiobutton: UIButton! @IBOutlet weak var audioprogressbar: UIProgressView! @IBAction func audiobottunpressed(sender: UIButton) { if assetTableView.editing{ if audiobutton.selected{ audioRecorder.stop() audiobutton.selected = false } else { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { // let recordurl = NSURL() // let recordSettings = [ // AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, // AVFormatIDKey : kAudioFormatLinearPCM, // AVEncoderBitRateKey: 16, // AVNumberOfChannelsKey: 2, // AVSampleRateKey: 44100.0] // //self.recorder = AVAudioRecorder(URL: recordurl, settings: recordSettings , error: nil) self.audioRecorder.record() } else { print("Permission to record not granted") } }) audiobutton.selected=true } } else { if audiobutton.selected{ audioPlayer.stop() audiobutton.selected = false }else { audioPlayer.play() audiobutton.selected = true } } } var tempimage = UIImageView() override func viewDidLoad() { super.viewDidLoad() assetTableView.delegate = self assetTableView.dataSource = self self.navigationItem.rightBarButtonItem = self.editButtonItem() let annotation = MKPointAnnotation() annotation.coordinate = CLLocation(latitude: asset.latitude, longitude: asset.longitude).coordinate annotation.title = asset.title smallMap.addAnnotation(annotation) let span = MKCoordinateSpanMake(0.005, 0.005) let region = MKCoordinateRegion(center: CLLocation(latitude: asset.latitude, longitude: asset.longitude).coordinate, span: span) smallMap.setRegion(region, animated: true) smallMap.showsBuildings = true // image.image = UIImage(data:asset.image) assetTitleLabel.text = asset.title // let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) // let docsDir = dirPaths[0] as! String let directoryURL = try?NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true) let soundFilePath = directoryURL!.URLByAppendingPathComponent("sound.wav") // let soundFilePath = docsDir.stringByAppendingPathComponent("sound.wav") let soundFileURL = NSURL(fileURLWithPath: soundFilePath.absoluteString) let recordSettings:[String:AnyObject] = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, AVFormatIDKey : NSNumber(unsignedInt: kAudioFormatLinearPCM), AVEncoderBitRateKey: NSNumber(int:16), AVNumberOfChannelsKey: NSNumber(int:2), AVSampleRateKey: NSNumber(float:44100.0)] var error: NSError? let audioSession = AVAudioSession.sharedInstance() try? audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) if let err = error { print("audioSession error: \(err.localizedDescription)") } audioRecorder = try? AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [String : AnyObject]) audioRecorder.delegate = self if let err = error { print("audioSession error: \(err.localizedDescription)") } else { audioRecorder?.prepareToRecord() } let u = NSURL.fileURLWithPath( NSBundle.mainBundle().pathForResource("55", ofType: "mp3")!) var e: NSError? // do { self.audioPlayer = try! AVAudioPlayer(contentsOfURL: u) // catch { // print("audioPlayer error") // } // else { self.audioPlayer.numberOfLoops = 0 self.audioPlayer.delegate = self self.audioPlayer.prepareToPlay() self.updater = CADisplayLink(target: self, selector: Selector("trackAudio")) self.updater.frameInterval = 1 self.updater.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) // } } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { if flag{ print("recorded") //asset.audio = nsdata( recorder.url try! self.audioPlayer = AVAudioPlayer(contentsOfURL: recorder.url) } else { print("problem saving or something ") } } func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) { if flag{ audiobutton.selected = false } } func trackAudio() { audioprogressbar.setProgress(Float(audioPlayer.currentTime / audioPlayer.duration), animated: false) } func imageTapped(img: AnyObject) { print("image pressed") if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.mediaTypes = [kUTTypeImage as NSString as String] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) newMedia = true } } func useCameraRoll(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.SavedPhotosAlbum) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.mediaTypes = [kUTTypeImage as NSString as String] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) newMedia = false } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as! String self.dismissViewControllerAnimated(true, completion: nil) if mediaType == (kUTTypeImage as! String) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage removeImageViewSubviews(self.image) self.image.image = image if (newMedia == true) { UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil) } else if mediaType == (kUTTypeMovie as! String) { // Code to support video here } } } func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) { if error != nil { let alert = UIAlertController(title: "Save Failed", message: "Failed to save image", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } } func removeImageViewSubviews( img : UIImageView){ for sv in img.subviews{ sv.removeFromSuperview() } } override func setEditing(editing: Bool, animated: Bool) { if editing { print("edit ") //ShowAttributeAddViews(true) assetTableView.editing = true var imagegesture = UITapGestureRecognizer(target:self, action:Selector("imageTapped:")) image.addGestureRecognizer(imagegesture) editImage() audiobutton.setImage(UIImage(named: "microphone"), forState: UIControlState.Normal) assetTableView.reloadData() } else { print("save ") // ShowAttributeAddViews(false) image.gestureRecognizers?.removeAll(keepCapacity: false) assetTableView.editing = false removeImageViewSubviews(image) UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil) asset.title = assetTitleLabel.text! audiobutton.setImage(UIImage(named: "play"), forState: UIControlState.Normal) assetTableView.reloadData() } super.setEditing(editing, animated: animated) } func editImage(){ let drawText = "EDIT" var effect = UIBlurEffect(style: UIBlurEffectStyle.ExtraLight) var blurView = UIVisualEffectView(effect: effect) blurView.frame = image.bounds var cam = UIImageView(image: UIImage(named: "Camera.png")) cam.frame = CGRectMake(0, 0, 20, 20) cam.center = CGPoint(x: 50, y: 50) image.addSubview(blurView) image.addSubview(cam) // // Setup the font specific variables // var textColor: UIColor = UIColor.whiteColor() // var textFont: UIFont = UIFont(name: "Helvetica Bold", size: 62)! // // //Setup the image context using the passed image. // UIGraphicsBeginImageContext(inImage.size) // // //Setups up the font attributes that will be later used to dictate how the text should be drawn // let textFontAttributes = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor,] // // //Put the image into a rectangle as large as the original image. // inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height)) // // // Creating a point within the space that is as bit as the image. // var rect: CGRect = CGRectMake(20, 20, inImage.size.width, inImage.size.height) // // //Now Draw the text into an image. // drawText.drawInRect(rect, withAttributes: textFontAttributes) // // // Create a new image out of the images we have created // inImage = UIGraphicsGetImageFromCurrentImageContext() // // // End the context now that we have the image we need // UIGraphicsEndImageContext() } // func playAudio(sender: AnyObject) { // // var playing = false // // if let currentPlayer = audioPlayer { // playing = audioPlayer!.playing; // }else{ // return; // } // // if !playing { // let filePath = NSBundle.mainBundle().pathForResource("3e6129f2-8d6d-4cf4-a5ec-1b51b6c8e18b", ofType: "wav") // if let path = filePath{ // let fileURL = NSURL(string: path) // player = AVAudioPlayer(contentsOfURL: fileURL, error: nil) // player.numberOfLoops = -1 // play indefinitely // player.prepareToPlay() // player.delegate = self // player.play() // // displayLink = CADisplayLink(target: self, selector: ("updateSliderProgress")) // displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode!) // } // // } else { // player.stop() // displayLink.invalidate() // } // } // // func updateSliderProgress(){ // var progress = player.currentTime / player.duration // timeSlider.setValue(Float(progress), animated: false) // } // TABLE VIEW DELEGATE METHODS func numberOfSectionsInTableView(tableView: UITableView) -> Int { if tableView.editing {return 2} else {return 1} } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { //let title = section == 1 ? "New" : "Current" if tableView.editing { if section == 1 { return "Assets" } else { return "Add new asset" } }else { return "Assets" } } // func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { // // } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.editing { if section == 0 { return 1 }else{ return asset.attributes.count } } else { return asset.attributes.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView.editing { if indexPath.section == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("AssetAddReusableCell", forIndexPath: indexPath) as! UITableViewCell let c = cell as! AssetAttributeAddCellView c.attributeName.text = "" c.attributeValue.text = "" return cell }else { let cell = tableView.dequeueReusableCellWithIdentifier("AssetViewReusableCell", forIndexPath: indexPath) as! UITableViewCell let c = cell as! AssetViewCellView c.attribute.text = asset.attributes[indexPath.row].attributeName c.value.text = asset.attributes[indexPath.row].attributeData return cell } } else { let cell = tableView.dequeueReusableCellWithIdentifier("AssetViewReusableCell", forIndexPath: indexPath) as! UITableViewCell let c = cell as! AssetViewCellView c.attribute.text = asset.attributes[indexPath.row].attributeName c.value.text = asset.attributes[indexPath.row].attributeData return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let c = (tableView.cellForRowAtIndexPath(indexPath) as? TableViewCellView){ print(c.cellViewSubtitle.text!) //performSegueWithIdentifier("TableViewToAssetView", sender: c.cellViewSubtitle.text!) //tableView.deselectRowAtIndexPath(indexPath, animated: true) } } // func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { // println("tapped") // let cell = tableView.dequeueReusableCellWithIdentifier("AssetViewReusableCell", forIndexPath: indexPath) as! UITableViewCell // if let c = cell as? AssetViewCellView { // println(asset.attributes[c.tag].attributeName) // } // } // Override to support conditional editing of the table view. func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if tableView.editing && indexPath.section == 0 && indexPath.row == 0 { return false } // Return NO if you do not want the specified item to be editable. return true } //Override to support editing the table view. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // let thecell = tableView.cellForRowAtIndexPath(indexPath) as! AssetViewCellView // asset.attributes[indexPath.row].attributeName = thecell.assetViewCellAttribute.text // asset.attributes[indexPath.row].attributeData = thecell.assetViewCellValue.text // if editingStyle == .Delete { // Delete the row from the data source asset.attributes.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // // // MARK: - Navigation // // // In a storyboard-based application, you will often want to do a little preparation before navigation // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // if segue.identifier == "TableViewToAssetView"{ // let assetVC = segue.destinationViewController as! AssetViewController // let key = sender as! String // let asset = Assets.sharedInstance.findAssetWithKey(key) // assetVC.theLocation = asset!.location // assetVC.theTitle = asset!.title // } // } }<file_sep><?php include "../config.php"; include 'db_functions.php'; session_start(); if(empty($_SESSION['login_user'])) { header('Location: index.php'); } if ( !empty($_POST)) { // keep track validation errors $firstnameError = null; $username = null; $password = null; // keep track post values $firstname = $_POST['firstname']; $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $lastname = $_POST['lastname']; $email = $_POST['email']; $role = $_POST['role']; // validate input $valid = true; if (empty($firstname)) { $firstnameError = 'Please enter First Name'; $valid = false; } if (empty($username)) { $usernameError = 'Please enter Username'; $valid = false; } if (empty($password)) { $passwordError = 'Please enter Password'; $valid = false; } if($role == "Admin") $role = 0; else $role = 1; if ($valid) { $pdo = Database::connect(); //ASSET $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $assetSql = "INSERT INTO users (firstname,username, lastname, email, role, password) values(?, ?, ?, ?, ?, ?)"; $assetQuery = $pdo->prepare($assetSql); $assetQuery->execute(array($firstname,$username, $lastname, $email, $role, password_hash($password, PASSWORD_DEFAULT))); Database::disconnect(); header("Location: accounts.php"); } } ?> <?php include_once 'header.php'; ?> <div class="container"> <div class="row"> <div id="top-bar"> <div id="left" class="column"><a class="btn btn-primary" data-toggle="modal" data-target="#modal" id="newuser">+ New User</a></div> </div> </div> <div class="row"> <span id="mobile-assets-table"></span> <table class="table table-striped table-bordered" id="assets-table"> <thead> <tr> <th>UserId</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th>Email</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> <?php $db = new DB_Functions(); $users = $db->getAllUsers(); foreach ($users as $user) { echo '<a href="read.php?user_id='.$user['user_id'].'" class="list-group-item">'; echo '<h4 class="list-group-item-heading">'; echo $user['firstname'] . ' ' . $user['lastname']; echo '</h4><p class="list-group-item-text">' . $user['username'] . '</p></a>'; echo '<tr>'; echo '<td>'. $user['user_id'] . '</td>'; echo '<td>'. $user['firstname'] . '</td>'; echo '<td>'. $user['lastname'] . '</td>'; echo '<td>'. $user['username'] . '</td>'; echo '<td>'. $user['email'] . '</td>'; echo '<td>'; if ($user['role'] == 0) echo 'Admin'; else echo 'User'; echo '</td>'; echo '<td width=250>'; echo '<a class="btn btn-default" href="editUser.php?user_id='.$user['user_id'].'">Edit</a>'; echo '&nbsp;'; echo '<a class="btn btn-danger" href="deleteUser.php?user_id='.$user['user_id'].'">Delete</a>'; echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div> <div class="modal fade" id="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">Create User</h4> </div> <div class="modal-body"> <div class="well bs-component"> <form class="form-horizontal" action="accounts.php" method="post"> <fieldset> <div class="form-group <?php echo !empty($usernameError)?'has-error':'';?>"> <label class="col-lg-2 control-label" for="inputDefault">Username</label> <div class="col-lg-10"> <input name="username" type="text" placeholder="Username" value="<?php echo !empty($username)?$username:'';?>" onkeyup="validateFields();" class="form-control" id="username"> <?php if (!empty($usernameError)): ?> <span class="help-inline"><?php echo $usernameError;?></span> <?php endif;?> </div> </div> <div class="form-group <?php echo !empty($firstnameError)?'has-error':'';?>"> <label class="col-lg-2 control-label" for="inputDefault">First Name</label> <div class="col-lg-10"> <input name="firstname" type="text" placeholder="<NAME>" value="<?php echo !empty($firstname)?$firstname:'';?>" onkeyup="validateFields();" class="form-control" id="firstname"> <?php if (!empty($firstnameError)): ?> <span class="help-inline"><?php echo $firstnameError;?></span> <?php endif;?> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Last Name</label> <div class="col-lg-10"> <input name="lastname" type="text" id="lastname" class="form-control" placeholder="Last Name" value="<?php echo !empty($lastname)?$lastname:'';?>"> </div> </div> <div class="form-group <?php echo !empty($passwordError)?'has-error':'';?>"> <label class="col-lg-2 control-label" for="inputDefault">Password</label> <div class="col-lg-10"> <input name="password" type="<PASSWORD>" placeholder="<PASSWORD>" value="<?php echo !empty($password)?$password:'';?>" onkeyup="validateFields();" class="form-control" id="password" > <?php if (!empty($passwordError)): ?> <span class="help-inline"><?php echo $passwordError;?></span> <?php endif;?> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Confirm Password</label> <div class="col-lg-10"> <input name="confirm-password" type="password" id="confirm-password" class="form-control" placeholder="Password" onkeyup="validateFields(); checkPass(); return false;"> <span id="confirmMessage" class="confirmMessage"></span> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Email</label> <div class="col-lg-10"> <input name="email" type="email" id="lat" class="form-control" placeholder="Email" value="<?php echo !empty($email)?$email:'';?>"> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Admin?</label>     <input type="checkbox" name="role" value="Admin" /> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" id="create-btn">Create User</button> </div> </div> </div> </fieldset> </form> </div> </div> </div> </div> <!-- /container --> <?php include_once 'footer.php'; ?><file_sep><?php include_once './db_functions.php'; include_once '../../config.php'; class DeleteAsset { public function processDeleteAsset($data) { error_log("DELETE STARTED"); //Create Object for DB_Functions clas $db = new DB_Functions(); //Util arrays to create response JSON $a=array(); $b=array(); //Loop through an Array and insert data read from JSON into MySQL DB for($i=0; $i<count($data) ; $i++) { if (isset($data[$i]->asset_id) && isset($data[$i]->updated_at)) { $query = $db->deleteAsset($data[$i]->asset_id, $data[$i]->updated_at); } else { return "asset_id & updated_at is Required"; } //Based on inserttion, create JSON response to set the asset flags if($query) { //if success $b[_ASSETS_COLUMN_ASSET_ID] = $data[$i]->asset_id; $b[_ASSETS_COLUMN_NEEDSSYNC] = 0; $b["purgeAsset"] = 1; //if asset was successfully deleted, purged from client $b["error"] = 0; //return 0 if success array_push($a,$b); } else { //if insert failed $b[_ASSETS_COLUMN_ASSET_ID] = $data[$i]->asset_id; $b[_ASSETS_COLUMN_NEEDSSYNC] = 1; $b["purgeAsset"] = 0; $b["error"] = 1; //return 1 if fail array_push($a,$b); } } //Post JSON response back to Android Application error_log("DELETE ENDED"); return $a; //error_log("PUSH SERVER RESPONSE: ".json_encode($a),0); } } ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.2.12deb2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Dec 17, 2015 at 12:59 PM -- Server version: 5.5.44-0+deb7u1 -- PHP Version: 5.6.13-0+deb8u1 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 utf8 */; -- -- Database: `tams` -- CREATE DATABASE IF NOT EXISTS `tams` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `tams`; -- -------------------------------------------------------- -- -- Table structure for table `api_auth` -- DROP TABLE IF EXISTS `api_auth`; CREATE TABLE IF NOT EXISTS `api_auth` ( `api_auth_id` int(11) NOT NULL, `key` varchar(255) NOT NULL, `practice` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `assets` -- DROP TABLE IF EXISTS `assets`; CREATE TABLE IF NOT EXISTS `assets` ( `asset_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `type_id` int(11) DEFAULT NULL, `created_at` int(11) NOT NULL, `updated_at` int(11) NOT NULL, `created_by` varchar(255) NOT NULL, `updated_by` varchar(255) NOT NULL, `deleted` int(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB AUTO_INCREMENT=2147483647 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `asset_types` -- DROP TABLE IF EXISTS `asset_types`; CREATE TABLE IF NOT EXISTS `asset_types` ( `asset_type_id` int(11) NOT NULL, `type_value` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `attributes` -- DROP TABLE IF EXISTS `attributes`; CREATE TABLE IF NOT EXISTS `attributes` ( `attribute_id` int(11) NOT NULL, `attribute_label` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `attributes_indexes` -- DROP TABLE IF EXISTS `attributes_indexes`; CREATE TABLE IF NOT EXISTS `attributes_indexes` ( `attribute_index_id` int(11) NOT NULL, `asset_id` int(11) NOT NULL, `attribute_id` int(11) NOT NULL, `attribute_value_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `attributes_values` -- DROP TABLE IF EXISTS `attributes_values`; CREATE TABLE IF NOT EXISTS `attributes_values` ( `attribute_value_id` int(10) NOT NULL, `attribute_value` varchar(255) NOT NULL, `attribute_id` int(11) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `locations` -- DROP TABLE IF EXISTS `locations`; CREATE TABLE IF NOT EXISTS `locations` ( `location_id` int(11) NOT NULL, `asset_id` int(11) NOT NULL, `address` varchar(255) NOT NULL, `longitude` float NOT NULL, `latitude` float NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=713 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `media` -- DROP TABLE IF EXISTS `media`; CREATE TABLE IF NOT EXISTS `media` ( `media_id` int(11) NOT NULL, `asset_id` int(11) NOT NULL, `images` longblob, `voice_memo` varchar(255) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=607 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL, `firstname` varchar(50) NOT NULL, `lastname` varchar(50) DEFAULT NULL, `username` varchar(50) NOT NULL, `email` varchar(50) DEFAULT NULL, `role` tinyint(1) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `api_auth` -- ALTER TABLE `api_auth` ADD PRIMARY KEY (`api_auth_id`); -- -- Indexes for table `assets` -- ALTER TABLE `assets` ADD PRIMARY KEY (`asset_id`), ADD KEY `type_id` (`type_id`); -- -- Indexes for table `asset_types` -- ALTER TABLE `asset_types` ADD PRIMARY KEY (`asset_type_id`); -- -- Indexes for table `attributes` -- ALTER TABLE `attributes` ADD PRIMARY KEY (`attribute_id`); -- -- Indexes for table `attributes_indexes` -- ALTER TABLE `attributes_indexes` ADD PRIMARY KEY (`attribute_index_id`), ADD KEY `asset_id` (`asset_id`), ADD KEY `attribute_id` (`attribute_id`), ADD KEY `attribute_value_id` (`attribute_value_id`); -- -- Indexes for table `attributes_values` -- ALTER TABLE `attributes_values` ADD PRIMARY KEY (`attribute_value_id`), ADD KEY `attribute_id` (`attribute_id`); -- -- Indexes for table `locations` -- ALTER TABLE `locations` ADD PRIMARY KEY (`location_id`), ADD KEY `asset_id` (`asset_id`); -- -- Indexes for table `media` -- ALTER TABLE `media` ADD PRIMARY KEY (`media_id`), ADD KEY `asset_id` (`asset_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `api_auth` -- ALTER TABLE `api_auth` MODIFY `api_auth_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `assets` -- ALTER TABLE `assets` MODIFY `asset_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2147483647; -- -- AUTO_INCREMENT for table `asset_types` -- ALTER TABLE `asset_types` MODIFY `asset_type_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `attributes` -- ALTER TABLE `attributes` MODIFY `attribute_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `attributes_indexes` -- ALTER TABLE `attributes_indexes` MODIFY `attribute_index_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `attributes_values` -- ALTER TABLE `attributes_values` MODIFY `attribute_value_id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `locations` -- ALTER TABLE `locations` MODIFY `location_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=713; -- -- AUTO_INCREMENT for table `media` -- ALTER TABLE `media` MODIFY `media_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=607; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15; -- -- Constraints for dumped tables -- -- -- Constraints for table `assets` -- ALTER TABLE `assets` ADD CONSTRAINT `assets_ibfk_4` FOREIGN KEY (`type_id`) REFERENCES `asset_types` (`asset_type_id`); -- -- Constraints for table `attributes_indexes` -- ALTER TABLE `attributes_indexes` ADD CONSTRAINT `attributes_indexes_ibfk_1` FOREIGN KEY (`asset_id`) REFERENCES `assets` (`asset_id`), ADD CONSTRAINT `attributes_indexes_ibfk_2` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`attribute_id`), ADD CONSTRAINT `attributes_indexes_ibfk_3` FOREIGN KEY (`attribute_value_id`) REFERENCES `attributes_values` (`attribute_value_id`); -- -- Constraints for table `attributes_values` -- ALTER TABLE `attributes_values` ADD CONSTRAINT `attributes_values_ibfk_1` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `locations` -- ALTER TABLE `locations` ADD CONSTRAINT `locations_ibfk_1` FOREIGN KEY (`asset_id`) REFERENCES `assets` (`asset_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `media` -- ALTER TABLE `media` ADD CONSTRAINT `media_ibfk_1` FOREIGN KEY (`asset_id`) REFERENCES `assets` (`asset_id`) ON DELETE CASCADE ON UPDATE CASCADE; /*!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>#!/usr/bin/env bash echo "Perform any cool tests here.. Havent had time yet."
515c3f545ab0c95cf6d783160c9c1b27ade305ba
[ "SQL", "Swift", "Markdown", "Java", "PHP", "Shell" ]
36
PHP
skennedsl/Documentation
cf45a2dcc85d3b96526574e7440860a4c7a3a63a
84657361ec6c20957b570047265073a0d2345303
refs/heads/master
<file_sep>import React, { Component } from 'react'; import "./Reports.css"; class Reports extends Component { constructor(props) { super(props); this.state = { data: [] } } loadReports() { const url = "http://localhost:3004/reports"; fetch(url).then(response => response.json()).then(json => { this.setState({ data: json }); }); } componentDidMount() { this.loadReports(); } render() { return ( <div> <div><h5 className="title">Reports</h5></div> {this.state.data.map(report => <article key={report.id}> {/* eslint-disable-next-line */} <img src={report.image} className="rounded-circle"></img> <h5>{report.user}</h5> <h6>{report.message}</h6> <h6 className="time">{report.time}</h6> </article> )} </div> ) } } export default Reports;<file_sep>import React, { Component } from 'react'; import Highcharts from "highcharts"; import Chart from "../Chart/Chart.js"; require('highcharts/modules/map')(Highcharts); let options = { title: { text: "Site Traffic Overview" }, series: [{ allowPointSelect: true, data: null, type: "column" }], xAxis: { type: "category", labels: { style: { fontSize: "13px", fontFamily: "Verdana, sans-serif" } }, categories: [] }, yAxis: [ { min: 0, title: { text: "" } }, { title: { text: "", align: "high", }, } ], credits: false }; class Sales extends Component { componentDidMount() { this.loadSales(); } loadSales() { const url = "http://localhost:3004/sales"; fetch(url).then(response => response.json()).then(data => { let newData = []; for (let i = 0; i < data.length; i++) { newData.push({ name: data[i].month, x: i, y: data[i].sales }); } options.series[0].data = newData; this.setState({ data: newData }); }); } render() { return ( <div> {this.state && this.state.data && ( <Chart options={options} highcharts={Highcharts} ref={"chart"} /> )} </div> ); } } export default Sales;
01f7a7270fa8d1291fd5902fd52e46ca6059145e
[ "JavaScript" ]
2
JavaScript
fonsecaricardos/teste-nave
202c0c3fc05c176a7785fbf44fe86259bbc98f0a
2363490103c6c9da316dab8d7de21669b99bd854
refs/heads/master
<repo_name>surajsingh2/pixelindia<file_sep>/Pixel_India/src/com/pixelindia/action/MessageAction.java package com.pixelindia.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.pixelindia.dao.MessageDAO; import com.pixelindia.model.MessageDetails; public class MessageAction extends ActionSupport implements ModelDriven<MessageDetails>{ private static final long serialVersionUID = 1L; private MessageDetails msgobj = new MessageDetails(); @Override public MessageDetails getModel() { return msgobj; } private String jsppagemsg = ""; public String getJsppagemsg() { return jsppagemsg; } public void setJsppagemsg(String jsppagemsg) { this.jsppagemsg = jsppagemsg; } public String msgPageDisplay() { return "MESSAGEPAGEVIEW"; } public String addmessageRecord() { System.out.println("INSIDE ADD USER RECORD"); MessageDAO msgdaoobj = new MessageDAO(); boolean reply = msgdaoobj.addMessageRecord(msgobj); if(reply) { jsppagemsg = "REGISTRATION SUCCESSFULL"; } else { jsppagemsg = "ERROR OCCURRED"; } return "REGREPLY"; } } <file_sep>/Pixel_India/src/com/pixelindia/action/LoginLogoutClientAction.java package com.pixelindia.action; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; import com.pixelindia.dao.ClientDAO; public class LoginLogoutClientAction extends ActionSupport implements SessionAware { private static final long serialVersionUID = 1L; private String email; private String password; private String jsppagemsg = ""; private Map<String, Object> sessionMap; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getJsppagemsg() { return jsppagemsg; } public void setJsppagemsg(String jsppagemsg) { this.jsppagemsg = jsppagemsg; } public Map<String, Object> getSessionMap() { return sessionMap; } public void setSessionMap(Map<String, Object> sessionMap) { this.sessionMap = sessionMap; } public String loginPageDisplay() { return "LOGINPAGEVIEW"; } // FOR SESSION CREATION @Override public void setSession(Map<String, Object> sessionMap) { this.sessionMap = sessionMap; } public String ClientLoginCheck() { ClientDAO clientdaoobj = new ClientDAO(); boolean reply = clientdaoobj.ClientLoginCheck(email, password); if(reply) { sessionMap.put("uname", email); return "SUCCESS"; } else { jsppagemsg = "INVALID USERID OR PASSWORD"; return "INVALID"; } } public String logout() { // remove userName from the session if (sessionMap.containsKey("uname")) { sessionMap.remove("uname"); } return "HOME"; } public void validate() { if("".equals(email)) { addFieldError("email", "EMAIL CAN'T BE BLANK"); } if("".equals(password)) { addFieldError("password", "PASSWORD CAN'T BE BLANK"); } } } <file_sep>/Pixel_India/src/com/pixelindia/model/BookingDetails.java package com.pixelindia.model; import com.opensymphony.xwork2.ActionSupport; public class BookingDetails extends ActionSupport { private static final long serialVersionUID = 1L; private Integer pid; private String name; private String mobileno; private String meetup; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobileno() { return mobileno; } public void setMobileno(String mobileno) { this.mobileno = mobileno; } public String getMeetup() { return meetup; } public void setMeetup(String meetup) { this.meetup = meetup; } } <file_sep>/Pixel_India/src/com/pixelindia/dao/MessageDAO.java package com.pixelindia.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.pixelindia.model.MessageDetails; public class MessageDAO { public boolean addMessageRecord(MessageDetails msgobj) { //System.out.println("INSIDE ADD RECORD METHOD IN DAO"); //System.out.println(userobj.getEmail() + " "+ userobj.getCountry()); Connection connectionobject = null; PreparedStatement pst = null; boolean f = false; try { connectionobject = DBConnect.getMySQLConnection(); pst = connectionobject.prepareStatement("insert into message values(?,?,?)"); pst.setString(1, msgobj.getName()); pst.setString(2, msgobj.getEmailid()); pst.setString(3, msgobj.getQuery()); int i = pst.executeUpdate(); System.out.println(i); if(i > 0 ) f = true; }catch(SQLException e){e.printStackTrace();} finally { DBConnect.closeMySQLPreaparedStatementConnection(pst); DBConnect.closeMySQLConnection(connectionobject); } return f; } public List<MessageDetails> displayAllMRecord() { Connection connectionobject = null; PreparedStatement pst = null; ResultSet rs =null; List<MessageDetails> photolist = new ArrayList<MessageDetails>(); try { connectionobject = DBConnect.getMySQLConnection(); pst = connectionobject.prepareStatement("select * from message"); rs = pst.executeQuery(); while(rs.next()) { //CREATE STUDENT DETAIL OBJECT MessageDetails pcobj = new MessageDetails(); //FETCH FROM RESULTSET & STORE VALUE WITIN OBJECT pcobj.setName(rs.getString(1)); pcobj.setEmailid(rs.getString(2)); pcobj.setQuery(rs.getString(3)); //ADDED TO THE ARRAYLIST photolist.add(pcobj); } }catch(SQLException e){System.out.print(e.toString());} finally { DBConnect.closeMySQLPreaparedStatementConnection(pst); DBConnect.closeMySQLResulsetConnection(rs); DBConnect.closeMySQLConnection(connectionobject); } System.out.println(photolist.size()); System.out.println("inside the list"); return photolist; } public List<MessageDetails> searchRecord(String emailid) { //System.out.println("DAO "+emailid); Connection connectionobject = null; PreparedStatement pst = null; ResultSet rs =null; List<MessageDetails> msglist= new ArrayList<MessageDetails>(); try { connectionobject = DBConnect.getMySQLConnection(); pst = connectionobject.prepareStatement("select * from message where emailid= ?"); pst.setString(1, emailid); rs = pst.executeQuery(); while(rs.next()) { //CREATE STUDENT DETAIL OBJECT MessageDetails mobj = new MessageDetails(); //FETCH FROM RESULTSET & STORE VALUE WITIN OBJECT mobj.setName(rs.getString(1)); mobj.setEmailid(rs.getString(2)); mobj.setQuery(rs.getString(3)); //ADDED TO THE ARRAYLIST msglist.add(mobj); } }catch(SQLException e){System.out.print(e.toString());} finally { DBConnect.closeMySQLPreaparedStatementConnection(pst); DBConnect.closeMySQLResulsetConnection(rs); DBConnect.closeMySQLConnection(connectionobject); } //System.out.println("LIST SIZE DAO " + studentlist.size()); return msglist; } } <file_sep>/Pixel_India/src/com/pixelindia/action/SearchCategoryAction.java package com.pixelindia.action; import java.util.List; import com.opensymphony.xwork2.ActionSupport; import com.pixelindia.dao.PhotographerDAO; import com.pixelindia.model.PhotographerDetails; public class SearchCategoryAction extends ActionSupport { private static final long serialVersionUID = 1L; private String category=""; private String searcherrmsg = ""; private List<PhotographerDetails> usrlist1 = null; public String searchPageDisplay() { return "SEARCHPAGEVIEW"; } public String searchCategory() { PhotographerDAO cdaoobj = new PhotographerDAO(); usrlist1 = cdaoobj.searchRecord(category.trim()); if(usrlist1.size()>0) { return "USERFOUND"; } else { searcherrmsg = "NO DATA FOUND FOR THE SELECTED CATEGORY"; return "USERNOTFOUND"; } } public String getSearcherrmsg() { return searcherrmsg; } public void setSearcherrmsg(String searcherrmsg) { this.searcherrmsg = searcherrmsg; } public List<PhotographerDetails> getUsrlist1() { return usrlist1; } public void setUsrlist1(List<PhotographerDetails> usrlist1) { this.usrlist1 = usrlist1; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } } <file_sep>/Pixel_India/src/com/pixelindia/action/DeleteUserAction.java package com.pixelindia.action; import com.opensymphony.xwork2.ActionSupport; import com.pixelindia.dao.PhotographerDAO; public class DeleteUserAction extends ActionSupport { private static final long serialVersionUID = 1L; String email=""; String deletemsg=""; @Override public String execute() { PhotographerDAO sdaoobj = new PhotographerDAO(); boolean reply = sdaoobj.deleteRecord(email); if(reply) { deletemsg = "DELETE SUCCESSFULL"; } else { deletemsg = "NOT DELETED"; } return "DELETEUSER"; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDeletemsg() { return deletemsg; } public void setDeletemsg(String deletemsg) { this.deletemsg = deletemsg; } } <file_sep>/Pixel_India/src/com/pixelindia/action/RegistrationAction.java package com.pixelindia.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.pixelindia.dao.PhotographerDAO; import com.pixelindia.model.PhotographerDetails; public class RegistrationAction extends ActionSupport implements ModelDriven<PhotographerDetails>{ private static final long serialVersionUID = 1L; private int pid; public int getPid() { return pid; } public void setPid(int pid) { this.pid=pid; } private PhotographerDetails userobj = new PhotographerDetails(); @Override public PhotographerDetails getModel() { return userobj; } private String jsppagemsg = ""; public String getJsppagemsg() { return jsppagemsg; } public void setJsppagemsg(String jsppagemsg) { this.jsppagemsg = jsppagemsg; } public String regPageDisplay() { return "REGISTRATIONPAGEVIEW"; } public String addPhotographerRecord() { System.out.println("INSIDE ADD USER RECORD"); PhotographerDAO userdaoobj = new PhotographerDAO(); boolean reply = userdaoobj.addRecord(userobj); if(reply) { jsppagemsg = "REGISTRATION SUCCESSFULL"; } else { jsppagemsg = "ERROR OCCURRED"; } return "REGREPLY"; } public void validate() { if("".equals(userobj.getEmail())) { addFieldError("email", "EMAIL CAN'T BE BLANK"); } if("".equals(userobj.getPassword())) { addFieldError("password", "PASSWORD CAN'T BE BLANK"); } if(userobj.getPassword() != null) { if((userobj.getPassword().length() > 0) && (userobj.getPassword().length() < 8)) { addFieldError("password", "PASSWORD SHOULD BE MIN 8 CHAR"); } } if("".equals(userobj.getMobileno())) { addFieldError("mobileno", "MOBILE NO CAN'T BE BLANK"); } if(userobj.getMobileno() != null) { if((userobj.getMobileno().length() > 0) && (userobj.getMobileno().length() != 10)) { addFieldError("mobileno", "MOBILE NO SHOULD BE 10 DIGIT"); } } } }
2cb77ec844a1a1103fb1ef6e03da3a4ea61ef041
[ "Java" ]
7
Java
surajsingh2/pixelindia
465e89a5921f901f1a6f888a898425bf1047ea32
285cf7b927ec4f832b79115cec221b9140e86959
refs/heads/master
<file_sep>package com.mms.cases.design.strategy; import org.springframework.lang.NonNull; import java.io.Serializable; public interface FormService { CommonPairResponse<String, Serializable> submitForm(@NonNull FormSubmitRequest request); } <file_sep>package com.mms.cases.leetcode.link; /** * 删除字符串中的所有相邻重复项 * 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 * * 在 S 上反复执行重复项删除操作,直到无法继续删除。 * * 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 * *   * * 示例: * * 输入:"abbaca" * 输出:"ca" * 解释: * 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Solution1047 { public String removeDuplicates(String S) { return null; } } <file_sep>策略模式 我自己的理解: 什么是策略模式?(what) 当一个业务场景,需要根据不同的情况,执行不同的方法的时候,就需要用到策略模式。 可以避免很多冗长的if else分支。 如何实现?(how) 首先定义一个策略接口,不同的实现方式,分别继承这一个接口,并单独实现接口的方法。 使用工厂模式,在spring启动时,把实现了所有策略接口实现类的对象,放到一个map中。 使用是,根据不同的请求参数,获取不同的实例。 资料方面正式的解释: 策略模式包含一个策略接口,和一组实现这个接口的策略类。 所有的策略类都实现相同的接口,所以,客户端基于接口而非实现编程。 可以灵活的替换不同的策略。<file_sep>package com.mms.cases.design.strategy.impl; import com.mms.cases.design.strategy.CommonPairResponse; import com.mms.cases.design.strategy.FormSubmitHandler; import com.mms.cases.design.strategy.FormSubmitRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class FormModelSubmitHandler implements FormSubmitHandler<Long> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public String getSubmitType() { return "model"; } @Override public CommonPairResponse handleSubmit(FormSubmitRequest request) { logger.info("模型提交:userId={}, formInput={}", request.getUserId(), request.getFormInput()); // 模型创建成功后获得模型的 id Long modelId = createModel(request); return CommonPairResponse.success("模型提交成功!", modelId); } public long createModel(FormSubmitRequest request){ return 0l; } }
ba312b361d4b3d9e6d0c3beda8fe988c9333526c
[ "Markdown", "Java" ]
4
Java
mmszhou/personal-cases
ca0c30e2cf9682d27a3394dd6538a8384eb150ef
09ecac7a238269b117554ec9942440a8c3e03bdf
refs/heads/master
<repo_name>Macarse/sia2011<file_sep>/tp02/images/generate_noise.py # -*- coding: iso-8859-1 -*- import Image import sys import random def generate(): random.seed(1337) func = get_value_random func_name = "" if "inverse" == sys.argv[1]: func = get_value_inverse func_name = "inverse" else: func = get_value_random func_name = "noise" path = sys.argv[2] name = path.split("/")[-1].split(".")[0] for porcentage in range(10, 101, 10): origin = Image.open(path) dest = Image.new('RGB', (64, 64), "black") pixels_origin = origin.load() pixels_dest = dest.load() for i in xrange(dest.size[1]): for j in xrange(dest.size[0]): if random.randint(0, 100) <= porcentage: pixels_dest[j, i] = func(pixels_origin[j,i], True) else: pixels_dest[j, i] = func(pixels_origin[j,i], False) dest.save("%s_%s_%s.png" % (name, func_name, str(porcentage))) def get_value_random(v, noise): if not noise: return v return random.sample([(0, 0, 0, 255), (255,255,255, 255)], 1)[0] def get_value_inverse(v, noise): if not noise: return v if (0, 0, 0, 255) == v: return (255,255,255, 255) else: return (0, 0, 0, 255) if __name__ == '__main__': generate()<file_sep>/tp02/convert.py #! /usr/bin/python import sys import Image def convert(): path = sys.argv[1] im = Image.open(path) name = path.split("/")[-1].split(".")[0] data = im.getdata() fin = open("data/"+name+".txt","w") for t in data: r = t[0] bool = -1 if r == 0 else 1 fin.write(str(bool)+"\n") fin.close() if __name__ == '__main__': convert() <file_sep>/tp03/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>sia13</groupId> <artifactId>tp3</artifactId> <name>tp3</name> <version>1.0</version> <dependencies> <dependency> <groupId>com.google.collections</groupId> <artifactId>google-collections</artifactId> <version>1.0-rc5</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-multibindings</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-assisted-inject</artifactId> <version>2.0</version> </dependency> </dependencies> </project><file_sep>/tp03/src/main/java/gps/sia13/model/ChainReactionMove.java package gps.sia13.model; import d.g.boardgames.Cell; public class ChainReactionMove { private Cell fromCell; private Cell toCell; public ChainReactionMove (Cell fromCell, Cell toCell) { this.fromCell = fromCell; this.toCell = toCell; } public Cell getFromCell() { return fromCell; } public void setFromCell(Cell fromCell) { this.fromCell = fromCell; } public Cell getToCell() { return toCell; } public void setToCell(Cell toCell) { this.toCell = toCell; } public String toString () { String retVal = ""; if (fromCell != null) { retVal += fromCell + " "; } if (toCell != null) { retVal += toCell; } return retVal ; } }<file_sep>/tp02/main.py from __future__ import generators import os MEMORIZE_PATTERNS = 'patterns' TEST_PATTERNS = 'test_patterns' DATA = 'data' GET_PATTERNS_TO_MEMORIZE_CODE = """ function ret = get_patterns_to_memorize() ret = {}; ret.names = { %s }; ret.values = [ %s ]; end """ GET_PATTERNS_TO_TEST_CODE = """ function ret = get_patterns_to_test() ret = {}; ret.names = { %s }; ret.values = [ %s ]; end """ LOAD_TEMPLATE = """ load('%s')';\n""" NAME_TEMPLATE = """ '%s';\n""" def conversion(path): print 'Converting file %s to matrix' % path os.system('python convert.py %s' % path) def dump_image(name): print 'Converting data %s to image' % name os.system('python out2png.py %s' % name) def main(): load_list = "" load_list_names = "" load_list_test = "" load_list_test_names = "" memorize_patterns = os.listdir(MEMORIZE_PATTERNS) test_patterns = os.listdir(TEST_PATTERNS) for item in set(memorize_patterns+test_patterns): path = os.path.join(MEMORIZE_PATTERNS if item in memorize_patterns else TEST_PATTERNS, item) name = item.split(".")[0] if not path.endswith(".png") or \ not os.path.isfile(path): continue # convert images to octave data files conversion(path) # inject data objects in octave get_pattern scripts load_element = LOAD_TEMPLATE % (os.path.join(DATA, name+".txt")) load_element_name = NAME_TEMPLATE % name if item in memorize_patterns and load_element not in load_list: load_list += load_element load_list_names += load_element_name if item in test_patterns and load_element not in load_list_test: load_list_test += load_element load_list_test_names += load_element_name # write patterns to memorize in octave script gptm_file = open("get_patterns_to_memorize.m", "w") gptm_file.write(GET_PATTERNS_TO_MEMORIZE_CODE % (load_list_names, load_list)) gptm_file.close() print "get_patterns_to_memorize.m file written" # write patterns to test in octave script gptt_file = open("get_patterns_to_test.m", "w") gptt_file.write(GET_PATTERNS_TO_TEST_CODE % (load_list_test_names, load_list_test)) gptt_file.close() print "get_patterns_to_test.m file written" # HERE WE SHOULD RUN main.m in octave! print "running octave scripted main" os.system('./scripted_main') # convert data output from octave to images for item in [item for item in test_patterns if item.endswith(".png")]: path = os.path.join(TEST_PATTERNS, item) name = item.split(".")[0] if not path.endswith(".png") or \ not os.path.isfile(path): continue dump_image(item.replace(".png", "")) if __name__ == '__main__': main() <file_sep>/tp03/src/main/java/gps/sia13/problem/ChainReactionProblem.java package gps.sia13.problem; import gps.api.GPSProblem; import gps.api.GPSRule; import gps.api.GPSState; import gps.sia13.model.ChainReactionBoard; import gps.sia13.model.ChainReactionCellState; import java.util.List; public class ChainReactionProblem implements GPSProblem { public GPSState getInitState() { ChainReactionBoard board = new ChainReactionBoard(2, 2); board.setCellState(0, 0, ChainReactionCellState .makeActual(ChainReactionCellState.RECTANGLE_GREEN)); board.setCellState(0, 1, ChainReactionCellState.RECTANGLE_RED); board.setCellState(1, 0, ChainReactionCellState.CIRCLE_GREEN); board.setCellState(1, 1, ChainReactionCellState.CIRCLE_RED); return board; } public GPSState getGoalState() { ChainReactionBoard board = new ChainReactionBoard(2, 2); board.setCellState(0, 0, ChainReactionCellState .makeVisited(ChainReactionCellState.RECTANGLE_GREEN)); board.setCellState(0, 1, ChainReactionCellState .makeVisited(ChainReactionCellState.RECTANGLE_RED)); board.setCellState(1, 0, ChainReactionCellState .makeVisited(ChainReactionCellState.CIRCLE_GREEN)); board.setCellState(1, 1, ChainReactionCellState .makeVisited(ChainReactionCellState.CIRCLE_RED)); return board; } public List<GPSRule> getRules() { return ChainReactionRule.getRules(); } public Integer getHValue(GPSState state) { ChainReactionBoard board = (ChainReactionBoard) state; if ( board.isComplete() ) { return 0; } else { return 1; } } } <file_sep>/tp03/src/main/java/gps/sia13/model/ChainReactionBoard.java package gps.sia13.model; import gps.api.GPSState; import gps.sia13.gui.GUI; import d.g.boardgames.Board; import d.g.boardgames.Cell; public class ChainReactionBoard extends Board<ChainReactionCellState, ChainReactionMove> implements GPSState { public ChainReactionBoard(int row, int col) { super(row, col); } public ChainReactionBoard() { super(2, 2); setCellState(0, 0, ChainReactionCellState .makeActual(ChainReactionCellState.RECTANGLE_GREEN)); setCellState(0, 1, ChainReactionCellState.RECTANGLE_RED); setCellState(1, 0, ChainReactionCellState.CIRCLE_GREEN); setCellState(1, 1, ChainReactionCellState.CIRCLE_RED); } public boolean isComplete() { for (int row = 0; row < getRowCount(); row++) { for (int col = 0; col < getColCount(); col++) { ChainReactionCellState cellState = getCellState(row, col); if ( cellState.state == ChainReactionCellState.State.NOT_VISITED ) { return false; } } } return true; } @Override public Board<ChainReactionCellState, ChainReactionMove> clone() { ChainReactionBoard ret = new ChainReactionBoard(getRowCount(), getColCount()); for (int row = 0; row < getRowCount(); row++) { for (int col = 0; col < getColCount(); col++) { ret.setCellState(row, col, getCellState(row, col)); } } return ret; } /* TODO: IMPROVE THIS */ public Cell getActualCoordinates() { for (int row = 0; row < getRowCount(); row++) { for (int col = 0; col < getColCount(); col++) { ChainReactionCellState cellState = getCellState(row, col); if ( cellState.state.equals(ChainReactionCellState.State.ACTUAL) ) return new Cell(row, col); } } return null; } public ChainReactionCellState getAdjacentState(Cell delta) { Cell adjacentCell = getAdjacentCell(delta); return getCellState(adjacentCell); } public Cell getAdjacentCell(Cell delta) { Cell coordinate = getActualCoordinates(); int a = (coordinate.getRow() + delta.getRow()) % getRowCount(); if ( a < 0 ) { a += getRowCount(); } int b = (coordinate.getCol() + delta.getCol()) % getColCount(); if ( b < 0 ) { b+= getColCount(); } return new Cell(a, b); } public boolean compare(GPSState state) { ChainReactionBoard board = (ChainReactionBoard) state; if ( board.getRowCount() != getRowCount() ) { return false; } if ( board.getColCount() != getColCount() ) { return false; } for (int row = 0; row < getRowCount(); row++) { for (int col = 0; col < getColCount(); col++) { ChainReactionCellState otherState = board.getCellState(row, col); ChainReactionCellState myState = getCellState(row, col); if ( !otherState.equals(myState) ) { return false; } } } return true; } public ChainReactionCellState getActualCellState() { return getCellState(getActualCoordinates()); } @Override public String toString() { GUI gui = GUI.getInstance(); gui.setBoard(this); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.toString(); } }<file_sep>/tp03/src/main/java/gps/sia13/model/ChainReactionCellState.java package gps.sia13.model; public class ChainReactionCellState { public static enum FigureType {RECTANGLE, CIRCLE}; public static enum Color {RED, GREEN}; public static enum State {NOT_VISITED, VISITED, ACTUAL}; public static final ChainReactionCellState RECTANGLE_RED = new ChainReactionCellState(FigureType.RECTANGLE, State.NOT_VISITED, Color.RED); public static final ChainReactionCellState RECTANGLE_GREEN = new ChainReactionCellState(FigureType.RECTANGLE, State.NOT_VISITED, Color.GREEN); public static final ChainReactionCellState CIRCLE_RED = new ChainReactionCellState(FigureType.CIRCLE, State.NOT_VISITED, Color.RED); public static final ChainReactionCellState CIRCLE_GREEN = new ChainReactionCellState(FigureType.CIRCLE, State.NOT_VISITED, Color.GREEN); public FigureType figureType; public Color color; public State state; public static ChainReactionCellState makeActual(ChainReactionCellState cellState) { return new ChainReactionCellState(cellState.figureType, State.ACTUAL, cellState.color); } public static ChainReactionCellState makeVisited( ChainReactionCellState cellState) { return new ChainReactionCellState(cellState.figureType, State.VISITED, cellState.color); } public ChainReactionCellState (FigureType figureType, State state, Color color) { this.figureType = figureType; this.state = state; this.color = color; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + ((figureType == null) ? 0 : figureType.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChainReactionCellState other = (ChainReactionCellState) obj; if (color != other.color) return false; if (figureType != other.figureType) return false; if (state != other.state) { if ( state == State.NOT_VISITED || other.state == State.NOT_VISITED) { return false; } } return true; } }<file_sep>/tp02/clean_dirs #! /bin/bash rm output/* rm output_img/* rm patterns/* rm test_patterns/* rm data/* <file_sep>/tp03/src/main/java/gps/sia13/Main.java package gps.sia13; import gps.GPSEngine; import gps.SearchStrategy; import gps.sia13.gui.GUI; import gps.sia13.problem.ChainReactionProblem; public class Main { public static void main(String[] args) { GUI.getInstance(); GPSEngine.engine(new ChainReactionProblem(), SearchStrategy.DFS); } } <file_sep>/tp03/src/main/java/gps/sia13/ChainState.java package gps.sia13; import gps.api.GPSState; public class ChainState implements GPSState { public static final ChainState INIT_STATE = new ChainState(); public static final ChainState GOAL_STATE = new ChainState(); public boolean compare(GPSState state) { return this.equals(state); } } <file_sep>/tp02/out2png.py # -*- coding: iso-8859-1 -*- import Image import sys def out2png(): name = sys.argv[1] v = [int(i.strip()) for i in open('output/'+name+".txt")] img = Image.new('RGB', (64, 64), "black") pixels = img.load() for i in xrange(img.size[1]): for j in xrange(img.size[0]): pixels[j, i] = get_value(v[i*img.size[0]+j]) #img.show() img.save('output_img/'+name+".png") def get_value(v): if v == -1: return (0,0,0) else: return (255,255,255) if __name__ == '__main__': out2png()
171e445859c4ba6e670b5ca9121e610cf3c6527b
[ "Java", "Python", "Maven POM", "Shell" ]
12
Python
Macarse/sia2011
2bc461c915d37b844bf68d8ce7c49adc00ad894a
3c9edbee25fa63a5f2732112221788b133f8a009
refs/heads/master
<file_sep>from tkinter import * from tkinter import ttk from tkinter import ttk root = Tk() root.title('title') root.geometry("400x400") def comboclick(event): msg = f"index: {myCombo.current()}, value: {myCombo.get()}" Label(root, text=msg).pack() Label(root, text=clicked.get()).pack() options = [ "red", "green", "blue", "yellow" ] clicked = StringVar(value=options[0]) Label(root, text = "what is your favorite color?").pack() myCombo = ttk.Combobox(root, value=options, textvariable = clicked) myCombo.bind("<<ComboboxSelected>>", comboclick) myCombo.pack() root.mainloop() # TODO: create a combo box that gets its values from the DB "City" table <file_sep>import tkinter as tk from tkinter.ttk import * def close_current_window_show_main(win): root.deiconify() win.destroy() def open_new_window(): root.withdraw() # global newWindow # need to be global else the new window is a local variable and cannot be closed newWindow = tk.Toplevel(root) newWindow.title("New Window") newWindow.geometry("300x200+150+300") Label(newWindow, text="This is a new window").pack() l = Label(root, text="This is the main window") Button(newWindow, text = "Go back", command = lambda : close_current_window_show_main(newWindow)).pack() root = tk.Tk() root.title('this is a title') tk.Label(root, text = "click the button").pack() tk.Button(root, text="Click Me!", command= open_new_window).pack() root.mainloop() <file_sep>from tkinter import * from tkinter import ttk root = Tk() root.title('tabs') tabControl = ttk.Notebook(root, width = 1000, height = 500) tabControl.pack() def show(): tabControl.add(my_frame2, text="Red Tab") my_frame1 = Frame(tabControl, bg="blue") my_frame2 = Frame(tabControl, bg="red") tabControl.add(my_frame1, text="Blue Tab") tabControl.add(my_frame2, text="Red Tab") # Hide a tab Button(my_frame1, text="Hide Tab 2", command=lambda: tabControl.hide(my_frame2)).pack(pady=10) # Show a tab # Button(my_frame1, text="Show Tab 2", command=show).pack(pady=10) # Navigate to a tab # Button(my_frame1, text="Navigate To Tab 2", command=lambda: tabControl.select(1)).pack(pady=10) Label(my_frame2, text = "this is a label").pack() root.mainloop() <file_sep>from tkinter import * def xyz(username, password): if username == "Rotem" and password == "123": for child in tkWindow.winfo_children(): child.destroy() Label(tkWindow, text = "Hello Rotem").grid(row=0, column=0, pady = 20, padx = 20 ) #window tkWindow = Tk() tkWindow.title('Tkinter Login Form') tkWindow.geometry("+300+300") data = { 'user': StringVar(), 'pass': StringVar() } #username label and text entry box Label(tkWindow, text="User Name").grid(row=0, column=0) Entry(tkWindow, textvariable = data['user']).grid(row=0, column=1) #password label and password entry box Label(tkWindow,text="Password").grid(row=1, column=0) Entry(tkWindow, show='*', textvariable = data['pass']).grid(row=1, column=1) #login button login_Button = Button(tkWindow, text="Login", command=lambda: xyz(data['user'].get(), data['pass'].get())) login_Button.grid(row=4, column=0, columnspan = 2) tkWindow.mainloop()<file_sep>import tkinter as tk # 1. create window root = tk.Tk() root.title('this is a title') root.geometry("500x450") # 2. add content # 2.1 Creating a Label Widget myLabel = tk.Label(root, text="Hello World!") myLabel2 = tk.Label(root, text="label2") """ ----- text color, font and size ----- """ myLabel['fg']="red" myLabel['font']=("ariel", 18) # (font, font_size) """ ----- background color ----- """ # myLabel['bg']="black" """ ----- size ----- """ # myLabel['height']= 10 # myLabel['width']= 100 # # myLabel["text"] = "other text" # set new text # 2.2 put it onto the screen # myLabel.pack() # myLabel.pack(anchor = "w") # myLabel.pack(anchor = "e") """ ----- padding ----- """ myLabel.pack(pady = 50, padx = 100) myLabel2.pack() # 3. run window root.mainloop() # clicking on the X closes the window and ends the program <file_sep>from tkinter import * from tkinter import ttk import mysql.connector conn_gooly = mysql.connector.connect(host="localhost", user="root", password="<PASSWORD>", database="Gooly") cursor = conn_gooly.cursor() """========== funtions ==========""" def get_data_from_DB(cur, columns_list=[]): if len(columns_list) > 0: columns = ", ".join(columns_list) cur.execute(f'SELECT {columns} FROM gooly.sadnaot;') ans = cur.fetchall() return ans def add_row(row): my_table.insert(parent='', index='end', values=row) def populate_table(cur, columns_list=[]): data = get_data_from_DB(cur, columns_list) for row in data: add_row(row) def populate_entries_with_selected_row(event): # print(event) values = my_table.item(my_table.focus(), 'values') # turn values (list) to dictionary {col_name: value) ans = {my_table['columns'][i]: val for i, val in enumerate(values)} ans = {} for i, val in enumerate(values): key = my_table['columns'][i] ans[key]= val for col in ans.keys(): selected_sadna[col].set(ans[col]) """========================================""" root = Tk() root.title('Title') my_table = ttk.Treeview(root, columns=["sadna_id", "name", "description", "duration", "base_cost", "base_price"]) # Formate Our Columns + Create Headings my_table.column("#0", width=0, stretch=NO) my_table.heading("#0", text="", anchor=CENTER) for col in my_table['columns']: my_table.column(col, anchor=CENTER, minwidth=10, stretch=YES) my_table.heading(col, text=col, anchor=CENTER) populate_table(cursor, my_table['columns']) selected_sadna = {"sadna_id": StringVar(), "name": StringVar(), "description":StringVar(), "duration": StringVar(), "base_cost": StringVar(), "base_price": StringVar() } # ----------- set text entry ----------- entry_frame = LabelFrame(root, padx=10, pady=10, text="Row Frame") entry_frame.pack(pady=20) for i, (col, var) in enumerate(selected_sadna.items()): Label(entry_frame, text=col).grid(row=0, column=i) if col == 'sadna_id': Label(entry_frame, textvariable = var, width=20, justify='center').grid(row = 1, column = i) else: Entry(entry_frame, textvariable = var, width=20, justify='center').grid(row = 1, column = i) my_table.bind("<<TreeviewSelect>>", populate_entries_with_selected_row) my_table.pack() root.mainloop() # TODO: change the table to select data from customers <file_sep>from tkinter import * from tkinter import ttk root = Tk() root.title('title') root.geometry("400x400") def show_order(): top_text = "" for top in toppings.values(): if top.get() != "": top_text += top.get() +", " text = f"{pizza_size.get()}\n{top_text}" Label(root, text = text).pack(pady = 5) orders = [child_obj for child_name, child_obj in root.children.items() if 'label' in child_name.lower()] if len(orders) > 3: for ord in orders: ord.destroy() pizza_size_options = ["Small", "Medium", "Large"] pizza_size = StringVar(value=pizza_size_options[0]) # pizza_size = StringVar() for pz in pizza_size_options: Radiobutton(root, text=pz, variable=pizza_size, value=pz).pack(anchor=W, pady= 5) Label(root, name = "top", text = "Topping").pack() toppings = { 'Pepperoni': StringVar(), 'Cheese': StringVar(), 'Mushroom': StringVar(), 'Onion' : StringVar() } for top_name, top_var in toppings.items(): Checkbutton(root, text=top_name, variable=top_var, onvalue=top_name, offvalue="").pack(anchor=W) Button(root, text="show order", command = show_order).pack() root.mainloop()<file_sep>from tkinter import * from tkinter import ttk def add_row(row): my_table.insert(parent='', index='end', values=row) def populate_entries_with_selected_row(event): # print(event) row_index = my_table.focus() values = my_table.item(row_index, 'values') selected_row['id'].set(values[0]) selected_row['name'].set(values[1]) selected_row['last_name'].set(values[2]) selected_row['ice_cream'].set(values[3]) # for i, var in enumerate(selected_row.values()): # var.set(values[i]) root = Tk() root.title('Title') root.geometry("700x400") my_table = ttk.Treeview(root) my_table['columns'] = ["id", "name", "last_name", 'ice_cream'] # Formate Our Columns my_table.column("#0", width=0, stretch=NO) my_table.column("id", anchor=CENTER, width=10) my_table.column("name", anchor=CENTER, width=140) my_table.column("last_name", anchor=CENTER, width=140) my_table.column("ice_cream", anchor=CENTER, width=140) # Create Headings my_table.heading("#0", text="", anchor=CENTER) my_table.heading("id", text="ID", anchor=CENTER) my_table.heading("name", text="Name", anchor=CENTER) my_table.heading("last_name", text="Last Name", anchor=CENTER) my_table.heading("ice_cream", text="Favorite Ice Cream", anchor=CENTER) """============================ Data ============================""" data = [(1,"ישראל", "רוזן", "Coffee"), (2,"Dima", "Omberg", "Choco Chips"), (3,"Shlomo", "Artzi", "banana"), (4,"Arik", "Einstein", "Strawberry"), ] selected_row = { 'id': StringVar(), 'name': StringVar(), 'last_name': StringVar(), 'ice_cream':StringVar() } for row in data: add_row(row) # ----------- set text entry ----------- entry_frame = LabelFrame(root, padx=10, pady=10, text = "Row Frame") entry_frame.pack(pady=20) for i, (col, var) in enumerate(selected_row.items()): Label(entry_frame, text=col).grid(row=0, column=i) Entry(entry_frame, textvariable = var, width=20, justify='center').grid(row = 1, column = i) my_table.bind("<<TreeviewSelect>>", populate_entries_with_selected_row) my_table.pack() root.mainloop() <file_sep>from tkinter import * root = Tk() root.title('title') TOPPINGS = ['Pepperoni', 'Cheese', 'Mushroom', 'Onion'] pizza = StringVar() pizza.set(TOPPINGS[0]) for text in TOPPINGS: # Radiobutton(root, text=text, variable=pizza, value=text, command = lambda: clicked(pizza.get())).pack(anchor=W, pady= 5) Radiobutton(root, text=text, variable=pizza, value=text).pack(anchor=W, pady= 5) def clicked(value): Label(root, text=value).pack() myButton = Button(root, text="Add Pizza Topping", command=lambda: clicked(pizza.get())) myButton.pack(pady=20) mainloop() #TODO: create a pizza menu: # Radiobox to select size of pizza: small, medium, large # check boxes for the topping # button will display the order in a new label<file_sep>from tkinter import * root = Tk() root.geometry("100x100") my_name = StringVar() # my_name.set("Dima") Entry(root, width=20, textvariable = my_name).pack() Label(root, textvariable = my_name).pack() Button(root, text = 'remove text', command = lambda: my_name.set("")).pack() #TODO: login form with string vars root.mainloop() <file_sep>import tkinter as tk def myClick(txt, color): tk.Label(root, text=txt, fg = color).pack() root = tk.Tk() root.title('this is a title') root.geometry("300x500") tk.Button(root, text="red", command=lambda: myClick("hello", "red")).pack() tk.Button(root, text="yellow", command=lambda: myClick("hello","yellow")).pack() tk.Button(root, text="green", command=lambda: myClick("hello", "green")).pack() tk.Button(root, text="blue", command=lambda: myClick("hello", "blue")).pack() root.mainloop() <file_sep>from tkinter import * root = Tk() root.title('title') root.geometry("400x400") def show(): text = want_pizza.get() + " " + size.get() Label(root, text=text).pack() want_pizza = StringVar() size = StringVar() pizza_check = Checkbutton(root, text="Want a pizza?", variable=want_pizza, onvalue="Yes :)", offvalue="No :(" , command=show) size_check = Checkbutton(root, text="Big?", variable=size, onvalue="Big", offvalue="Small" ,command=show) pizza_check.deselect() pizza_check.pack() size_check.deselect() size_check.pack() # c.pack(pady = 20, padx = 20) myButton = Button(root, text="Show Selection", command=show).pack() root.mainloop() <file_sep>import tkinter as tk # tk.TkVersion # 1. create window root = tk.Tk() root.title('this is a title') """---- set window_size + location ----""" root.geometry("500x100") # .geometry("widthxheight") # root.geometry("500x100+300+300") # .geometry("window width x window height + position right + position down") """---- set max\min window size ----""" root.maxsize(width = 500, height=200) root.minsize(width = 100, height=10) """---- set max\min window size ----""" root.resizable(width=False, height=True) """---- set window background color ----""" # root.configure(bg='blue') # bg = background_color # root['bg']='green' root['background']='yellow' # root['background']='#856ff8' # Using HEX code for background color root['cursor'] = "pirate" # arrow \ pirate \ mouse """ ====================== content goes here ====================== """ # 2. run window tk.mainloop() # clicking on the X closes the window and ends the program <file_sep>from tkinter import * root = Tk() root.title('title') frame1 = LabelFrame(root, padx=50, pady=50, text ="im a label") frame1.pack(padx=10, pady=10) frame2 = LabelFrame(root, padx=50, pady=50) frame2.pack(padx=10, pady=10) Button(frame1, text="Don't Click Here!").pack() Label(frame1, text="im in the frame!").pack() Label(root, text="im NOT in the frame!").pack() Label(frame2, text="im in the OTHER frame!").pack() root.mainloop() <file_sep>from tkinter import * root = Tk() root.geometry("300x100") e = Entry(root, width=20) e.pack() def myClick(): Label(root, text = e.get()).pack() main_label['text'] = e.get() e.delete(0, 'end') Button(root, text="Say Hello", command=myClick).pack() main_label = Label(root) main_label.pack() root.mainloop() <file_sep>from tkinter import * root = Tk() root.title('title') root.geometry("400x400") def show(): text = var.get() Label(root, text=text).pack() var = StringVar() c = Checkbutton(root, text="Want a pizza?", variable=var, onvalue="Yes :)", offvalue="No :(", # bg = 'yellow', # selectcolor = 'red', # font = 20, # state=DISABLED, # pady = 20, padx = 20, command = lambda : show()) c.deselect() # without it the check box starts as selected by default c.pack() # c.pack(pady = 20, padx = 20) myButton = Button(root, text="Show Selection", command=show).pack() root.mainloop() #TODO: add another checkbox and every time one of the check boxes will be checked both string's values will be shown<file_sep>from tkinter import * from tkinter import ttk root = Tk() root.title('Title') # root.geometry("700x400") def set_table(columns): table = ttk.Treeview(root, columns = columns) # Formate Our Columns table.column("#0", width=0, stretch=NO) table.heading("#0", text="", anchor=CENTER) for col in columns: table.column(col, anchor=CENTER, width=140) # Create Headings table.heading(col, text=col, anchor=CENTER) table.column("ID", anchor=CENTER, width=10) return table my_table = set_table(["ID", "Name", "Last Name", 'Favorite Ice Cream']) data = [(1,"ישראל", "רוזן", "Coffee"), (2,"Dima", "Omberg", "Choco Chips"), (3,"Shlomo", "Artzi", "banana"), (4,"Arik", "Einstein", "Strawberry"), ] def add_row(row): my_table.insert(parent='', index='end', values=row) for row in data: add_row(row) selected_row = { 'id': StringVar(), 'name': StringVar(), 'last_name': StringVar(), 'ice_cream': StringVar() } # ----------- set text entry ----------- entry_frame = LabelFrame(root, padx=10, pady=10, text = "Row Frame") entry_frame.pack(pady=20) for i, (col, var) in enumerate(selected_row.items()): Label(entry_frame, text=col).grid(row=0, column=i) Entry(entry_frame, textvariable = var, width=20, justify='center').grid(row = 1, column = i) def clear_entries(): for var in selected_row.values(): var.set('') def populate_entries_with_selected_row(event): # print(event) values = my_table.item(my_table.focus(), 'values') # print(values) for i, var in enumerate(selected_row.values()): var.set(values[i]) def add_new_row(): new_row = [var.get() for var in selected_row.values()] add_row(new_row) clear_entries() def update_selcted_row(): selected_row_index = my_table.focus() # index values_from_dict = [var.get() for var in selected_row.values()] my_table.item(selected_row_index, values=values_from_dict) def delete_selected_rows(): clear_entries() for record in my_table.selection(): my_table.delete(record) my_table.bind("<<TreeviewSelect>>", populate_entries_with_selected_row) my_table.pack() # ----------- buttons ----------- button_frame = LabelFrame(root, padx=10, pady=10, text = "Buttons Frame") button_frame.pack(pady=20) clear_btn = Button(button_frame, text = 'Clear Entry', comman = clear_entries) clear_btn.grid(row = 0, column = 0, padx= 5) add_new_row_btn = Button(button_frame, text = 'Add New', comman = add_new_row) add_new_row_btn.grid(row = 0, column = 1, padx= 5) update_row_btn = Button(button_frame, text = 'Update', comman = update_selcted_row) update_row_btn.grid(row = 0, column = 2, padx= 5) delete_rows_btn = Button(button_frame, text = 'Delete', comman = delete_selected_rows) delete_rows_btn.grid(row = 0, column = 3, padx= 5) root.mainloop() <file_sep>from tkinter import * from tkinter import ttk root = Tk() root.title('title') root.geometry("400x400") clicked = StringVar() Label(root, text = "what is your favorite color?").pack() myCombo = ttk.Combobox(root, value=["red","green","blue","yellow"], textvariable = clicked, # state="readonly", state="disabled" ) # myCombo.current(0) myCombo.pack() Label(root, textvariable = clicked).pack() root.mainloop()<file_sep>from tkinter import * from tkinter import ttk import mysql.connector import os import sys mysql.connector.__version__ def get_city_data(): conn = mysql.connector.connect(host="localhost", user="root", password="<PASSWORD>", database="gooly") cur = conn.cursor() sql = "select * from city;" cur.execute(sql) ans = [_[0] for _ in cur.fetchall()] return ans root = Tk() root.title('title') root.geometry("400x400") cities = get_city_data() clicked = StringVar(value = cities[0]) myCombo = ttk.Combobox(root, value=cities, textvariable=clicked, state="readonly") myCombo.pack() Label(root, textvariable=clicked).pack() root.mainloop() <file_sep>import tkinter as tk import random as rnd def myClick(txt): color = rnd.choice(['red', 'black', 'green', 'blue']) tk.Label(root, text=txt, fg = color).pack() root = tk.Tk() root.title('this is a title') tk.Button(root, text="Click Me!", command=lambda: myClick("hello")).pack() # TODO: add a function that receives color + text and outputs a label with color and text. # TODO: add 4 buttons when each calls the function with different params root.mainloop() <file_sep>import tkinter as tk from tkinter.ttk import * def open_new_window(): newWindow = tk.Toplevel(root) newWindow.title("New Window") newWindow.geometry("200x200") Label(newWindow, text="This is a new window").pack() l = Label(root, text="This is the main window") root = tk.Tk() root.title('this is a title') tk.Button(root, text="Click Me!", command= open_new_window).pack() root.mainloop() <file_sep>from tkinter import * root = Tk() # root.geometry("100x100") e = Entry(root, width=20) e.pack() e.insert(0, "name: ") def myClick(): hello = "Hello " + e.get() myLabel = Label(root, text=hello) e.delete(0, 'end') myLabel.pack() Button(root, text="Say Hello", command= lambda: myClick() ).pack() Button(root, text="remove entry", command=e.destroy).pack() #TODO: 1. add button that changes text in the same Label #TODO: 2. add button that changes text in the same Label and adds another label root.mainloop() <file_sep>import tkinter as tk import random as rnd root = tk.Tk() root.title('this is a title') myButton = tk.Button(root, text="i dont do anything") """--------- activeforeground \ activeforeground ---------""" myButton.config(activeforeground= 'yellow') myButton.config(activebackground= 'blue') """ ---- state ---- """ # myButton['state'] = tk.DISABLED # myButton['state'] = tk.ACTIVE """--------- size ---------""" myButton['width'] = 100 myButton['height'] = 10 myButton.pack() """============= button with command ================""" tk.Button(root, text="i print Hello!", command=lambda: print("hello")).pack() tk.mainloop() <file_sep>import tkinter as tk from tkinter.messagebox import * root = tk.Tk() root.title('title') def popup(): # response = showinfo(title="this is title", message="this is msg") response = showwarning(title="this is title", message="this is msg") # response = askquestion(title="this is title", message="this is msg") response = askokcancel(title="this is title", message="this is msg") # response = askyesno(title="this is title", message="this is msg") response = askyesnocancel(title="this is title", message="this is msg") tk.Button(root, text='show pop up', command= popup).pack() tk.mainloop() <file_sep>from tkinter import * def login_Dima(username, password): if username == "Dima" and password == "123": # usernameLabel.destroy() # usernameEntry.destroy() # passwordLabel.destroy() # passwordEntry.destroy() # login_Button.destroy() # we can do it with this function also for child in tkWindow.winfo_children(): child.destroy() Label(tkWindow, text = "Hello Dima").grid(row=0, column=0, pady = 20, padx = 20 ) #window tkWindow = Tk() tkWindow.title('Tkinter Login Form') tkWindow.geometry("+300+300") #username label and text entry box usernameLabel = Label(tkWindow, text="User Name") usernameLabel.grid(row=0, column=0) usernameEntry = Entry(tkWindow) usernameEntry.grid(row=0, column=1) #password label and password entry box passwordLabel = Label(tkWindow,text="Password") passwordLabel.grid(row=1, column=0) passwordEntry = Entry(tkWindow, show='*') passwordEntry.grid(row=1, column=1) #login button login_Button = Button(tkWindow, text="Login", command=lambda: login_Dima(usernameEntry.get(), passwordEntry.get())) # login_Button = Button(tkWindow, text="Login", command=login_Dima) login_Button.grid(row=4, column=0, columnspan = 2) tkWindow.mainloop()<file_sep>import tkinter as tk # tk.TkVersion # 1. create window root = tk.Tk() """ ====================== content goes here ====================== """ # 2. run window tk.mainloop() # clicking on the X closes the window and ends the program <file_sep>from tkinter import * root = Tk() root.title('title') frame1 = LabelFrame(root, padx=50, pady=50, text ="im a label") frame1.grid(column = 0, row= 0, padx=10, pady=10) frame2 = LabelFrame(root, padx=50, pady=50) frame2.grid(column = 1, row= 0, padx=10, pady=10) Button(frame1, text="Don't Click Here!").pack() Label(frame1, text="im in the frame!").pack() Label(frame2, text="im in the OTHER frame!").pack() Label(root, text="im NOT in the frame!").grid(column = 0, row= 1, columnspan = 2, padx=10, pady=10) root.mainloop() <file_sep>from tkinter import * def Login(username, password): print("username entered :", username) print("password entered :", password) #window tkWindow = Tk() tkWindow.title('Tkinter Login Form') # tkWindow.geometry("500x100+300+300") #username label and text entry box usernameLabel = Label(tkWindow, text="<NAME>") usernameLabel.grid(row=0, column=0) usernameEntry = Entry(tkWindow) usernameEntry.grid(row=0, column=1) #password label and password entry box passwordLabel = Label(tkWindow,text="<PASSWORD>") passwordLabel.grid(row=1, column=0) passwordEntry = Entry(tkWindow, show='*') passwordEntry.grid(row=1, column=1) #login button login_Button = Button(tkWindow, text="Login", command=lambda: Login(usernameEntry.get(), passwordEntry.get())) login_Button.grid(row=2, column=0, columnspan = 2) # TODO: add function that if the user_name == YOUR_NAME and password == 123 then delete everything on the screen and add "Hello YOUR_NAME" Label tkWindow.mainloop()<file_sep>from tkinter import * from tkinter import ttk root = Tk() root.title('tabs') tabControl = ttk.Notebook(root, width = 1000, height = 500) tabControl.pack() sadnaot_tab = Frame(tabControl) customers_tab = Frame(tabControl) orders_tab = Frame(tabControl) tabControl.add(sadnaot_tab, text="tab1") tabControl.add(customers_tab, text="tab2") tabControl.add(orders_tab, text="tab3") Label(sadnaot_tab, text = "this is the first tab").pack(pady=20) Entry(sadnaot_tab).pack() Label(customers_tab, text = "this is the second tab").pack(pady=20) Label(orders_tab, text = "this is the third tab").pack(pady=20) # with function def put_inside_tab(tab): Label(tab, text = "this is a label1 from function").pack() Label(tab, text = "this is a label2 from function").pack() Label(tab, text = "this is a label3 from function").pack() Label(tab, text = "this is a label4 from function").pack() put_inside_tab(orders_tab) put_inside_tab(sadnaot_tab) put_inside_tab(sadnaot_tab) root.mainloop() <file_sep>from tkinter import * root = Tk() # root.geometry("200x100") e = Entry(root) """-------- size --------""" e.config(width = 100) e.config(font = 100) e.config(bd = 5) # border """-------- color --------""" # e.config(fg = "red") # e.config(bg = "yellow") """-------- state --------""" # e.config(state = DISABLED) """-------- password mode --------""" # e.config(show="*") e.pack() # e.pack(pady = 100, padx = 50) e.insert(0, "name: ") root.mainloop()
6a4326f294dda8fc320d0058efa56b08aaef7049
[ "Python" ]
30
Python
DimaOmb/Tkinter_Lecture
a59e1932f21553f90b05823904aa7505759041a7
620aff056c416ee3b1aa372f9a5ebaf287e6c4bc
refs/heads/master
<file_sep>''' Setup of Python virtualenv sandboxes via virtualenvwrapper. ===================================== ''' # Import python libs import logging import os logger = logging.getLogger(__name__) # pylint: disable-msg=C0103 def _venv_data(name, runas): # run a dummy/useless operation to ensure the virtualenvwrapper is initialised for the first time __salt__['cmd.run']('/bin/bash -lc "ls"', runas=runas) venv = venv_py = '' # determine if the virtualenv exists or not by trying to activate it. venv_exists = __salt__['cmd.run']('/bin/bash -lc "workon {0}"'.format(name), runas=runas) # if the result from the above is blank, we're good to go. venv_exists = venv_exists == '' if venv_exists: # get the path to the virtualenv venv = __salt__['cmd.run']('/bin/bash -lc "workon {0}; cdvirtualenv; pwd"'.format(name), runas=runas) # get the python binary in the virtualenv venv_py = os.path.join(venv, 'bin', 'python') return venv_exists, venv, venv_py def managed(name, requirements='', no_site_packages=False, system_site_packages=False, distribute=False, no_pip=False, no_setuptools=False, setuptools=False, clear=False, python='', unzip_setuptools=False, relocatable=False, extra_search_dir='', never_download=False, prompt='', __env__='base', runas=None, cwd=None, index_url=None, extra_index_url=None, add_path=''): ''' Create a virtualenv and optionally manage it with pip name Name of the virtualenv requirements Path to a pip requirements file. If the path begins with ``salt://`` the file will be transferred from the master file server. cwd Path to the working directory where "pip install" is executed. add_path project path to associate with the current virtualenv Also accepts any kwargs that the virtualenv module will. .. code-block:: yaml myvirtualenv.com: virtualenvwrapper.managed: - no_site_packages: True - requirements: salt://REQUIREMENTS.txt ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if 'virtualenvwrapper.mkvirtualenv' not in __salt__ or 'virtualenv.create' not in __salt__: ret['result'] = False ret['comment'] = 'virtualenvwrapper and/or virtualenv not detected on this system' return ret venv_exists, venv, venv_py = _venv_data(name, runas) # Bail out early if the specified requirements file can't be found if requirements and requirements.startswith('salt://'): cached_requirements = __salt__['cp.is_cached'](requirements, __env__) if not cached_requirements: # It's not cached, let's cache it. cached_requirements = __salt__['cp.cache_file'](requirements, __env__) # Check if the master version has changed. if __salt__['cp.hash_file'](requirements, __env__) != \ __salt__['cp.hash_file'](cached_requirements, __env__): cached_requirements = __salt__['cp.cache_file'](requirements, __env__) if not cached_requirements: ret.update({ 'result': False, 'comment': "pip requirements file '{0}' not found".format( requirements ) }) return ret # If it already exists, grab the version for posterity if venv_exists and clear: ret['changes']['cleared_packages'] = \ __salt__['pip.freeze'](bin_env=venv) ret['changes']['old'] = \ __salt__['cmd.run_stderr']('{0} -V'.format(venv_py), runas=runas).strip('\n') # Create (or clear) the virtualenv if __opts__['test']: if venv_exists and clear: ret['result'] = None ret['comment'] = 'Virtualenv {0} is set to be cleared'.format(name) return ret if venv_exists and not clear: #ret['result'] = None ret['comment'] = 'Virtualenv {0} is already created'.format(name) return ret ret['result'] = None ret['comment'] = 'Virtualenv {0} is set to be created'.format(name) return ret if not venv_exists or (venv_exists and clear): _ret = __salt__['virtualenvwrapper.mkvirtualenv'](name, no_site_packages=no_site_packages, system_site_packages=system_site_packages, distribute=distribute, no_pip=no_pip, no_setuptools=no_setuptools, setuptools=setuptools, clear=clear, python=python, unzip_setuptools=unzip_setuptools, relocatable=relocatable, extra_search_dir=extra_search_dir, never_download=never_download, prompt=prompt, runas=runas) if add_path: __salt__['virtualenvwrapper.add2virtualenv'](name, add_path, runas=runas) # update things now... if virtualenv was created, these should # be populated venv_exists_now, venv, venv_py = _venv_data(name, runas) ret['result'] = _ret['retcode'] == 0 ret['changes']['new'] = __salt__['cmd.run_stderr']( '{0} -V'.format(venv_py), runas=runas).strip('\n') ret['comment'] = "Created new virtualenv" elif venv_exists: ret['comment'] = "virtualenv exists" # Populate the venv via a requirements file if requirements: before = set(__salt__['pip.freeze'](bin_env=venv)) _ret = __salt__['pip.install']( requirements=requirements, bin_env=venv, runas=runas, cwd=cwd, index_url=index_url, extra_index_url=extra_index_url, __env__=__env__ ) ret['result'] &= _ret['retcode'] == 0 if _ret['retcode'] > 0: ret['comment'] = '{0}\n{1}\n{2}'.format(ret['comment'], _ret['stdout'], _ret['stderr']) after = set(__salt__['pip.freeze'](bin_env=venv)) new = list(after - before) old = list(before - after) if new or old: ret['changes']['packages'] = { 'new': new if new else '', 'old': old if old else ''} return ret def add_path(name, venv, runas=None): ''' Add a path to a virtualenvwrapper-managed virtualenv name path to associate with the current virtualenv venv Name of the virtualenv .. code-block:: yaml myvirtualenv.com: virtualenvwrapper.managed: - no_site_packages: True - requirements: salt://REQUIREMENTS.txt ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if 'virtualenvwrapper.add2virtualenv' not in __salt__: ret['result'] = False ret['comment'] = 'virtualenvwrapper not detected on this system' return ret _ret = __salt__['virtualenvwrapper.add2virtualenv'](venv, name, runas=runas) ret['result'] = _ret['retcode'] == 0 ret['comment'] = "added path to virtualenv" return ret manage = managed # pylint: disable-msg=C0103<file_sep>###Overview This repo is meant to be used as a git submodule. See [this repo](https://github.com/jaddison/vagrant-salt-demo) for an example using it as a submodule. <file_sep>''' Create virtualenv environments using virtualenvwrapper ''' # Import python libs from salt import utils __opts__ = {} __pillar__ = {} def mkvirtualenv(env_name, no_site_packages=False, system_site_packages=False, distribute=False, no_pip=False, no_setuptools=False, setuptools=False, clear=False, python='', unzip_setuptools=False, relocatable=False, extra_search_dir='', never_download=False, prompt='', runas=None): ''' Create a virtualenv using virtualenvwrapper env_name The virtualenv name to create in $WORKON_HOME if set or ~/.virtualenvs no_site_packages : False Passthrough argument given to virtualenv system_site_packages : False Passthrough argument given to virtualenv distribute : False Passthrough argument given to virtualenv no_pip : False Passthrough argument given to virtualenv no_setuptools: False Passthrough argument given to virtualenv setuptools : False Passthrough argument given to virtualenv clear : False Passthrough argument given to virtualenv python : (default) Passthrough argument given to virtualenv unzip_setuptools: False Passthrough argument given to virtualenv relocatable: False Passthrough argument given to virtualenv extra_search_dir : (default) Passthrough argument given to virtualenv never_download : (default) Passthrough argument given to virtualenv prompt : (default) Passthrough argument given to virtualenv runas : None Set ownership for the virtualenv CLI Example:: salt '*' virtualenvwrapper.mkvirtualenv my_env ''' # if env_name is None: # env_name = __opts__.get('env_name') or __pillar__.get('env_name') # # raise CommandNotFoundError if venv_bin is missing # utils.check_or_die(env_name) cmd = '/bin/bash -lc "mkvirtualenv {args} {env_name}"'.format( args=''.join([ ' --no-site-packages' if no_site_packages else '', ' --system-site-packages' if system_site_packages else '', ' --distribute' if distribute else '', ' --no-pip' if no_pip else '', ' --no-setuptools' if no_setuptools else '', ' --setuptools' if setuptools else '', ' --clear' if clear else '', ' --python {0}'.format(python) if python else '', ' --unzip_setuptools' if unzip_setuptools else '', ' --relocatable' if relocatable else '', ' --extra-search-dir {0}'.format(extra_search_dir ) if extra_search_dir else '', ' --never-download' if never_download else '', ' --prompt {0}'.format(prompt) if prompt else '']), env_name=env_name) return __salt__['cmd.run_all'](cmd, runas=runas) def add2virtualenv(env_name, path='', runas=None): ''' Create a virtualenv using virtualenvwrapper env_name The virtualenv name to create in $WORKON_HOME if set or ~/.virtualenvs runas : None Set ownership for the virtualenv CLI Example:: salt '*' virtualenvwrapper.add2virtualenv my_env /projects/proj1 ''' # determine if the path has already been added to the virtualenv; by not # passing the path in, add2virtualenv returns a list of the current # paths for the virtualenv cmd = '/bin/bash -lc "workon {env_name}; add2virtualenv"'.format( env_name=env_name) tmp = __salt__['cmd.run'](cmd, runas=runas).split('Existing paths:') exists = False if len(tmp) > 1: for line in tmp[1].split('\n'): if line == path.rstrip('/'): exists = True break if not exists: cmd = '/bin/bash -lc "workon {env_name}; add2virtualenv {path}"'.format( env_name=env_name, path=path) else: cmd = '/bin/bash -lc "workon {env_name}"'.format( env_name=env_name) return __salt__['cmd.run_all'](cmd, runas=runas) <file_sep>__author__ = 'jaddison'
fc68536c01e08205c0351b91da87cf0573a4c420
[ "Markdown", "Python" ]
4
Python
jaddison/salt-base-states
e020f431e64f05a329246a4444e2bfdf0382a95d
675ccee0f8360fb3263374141914787b9f7f14b8
refs/heads/main
<file_sep>import { PokeApiSearchPokemonResultType } from '../types/PokeApi'; const pokeApiUrl: string = 'https://pokeapi.co/api/v2'; export async function getPokemonById(pokemonId: number|string) : Promise<PokeApiSearchPokemonResultType> { let url: string = `${pokeApiUrl}/pokemon/${pokemonId}`; let response = await fetch(url); return await response.json(); } <file_sep>export type PokeApiSearchPokemonResultType = { id: number; name: string; sprites: PokemonSprite; stats: Array<PokemonStat>; types: Array<PokemonType> } export type PokemonStat = { base_stat: number; effort: number; stat: Stat; } export type PokemonType = { slot: number; type: Type; } type PokemonSprite = { front_default: string; back_default: string; } type Stat = { name: string; } type Type = { name: string; } <file_sep># Pokedex React ![build](https://github.com/AkeUS/pokedex-react/workflows/build/badge.svg?branch=main) Aplicación construida con ReactJS, haciendo uso de hooks y typescript. [Pokedex React](https://pokedex-react.akeus.vercel.app) ## Ejecutar con NodeJs Clonar el proyecto y ejecutar los siguientes comandos Descargar dependencias ```shell npm install ``` Ejecutar aplicación ```shell npm start ``` ## Ejecutar con Docker ```shell docker run -d -p 3000:80 akeus/pokedex-react ``` Abrir un navegador e ingresar a http://localhost:3000 <file_sep>FROM node:15.2-alpine AS build WORKDIR /app COPY . . RUN npm install \ && npm run build FROM nginx:1.19-alpine AS release WORKDIR /usr/share/nginx/html COPY --from=build /app/build/. .
4f8e6c73438266afd66418a7c2556a251264830a
[ "Markdown", "TypeScript", "Dockerfile" ]
4
TypeScript
AkeUs/pokedex-react
5475a43acc64e5d21c90122af1c6a8d7e971e5b7
a68029fa6d0fc0436de4a52edfca435fb67c477f
refs/heads/master
<file_sep>import _ from 'lodash'; import { FETCH_POSTS,FETCH_POST, DELETE_POST } from '../actions'; export default function(state = {},action){ switch(action.type){ case DELETE_POST: return _.omit(state,action.payload); case FETCH_POST: // const post = action.payload.data; // const newState = { ...state }; // newState[post.id] = post; // return newState; ES5 WAY return { ...state, [action.payload.data.id] : action.payload.data }; //we are not creating array we are doing key interpolation case FETCH_POSTS: console.log(action.payload.data); // [post1,post2] (an array) // we need an object this way {id1:{},id2:{}}, so we access easily the data without loops // lodash provides this library to transform the object return _.mapKeys(action.payload.data,'id'); //transformed object default: return state; } }<file_sep># BLOG POSTS ON REDUX, HANDLING OF FORMS. Subjects: Validations of Forms with redux, Touched property on forms Show class on touched state. ES6 ### Getting Started ``` > npm install > npm start ```
26ce1e5605d71d206e32e37c0060bf8a933f5766
[ "JavaScript", "Markdown" ]
2
JavaScript
rafaalb/BlogsReact
573828147705684e8f6b1fdc29674192f2f3745c
448ba7f45acfce752c9aae1db86abd78e6157005
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceProgramm { class TextUser { } } <file_sep>using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Net; using System.Diagnostics; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Windows.Forms; using System.Management; using System.Media; using System.Xml; using System.ComponentModel; using System.Data.Sql; using MySql.Data.MySqlClient; namespace ServiceProgramm { public partial class Form2 : MetroFramework.Forms.MetroForm { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { } public string loggeduser { get { return metroLabel1.Text; } set { metroLabel1.Text = "Вы вошли как : " + value; } } private void Label1_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Net; using System.Diagnostics; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Windows.Forms; using System.Management; using System.Media; using System.Xml; using System.ComponentModel; using System.Data.Sql; using MySql.Data.MySqlClient; namespace ServiceProgramm { public partial class Form1 : MetroFramework.Forms.MetroForm { int i = 10;//значение счетчика переподключения private bool botimer = false;//отключает формы ввода и кнопку авторизации string Connect = "server=localhost;user id=mysql;password=<PASSWORD>;persistsecurityinfo=True;database=main";//данные от базы данных public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { timer1.Interval = 1; timer1.Tick += new EventHandler(OnTimer); timer1.Enabled = true; timer2.Interval = 1000; timer2.Tick += new EventHandler(OnTimer2); timer2.Enabled = false; } private void OnTimer(object sender, EventArgs e) { try { //Задаем команду string CommandText = "SELECT Count(*) FROM checkConnection WHERE connection = 1"; MySqlConnection myConnection = new MySqlConnection(Connect); //выполняем команду MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection); //открытие подключения myConnection.Open(); myCommand.ExecuteNonQuery(); MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myCommand); DataTable dt = new DataTable(); dataAdapter.Fill(dt); if (dt.Rows[0][0].ToString() == "1") // сверка значений { timer1.Interval = 10000; label1.ForeColor = Color.Green; label1.Text = "соединение установлено"; label3.Enabled = false; label3.Visible = false; botimer = false; timer2.Enabled = false; } else { timer1.Interval = 10000; label2.ForeColor = Color.Red; label2.Text = "нету подключения к базе"; botimer = true; timer2.Enabled = true; } myConnection.Close(); //Code } catch (Exception) { timer1.Interval = 10000; label1.ForeColor = Color.Red; label1.Text = "нету подключения к базе"; botimer = true; timer2.Enabled = true; } } private void OnTimer2(object sender, EventArgs e) { if (i == 0) { } else { do { i--; } while (i == 0); { label3.Text = "До переподключения "+i +" секунд"; if(i <= 1) { label3.Text = "Попытка переподключения"; i = +10; } } } if (botimer == true) { metroTextBox1.Enabled = false; metroTextBox2.Enabled = false; pictureBox1.Enabled = false; label3.Enabled = true; label3.Visible = true; } } public double loggedUser { get { return Convert.ToDouble(metroTextBox1.Text); } } private void MetroTextBox1_Click(object sender, EventArgs e) { } private void MetroTextBox2_Click(object sender, EventArgs e) { } private void TextBox1_TextChanged(object sender, EventArgs e) { } private void TextBox1_TextChanged_1(object sender, EventArgs e) { } private void PictureBox1_Click(object sender, EventArgs e) { //Задаем команду string CommandText = "SELECT Count(*) FROM authorization WHERE login = '" + metroTextBox1.Text + "' AND password = '" + <PASSWORD>TextBox2.Text + "' LIMIT 1"; MySqlConnection myConnection = new MySqlConnection(Connect); //выполняем команду MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection); //открытие подключения myConnection.Open(); myCommand.ExecuteNonQuery(); MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myCommand); DataTable dt = new DataTable(); dataAdapter.Fill(dt); if (dt.Rows[0][0].ToString() == "1") // сверка значений { Form2 frm = new Form2(); frm.loggeduser = metroTextBox1.Text; frm.Show(); this.Hide(); timer1.Enabled = false; timer2.Enabled = false; } else { MessageBox.Show("Пожалуйста, проверьте правильность введенных данных!"); } myConnection.Close(); } private void Timer1_Tick_1(object sender, EventArgs e) { } } }
7b874bd1d2cdbf4a56eb55b1c628149b55901ae3
[ "C#" ]
3
C#
Tentrun/mysql-authorization
57b7be22184acf7bd9b7b0de39458900b64b2491
7573dbb1612fc86f37bd4e2d74f8b7014950b55e
refs/heads/master
<file_sep>import sys from ProvModel import Module, Object import fn_logged in1 = sys.argv[1] d1 = Object(in1) m = fn_logged.cr_to_bed_logged(d1) d2 = m.run() sys.stdout.write(d2.ref) <file_sep># takes 2 arguments and sums them up # arguments are passed as command line arguments # invocation command : python Add_ProVerna.py %%in1%% %%in2%% import sys from Functions_logged import Add_logged from lib.ProvModel import Object, File, Module # getting command line arguments script_name = sys.argv[0] in1 = sys.argv[1] in2 = sys.argv[2] # packing necessary arguments d1 = Object(in1) d2 = Object(in2) # initiating tool m = Add_logged(d1, d2) # executing tool and getting packed result d3 = m.run() # sending result value to stdout result = str(d3.ref) sys.stdout.write(result)<file_sep>## numpy is used for creating fake data import numpy as np import matplotlib as mpl ## agg backend is used to create plot as a .png file mpl.use('agg') import matplotlib.pyplot as plt ''' collection1 = [] collection2 = [] prov = open('prov.csv', 'r') noprov = open('noprov.csv', 'r') for line in prov: print line collection1.append(float(line)) for line in noprov: print line collection2.append(float(line)) print collection1 print collection2 data_to_plot = [collection1, collection2] # Create a figure instance fig = plt.figure(1, figsize=(9, 6)) plt.xlabel('Test Scenario') plt.ylabel('Execution Time (sec)') # Create an axes instance ax = fig.add_subplot(111) ## Custom x-axis labels # Create the boxplot bp = ax.boxplot(data_to_plot, labels = ['prov', 'no prov']) # Save the figure fig.savefig('boxplot.png', bbox_inches='tight') ''' # Create data N = 500 f = open('time vs nodes.csv', 'r') x = [] y = [] for line in f: d = line.split(',') x.append(float(d[0])) y.append(int(d[1].strip())) print x print y colors = (0, 0, 1) area = np.pi*5 # Plot plt.scatter(y, x, s=area, c=colors, alpha=0.5) plt.xlabel('Total Nodes in GDB') plt.ylabel('Workflow Execution Time (sec)') plt.show() plt.savefig('scatter.png', bbox_inches='tight') ''' # Create data N = 500 f = open('qtime vs nodes.csv', 'r') x = [] y = [] for line in f: d = line.split(',') x.append(float(d[0])) y.append(int(d[1].strip())) print x print y colors = (1, 0, 0) area = np.pi*5 # Plot plt.scatter(y, x, s=area, c=colors, alpha=0.5) plt.xlabel('Total Nodes in GDB') plt.ylabel('Query Time (sec)') plt.show() plt.savefig('qscatter.png', bbox_inches='tight') '''<file_sep>from ProvModel import Module, Object class T(Module): def body(self): in1 = self.P[0].ref print in1 + ' as in' return Object(in1 + ' as out') d1 = Object('INSTR') m = T(d1) d2 = m.run() print d2.ref<file_sep>from ProvModel import Object, Module d = Object(111) print d.ref<file_sep># takes 2 arguments and sums them up # a : int # b : int # return : int def Add(in1, in2): a = int(in1) b = int(in2) sum = a + b return sum def Sub(in1, in2): return int(in1)-int(in2) def Mul(in1, in2): return in1*in2 def Div(in1, in2): try: return in1/in2 except Exception as e: print e <file_sep>import sys # this script's name src = sys.argv[0] # this scripts first input as command line argument in1 = sys.argv[1] f = open(in1) out = open('noSpace.txt', 'w') for line in f: for word in line: for letter in word: if letter == ' ' : pass else: out.write(letter) print out.name<file_sep>import json import os def jsonify(r): r = json.dumps(r) return r def write_logic(in1): f = open('N.txt', 'w') f.write(str(in1)) print 'value saved into file N.txt'<file_sep>def start_raw(in1): import time millis = int(round(time.time() * 1000)) f = open('/home/aapon/taverna/time.csv', 'a') f.write(str(millis) + ',') return in1 def cr_to_csv_raw(bedfile): filename = bedfile with open(filename, 'r') as f: out = open(bedfile[:-4] + '.csv', 'w') out.write( 'exonchrome,exonstart,exonend,exonid,exonval,exonsign,snpchrome,snpstart,snpend,snpid,snpval,snpsign\n') for line in f: full_line = [] for data in line.split('\t'): full_line.append(data) out.write(','.join(full_line) + '\n') return out.name def count_raw(filename, target_id): import pandas as pd df = pd.read_csv(filename) t = target_id d = {} for i, r in df.iterrows(): k = r[t] if k not in d: d[k] = 1 else: d[k] = d[k] + 1 out = open(t + '_count_index.csv', 'w') out.write('id,count\n') for k in d: out.write(str(k) + ',' + str(d[k]) + '\n') return out.name def top_k_raw(in1): import pandas as pd df = pd.read_csv(in1) srt = df.sort_values('count', ascending=False).head(10) out = open('top_10_' + in1[:-4] + '.csv', 'w') srt.to_csv(out) return out.name def show_raw(in1): import sys f = open(in1) for line in f: sys.stdout.write(line) return '---' def end_raw(in1): import time millis = int(round(time.time() * 1000)) f = open('/home/aapon/taverna/time.csv', 'a') f.write(str(millis) + '\n') return 'success!' <file_sep>from ProvModel import Object, File, Module import Tools from random import randint import time from py2neo import Graph graph = Graph(password = '<PASSWORD>') result = open('qtime vs nodes.csv', 'w') for i in range(0, 500): print 'step', i fq0 = File(open('gene/fq0.fq')) fq1 = File(open('gene/fq1.bed')) fq2 = File(open('gene/fq2.fa')) fq3 = File(open('gene/fq3.fastq')) fq4 = File(open('gene/fq4.fastq')) dna0 = File(open('gene/dna0.txt')) dna1 = File(open('gene/dna1.txt')) dna2 = File(open('gene/dna2.txt')) dna3 = File(open('gene/dna3.txt')) ''' mfq = Tools.FastQC(fq0) r1, r2 = mfq.run() mfq = Tools.FastQC(fq1) r = mfq.run() mfq = Tools.FastQC(fq2) r = mfq.run() mfq = Tools.FastQC(fq3) r = mfq.run() mfq = Tools.FastQC(fq4) r = mfq.run() ''' mcount = Tools.DNALetterCount(dna0) r1, r2, r3, r4, r5 = mcount.run() mentropy = Tools.Entropy(r1, r2, r3, r4) mcount = Tools.DNALetterCount(dna1) r1, r2, r3, r4, r5 = mcount.run() mentropy = Tools.Entropy(r1, r2, r3, r4) mcount = Tools.DNALetterCount(dna2) r1, r2, r3, r4, r5 = mcount.run() mentropy = Tools.Entropy(r1, r2, r3, r4) mcount = Tools.DNALetterCount(dna3) r1, r2, r3, r4, r5 = mcount.run() mentropy = Tools.Entropy(r1, r2, r3, r4) start_time = time.time() q = 'match (n:File) return n' qresult = graph.run(q) qduration = time.time() - start_time query = 'MATCH (n) RETURN count(*)' data = graph.run(query) nodes = 0 for k in data: nodes = k[0] print qduration, nodes result.write(str(qduration) + ',' + str(nodes) + '\n') <file_sep>import sys f = open(sys.argv[1]) for line in f: print line<file_sep>from Functions import Add from lib.ProvModel import Object, Module # takes 2 arguments and sums them up with ProvMod # in1 : Object # in2 : Object # return Object class Add_logged(Module): def body(self): # unpacking value only in1 = self.P[0].ref in2 = self.P[1].ref # applying raw function r = Add(in1, in2) # returning packed value return Object(r)<file_sep>from ProvModel import Object, File, Module import Tools m = Tools.Error() m.run() <file_sep># input targetID import sys import pandas as pd import psutil df = pd.read_csv(sys.argv[1]) t = sys.argv[2] d = {} for i, r in df.iterrows(): k = r[t] if k not in d: d[k] = 1 else: d[k] = d[k]+1 out = open(t + '_count_index.csv', 'w') out.write('id,count\n') for k in d: out.write(str(k) + ',' + str(d[k]) + '\n') sys.stdout.write( t + '_count_index.csv' ) mem = open('memory.csv', 'a') mem.write(str(psutil.virtual_memory()[3]) + ',') <file_sep># Provmod Provmod is a workflow provenance programming model implemented in Python. It makes use of the work from https://github.com/rayhan-ferdous/DPLib which is a higher-level logging library made on the layer of Python Logging and creates automated workflow logs when implemented. # Research Thesis https://harvest.usask.ca/handle/10388/11902 # Video Demo ## System Core Demonstration [![Watch the video](https://assets.entrepreneur.com/content/3x2/2000/20180117155526-youtube.jpeg?width=600&crop=16:9)](https://youtu.be/nCWFRhHe7es "System Core Demonstration") ## Implementation Integrated with Neo4j + ELK Stack Demonstration [![Watch the video](https://assets.entrepreneur.com/content/3x2/2000/20180117155526-youtube.jpeg?width=600&crop=16:9)](https://youtu.be/dUELPZyriE0 "ProvMod + Neo4j + ELK Stack") # Learn Provmod See the wiki page https://github.com/rayhan-ferdous/Provmod/wiki for simple tutorial at a glance. The work is made by <NAME>, graduate researcher at the Dept. of CS (SR Lab), University of Saskatchewan, Canada during MSc studies. # Visualization Samples ![Sample 2](https://github.com/rayhan-ferdous/ProvMod/blob/master/pie2.png) ![Sample 1](https://github.com/rayhan-ferdous/ProvMod/blob/master/timeseries.png) ![Sample 3](https://github.com/rayhan-ferdous/ProvMod/blob/master/graph.png) <file_sep>import sys import time millis = int(round(time.time() * 1000)) f = open('/home/aapon/taverna/time.csv', 'a') f.write( str(millis) + ',' ) sys.stdout.write(sys.argv[1]) <file_sep>import sys from ProvModel import Object, Module import fn_logged in1 = sys.argv[1] in2 = sys.argv[2] d1 = Object(in1) d2 = Object(in2) m = fn_logged.count_logged(d1, d2) d3 = m.run() sys.stdout.write(d3.ref)<file_sep>import psutil from py2neo import Graph import time #import Queries query1 = 'match(n:Module) return n' graph = Graph(password = '<PASSWORD>') query = query1 data = graph.run(query) f = open('data/viz2.tsv', 'w') f.write('time\tname\tstatus\tcpu\tmemory\tduration\n') f.write('123\tdefault\tsuccess\t0\t0\t0') for d in data: #print d['n']['NAME'], d['n']['error'], d['n']['cpu'], d['n']['memory'], d['n']['duration'] name = d['n']['NAME'] status = 'error' if d['n']['error'] == 'Null': status = 'success' cpu = '0' if str(d['n']['cpu']) != 'None': cpu = str(d['n']['cpu']) memory = '0' if str(d['n']['memory']) != 'None': memory = str(d['n']['memory']) duration = '0' if str(d['n']['duration']) != 'None': duration = str(d['n']['duration']) time = d['n']['time'] print name, status, cpu, memory, duration f.write(time + '\t' + name + '\t' + status + '\t' + cpu + '\t' + memory + '\t' + duration + '\n') f.close() print psutil.virtual_memory()[3]<file_sep> get_all_modules = 'match (n:Module) return n' get_frequency_of_all_modules = 'match (n:Module) ' <file_sep>import sys from ProvModel import Module, Object import fn_logged in1 = sys.argv[1] d1 = Object(in1) m = fn_logged.show_logged(d1) d2 = m.run() sys.stdout.write(d2.ref)<file_sep>'''run simulation''' from ProvModel import Object, File, Module import Tools from random import randint import time fq0 = File(open('gene/fq0.fq')) fq1 = File(open('gene/fq1.bed')) fq2 = File(open('gene/fq2.fa')) fq3 = File(open('gene/fq3.fastq')) fq4 = File(open('gene/fq4.fastq')) dna0 = File(open('gene/dna0.txt')) dna1 = File(open('gene/dna1.txt')) dna2 = File(open('gene/dna2.txt')) dna3 = File(open('gene/dna3.txt')) fqset = [fq0, fq1, fq2, fq3, fq4] dnaset = [dna0, dna1, dna2, dna3] m1 = Tools.DNALetterCount(dnaset[0]) a, c, t, g, n = m1.run() m2 = Tools.Entropy(a, c, t, g) ent = m2.run() m3 = Tools.MaxMinProb(a, c, t, g) maxbase, minbase = m3.run() while True: time.sleep(randint(1, 8)) print 'simulating...', time.time() rand = randint(0,7) if 0 <= rand <= 4: m = Tools.FastQC(fqset[rand]) n = m.run() else: pass if 0 <= rand <= 1: m1 = Tools.DNALetterCount(dnaset[rand]) a, c, t, g, n = m1.run() elif 2 <= rand <= 3: m1 = Tools.DNALetterCount(dnaset[rand]) a, c, t, g, n = m1.run() m2 = Tools.Entropy(a, c, t, g) ent = m2.run() else: m1 = Tools.DNALetterCount(dnaset[rand%4]) a, c, t, g, n = m1.run() m2 = Tools.Entropy(a, c, t, g) ent = m2.run() m3 = Tools.MaxMinProb(a, c, t, g) maxbase, minbase = m3.run() <file_sep>from py2neo import Graph graph = Graph(password = '<PASSWORD>') graph.delete_all() f = open('bioblend.xml', 'r') clones = [] for line in f: if '<source file=' in line: coms = line.split() fname = coms[1][6:-1] start = coms[2][11:-1] end = coms[3][9:-1] pcid = coms[4][6:-11] clones.append( (fname, start, end, pcid) ) for i in range(0, len(clones), 2): first = clones[i] second = clones[i+1] fname1 = first[0] start1 = first[1] end1 = first[2] pcid1 = first[3] createnode1 = 'create(n:fragments) set n.file="' + fname1 + '", n.start="' + start1 + '", n.end="' + end1 + '", n.pcid="' + pcid1 + '"' graph.run(createnode1) fname2 = second[0] start2 = second[1] end2 = second[2] pcid2 = second[3] createnode2 = 'create(n:fragments) set n.file="' + fname2 + '", n.start="' + start2 + '", n.end="' + end2 + '", n.pcid="' + pcid2 + '"' graph.run(createnode2) for i in range(0, len(clones), 2): first = clones[i] second = clones[i+1] pcid1 = first[3] pcid2 = second[3] createrelation = 'match(n1), (n2) where n1.pcid="' + pcid1 + '" and n2.pcid="' + pcid2 + '" create (n1)-[:cloneof]->(n2)' graph.run(createrelation) <file_sep>import sys from ProvModel import Object, Module import fn_logged import psutil import os in1 = sys.argv[1] in2 = sys.argv[2] d1 = Object(in1) d2 = Object(in2) m = fn_logged.count_logged(d1, d2) d3 = m.run() sys.stdout.write(d3.ref) process = psutil.Process(os.getpid()) ram = process.memory_info().rss mem = open('memory.csv', 'a') mem.write(str(ram) + ',') <file_sep>import sys from ProvModel import Module, File, Object import fn_logged in1 = sys.argv[1] d1 = Object(in1) m = fn_logged.end_logged(d1) d2 = m.run() sys.stdout.write(d2.ref)<file_sep># version 2.4.1 import uuid import logging import configuration import os.path import couchdb import getpass from typing import Any import collections failure = False # to disable all logging #logging.disable(logging.CRITICAL) # to re-enable all logging logging.disable(logging.NOTSET) # logger for the current script logger_name = 'Model_Logger' # log file for the whole experiment log_file = 'workflow.log' # create the loggers that you want to use in this file # params : logger_name, output_file info = configuration.logger_info(logger_name, log_file) info_start = configuration.logger_info_start(logger_name, log_file) info_end = configuration.logger_info_end(logger_name, log_file) deb = configuration.logger_debug(logger_name, log_file) warn = configuration.logger_warn(logger_name, log_file) err = configuration.logger_error(logger_name, log_file) fatalerr = configuration.logger_fatal(logger_name, log_file) class User: def __init__(self): self.id = uuid.uuid4() self.name =getpass.getuser() msg = [] msg.append('event :: ' + 'user invocation') msg.append('id :: ' + str(self.id)) msg.append('name :: ' + str(self.name)) deb.debug(';'.join(msg)) USER = User() class Data: def __init__(self): self.id = None self.ref = None self.user = None class Object(Data): def __init__(self, reference): # type: (Any) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # preoondition management pass else: # if all preconditions passed try: self.ref = reference msg = [] msg.append('event :: ' + 'object data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(reference)) ) msg.append('value :: ' + str(reference)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) except Exception as e: # if any further error occurs somehow msg = [] msg.append('event :: ' + 'object data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(reference))) msg.append('value :: ' + str(reference)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + str(e)) err.error(';'.join(msg)) class File(Data): def __init__(self, f): # type: (file) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # precondition management pass elif not isinstance(f, file): # if file not found msg = [] msg.append('event :: ' + 'file data creation') msg.append('id :: ' + str(self.id)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + 'file not found') err.error(';'.join(msg)) else: # if all exceptions passed try: self.ref = f msg = [] msg.append('event :: ' + 'file data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(f))) msg.append('source :: ' + str(f.name)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) except Exception as e: # if any further exception occurs msg = [] msg.append('event :: ' + 'file data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(f))) msg.append('source :: ' + str(f.name)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + str(e)) err.error(';'.join(msg)) class Document(Data): def __init__(self, document): # type: (couchdb.Document) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # precondition management pass elif not isinstance(document, couchdb.Document): msg = [] msg.append('event :: ' + 'document data creation') msg.append('id :: ' + str(self.id)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + 'document not found') err.error(';'.join(msg)) else: # if all exceptions passed try: self.ref = document msg = [] msg.append('event :: ' + 'document data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(document))) msg.append('address :: ' + str(document)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) except Exception as e: # if any further exception occurs msg = [] msg.append('event :: ' + 'document data creation') msg.append('id :: ' + str(self.id)) msg.append('type :: ' + str(type(document))) msg.append('address :: ' + str(document)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + str(e)) err.error(';'.join(msg)) class Module: def logStart(self): msg = [] msg.append('event :: ' + 'module start') msg.append('id :: ' + str(self.id)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) def logEnd(self): msg = [] msg.append('event :: ' + 'module end') msg.append('id :: ' + str(self.id)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) def body(self): """ :param interfaceParam: :return: """ def __init__(self, *args): self.id = uuid.uuid4() self.user = USER.id self.P = args try: msg = [] count = 0 for i in args: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): msg.append('p@' + str(count) + ' :: ' + str(i.id)) msg.append('p@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 else: msg.append('p@' + str(count) + ' :: ' + str(i)) msg.append('p@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 msg.append('event :: ' + 'module creation') msg.append('id :: ' + str(self.id)) msg.append('name :: ' + str(self.__class__.__name__)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) except Exception as e: msg = [] count = 0 for i in args: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): msg.append('p@' + str(count) + ' :: ' + str(i.id)) msg.append('p@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 else: msg.append('p@' + str(count) + ' :: ' + str(i)) msg.append('p@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 msg.append('event :: ' + 'module creation') msg.append('id :: ' + str(self.id)) msg.append('name :: ' + str(self.__class__.__name__)) msg.append('user :: ' + str(USER.id)) msg.append('error :: ' + str(e)) err.error(';'.join(msg)) def run(self, when = True, false_return = None): if when is True: self.logStart() self.outgoing = self.body() msg = [] if isinstance(self.outgoing, collections.Iterable): count = 0 for i in self.outgoing: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): msg.append('o@' + str(count) + ' :: ' + str(i.id)) msg.append('o@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 else: if isinstance(self.outgoing, Object) or isinstance(self.outgoing, File) or isinstance(self.outgoing, Document): msg.append('o@' + '0' + ' :: ' + str(self.outgoing.id)) msg.append('o@@' + '0' + ' :: ' + str(self.outgoing.__class__.__name__)) msg.append('event :: ' + 'module execution true') msg.append('id :: ' + str(self.id)) msg.append('name :: ' + str(self.__class__.__name__)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) self.logEnd() return self.outgoing else: msg = [] count = 0 for i in false_return: msg.append('o@' + str(count) + ' :: ' + str(i)) msg.append('o@@' + str(count) + ' :: ' + str(i.__class__.__name__)) count += 1 msg.append('event :: ' + 'module execution false') msg.append('id :: ' + str(self.id)) msg.append('name :: ' + str(self.__class__.__name__)) msg.append('user :: ' + str(USER.id)) deb.debug(';'.join(msg)) return false_return <file_sep>import logging # use with locals() # debug level messages formatter_debug = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, line: %(lineno)d, module: %(module)s, msecs: %(msecs)d, output: %(message)s, logger: %(name)s, path: %(pathname)s, procID: %(process)d, proc: %(processName)s, threadID: %(thread)d, thread: %(threadName)s' + '\n*********') # informatin level messages formatter_info_start = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, module: %(module)s, msecs: %(msecs)d, msg: %(message)s, logger: %(name)s' + '\n---') formatter_info_end = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, module: %(module)s, msecs: %(msecs)d, output: %(message)s, logger: %(name)s' + '\n---------') # warning formatter_warn = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, line: %(lineno)d, module: %(module)s, msecs: %(msecs)d, msg: %(message)s, logger: %(name)s, path: %(pathname)s' + '\n!!!!!!!!!') # error with locals() formatter_error = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, line: %(lineno)d, module: %(module)s, msecs: %(msecs)d, except: %(message)s, logger: %(name)s, path: %(pathname)s, procID: %(process)d, proc: %(processName)s, threadID: %(thread)d, thread: %(threadName)s' + '\nXXXXXXXXX') # fatal error with locals() formatter_fatal = logging.Formatter( 'time: %(asctime)s, file: %(filename)s, func: %(funcName)s, level: %(levelname)s, line: %(lineno)d, module: %(module)s, msecs: %(msecs)d, msg: %(message)s, logger: %(name)s, path: %(pathname)s, procID: %(process)d, proc: %(processName)s, threadID: %(thread)d, thread: %(threadName)s' + '\n$$$$$$$$$') # info config def logger_info_start(name, log_file, level=logging.INFO): handler = logging.FileHandler(log_file) handler.setFormatter(formatter_info_start) logger = logging.getLogger(name + '-INFOST') logger.setLevel(level) logger.addHandler(handler) return logger def logger_info_end(name, log_file, level=logging.INFO): handler = logging.FileHandler(log_file) handler.setFormatter(formatter_info_end) logger = logging.getLogger(name + '-INFOND') logger.setLevel(level) logger.addHandler(handler) return logger # debug config def logger_debug(name, log_file, level=logging.DEBUG): handler = logging.FileHandler(log_file) handler.setFormatter(formatter_debug) logger = logging.getLogger(name + '-DEBUG') logger.setLevel(level) logger.addHandler(handler) return logger # warn config def logger_warn(name, log_file, level=logging.WARNING): handler = logging.FileHandler(log_file) handler.setFormatter(formatter_warn) logger = logging.getLogger(name + '-WARN') logger.setLevel(level) logger.addHandler(handler) return logger # error config def logger_error(name, log_file, level=logging.ERROR): # type: (object, object, object) -> object handler = logging.FileHandler(log_file) handler.setFormatter(formatter_error) logger = logging.getLogger(name + '-ERROR') logger.setLevel(level) logger.addHandler(handler) return logger # fatal config def logger_fatal(name, log_file, level=logging.CRITICAL): # type: (object, object, object) -> object handler = logging.FileHandler(log_file) handler.setFormatter(formatter_fatal) logger = logging.getLogger(name + '-FATAL') logger.setLevel(level) logger.addHandler(handler) return logger <file_sep>from ProvModel import Object, File, Document, Module from ProvModel import err from Operators import jsonify import time from random import randint class FastQC(Module): def body(self): import subprocess cmd = 'FastQC/./fastqc ' + str(self.P[0].ref.name) returned_value = subprocess.call(cmd, shell=True) r1 = File(open(str(self.P[0].ref.name)[:-3] + '_fastqc.html')) r2 = File(open(str(self.P[0].ref.name)[:-3] + '_fastqc.zip')) #print r1, r2 return r1, r2 class DNALetterCount(Module): def body(self): filename = self.P[0].ref.name n = 0.0 a = 0 t = 0 c = 0 g = 0 with open(filename) as f: for line in f: n = float(len(line)) #print line for letter in line: if letter == 'A': a = a+1 elif letter == 'T': t = t+1 elif letter == 'C': c = c+1 elif letter == 'G': g = g+1 r1 = ('a', a/n) r2 = ('c', t/n) r3 = ('t', c/n) r4 = ('g', g/n) r5 = ('Len', n) return Object(r1), Object(r2), Object(r3), Object(r4), Object(r5) class Entropy(Module): def body(self): import math aprob = self.P[0].ref[1] cprob = self.P[1].ref[1] tprob = self.P[2].ref[1] gprob = self.P[3].ref[1] H = aprob*math.log(aprob, 4) + cprob*math.log(cprob, 4) + tprob*math.log(tprob, 4) + gprob*math.log(gprob, 4) #print H return Object(H) class MaxMinProb(Module): def body(self): b1 = self.P[0].ref b2 = self.P[1].ref b3 = self.P[2].ref b4 = self.P[3].ref data = (b1, b2, b3, b4) #print data maxval = 0 maxname = '' minval = 1 minname = '' for i in data: if i[1] >= maxval: maxval = i[1] maxname = i[0] if i[1] <= minval: minval = i[1] minname = i[0] return Object((maxname, maxval)), Object((minname, minval)) <file_sep>import json import os def jsonify(r): r = json.dumps(r) return r <file_sep> from datetime import datetime import uuid import logging import configuration import os.path import couchdb import getpass from typing import Any import collections from Operators import jsonify import os import psutil ''' GDB part ''' from py2neo import Graph graph = Graph(password = '<PASSWORD>') #graph.delete_all() ''' modelling part ''' failure = False # to disable all logging #logging.disable(logging.CRITICAL) # to re-enable all logging logging.disable(logging.NOTSET) # logger for the current script logger_name = 'Model_Logger' # log file for the whole experiment log_file = 'workflow.log' # create the loggers that you want to use in this file # params : logger_name, output_file info = configuration.logger_info(logger_name, log_file) info_start = configuration.logger_info_start(logger_name, log_file) info_end = configuration.logger_info_end(logger_name, log_file) deb = configuration.logger_debug(logger_name, log_file) warn = configuration.logger_warn(logger_name, log_file) err = configuration.logger_error(logger_name, log_file) fatalerr = configuration.logger_fatal(logger_name, log_file) def elasticuser(id, name, time): #print 'curl XPUT 127.0.0.1:9200/provenance/users/' + str(id) + ' -d\' {"time": "' + str(time) + '", "name": "' + str(name) + '"}\' ' os.system('curl --silent --output XPUT 127.0.0.1:9200/userindex/users/' + str(id) + ' -d\' {"time": "' + str(time) + '", "name": "' + str(name) + '"}\' ') class User: def __init__(self): self.id = uuid.uuid4() self.name = getpass.getuser() msg = {"event": "USR-INVK", "id": str(self.id), "name": str(self.name), 'time': str( datetime.utcnow() )} deb.debug(jsonify(msg)) elasticuser(msg['id'], msg['name'], msg['time']) USER = User() class Data: def __init__(self): self.id = None self.ref = None self.user = None def elasticobject(id, type, value, user, memory, cpu, time, error): #print 'curl XPUT 127.0.0.1:9200/objectindex/modules/' + str(id) + ' -d\' {"time": "' + str(time) + '", "type": "' + str(type) + '", "value": "' + str(value) + '", "user": "' + str(user) + '", "memory": ' + str(memory) + ', "cpu": ' + str(cpu) + ', "error": "' + str(error) + '" }\' ' os.system('curl --silent --output XPUT 127.0.0.1:9200/objectindex/objects/' + str(id) + ' -d\' {"time": "' + str(time) + '", "type": "' + str(type) + '", "value": "' + str(value) + '", "user": "' + str(user) + '", "memory": ' + str(memory) + ', "cpu": ' + str(cpu) + ', "error": "' + str(error) + '" }\' ') class Object(Data): def __init__(self, reference): # type: (Any) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # precondition management pass else: # if all preconditions passed try: self.ref = reference msg = { 'event': 'OB-CRTN', 'id': str(self.id), 'type': str(type(reference)), 'value': str(reference), 'user': str(USER.id), 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'object', 'error': 'success' } deb.debug(jsonify(msg)) elasticobject(msg['id'], msg['type'], msg['value'], msg['user'], msg['memory'], msg['cpu'], msg['time'], msg['error']) ''' GDB part ''' props = ['VALUE:\"' + msg['value'] + '\"', 'id:\"' + msg['id'] + '\"', 'type:\"' + msg['type'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"null\"', 'time:\"' + str(msg['time']) + '\"', 'memory:\"' + str(msg['memory']) + '\"', 'cpu:\"' + str(msg['cpu']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) #print propsQuery query = 'create (n:Object{' + propsQuery + '})' graph.run(query) except Exception as e: # if any further error occurs somehow #pid = os.getpid() #py = psutil.Process(pid) #memoryUse = py.memory_info()[0] / 2. ** 30 msg = { 'event': 'OB-CRTN', 'id': str(self.id), 'type': str(type(reference)), 'value': str(reference), 'user': str(USER.id), 'error': 'OCE', 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'object' } err.error(jsonify(msg)) elasticobject(msg['id'], msg['type'], msg['value'], msg['user'], msg['memory'], msg['cpu'], msg['time'], msg['error']) ''' GDB part ''' props = ['VALUE:\"' + msg['value'] + '\"', 'id:\"' + msg['id'] + '\"', 'type:\"' + msg['type'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"' + msg['error'] + '\"', 'time:\"' + str(msg['time']) + '\"', 'memory:\"' + str(msg['memory']) + '\"', 'cpu:\"' + str(msg['cpu']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) #print propsQuery query = 'create (n:Object{' + propsQuery + '})' graph.run(query) def elasticfile(id, user, source, memory, cpu, time, error): #print 'curl XPUT 127.0.0.1:9200/fileindex/files/' + str(id) + ' -d\' {"time": "' + str(time) + '", "user": "' + str(user) + '", "source": "' + str(source) + '", "memory": ' + str(memory) + ', "cpu": ' + str(cpu) + ', "error": "' + str(error) + '" }\' ' os.system('curl --silent --output XPUT 127.0.0.1:9200/fileindex/files/' + str(id) + ' -d\' {"time": "' + str(time) + '", "user": "' + str(user) + '", "source": "' + str(source) + '", "memory": ' + str(memory) + ', "cpu": ' + str(cpu) + ', "error": "' + str(error) + '" }\' ') class File(Data): def __init__(self, f): # type: (file) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # precondition management pass elif not isinstance(f, file): # if file not found msg = { 'event': 'FIL-CRTN', 'id': str(self.id), 'user': str(USER.id), 'error': 'FCE', 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'file' } err.error(jsonify(msg)) elasticfile(msg['id'], msg['user'], 'InvalidFile', msg['memory'], msg['cpu'], msg['time'], msg['error']) ''' GDB part this part is never executed props = ['SOURCE:\"' + msg['source'] + '\"', 'id:\"' + msg['id'] + '\"', 'type:\"' + msg['type'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"' + msg['error'] + '\"', 'time:\"' + str(msg['time']) + '\"', 'memory:\"' + str(msg['memory']) + '\"', 'cpu:\"' + str(msg['cpu']) + '\"'] propsQuery = ','.join(props) # print propsQuery query = 'create (n:File{' + propsQuery + '})' graph.run(query) ''' else: # if all exceptions passed try: self.ref = f msg = { 'event': 'FIL-CRTN', 'id': str(self.id), 'type': str(type(f)), 'source': str(f.name), 'user': str(USER.id), 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'file', 'error': 'success' } deb.debug(jsonify(msg)) elasticfile(msg['id'], msg['user'], msg['source'] ,msg['memory'], msg['cpu'], msg['time'], msg['error']) ''' GDB part ''' props = ['SOURCE:\"' + msg['source'] + '\"', 'id:\"' + msg['id'] + '\"', 'type:\"' + msg['type'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"null\"', 'time:\"' + str(msg['time']) + '\"', 'memory:\"' + str(msg['memory']) + '\"', 'cpu:\"' + str(msg['cpu']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) #print propsQuery query = 'create (n:File{' + propsQuery + '})' graph.run(query) except Exception as e: # if any further exception occurs msg = { 'event': 'FIL-CRTN', 'id': str(self.id), 'type': str(type(f)), 'source': str(f.name), 'user': str(USER.id), 'error': 'OE', 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'file' } err.error(jsonify(msg)) elasticfile(msg['id'], msg['user'], msg['source'], msg['memory'], msg['cpu'], msg['time'], msg['error']) ''' GDB part ''' props = ['SOURCE:\"' + msg['source'] + '\"', 'id:\"' + msg['id'] + '\"', 'type:\"' + msg['type'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"' + msg['error'] + '\"', 'time:\"' + str(msg['time']) + '\"', 'cpu:\"' + str(msg['cpu']) + '\"', 'memory:\"' + str(msg['memory']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) # print propsQuery query = 'create (n:File{' + propsQuery + '})' graph.run(query) class Document(Data): def __init__(self, document): # type: (couchdb.Document) -> None self.id = uuid.uuid4() self.user = USER.id if failure is True: # precondition management pass elif not isinstance(document, couchdb.Document): msg = { 'event': 'DOC-CRTN', 'id': str(self.id), 'user': str(USER.id), 'error': 'error', 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'document' } err.error(jsonify(msg)) else: # if all exceptions passed try: self.ref = document msg = { 'event': 'DOC-CRTN', 'id': str(self.id), 'type': str(type(document)), 'address': str(document), 'user': str(USER.id), 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'document' } deb.debug(jsonify(msg)) except Exception as e: # if any further exception occurs msg = { 'event': 'DOC-CRTN', 'id': str(self.id), 'type': str(type(document)), 'address': str(document), 'user': str(USER.id), 'error': 'error', 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'label': 'document' } err.error(jsonify(msg)) def elasticmodule(id, time, name, user, memory_run, memory_init, cpu_run, cpu_init, duration_run, duration_init, error): #print 'curl XPUT 127.0.0.1:9200/moduleindex/modules/' + str(id) + ' -d\' {"time": "' + str(time) + '", "name": "' + str(name) + '", "user": "' + str(user) + '", "memory_run": ' + str(memory_run) + ', "memory_init": ' + str(memory_init) + ', "cpu_run": ' + str(cpu_run) + ', "cpu_init": ' + str(cpu_init) + ', "duration_run": "' + str(duration_run) + '", "duration_init": "' + str(duration_init) + '", "error": "' + str(error) + '" }\' ' os.system('curl --silent --output XPUT 127.0.0.1:9200/moduleindex/modules/' + str(id) + ' -d\' {"time": "' + str(time) + '", "name": "' + str(name) + '", "user": "' + str(user) + '", "memory_run": ' + str(memory_run) + ', "memory_init": ' + str(memory_init) + ', "cpu_run": ' + str(cpu_run) + ', "cpu_init": ' + str(cpu_init) + ', "duration_run": "' + str(duration_run) + '", "duration_init": "' + str(duration_init) + '", "error": "' + str(error) + '" }\' ') class Module: def logStart(self): msg = { 'event': 'MOD-STRT', 'id': str(self.id), 'user': str(USER.id) } deb.debug(jsonify(msg)) def logEnd(self): msg = { 'event': 'MOD-END', 'id': str(self.id), 'user': str(USER.id) } deb.debug(jsonify(msg)) def body(self): """ :param interfaceParam: :return: """ def __init__(self, *args): start_time = datetime.utcnow() self.id = uuid.uuid4() self.user = USER.id self.P = args try: param_ids = [] for i in args: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): param_ids.append(str(i.id)) else: param_ids.append(str(i)) msg = { 'p@': param_ids, 'event': 'MOD-CRTN', 'id': str(self.id), 'name': str(self.__class__.__name__), 'user': str(USER.id), 'memory_init': (psutil.virtual_memory()[2])*(.000001), 'cpu_init': (psutil.cpu_percent()), 'duration_init': str(datetime.utcnow()-start_time), 'time': str(datetime.utcnow()), 'cpu_run': 0, 'memory_run': 0, 'duration_run': "00:00:00.000000", 'label': 'module', 'error': 'success' } deb.debug(jsonify(msg)) elasticmodule(msg['id'], msg['time'], msg['name'], msg['user'], msg['memory_run'], msg['memory_init'], msg['cpu_run'], msg['cpu_init'], msg['duration_run'], msg['duration_init'], msg['error']) ''' GDB part ''' props = ['NAME:\"' + msg['name'] + '\"', 'id:\"' + msg['id'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"null\"', 'time:\"' + str(msg['time']) + '\"', 'memory_init:\"' + str(msg['memory_init']) + '\"', 'cpu_init:\"' + str(msg['cpu_init']) + '\"', 'duration_init:\"' + str(msg['duration_init']) + '\"', 'duration_run:\"' + str(msg['duration_run']) + '\"', 'memory_run:\"' + str(msg['memory_run']) + '\"', 'cpu_run:\"' + str(msg['cpu_run']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) #print propsQuery query = 'create (n:Module{' + propsQuery + '})' graph.run(query) ''' relationships ''' for uninqid in param_ids: # match (n:Object{id:uniqid}), (m:Module{id:id}) # create (n)-[:IN]-> (m) query = ' match (n),(m) where n.id = \"' + uninqid + '\" and m.id = \"' + msg['id'] + '\" create (n)-[:IN]-> (m)' #print query graph.run(query) except Exception as e: param_ids = [] for i in args: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): param_ids.append(str(i.id)) else: param_ids.append(str(i)) msg = { 'p@': param_ids, 'event': 'MOD-CRTN', 'id': str(self.id), 'name': str(self.__class__.__name__), 'user': str(USER.id), 'error': 'MIE', 'memory_init': (psutil.virtual_memory()[2])*(.000001), 'cpu_init': (psutil.cpu_percent()), 'duration_init': str(datetime.utcnow()-start_time), 'time': str(datetime.utcnow()), 'cpu_run': 0, 'memory_run': 0, 'duration_run': "00:00:00.000000", 'label': 'module' } #print msg err.error(jsonify(msg)) elasticmodule(msg['id'], msg['time'], msg['name'], msg['user'], msg['memory_run'], msg['memory_init'], msg['cpu_run'], msg['cpu_init'], msg['duration_run'], msg['duration_init'], msg['error']) ''' GDB part ''' props = ['NAME:\"' + msg['name'] + '\"', 'id:\"' + msg['id'] + '\"', 'user:\"' + msg['user'] + '\"', 'error:\"' + msg['error'] + '\"', 'time:\"' + str(msg['time']) + '\"', 'memory_init:\"' + str(msg['memory_init']) + '\"', 'cpu_init:\"' + str(msg['cpu_init']) + '\"', 'duration_init:\"' + str(msg['duration_init']) + '\"', 'cpu_run:\"' + str(msg['cpu_run']) + '\"', 'memory_run:\"' + str(msg['memory_run']) + '\"', 'duration_run:\"' + str(msg['duration_run']) + '\"', 'label:\"' + str(msg['label']) + '\"'] propsQuery = ','.join(props) #print propsQuery query = 'create (n:Module{' + propsQuery + '})' graph.run(query) def run(self, when = True, false_return = None): start_time = datetime.utcnow() if when is True: try: self.logStart() self.outgoing = self.body() ret_ids = [] if isinstance(self.outgoing, collections.Iterable): for i in self.outgoing: if isinstance(i, Object) or isinstance(i, File) or isinstance(i, Document): ret_ids.append(str(i.id)) else: if isinstance(self.outgoing, Object) or isinstance(self.outgoing, File) or isinstance(self.outgoing, Document): ret_ids.append(str(self.outgoing.id)) msg = { 'o@': ret_ids, 'event': 'BODY-TRU', 'id': str(self.id), 'name': str(self.__class__.__name__), 'user': str(USER.id), 'duration_run': str(datetime.utcnow()-start_time), 'memory_run': (psutil.virtual_memory()[2])*(.000001), 'cpu_run': (psutil.cpu_percent()), 'time_run': str(datetime.utcnow()), 'error': 'success' } deb.debug(jsonify(msg)) elasticmodule(msg['id'], msg['time_run'], msg['name'], msg['user'], msg['memory_run'], 0, msg['cpu_run'], 0, msg['duration_run'], "00:00:00.000000", msg['error']) ''' relationships ''' for uninqid in ret_ids: # match (n:Object{id:uniqid}), (m:Module{id:id}) # create (m)-[:OUT]-> (n) query = ' match (n),(m) where n.id = \"' + uninqid + '\" and m.id = \"' + msg['id'] + '\" create (m)-[:OUT]-> (n) ' + 'set m.duration_run = \"' + str(msg['duration_run']) + '\"' + ', m.cpu_run = \"' + str(msg['cpu_run']) + '\"' + ', m.memory_run = \"' + str(msg['memory_run']) + '\"' + ', m.time_run = \"' + str(msg['time_run']) + '\"' #print query graph.run(query) self.logEnd() return self.outgoing except Exception as e: msg = { 'event': 'MOD-RUN', 'id': str(self.id), 'name': str(self.__class__.__name__), 'user': str(USER.id), 'error': 'MRE', 'duration_run': str(datetime.utcnow() - start_time), 'memory_run': (psutil.virtual_memory()[2])*(.000001), 'cpu_run': (psutil.cpu_percent()), 'time_run': str(datetime.utcnow()), 'label': 'module' } err.error(jsonify(msg)) elasticmodule(msg['id'], msg['time_run'], msg['name'], msg['user'], msg['memory_run'], 0, msg['cpu_run'], 0, msg['duration_run'], "00:00:00.000000", msg['error']) ''' GDB part ''' #props = ['NAME:\"' + msg['name'] + '\"', 'id:\"' + msg['id'] + '\"', # 'user:\"' + msg['user'] + '\"', 'error:\"' + msg['error'] + '\"', 'time:\"' + str(msg['time']) + '\"'] #propsQuery = ','.join(props) # print propsQuery query = 'match (n:Module{id:\"' + msg['id'] + '\"}) set n.error = \"' + str(msg['error']) + '\"' + ', n.duration_run = \"' + str(msg['duration_run']) + '\"' + ', n.cpu_run = \"' + str(msg['cpu_run']) + '\"' + ', n.memory_run = \"' + str(msg['memory_run']) + '\"' + ', n.time_run = \"' + str(msg['time_run']) + '\"' + ', n.label = \"' + str(msg['label']) + '\"' #print query graph.run(query) else: '''not using this part for implementation''' ret_ids = [] for i in false_return: ret_ids.append(str(i)) msg = { 'o@': ret_ids, 'event': 'BODY-FLS', 'id': str(self.id), 'name': str(self.__class__.__name__), 'user': str(USER.id), 'duration': str(datetime.utcnow() - start_time), 'memory': (psutil.virtual_memory()[2])*(.000001), 'cpu': (psutil.cpu_percent()), 'time': str(datetime.utcnow()), 'error': 'success' } deb.debug(jsonify(msg)) return false_return <file_sep>from ProvModel import Module, Object from py2neo import Graph import time from py2neo import Graph graph = Graph(password = '<PASSWORD>') class T(Module): def body(self): in1 = self.P[0].ref print in1 + ' as in' return Object(in1 + ' as out') Qres = open('query eval.csv', 'a') # millis = int(round(time.time() * 1000)) for i in range(0, 5000): d1 = Object(str(i)) m = T(d1) d2 = m.run() t0 = int(round(time.time() * 1000)) q1 = 'match(n) return n' d = graph.run(q1) t1 = int(round(time.time() * 1000)) Qres.write(str(t1-t0) + ',') t0 = int(round(time.time() * 1000)) q2 = 'match(n:Object) where n.VALUE = \'' + str(i) + '\' return n' d = graph.run(q2) t1 = int(round(time.time() * 1000)) Qres.write(str(t1-t0) + ',') t0 = int(round(time.time() * 1000)) q3 = 'match(n:Object) return n.VALUE order by n.time' d = graph.run(q3) t1 = int(round(time.time() * 1000)) Qres.write(str(t1-t0) + ',') t0 = int(round(time.time() * 1000)) q4 = 'match(n:Object) return n.cpu, n.memory' d = graph.run(q4) t1 = int(round(time.time() * 1000)) Qres.write(str(t1-t0) + '\n') print d2.ref <file_sep>def Flatten(*args): flat_list = [] for i in args: if i is not None: flat_list.append(i) return flat_list <file_sep>def get_all_nodes(): pass def get_all_object(): query = 'match (n:Object) return n' return query def get_all_file(): query = 'match(n:File) return n' return query def get_all_module(): query = 'match (n:Module) return n' return query def get_node(**kwargs): pass def get_object(**kwargs): where_clauses = [] for k in kwargs: where_clauses.append('n.' + str(k) + ' = ' + str(kwargs[k])) where_full = ' and '.join(where_clauses) query = 'match(n:Object) ' + where_full + ' return n' return query def get_file(**kwargs): where_clauses = [] for k in kwargs: where_clauses.append('n.' + str(k) + ' = ' + str(kwargs[k])) where_full = ' and '.join(where_clauses) query = 'match(n:File) ' + where_full + ' return n' return query def get_module(**kwargs): pass def get_object_source(**kwargs): pass def get_object_destination(**kwargs): pass def get_file_source(**kwargs): pass def get_file_destination(**kwargs): pass def get_module_input(**kwargs): pass def get_module_output(**kwargs): pass def get_node_property(**kwargs): pass def get_object_property(**kwargs): pass def get_file_property(**kwargs): pass def get_module_property(**kwargs): pass def get_all_node_frequency(): pass def get_all_object_frequency(): pass def get_all_file_frequency(): pass def get_all_module_frequency(): pass def get_node_frequency(**kwargs): pass def get_object_frequency(**kwargs): pass def get_file_frequency(**kwargs): pass def get_module_frequency(**kwargs): pass def get_object_property_frequency(**kwargs): pass def get_file_property_frequency(**kwargs): pass def get_module_property_frequency(**kwargs): pass def get_node_timeseries(start, end, **kwargs): pass <file_sep>import sys from ProvModel import Module, File, Object import fn_logged in1 = sys.argv[1] d1 = Object(in1) m = fn_logged.start_logged(d1) d2 = m.run() sys.stdout.write(d2.ref)<file_sep>import json def jsonify(r): r = json.dumps(r) return r <file_sep> get_all_modules = 'match (n:Module) return n' '''developers/domain experts add further queries '''<file_sep>import sys from ProvModel import Module, Object # create the logic function def removespace(in1): # taking input filename as parameter f = open(in1) # function logic out = open('noSpace.txt', 'w') for line in f: for word in line: for letter in word: if letter == ' ': pass else: out.write(letter) # return output filename return out.name # wrap the logic function with ProvMod class REMOVESPACE(Module): def body(self): #unpack input in1 = self.P[0].ref #apply logic res = removespace(in1) # pack value into Object flow = Object(res) #return Object return flow # this script's name as cmd line argument src = sys.argv[0] # this scripts first input as command line argument in1 = sys.argv[1] # create a tool invocation # input dataflow d1 = Object(in1) # tool initiation *** *** *** m = REMOVESPACE(d1) # output dataflow d2 = m.run() # output to STDOUT print d2.ref<file_sep>import sys from ProvModel import Module, Object import fn_logged import psutil import os in1 = sys.argv[1] d1 = Object(in1) m = fn_logged.cr_to_bed_logged(d1) d2 = m.run() sys.stdout.write(d2.ref) process = psutil.Process(os.getpid()) ram = process.memory_info().rss mem = open('memory.csv', 'a') mem.write(str(ram) + ',') <file_sep>from py2neo import Graph graph = Graph(password = '<PASSWORD>') graph.delete_all() <file_sep>from ProvModel import Object, File, Document, Module from ProvModel import err from Operators import jsonify class Add(Module): def body(self): a = self.P[0].ref b = self.P[1].ref r = a+b return Object(r) class Sub(Module): def body(self): a = self.P[0].ref b = self.P[1].ref r = a-b return Object(r) class Mul(Module): def body(self): a = self.P[0].ref b = self.P[1].ref r = a*b return Object(r) class Div(Module): def body(self): a = self.P[0].ref b = self.P[1].ref import numpy r = numpy.nan try: r = a/b except Exception as e: print e err.error("\"div-0-err\"") return Object(r) class TensorAdd(Module): def body(self): a = self.P[0].ref b = self.P[1].ref import numpy r = numpy.add(a, b) return Object(r) class TensorSub(Module): def body(self): a = self.P[0].ref b = self.P[1].ref import numpy r = numpy.subtract(a, b) return Object(r) class TensorMul(Module): def body(self): a = self.P[0].ref b = self.P[1].ref import numpy r = numpy.matmul(a, b) return Object(r) <file_sep>from ProvModel import Module, Object from Tools import GrabN from Operators import write_logic write_logic(3)<file_sep>py2neo=3.1.2 or 3.x.x with latest reducer query match(n1:Object), (n2:Object) where n1.time<n2.time and n1.VALUE=n2.VALUE create (n1)-[r:FLOW]->(n2)<file_sep>def write_logic(in1): f = open('N.txt', 'w') f.write(str(in1)) print 'value saved into file N.txt' <file_sep>from ProvModel import Object, Module # raw functions def fn_add(a, b): return a+b def fn_mul(a, b): return a*b def fn_double(a): return a*2 # creating modules class Add(Module): # overwrite the body def body(self): #unpack values from input dataflows in1 = self.P[0].ref in2 = self.P[1].ref # apply function res = fn_add(in1, in2) # pack the values again flow = Object(res) # return output dataflow return flow class Mul(Module): # overwrite the body def body(self): #unpack values from input dataflows in1 = self.P[0].ref in2 = self.P[1].ref # apply function res = fn_mul(in1, in2) # pack the values again flow = Object(res) # return output dataflow return flow class Double(Module): # overwrite the body def body(self): #unpack values from input dataflows in1 = self.P[0].ref # apply function res = fn_double(in1) # pack the values again flow = Object(res) # return output dataflow return flow d1 = Object(111) d2 = Object(222) d3 = Add(d1, d2).run() d4 = Object(1000) d5 = Mul(d3, d4).run() print d5.ref<file_sep>from ProvModel import Module, File, Object import fn_raw class start_logged(Module): def body(self): in1 = self.P[0].ref r = fn_raw.start_raw(in1) flow = Object(r) return flow class cr_to_bed_logged(Module): def body(self): in1 = self.P[0].ref r = fn_raw.cr_to_csv_raw(in1) flow = Object(r) return flow class count_logged(Module): def body(self): in1 = self.P[0].ref in2 = self.P[1].ref r = fn_raw.count_raw(in1, in2) flow = Object(r) return flow class top_k_logged(Module): def body(self): in1 = self.P[0].ref r = fn_raw.top_k_raw(in1) flow = Object(r) return flow class show_logged(Module): def body(self): in1 = self.P[0].ref r = fn_raw.show_raw(in1) flow = Object(r) return flow class end_logged(Module): def body(self): in1 = self.P[0].ref r = fn_raw.end_raw(in1) flow = Object(r) return flow<file_sep>import uuid import logging import configuration import os.path import couchdb import getpass # logger for the current script logger_name = 'Model_Logger' # log file for the whole experiment log_file = 'workflow.log' # create the loggers that you want to use in this file # params : logger_name, output_file info_start = configuration.logger_info_start(logger_name, log_file) info_end = configuration.logger_info_end(logger_name, log_file) deb = configuration.logger_debug(logger_name, log_file) warn = configuration.logger_warn(logger_name, log_file) err = configuration.logger_error(logger_name, log_file) fatalerr = configuration.logger_fatal(logger_name, log_file) class Data: def __init__(self): self.id = None self.reference = None self.user = None class Object(Data): def __init__(self, reference): self.id = uuid.uuid4() self.user = User() if reference is not None: self.reference = reference deb.debug('Object Data Created. (flowID, type, value, user) = (' + str(self.id) + ', ' + str(type(reference)) + ', ' + str(reference) + ', ' + str(self.user.id) + ')' ) else: err.error('Reference Not Found. (flowID) = ' + '(' + str(self.id) + ')') raise ReferenceError class File(Data): def __init__(self, file): self.id = uuid.uuid4() self.user = User() if os.path.exists(file): self.reference = file deb.debug('File Data Created. (flowID, type, value, user) = (' + str(self.id) + ',' + str(type(file)) + ', ' + str(file) + ', ' + str(self.user.id) + ')' ) else: err.error('File Not Found. (flowID) = ' + '(' + str(self.id) + ')') raise IOError class Document(Data): def __init__(self, document): self.id = uuid.uuid4() self.user = User() if document is not None: self.reference = document deb.debug('Document Data Created. (flowID, type, value, user) = (' + str(self.id) + ',' + str(type(document)) + ', ' + str(document) + ', ' + str(self.user.id) + ')' ) else: err.error('Document Not Found. (flowID) = ' + '(' + str(self.id) + ')') raise IOError class Module: def __init__(self, *args): self.id = uuid.uuid4() self.user = User() self.incoming = None self.args = args self.incoming = args[0] deb.debug('Incoming Dataflow Initiated. (inFlowID, type, moduleID, user) = ' + '(' + str(self.incoming.id) + ', ' + str(self.incoming.__class__.__name__) + ', ' + str(self.id) + ', ' + str(self.user.id) + ')') def logStart(self): deb.debug('Node Invokation Started. (moduleID) = ' + '(' + str(self.id) + ')') def logEnd(self): deb.debug('Node Invokation Ended. (moduleID) = ' + '(' + str(self.id) + ')') def body(self): return None def run(self): self.logStart() #add type checking for outgoing #add logging for outgoing flow self.outgoing = self.body() self.logEnd() return self.outgoing class User: def __init__(self): self.id = uuid.uuid4() self.name =getpass.getuser() <file_sep>from py2neo import Graph graph = Graph(password = '<PASSWORD>') graph.delete_all() open('workflow.log', 'w').close() <file_sep># input import sys import pandas as pd import psutil df = pd.read_csv(sys.argv[1]) srt = df.sort_values('count', ascending=False).head(10) out = open('top_10_' + sys.argv[1][:-4] + '.csv', 'w') srt.to_csv(out) sys.stdout.write( 'top_10_' + sys.argv[1][:-4] + '.csv' ) mem = open('memory.csv', 'a') mem.write(str(psutil.virtual_memory()[3]) + '\n') <file_sep># input import sys import pandas as pd df = pd.read_csv(sys.argv[1]) srt = df.sort_values('count', ascending=False).head(10) out = open('top_10_' + sys.argv[1][:-4] + '.csv', 'w') srt.to_csv(out) sys.stdout.write( 'top_10_' + sys.argv[1][:-4] + '.csv' ) <file_sep>'''parse GDB for visualization ''' from py2neo import Graph graph = Graph(password = '<PASSWORD>') import sys import time def parse(query, filename): data = graph.run(query) with open(filename, 'w') as f: header = data.keys() f.write('\t'.join(header) + '\n') for d in data: line = [] for k in header: line.append(str(d[k])) f.write('\t'.join(line) + '\n') # frequency query_freq = 'match(n) return n.label as label, count(n) as freq' # frequency of different modules query_module_freq = 'match (n:Module) return n.NAME as tool, count(n) as count' # fastqc only frequency query_single_mod_freq = 'match(n:Module) where n.NAME = "FastQC" return n.NAME as name, count(n) as freq' # time series of single modules' single property query_time_single_mod_single_prop = 'match(n:Module) where n.NAME="FastQC" and n.cpu_run >= "0" return n.time as time, n.cpu_run as cpuload order by n.time' # time series of multi-module single property query_time_multi_mod_single_prop = 'match(n:Module) where n.cpu_run >= "0" return n.time as time, n.NAME as tool, n.cpu_run as cpuload order by n.time' # time series of module names, error and cross props query_cross_prop = 'match(n:Module) where n.cpu_run >= "0" and n.duration_run >= "0" return n.time as time, n.NAME as name, n.error as error, n.cpu_run as cpu, n.duration_run as duration order by n.time' query_cross_prop_log = 'match(n:Module) where n.cpu_run >= "0" and n.duration_run >= "0" return n.time as time, n.NAME as name, n.error as error,toFloat (n.cpu_run) as cpu, log(toFloat(n.duration_run)) as duration order by n.time' # query module name vs error count group chart query_error_count = 'match(n:Module) return n.NAME as name, n.error as error, count(n) as freq' # query module name vs error count group chart query_error_cpu = 'match(n:Module) return n.NAME as name, n.error as error, n.cpu_run as cpu' while(True): time.sleep(1.5) print time.time() ''' parsing ''' parse(query_freq, 'data/frequency.tsv') parse(query_module_freq, 'data/mod_freq.tsv') parse(query_single_mod_freq, 'data/single_freq.tsv') parse(query_time_single_mod_single_prop, 'data/single_mod_single_prop.tsv') parse(query_time_multi_mod_single_prop, 'data/multi_mod_single_prop.tsv') parse(query_cross_prop, 'data/mod_name_error.tsv') parse(query_cross_prop, 'data/cross.tsv') parse(query_error_count, 'data/error_group.tsv') parse(query_error_cpu, 'data/error_group_cpu.tsv') parse(query_cross_prop_log, 'data/cpu_vs_log_duration.tsv')<file_sep>import sys import psutil filename = sys.argv[1] with open(filename, 'r') as f: out = open(sys.argv[1][:-4] + '.csv', 'w') out.write('exonchrome,exonstart,exonend,exonid,exonval,exonsign,snpchrome,snpstart,snpend,snpid,snpval,snpsign\n') for line in f: full_line = [] for data in line.split('\t'): full_line.append(data) #print full_line out.write(','.join(full_line)+'\n') #print ','.join(full_line)+'\n' #break sys.stdout.write( sys.argv[1][:-4] + '.csv' ) mem = open('memory.csv', 'a') mem.write(str(psutil.virtual_memory()[3]) + ',') <file_sep>import time def parse(): print 'parsing...' ''' GDB part ''' from py2neo import Graph import Queries graph = Graph(password = '<PASSWORD>') query = Queries.get_all_modules data = graph.run(query) usage = [] mapping = {} for d in data: target = d['n']['NAME'] if target in mapping: mapping[target] = mapping[target]+1 else: mapping[target] = 1 print mapping f = open('data/viz.tsv', 'w') f.write('Tools\tFrequency\n') for k in mapping: f.write(k + '\t' + str(mapping[k]) + '\n') f.close() while True: time.sleep(1) parse()
2a39265183a0a83d4f7693bd3f59f0f7a9729123
[ "Markdown", "Python", "Text" ]
51
Python
rayhan-ferdous/ProvMod
eb9d8b6555c65e2d76594812c6b314383f99285a
1f67811b1b19f47532b7f4f53b506953b7b989a8
refs/heads/master
<repo_name>neilgen/CCS<file_sep>/ccs/ScopeGuard.h #ifndef SCOPEGUARD_H #define SCOPEGUARD_H #include <functional> #define SCOPEGUARD_LINENAME_CAT(name, line) name##line #define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line) class ScopeGuard{ public: explicit ScopeGuard(std::function< void () > onExitScope) :_onExitScope(onExitScope), _dismiss(false){} ~ScopeGuard() { if(!_dismiss) { _onExitScope(); } } void Dismiss() { _dismiss = true; } private: ScopeGuard(ScopeGuard const &); ScopeGuard & operator = (ScopeGuard const &); std::function< void () > _onExitScope; bool _dismiss; }; #define ON_SCOPE_EXIT(callback) ScopeGuard SCOPEGUARD_LINENAME(EXIT, __LINE__)(callback) #endif // SCOPEGUARD_H <file_sep>/ccs/CCSTest.cpp #include "CCSTest.hpp" #include <iostream> void TestCCS::TestScopeGuard() { int * ptr = new int; ON_SCOPE_EXIT([&]{delete ptr;std::cout <<"release prt";}); } QTEST_MAIN(TestCCS) <file_sep>/README.md # linux,c/c++, qt snippet some code snippet is common in the work. <file_sep>/ccs/CCSTest.hpp #ifndef CCSTEST_HPP #define CCSTEST_HPP #include <QtTest> #include <QtTest/QTest> #include "ScopeGuard.h" class TestCCS: public QObject { Q_OBJECT private slots: void TestScopeGuard(); }; #endif // CCSTEST_HPP
6b5c390630bac584c9284bde7e556a8f4bf8184e
[ "Markdown", "C++" ]
4
C++
neilgen/CCS
69483388068226d5d0ad958fb622ebed0502bec0
6c5aef790573a517dc743634f3505fffcd44a603
refs/heads/master
<file_sep>Rails.application.routes.draw do root 'home#index' post 'results' => 'home#results' get 'results' => 'home#results' get 'test' => 'home#test' end<file_sep>json.extract! restaurant, :id, :name, :rating, :address, :address2, :address3, :city, :phone, :price, :url, :image, :created_at, :updated_at json.url restaurant_url(restaurant, format: :json)
02209a061b5d9ce450a6a88e4bcb3985cbe8bd04
[ "Ruby" ]
2
Ruby
geoffreycestaro/yelp2
7cac6e80f573a2d68d01e8ffce2cfcd8723286e7
4ef1e739bf488d5973cb424946f3a5809a8985d6
refs/heads/main
<repo_name>bap-rang-bo/face_mask_detection<file_sep>/main.py import cv2 import dlib # Load the detector detector = dlib.get_frontal_face_detector() # Load the predictor predictor = dlib.shape_predictor("/home/bau/Desktop/thay_lam/face_recognition/shape_predictor_68_face_landmarks.dat") # read the image cap = cv2.VideoCapture(0) a = 0 while True: _, frame = cap.read() frame = cv2.flip(frame, 1) # Convert image into grayscale gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY) # Use detector to find landmarks faces = detector(gray) for face in faces: x01 = face.left() # left point y01 = face.top() # top point x02 = face.right() # right point y02 = face.bottom() # bottom point # cv2.rectangle(img=frame, pt1=(x01, y01), pt2=(x02, y02), color=(0, 255, 0), thickness=4) # Create landmark object landmarks = predictor(image=gray, box=face) x27 = landmarks.part(27).x y27 = landmarks.part(27).y x0 = landmarks.part(0).x y0 = landmarks.part(0).y y15 = landmarks.part(15).y x16 = landmarks.part(16).x y16 = landmarks.part(16).y y17 = landmarks.part(17).y y1 = landmarks.part(1).y y26 = landmarks.part(26).y y33 = landmarks.part(33).y x8 = landmarks.part(8).x x37 = landmarks.part(37).x x44 = landmarks.part(44).x y28 = landmarks.part(28).y d1 = int(x27 - x0) # khoảng cách từ 0 đến 27 d2 = int(x16 - x27) # khoảng cách từ 27 đến 16 # Draw a circle if y0 < y17 or y0 > y28 or y0 == y33 or y16 < y26 or x8 < x37 or x8 > x44 or d1 * 2 < d2 or d1 > d2 * 2 or y27 > y1 or y27 > y15: cv2.putText(frame, 'K chap nhan', (x01, y01), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) else: cv2.putText(frame, 'Chap nhan', (x01, y01), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) # show the image cv2.imshow(winname="Face", mat=frame) # Exit when escape is pressed if cv2.waitKey(delay=1) == 27: break # When everything done, release the video capture and video write objects cap.release() # Close all windows cv2.destroyAllWindows()<file_sep>/train.py import cv2 import dlib import time import os import numpy as np detector = dlib.get_frontal_face_detector() detector1 = cv2.dnn.readNetFromCaffe('/home/bau/Desktop/thay_lam/face_recognition/face_detection_model/deploy.prototxt', '/home/bau/Desktop/thay_lam/face_recognition/face_detection_model/res10_300x300_ssd_iter_140000.caffemodel') # Load the predictor predictor = dlib.shape_predictor("/home/bau/Desktop/thay_lam/face_recognition/shape_predictor_68_face_landmarks.dat") class Video1(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): count = 0 preticked = time.time() while True: ret, frame = self.video.read() frame = cv2.flip(frame, 1) img = cv2.resize(frame, (300, 300)) gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY) faces = detector(gray) for face in faces: x01 = face.left() # left point y01 = face.top() # top point x02 = face.right() # right point y02 = face.bottom() # bottom point landmarks = predictor(image=gray, box=face) x27 = landmarks.part(27).x y27 = landmarks.part(27).y x0 = landmarks.part(0).x y0 = landmarks.part(0).y y15 = landmarks.part(15).y x16 = landmarks.part(16).x y16 = landmarks.part(16).y y17 = landmarks.part(17).y y1 = landmarks.part(1).y y26 = landmarks.part(26).y y33 = landmarks.part(33).y x8 = landmarks.part(8).x x37 = landmarks.part(37).x x44 = landmarks.part(44).x y28 = landmarks.part(28).y d1 = int(x27 - x0) # khoảng cách từ 0 đến 27 d2 = int(x16 - x27) # khoảng cách từ 27 đến 16 currenttime = time.time() if y0 < y17 or y0 > y28 or y0 == y33 or y16 < y26 or x8 < x37 or x8 > x44 or d1 * 2 < d2 or d1 > d2 * 2 or y27 > y1 or y27 > y15: cv2.putText(frame, 'K chap nhan', (x01, y01), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) else: imageBlob = cv2.dnn.blobFromImage(image=img, scalefactor=1.0, size=(300, 300), mean=(104.0, 177.0, 123.0), swapRB=False, crop=False) # Predict face areas detector1.setInput(imageBlob) detections = detector1.forward() currenttime = time.time() box = detections[0, 0, 0, 3:7] * np.array([300, 300, 300, 300]) box = box.astype('int') (startX, startY, endX, endY) = box if (currenttime - preticked > 0.1) and (detections[0, 0, 0, 2] > 0.9): cv2.imwrite(os.path.join('/home/bau/Desktop/1', "%d.jpg" % count), frame) count += 1 preticked = time.time() if count > 20: # cv2.putText(frame, 'Đã nhập dữ liệu xong', (x01, y01), cv2.FONT_HERSHEY_SIMPLEX, # 1, (0, 0, 255), 2, cv2.LINE_AA) break ret, jpg = cv2.imencode('.jpg', frame) return jpg.tobytes() <file_sep>/camera.py from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import numpy as np import os import PIL import tensorflow as tf import cv2 from skimage.transform import resize from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.models import Sequential from tensorflow.keras.models import load_model from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.models import load_model from imutils.video import VideoStream import numpy as np import imutils import time import cv2 import os import tensorflow as tf def detect_and_predict_mask(frame, faceNet, maskNet): # grab the dimensions of the frame and then construct a blob # from it (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224), (104.0, 177.0, 123.0)) faceNet.setInput(blob) detections = faceNet.forward() faces = [] locs = [] preds = [] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.5: box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") (startX, startY) = (max(0, startX), max(0, startY)) (endX, endY) = (min(w - 1, endX), min(h - 1, endY)) face = frame[startY:endY, startX:endX] face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face = cv2.resize(face, (224, 224)) face = img_to_array(face) # face = preprocess_input(face) faces.append(face) locs.append((startX, startY, endX, endY)) if len(faces) > 0: faces = np.array(faces) preds = maskNet.predict(faces) return (locs, preds) prototxtPath = r"C://Users//Admin//Untitled Folder//Tracking//Face-Mask-Detection-master//face_detector//deploy.prototxt" weightsPath = r"C://Users//Admin//Untitled Folder//Tracking//Face-Mask-Detection-master//face_detector//res10_300x300_ssd_iter_140000.caffemodel" faceNet = cv2.dnn.readNet(prototxtPath, weightsPath) maskNet = load_model("C://Users//Admin//Downloads//model3classFaceMarkssFaceMark224.h5") # maskNet = load_model("C://Users//Admin//Untitled Folder//Tracking//Face-Mask-Detection-master//mask_detector.model") class Video(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): count = int(0) while True: ret, frame = self.video.read() frame = cv2.flip(frame, 1) frame = imutils.resize(frame, width=900) # ret,frame = vs.read() # detect faces in the frame and determine if they are wearing a # face mask or not (locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet) # loop over the detected face locations and their corresponding # locations for (box, pred) in zip(locs, preds): # unpack the bounding box and predictions (startX, startY, endX, endY) = box pred = tf.nn.softmax(pred) (mask, withoutMask) = pred # determine the class label and color we'll use to draw # the bounding box and text labell = "Mask" if mask > withoutMask else "No Mask" color = (0, 255, 0) if labell == "Mask" else (0, 0, 255) # include the probability in the label label = "{}: {:.2f}%".format(labell, max(mask, withoutMask) * 100) # display the label and bounding box rectangle on the output # frame cv2.putText(frame, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2) cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2) if (labell=="No Mask"): cv2.imwrite(os.path.join('C://Users//Admin//OneDrive//Desktop//tkpm//face//DataNoMask', "%d.jpg", % count), frame) count = count + 1 print(count) ret, jpg = cv2.imencode('.jpg', frame) if (count > 20): break return jpg.tobytes()<file_sep>/app.py from flask import Flask, render_template, Response, request, redirect, url_for from camera import Video # from train import Video1 import os app = Flask(__name__) @app.route("/") def home(): return render_template('login.html') @app.route("/", methods = ['POST']) def login(): if request.method == "POST": user_name = request.form.get("name") password = request.form.get("pass") if str(user_name) == "vietdz" and str(password) == "1": return render_template('index.html') else: return render_template('login.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') #cam cho nhận diện @app.route('/video') def video_feed(): return Response(gen(Video()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == "__main__": # from waitress import serve app.run(debug=True)
089f555995ebc71af6e85f12a477f3b6bbbf1fa2
[ "Python" ]
4
Python
bap-rang-bo/face_mask_detection
82aed89a021a425383a1212f05af205cf0294350
85e9d39b454eef63ef682eeb057d86a6d9d71a70
refs/heads/master
<repo_name>joshdyer1992/JoshInc<file_sep>/JoshInc.Core/StockHistory.cs using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JoshInc.Core { public class StockHistory { public List<SharePrice> SharePrices { get; set; } public StockHistory() { SharePrices = new List<SharePrice>(); } public void AddSharePrice(SharePrice sharePrice) { SharePrices.Add(sharePrice); } public double GetHighest() { var highs = SharePrices.Select(sharePrice => sharePrice.High); return SharePrices.Select(sharePrice => sharePrice.High).Max(); } public double GetLowest() { return SharePrices.Select(sharePrice => sharePrice.Low).Min(); } } } <file_sep>/JoshInc.Cmd/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JoshInc.Core; namespace JoshInc.Cmd { class Program { static void Main(string[] args) { var reader = new StockHistoryReader(); StockHistory stockHistory = reader.LoadFile(); var highest = stockHistory.GetHighest(); var lowest = stockHistory.GetLowest(); Console.WriteLine($"Highest: {highest}"); Console.WriteLine($"Lowest: {lowest}"); Console.ReadLine(); } } } <file_sep>/JoshInc.Core/StockHistoryReader.cs using System; using System.Globalization; using System.IO; namespace JoshInc.Core { public class StockHistoryReader { public StockHistoryReader() { } public StockHistory LoadFile() { //List<SharePrice> sharePrices = new List<SharePrice>(); StockHistory stockHistory = new StockHistory(); FileStream file = File.Open(@"C:\Users\Paul\documents\visual studio 2017\Projects\JoshInc\JoshInc.Core\AAPL.csv", FileMode.Open); var reader = new StreamReader(file); reader.ReadLine(); while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(','); var sharePrice = new SharePrice { Date = DateTime.ParseExact(values[0], "yyyy-MM-dd", CultureInfo.InvariantCulture), Symbol = "APPL", Open = double.Parse(values[1]), High = double.Parse(values[2]), Low = double.Parse(values[3]), Close = double.Parse(values[4]) }; //sharePrices.Add(sharePrice); stockHistory.AddSharePrice(sharePrice); } //return sharePrices; return stockHistory; } } }<file_sep>/JoshInc.Core/SharePrice.cs using System; namespace JoshInc.Core { public class SharePrice { public string Symbol { get; set; } public DateTime Date { get; set; } public double High { get; set; } public double Low { get; set; } public double Open { get; set; } public double Close { get; set; } } }
289b37af93d194b93e3c19c4515e4359b8d3ff4f
[ "C#" ]
4
C#
joshdyer1992/JoshInc
a0f32c4cbbdb328464a2ca19bed3325adb20ed68
015825ddef287e599e14f6fd12bf607d8e0dbb40
refs/heads/master
<file_sep>// you can also use imports, for example: import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public int[] solution(String S, int[] P, int[] Q) { // write your code in Java SE 8 int [] result = new int[P.length]; for (int i = 0; i < P.length; i++) { String dif = S.substring(P[i], Q[i] + 1); char [] newS = dif.toCharArray(); int tmp = 0; Arrays.sort(newS); switch (newS[0]) { case 'A' : tmp = 1; break; case 'C' : tmp = 2; break; case 'G' : tmp = 3; break; case 'T' : tmp = 4; break; } result[i] = tmp; } return result; } } <file_sep>// you can write to stdout for debugging purposes, e.g. // console.log('this is a debug message'); function solution(S) { var S = S.split(""); var stack = []; for (var i = 0; i < S.length; i++) { var c = S[i]; if (c == '{' || c == '[' || c == '('){ stack.push(c); } else if (c == '}' || c == ')' || c == ']'){ var t = stack.pop() + c; if (t != "{}" && t != "[]" && t != "()") { return 0; } } else { return 0; } } if (stack.length > 0) { return 0; } return 1; }
67d478f30cd0a6d15e9af3a6cbf27d8637f7767b
[ "JavaScript", "Java" ]
2
Java
macpaik/algorithm
e3ee58c617666b5323cd5e494f0912262a6d0178
f0a63b317005ba1ec90a9a29297d36b28303baa7
refs/heads/master
<repo_name>chartjs/chartjs-chart-financial<file_sep>/src/element.candlestick.js 'use strict'; import {Chart} from 'chart.js'; import {merge, valueOrDefault} from 'chart.js/helpers'; import {FinancialElement} from './element.financial'; const globalOpts = Chart.defaults; export class CandlestickElement extends FinancialElement { draw(ctx) { const me = this; const {x, open, high, low, close} = me; let borderColors = me.borderColor; if (typeof borderColors === 'string') { borderColors = { up: borderColors, down: borderColors, unchanged: borderColors }; } let borderColor; if (close < open) { borderColor = valueOrDefault(borderColors ? borderColors.up : undefined, globalOpts.elements.candlestick.borderColor); ctx.fillStyle = valueOrDefault(me.color ? me.color.up : undefined, globalOpts.elements.candlestick.color.up); } else if (close > open) { borderColor = valueOrDefault(borderColors ? borderColors.down : undefined, globalOpts.elements.candlestick.borderColor); ctx.fillStyle = valueOrDefault(me.color ? me.color.down : undefined, globalOpts.elements.candlestick.color.down); } else { borderColor = valueOrDefault(borderColors ? borderColors.unchanged : undefined, globalOpts.elements.candlestick.borderColor); ctx.fillStyle = valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts.elements.candlestick.color.unchanged); } ctx.lineWidth = valueOrDefault(me.borderWidth, globalOpts.elements.candlestick.borderWidth); ctx.strokeStyle = valueOrDefault(borderColor, globalOpts.elements.candlestick.borderColor); ctx.beginPath(); ctx.moveTo(x, high); ctx.lineTo(x, Math.min(open, close)); ctx.moveTo(x, low); ctx.lineTo(x, Math.max(open, close)); ctx.stroke(); ctx.fillRect(x - me.width / 2, close, me.width, open - close); ctx.strokeRect(x - me.width / 2, close, me.width, open - close); ctx.closePath(); } } CandlestickElement.id = 'candlestick'; CandlestickElement.defaults = merge({}, [globalOpts.elements.financial, { borderColor: globalOpts.elements.financial.color.unchanged, borderWidth: 1, }]); <file_sep>/src/element.ohlc.js 'use strict'; import {Chart} from 'chart.js'; import {merge, valueOrDefault} from 'chart.js/helpers'; import {FinancialElement} from './element.financial'; const globalOpts = Chart.defaults; export class OhlcElement extends FinancialElement { draw(ctx) { const me = this; const {x, open, high, low, close} = me; const armLengthRatio = valueOrDefault(me.armLengthRatio, globalOpts.elements.ohlc.armLengthRatio); let armLength = valueOrDefault(me.armLength, globalOpts.elements.ohlc.armLength); if (armLength === null) { // The width of an ohlc is affected by barPercentage and categoryPercentage // This behavior is caused by extending controller.financial, which extends controller.bar // barPercentage and categoryPercentage are now set to 1.0 (see controller.ohlc) // and armLengthRatio is multipled by 0.5, // so that when armLengthRatio=1.0, the arms from neighbour ohcl touch, // and when armLengthRatio=0.0, ohcl are just vertical lines. armLength = me.width * armLengthRatio * 0.5; } if (close < open) { ctx.strokeStyle = valueOrDefault(me.color ? me.color.up : undefined, globalOpts.elements.ohlc.color.up); } else if (close > open) { ctx.strokeStyle = valueOrDefault(me.color ? me.color.down : undefined, globalOpts.elements.ohlc.color.down); } else { ctx.strokeStyle = valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts.elements.ohlc.color.unchanged); } ctx.lineWidth = valueOrDefault(me.lineWidth, globalOpts.elements.ohlc.lineWidth); ctx.beginPath(); ctx.moveTo(x, high); ctx.lineTo(x, low); ctx.moveTo(x - armLength, open); ctx.lineTo(x, open); ctx.moveTo(x + armLength, close); ctx.lineTo(x, close); ctx.stroke(); } } OhlcElement.id = 'ohlc'; OhlcElement.defaults = merge({}, [globalOpts.elements.financial, { lineWidth: 2, armLength: null, armLengthRatio: 0.8, }]); <file_sep>/docs/index.js var barCount = 60; var initialDateStr = '01 Apr 2017 00:00 Z'; var ctx = document.getElementById('chart').getContext('2d'); ctx.canvas.width = 1000; ctx.canvas.height = 250; var barData = getRandomData(initialDateStr, barCount); function lineData() { return barData.map(d => { return { x: d.x, y: d.c} }) }; var chart = new Chart(ctx, { type: 'candlestick', data: { datasets: [{ label: 'CHRT - Chart.js Corporation', data: barData }] } }); var getRandomInt = function(max) { return Math.floor(Math.random() * Math.floor(max)); }; function randomNumber(min, max) { return Math.random() * (max - min) + min; } function randomBar(date, lastClose) { var open = +randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2); var close = +randomNumber(open * 0.95, open * 1.05).toFixed(2); var high = +randomNumber(Math.max(open, close), Math.max(open, close) * 1.1).toFixed(2); var low = +randomNumber(Math.min(open, close) * 0.9, Math.min(open, close)).toFixed(2); return { x: date.valueOf(), o: open, h: high, l: low, c: close }; } function getRandomData(dateStr, count) { var date = luxon.DateTime.fromRFC2822(dateStr); var data = [randomBar(date, 30)]; while (data.length < count) { date = date.plus({days: 1}); if (date.weekday <= 5) { data.push(randomBar(date, data[data.length - 1].c)); } } return data; } var update = function() { var dataset = chart.config.data.datasets[0]; // candlestick vs ohlc var type = document.getElementById('type').value; dataset.type = type; // linear vs log var scaleType = document.getElementById('scale-type').value; chart.config.options.scales.y.type = scaleType; // color var colorScheme = document.getElementById('color-scheme').value; if (colorScheme === 'neon') { dataset.color = { up: '#01ff01', down: '#fe0000', unchanged: '#999', }; } else { delete dataset.color; } // border var border = document.getElementById('border').value; var defaultOpts = Chart.defaults.elements[type]; if (border === 'true') { dataset.borderColor = defaultOpts.borderColor; } else { dataset.borderColor = { up: defaultOpts.color.up, down: defaultOpts.color.down, unchanged: defaultOpts.color.up }; } // mixed charts var mixed = document.getElementById('mixed').value; if(mixed === 'true') { chart.config.data.datasets = [ { label: 'CHRT - Chart.js Corporation', data: barData }, { label: 'Close price', type: 'line', data: lineData() } ] } else { chart.config.data.datasets = [ { label: 'CHRT - Chart.js Corporation', data: barData } ] } chart.update(); }; document.getElementById('update').addEventListener('click', update); document.getElementById('randomizeData').addEventListener('click', function() { barData = getRandomData(initialDateStr, barCount); update(); }); <file_sep>/README.md # Chart.js Financial Charting Chart.js module for Candlestick and OHLC charts ## Roadmap Chart.js 2.7.0 added our timeseries scale as new option called [`distribution: series`](http://www.chartjs.org/docs/latest/axes/cartesian/time.html). This has greatly improved support for financial timeseries. Chart.js 2.7.1 added [fixes for timeseries](https://github.com/chartjs/Chart.js/pull/4779). Chart.js 2.7.2 added [formatting of timestamps in tooltips](https://github.com/chartjs/Chart.js/pull/5095). Chart.js 2.7.3 included a [fix for hovering](https://github.com/chartjs/Chart.js/pull/5570). Chart.js 2.8.0 added datetime adapters and [time scale performance improvements](https://github.com/chartjs/Chart.js/pull/6019). This allows users to use a datetime library of their choosing such as [Luxon](https://moment.github.io/luxon/) in order to get i18n and timezone support Chart.js 2.9.0 added [improved autoskipping](https://github.com/chartjs/Chart.js/pull/6509), [support for floating bars](https://github.com/chartjs/Chart.js/pull/6056), [better support for mixed chart types](https://github.com/chartjs/Chart.js/pull/5999), and [numerous performance improvements](https://github.com/chartjs/Chart.js/releases/tag/v2.9.0). Chart.js 3.0.0 removed the need for custom scales, which means logarithmic scale is now supported. It also has numerous performance improvements. ## Comparison We are aiming to make Chart.js the only popular JavaScript library that is both performant and has good timescale handling. Most chart libraries don't have great handling of timescale axes and will not always choose the first of the month, year, etc. as labels. This library leverages the concept of major ticks that we introduced in Chart.js. E.g. it will make sure that the first day of each month is plotted before plotting days in between. One of the best libraries we've found for financial charts is [react-stockcharts](https://github.com/rrag/react-stockcharts). However, it ties the user to utilizing React. Because Chart.js utilizes canvas it is more performant than the majority of JavaScript charting libraries. In a [benchmark of the fastest JavaScript chart libraries](https://github.com/leeoniya/uPlot#performance), Chart.js performs respectably. Chart.js is slower than some of the fastest libraries like uPlot because it accepts varied input (parsing, linear and timeseries support in time scale, etc.) and has animation support (which is still costly even when off due to the way the code is structured). ## Documentation As we near an initial release we will add additional documentation. For now, please see the docs directory. ### Examples Examples are available here: https://chartjs.github.io/chartjs-chart-financial/ ### Date Libraries & IE Support IE may not be supported because we use some newer ES features. We will need to apply Babel to fix this Chart.js requires that you supply a date library. The examples utilize [chartjs-adapter-luxon](https://github.com/chartjs/chartjs-adapter-luxon), which has the best support for i18n and time zones. However, in order to use [Luxon](http://moment.github.io/luxon/) with IE you need to supply polyfills. If you require IE support you may find it easier to use another date library like [Moment](https://momentjs.com/) or [date-fns](https://date-fns.org/). Please see the Chart.js documentation for more details on date adapters. ## Related Plugins The plugins below may be particularly interesting to use with financial charts. See [the Chart.js plugin API](https://www.chartjs.org/docs/latest/developers/plugins.html) and [longer list of plugins](https://www.chartjs.org/docs/latest/notes/extensions.html#plugins) for more info about Chart.js plugins generally. - [chartjs-plugin-zoom](https://github.com/chartjs/chartjs-plugin-zoom) - [chartjs-plugin-crosshair](https://github.com/abelheinsbroek/chartjs-plugin-crosshair) ([demo](https://www.abelheinsbroek.nl/financial/)) - [chartjs-plugin-streaming](https://github.com/nagix/chartjs-plugin-streaming) ([demo](https://nagix.github.io/chartjs-plugin-streaming/master/samples/integration/financial.html)) ## Building <a href="https://travis-ci.org/chartjs/chartjs-chart-financial"><img src="https://img.shields.io/travis/chartjs/chartjs-chart-financial.svg?style=flat-square&maxAge=600" alt="Builds"></a> ```sh npm install gulp build ``` <file_sep>/types/index.d.ts import { BarController, BarControllerChartOptions, BarControllerDatasetOptions, CartesianScaleTypeRegistry, Chart, ChartComponent } from 'chart.js'; declare module 'chart.js' { interface FinancialDataPoint { x: number, o: number, h: number, l: number, c: number } interface FinancialParsedData { // eslint-disable-next-line @typescript-eslint/no-explicit-any _custom?: any } interface ChartTypeRegistry { candlestick: { chartOptions: BarControllerChartOptions; datasetOptions: BarControllerDatasetOptions; defaultDataPoint: FinancialDataPoint; metaExtensions: {}; parsedDataType: FinancialParsedData; scales: keyof CartesianScaleTypeRegistry; }; ohlc: { chartOptions: BarControllerChartOptions; datasetOptions: BarControllerDatasetOptions; defaultDataPoint: FinancialDataPoint; metaExtensions: {}; parsedDataType: FinancialParsedData; scales: keyof CartesianScaleTypeRegistry; } } } declare const CandlestickController: ChartComponent & { prototype: BarController; new(chart: Chart, datasetIndex: number): BarController; }; declare const OhlcController: ChartComponent & { prototype: BarController; new(chart: Chart, datasetIndex: number): BarController; }; declare const CandlestickElement: Element; declare const OhlcElement: Element; <file_sep>/src/element.financial.js 'use strict'; import {Chart, Element} from 'chart.js'; const globalOpts = Chart.defaults; globalOpts.elements.financial = { color: { up: 'rgba(80, 160, 115, 1)', down: 'rgba(215, 85, 65, 1)', unchanged: 'rgba(90, 90, 90, 1)', } }; /** * Helper function to get the bounds of the bar regardless of the orientation * @param {Rectangle} bar the bar * @param {boolean} [useFinalPosition] * @return {object} bounds of the bar * @private */ function getBarBounds(bar, useFinalPosition) { const {x, y, base, width, height} = bar.getProps(['x', 'low', 'high', 'width', 'height'], useFinalPosition); let left, right, top, bottom, half; if (bar.horizontal) { half = height / 2; left = Math.min(x, base); right = Math.max(x, base); top = y - half; bottom = y + half; } else { half = width / 2; left = x - half; right = x + half; top = Math.min(y, base); // use min because 0 pixel at top of screen bottom = Math.max(y, base); } return {left, top, right, bottom}; } function inRange(bar, x, y, useFinalPosition) { const skipX = x === null; const skipY = y === null; const bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar, useFinalPosition); return bounds && (skipX || x >= bounds.left && x <= bounds.right) && (skipY || y >= bounds.top && y <= bounds.bottom); } export class FinancialElement extends Element { height() { return this.base - this.y; } inRange(mouseX, mouseY, useFinalPosition) { return inRange(this, mouseX, mouseY, useFinalPosition); } inXRange(mouseX, useFinalPosition) { return inRange(this, mouseX, null, useFinalPosition); } inYRange(mouseY, useFinalPosition) { return inRange(this, null, mouseY, useFinalPosition); } getRange(axis) { return axis === 'x' ? this.width / 2 : this.height / 2; } getCenterPoint(useFinalPosition) { const {x, low, high} = this.getProps(['x', 'low', 'high'], useFinalPosition); return { x, y: (high + low) / 2 }; } tooltipPosition(useFinalPosition) { const {x, open, close} = this.getProps(['x', 'open', 'close'], useFinalPosition); return { x, y: (open + close) / 2 }; } } <file_sep>/.github/PULL_REQUEST_TEMPLATE.md Thanks for contributing. - [ ] Tick to sign-off your agreement to the [Developer Certificate of Origin (DCO) 1.1](https://developercertificate.org) ## Description What was changed ## Testing Add a unit test as part of your change or include a screenshot here as appropriate <file_sep>/src/controller.financial.js 'use strict'; import {BarController, defaults} from 'chart.js'; import {clipArea, isNullOrUndef, unclipArea} from 'chart.js/helpers'; /** * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap. * @private */ function computeMinSampleSize(scale, pixels) { let min = scale._length; let prev, curr, i, ilen; for (i = 1, ilen = pixels.length; i < ilen; ++i) { min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1])); } for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { curr = scale.getPixelForTick(i); min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min; prev = curr; } return min; } /** * This class is based off controller.bar.js from the upstream Chart.js library */ export class FinancialController extends BarController { getLabelAndValue(index) { const me = this; const parsed = me.getParsed(index); const axis = me._cachedMeta.iScale.axis; const {o, h, l, c} = parsed; const value = `O: ${o} H: ${h} L: ${l} C: ${c}`; return { label: `${me._cachedMeta.iScale.getLabelForValue(parsed[axis])}`, value }; } getAllParsedValues() { const meta = this._cachedMeta; const axis = meta.iScale.axis; const parsed = meta._parsed; const values = []; for (let i = 0; i < parsed.length; ++i) { values.push(parsed[i][axis]); } return values; } /** * Implement this ourselves since it doesn't handle high and low values * https://github.com/chartjs/Chart.js/issues/7328 * @protected */ getMinMax(scale) { const meta = this._cachedMeta; const _parsed = meta._parsed; const axis = meta.iScale.axis; if (_parsed.length < 2) { return {min: 0, max: 1}; } if (scale === meta.iScale) { return {min: _parsed[0][axis], max: _parsed[_parsed.length - 1][axis]}; } let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; for (let i = 0; i < _parsed.length; i++) { const data = _parsed[i]; min = Math.min(min, data.l); max = Math.max(max, data.h); } return {min, max}; } _getRuler() { const me = this; const opts = me.options; const meta = me._cachedMeta; const iScale = meta.iScale; const axis = iScale.axis; const pixels = []; for (let i = 0; i < meta.data.length; ++i) { pixels.push(iScale.getPixelForValue(me.getParsed(i)[axis])); } const barThickness = opts.barThickness; const min = computeMinSampleSize(iScale, pixels); return { min, pixels, start: iScale._startPixel, end: iScale._endPixel, stackCount: me._getStackCount(), scale: iScale, ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage }; } /** * @protected */ calculateElementProperties(index, ruler, reset, options) { const me = this; const vscale = me._cachedMeta.vScale; const base = vscale.getBasePixel(); const ipixels = me._calculateBarIndexPixels(index, ruler, options); const data = me.chart.data.datasets[me.index].data[index]; const open = vscale.getPixelForValue(data.o); const high = vscale.getPixelForValue(data.h); const low = vscale.getPixelForValue(data.l); const close = vscale.getPixelForValue(data.c); return { base: reset ? base : low, x: ipixels.center, y: (low + high) / 2, width: ipixels.size, open, high, low, close }; } draw() { const me = this; const chart = me.chart; const rects = me._cachedMeta.data; clipArea(chart.ctx, chart.chartArea); for (let i = 0; i < rects.length; ++i) { rects[i].draw(me._ctx); } unclipArea(chart.ctx); } } FinancialController.overrides = { label: '', parsing: false, hover: { mode: 'label' }, datasets: { categoryPercentage: 0.8, barPercentage: 0.9, animation: { numbers: { type: 'number', properties: ['x', 'y', 'base', 'width', 'open', 'high', 'low', 'close'] } } }, scales: { x: { type: 'timeseries', offset: true, ticks: { major: { enabled: true, }, fontStyle: context => context.tick.major ? 'bold' : undefined, source: 'data', maxRotation: 0, autoSkip: true, autoSkipPadding: 75, sampleSize: 100 }, afterBuildTicks: scale => { const DateTime = window && window.luxon && window.luxon.DateTime; if (!DateTime) { return; } const majorUnit = scale._majorUnit; const ticks = scale.ticks; const firstTick = ticks[0]; if (!firstTick) { return; } let val = DateTime.fromMillis(firstTick.value); if ((majorUnit === 'minute' && val.second === 0) || (majorUnit === 'hour' && val.minute === 0) || (majorUnit === 'day' && val.hour === 9) || (majorUnit === 'month' && val.day <= 3 && val.weekday === 1) || (majorUnit === 'year' && val.month === 1)) { firstTick.major = true; } else { firstTick.major = false; } let lastMajor = val.get(majorUnit); for (let i = 1; i < ticks.length; i++) { const tick = ticks[i]; val = DateTime.fromMillis(tick.value); const currMajor = val.get(majorUnit); tick.major = currMajor !== lastMajor; lastMajor = currMajor; } scale.ticks = ticks; } }, y: { type: 'linear' } }, plugins: { tooltip: { intersect: false, mode: 'index', callbacks: { label(ctx) { const point = ctx.parsed; if (!isNullOrUndef(point.y)) { return defaults.plugins.tooltip.callbacks.label(ctx); } const {o, h, l, c} = point; return `O: ${o} H: ${h} L: ${l} C: ${c}`; } } } } }; <file_sep>/docs/chartjs-chart-financial.js /*! * @license * chartjs-chart-financial * http://chartjs.org/ * Version: 0.1.0 * * Copyright 2021 Chart.js Contributors * Released under the MIT license * https://github.com/chartjs/chartjs-chart-financial/blob/master/LICENSE.md */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js'), require('chart.js/helpers')) : typeof define === 'function' && define.amd ? define(['chart.js', 'chart.js/helpers'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Chart, global.Chart.helpers)); }(this, (function (chart_js, helpers) { 'use strict'; /** * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap. * @private */ function computeMinSampleSize(scale, pixels) { let min = scale._length; let prev, curr, i, ilen; for (i = 1, ilen = pixels.length; i < ilen; ++i) { min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1])); } for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { curr = scale.getPixelForTick(i); min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min; prev = curr; } return min; } /** * This class is based off controller.bar.js from the upstream Chart.js library */ class FinancialController extends chart_js.BarController { getLabelAndValue(index) { const me = this; const parsed = me.getParsed(index); const axis = me._cachedMeta.iScale.axis; const {o, h, l, c} = parsed; const value = `O: ${o} H: ${h} L: ${l} C: ${c}`; return { label: `${me._cachedMeta.iScale.getLabelForValue(parsed[axis])}`, value }; } getAllParsedValues() { const meta = this._cachedMeta; const axis = meta.iScale.axis; const parsed = meta._parsed; const values = []; for (let i = 0; i < parsed.length; ++i) { values.push(parsed[i][axis]); } return values; } /** * Implement this ourselves since it doesn't handle high and low values * https://github.com/chartjs/Chart.js/issues/7328 * @protected */ getMinMax(scale) { const meta = this._cachedMeta; const _parsed = meta._parsed; const axis = meta.iScale.axis; if (_parsed.length < 2) { return {min: 0, max: 1}; } if (scale === meta.iScale) { return {min: _parsed[0][axis], max: _parsed[_parsed.length - 1][axis]}; } let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; for (let i = 0; i < _parsed.length; i++) { const data = _parsed[i]; min = Math.min(min, data.l); max = Math.max(max, data.h); } return {min, max}; } _getRuler() { const me = this; const opts = me.options; const meta = me._cachedMeta; const iScale = meta.iScale; const axis = iScale.axis; const pixels = []; for (let i = 0; i < meta.data.length; ++i) { pixels.push(iScale.getPixelForValue(me.getParsed(i)[axis])); } const barThickness = opts.barThickness; const min = computeMinSampleSize(iScale, pixels); return { min, pixels, start: iScale._startPixel, end: iScale._endPixel, stackCount: me._getStackCount(), scale: iScale, ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage }; } /** * @protected */ calculateElementProperties(index, ruler, reset, options) { const me = this; const vscale = me._cachedMeta.vScale; const base = vscale.getBasePixel(); const ipixels = me._calculateBarIndexPixels(index, ruler, options); const data = me.chart.data.datasets[me.index].data[index]; const open = vscale.getPixelForValue(data.o); const high = vscale.getPixelForValue(data.h); const low = vscale.getPixelForValue(data.l); const close = vscale.getPixelForValue(data.c); return { base: reset ? base : low, x: ipixels.center, y: (low + high) / 2, width: ipixels.size, open, high, low, close }; } draw() { const me = this; const chart = me.chart; const rects = me._cachedMeta.data; helpers.clipArea(chart.ctx, chart.chartArea); for (let i = 0; i < rects.length; ++i) { rects[i].draw(me._ctx); } helpers.unclipArea(chart.ctx); } } FinancialController.overrides = { label: '', parsing: false, hover: { mode: 'label' }, datasets: { categoryPercentage: 0.8, barPercentage: 0.9, animation: { numbers: { type: 'number', properties: ['x', 'y', 'base', 'width', 'open', 'high', 'low', 'close'] } } }, scales: { x: { type: 'timeseries', offset: true, ticks: { major: { enabled: true, }, fontStyle: context => context.tick.major ? 'bold' : undefined, source: 'data', maxRotation: 0, autoSkip: true, autoSkipPadding: 75, sampleSize: 100 }, afterBuildTicks: scale => { const DateTime = window && window.luxon && window.luxon.DateTime; if (!DateTime) { return; } const majorUnit = scale._majorUnit; const ticks = scale.ticks; const firstTick = ticks[0]; if (!firstTick) { return; } let val = DateTime.fromMillis(firstTick.value); if ((majorUnit === 'minute' && val.second === 0) || (majorUnit === 'hour' && val.minute === 0) || (majorUnit === 'day' && val.hour === 9) || (majorUnit === 'month' && val.day <= 3 && val.weekday === 1) || (majorUnit === 'year' && val.month === 1)) { firstTick.major = true; } else { firstTick.major = false; } let lastMajor = val.get(majorUnit); for (let i = 1; i < ticks.length; i++) { const tick = ticks[i]; val = DateTime.fromMillis(tick.value); const currMajor = val.get(majorUnit); tick.major = currMajor !== lastMajor; lastMajor = currMajor; } scale.ticks = ticks; } }, y: { type: 'linear' } }, plugins: { tooltip: { intersect: false, mode: 'index', callbacks: { label(ctx) { const point = ctx.parsed; if (!helpers.isNullOrUndef(point.y)) { return chart_js.defaults.plugins.tooltip.callbacks.label(ctx); } const {o, h, l, c} = point; return `O: ${o} H: ${h} L: ${l} C: ${c}`; } } } } }; const globalOpts$2 = chart_js.Chart.defaults; globalOpts$2.elements.financial = { color: { up: 'rgba(80, 160, 115, 1)', down: 'rgba(215, 85, 65, 1)', unchanged: 'rgba(90, 90, 90, 1)', } }; /** * Helper function to get the bounds of the bar regardless of the orientation * @param {Rectangle} bar the bar * @param {boolean} [useFinalPosition] * @return {object} bounds of the bar * @private */ function getBarBounds(bar, useFinalPosition) { const {x, y, base, width, height} = bar.getProps(['x', 'low', 'high', 'width', 'height'], useFinalPosition); let left, right, top, bottom, half; if (bar.horizontal) { half = height / 2; left = Math.min(x, base); right = Math.max(x, base); top = y - half; bottom = y + half; } else { half = width / 2; left = x - half; right = x + half; top = Math.min(y, base); // use min because 0 pixel at top of screen bottom = Math.max(y, base); } return {left, top, right, bottom}; } function inRange(bar, x, y, useFinalPosition) { const skipX = x === null; const skipY = y === null; const bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar, useFinalPosition); return bounds && (skipX || x >= bounds.left && x <= bounds.right) && (skipY || y >= bounds.top && y <= bounds.bottom); } class FinancialElement extends chart_js.Element { height() { return this.base - this.y; } inRange(mouseX, mouseY, useFinalPosition) { return inRange(this, mouseX, mouseY, useFinalPosition); } inXRange(mouseX, useFinalPosition) { return inRange(this, mouseX, null, useFinalPosition); } inYRange(mouseY, useFinalPosition) { return inRange(this, null, mouseY, useFinalPosition); } getRange(axis) { return axis === 'x' ? this.width / 2 : this.height / 2; } getCenterPoint(useFinalPosition) { const {x, low, high} = this.getProps(['x', 'low', 'high'], useFinalPosition); return { x, y: (high + low) / 2 }; } tooltipPosition(useFinalPosition) { const {x, open, close} = this.getProps(['x', 'open', 'close'], useFinalPosition); return { x, y: (open + close) / 2 }; } } const globalOpts$1 = chart_js.Chart.defaults; class CandlestickElement extends FinancialElement { draw(ctx) { const me = this; const {x, open, high, low, close} = me; let borderColors = me.borderColor; if (typeof borderColors === 'string') { borderColors = { up: borderColors, down: borderColors, unchanged: borderColors }; } let borderColor; if (close < open) { borderColor = helpers.valueOrDefault(borderColors ? borderColors.up : undefined, globalOpts$1.elements.candlestick.borderColor); ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.up : undefined, globalOpts$1.elements.candlestick.color.up); } else if (close > open) { borderColor = helpers.valueOrDefault(borderColors ? borderColors.down : undefined, globalOpts$1.elements.candlestick.borderColor); ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.down : undefined, globalOpts$1.elements.candlestick.color.down); } else { borderColor = helpers.valueOrDefault(borderColors ? borderColors.unchanged : undefined, globalOpts$1.elements.candlestick.borderColor); ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts$1.elements.candlestick.color.unchanged); } ctx.lineWidth = helpers.valueOrDefault(me.borderWidth, globalOpts$1.elements.candlestick.borderWidth); ctx.strokeStyle = helpers.valueOrDefault(borderColor, globalOpts$1.elements.candlestick.borderColor); ctx.beginPath(); ctx.moveTo(x, high); ctx.lineTo(x, Math.min(open, close)); ctx.moveTo(x, low); ctx.lineTo(x, Math.max(open, close)); ctx.stroke(); ctx.fillRect(x - me.width / 2, close, me.width, open - close); ctx.strokeRect(x - me.width / 2, close, me.width, open - close); ctx.closePath(); } } CandlestickElement.id = 'candlestick'; CandlestickElement.defaults = helpers.merge({}, [globalOpts$1.elements.financial, { borderColor: globalOpts$1.elements.financial.color.unchanged, borderWidth: 1, }]); class CandlestickController extends FinancialController { updateElements(elements, start, count, mode) { const me = this; const dataset = me.getDataset(); const ruler = me._ruler || me._getRuler(); const firstOpts = me.resolveDataElementOptions(start, mode); const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); me.updateSharedOptions(sharedOptions, mode, firstOpts); for (let i = start; i < count; i++) { const options = sharedOptions || me.resolveDataElementOptions(i, mode); const baseProperties = me.calculateElementProperties(i, ruler, mode === 'reset', options); const properties = { ...baseProperties, datasetLabel: dataset.label || '', // label: '', // to get label value please use dataset.data[index].label // Appearance color: dataset.color, borderColor: dataset.borderColor, borderWidth: dataset.borderWidth, }; if (includeOptions) { properties.options = options; } me.updateElement(elements[i], i, properties, mode); } } } CandlestickController.id = 'candlestick'; CandlestickController.defaults = helpers.merge({ dataElementType: CandlestickElement.id }, chart_js.Chart.defaults.financial); const globalOpts = chart_js.Chart.defaults; class OhlcElement extends FinancialElement { draw(ctx) { const me = this; const {x, open, high, low, close} = me; const armLengthRatio = helpers.valueOrDefault(me.armLengthRatio, globalOpts.elements.ohlc.armLengthRatio); let armLength = helpers.valueOrDefault(me.armLength, globalOpts.elements.ohlc.armLength); if (armLength === null) { // The width of an ohlc is affected by barPercentage and categoryPercentage // This behavior is caused by extending controller.financial, which extends controller.bar // barPercentage and categoryPercentage are now set to 1.0 (see controller.ohlc) // and armLengthRatio is multipled by 0.5, // so that when armLengthRatio=1.0, the arms from neighbour ohcl touch, // and when armLengthRatio=0.0, ohcl are just vertical lines. armLength = me.width * armLengthRatio * 0.5; } if (close < open) { ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.up : undefined, globalOpts.elements.ohlc.color.up); } else if (close > open) { ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.down : undefined, globalOpts.elements.ohlc.color.down); } else { ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts.elements.ohlc.color.unchanged); } ctx.lineWidth = helpers.valueOrDefault(me.lineWidth, globalOpts.elements.ohlc.lineWidth); ctx.beginPath(); ctx.moveTo(x, high); ctx.lineTo(x, low); ctx.moveTo(x - armLength, open); ctx.lineTo(x, open); ctx.moveTo(x + armLength, close); ctx.lineTo(x, close); ctx.stroke(); } } OhlcElement.id = 'ohlc'; OhlcElement.defaults = helpers.merge({}, [globalOpts.elements.financial, { lineWidth: 2, armLength: null, armLengthRatio: 0.8, }]); class OhlcController extends FinancialController { updateElements(elements, start, count, mode) { const me = this; const dataset = me.getDataset(); const ruler = me._ruler || me._getRuler(); const firstOpts = me.resolveDataElementOptions(start, mode); const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); for (let i = 0; i < count; i++) { const options = sharedOptions || me.resolveDataElementOptions(i, mode); const baseProperties = me.calculateElementProperties(i, ruler, mode === 'reset', options); const properties = { ...baseProperties, datasetLabel: dataset.label || '', lineWidth: dataset.lineWidth, armLength: dataset.armLength, armLengthRatio: dataset.armLengthRatio, color: dataset.color, }; if (includeOptions) { properties.options = options; } me.updateElement(elements[i], i, properties, mode); } } } OhlcController.id = 'ohlc'; OhlcController.defaults = helpers.merge({ dataElementType: OhlcElement.id, datasets: { barPercentage: 1.0, categoryPercentage: 1.0 } }, chart_js.Chart.defaults.financial); chart_js.Chart.register(CandlestickController, OhlcController, CandlestickElement, OhlcElement); }))); <file_sep>/src/controller.candlestick.js 'use strict'; import {Chart} from 'chart.js'; import {merge} from 'chart.js/helpers'; import {FinancialController} from './controller.financial'; import {CandlestickElement} from './element.candlestick'; export class CandlestickController extends FinancialController { updateElements(elements, start, count, mode) { const me = this; const dataset = me.getDataset(); const ruler = me._ruler || me._getRuler(); const firstOpts = me.resolveDataElementOptions(start, mode); const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); me.updateSharedOptions(sharedOptions, mode, firstOpts); for (let i = start; i < count; i++) { const options = sharedOptions || me.resolveDataElementOptions(i, mode); const baseProperties = me.calculateElementProperties(i, ruler, mode === 'reset', options); const properties = { ...baseProperties, datasetLabel: dataset.label || '', // label: '', // to get label value please use dataset.data[index].label // Appearance color: dataset.color, borderColor: dataset.borderColor, borderWidth: dataset.borderWidth, }; if (includeOptions) { properties.options = options; } me.updateElement(elements[i], i, properties, mode); } } } CandlestickController.id = 'candlestick'; CandlestickController.defaults = merge({ dataElementType: CandlestickElement.id }, Chart.defaults.financial); <file_sep>/test/specs/element.candlestick.tests.js import {CandlestickElement} from '../../src/element.candlestick'; describe('Candlestick element tests', function() { it('Should correctly identify as in range', function() { const candle = new CandlestickElement(); Object.assign(candle, { base: 200, x: 10, y: 100, width: 50, open: 180, high: 100, low: 200, close: 120, }); expect(candle.inRange(10, 130)).toBe(true); expect(candle.inRange(10, 190)).toBe(true); expect(candle.inRange(10, 80)).toBe(false); expect(candle.inRange(5, 400)).toBe(false); }); }); <file_sep>/test/specs/controller.financial.tests.js describe('Financial controller tests', function() { it('Should create candlestick elements for each data item during initialization', function() { var chart = window.acquireChart({type: 'candlestick', data: { datasets: [{ data: [ {x: 1491004800, o: 70.87, h: 80.13, l: 40.94, c: 50.24}, {x: 1491091200, o: 60.23, h: 200.23, l: 50.29, c: 90.20}, {x: 1491177600, o: 40.00, h: 50.42, l: 20.31, c: 30.20}, {x: 1491264000, o: 60.90, h: 80.34, l: 40.14, c: 60.29}, {x: 1491350400, o: 60.94, h: 100.09, l: 50.78, c: 90.04}, {x: 1491436800, o: 30.49, h: 50.20, l: 20.09, c: 40.20}, {x: 1491523200, o: 50.04, h: 80.93, l: 40.94, c: 70.24}, {x: 1491609600, o: 60.29, h: 100.49, l: 50.49, c: 90.24}, {x: 1491696000, o: 40.04, h: 50.23, l: 20.23, c: 30.49}, {x: 1491782400, o: 30.23, h: 50.09, l: 20.87, c: 40.49} ] }] }, getDatasetMeta: function(datasetIndex) { this.data.datasets[datasetIndex].meta = this.data.datasets[datasetIndex].meta || { data: [], dataset: null }; return this.data.datasets[datasetIndex].meta; } }); var meta = chart.getDatasetMeta(0); expect(meta.data.length).toBe(10); for (var i = 0; i < meta.data.length; i++) { expect(meta.data[i].x > 0).toBe(true); expect(meta.data[i].y > 0).toBe(true); } }); }); <file_sep>/scripts/publish.sh #!/bin/bash set -e NPM_TAG="next" if [[ "$VERSION" =~ ^[^-]+$ ]]; then echo "Release tag indicates a full release. Releasing as \"latest\"." NPM_TAG="latest" fi npm publish --tag "$NPM_TAG" <file_sep>/types/tests/index.ts import { Chart } from 'chart.js'; // eslint-disable-next-line @typescript-eslint/no-unused-vars const chart = new Chart('id', { type: 'candlestick', data: { labels: [], datasets: [{ data: [{ c: 10, x: new Date(), h: 11, l: 3, o: 2 }] }] }, options: { plugins: {} }, plugins: [] }); <file_sep>/test/index.js 'use strict'; import utils from './utils'; // Keep track of all acquired charts to automatically release them after each specs var charts = {}; function acquireChart() { var chart = utils.acquireChart.apply(utils, arguments); charts[chart.id] = chart; return chart; } function releaseChart(chart) { utils.releaseChart.apply(utils, arguments); delete charts[chart.id]; } window.acquireChart = acquireChart; window.releaseChart = releaseChart; // some style initialization to limit differences between browsers across different plateforms. utils.injectCSS( '.chartjs-wrapper, .chartjs-wrapper canvas {' + 'border: 0;' + 'margin: 0;' + 'padding: 0;' + '}' + '.chartjs-wrapper {' + 'position: absolute' + '}'); afterEach(function() { // Auto releasing acquired charts Object.keys(charts).forEach(function(id) { var chart = charts[id]; if (!(chart.$test || {}).persistent) { releaseChart(chart); } }); });
f4bc3aedfb9c753283eb3920f823d0d3994b3cc0
[ "JavaScript", "TypeScript", "Markdown", "Shell" ]
15
JavaScript
chartjs/chartjs-chart-financial
1e2316369a2ec0df229ba8d154d8c9ac816dc90f
e759112db43536188a50c77d3652dfd6709116e0
refs/heads/master
<file_sep>//Function that swaps two elements in an array. //For an array a[] and two indexes i and j, we could exchange the i'th and j'th elemments by the call #define swap(a, i, j) \ {int t; t=a[i]; a[i]=a[j]; a[j]=t;} <file_sep>//Convert a number in the range 0..6 into a weekday name. //0 returns "Sun", 1 returns "Mon" //Work in progress, debug user interface #include <stdio.h> #include <stdlib.h> #include <err.h> #include <assert.h> #include <string.h> #define DAYS_OF_THE_WEEK 7 char *dayArray (int n); char *daySwitch (int n); int main (int argc, char *argv[]) { //argument processing if(argc < 3) err(1, "Mode: A,S; Day: 0..6"); char *day = NULL; int n = atoi(argv[2]); //choose mode if(strcmp(argv[1],"A")) day = dayArray(n); else if(strcmp(argv[1],"S")) day = daySwitch(n); printf("The day is %s\n", day); return EXIT_SUCCESS; } char *dayArray (int n) { //lookup table assert(0 <= n && n <= 6); char *days[DAYS_OF_THE_WEEK] = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"}; return days[n]; } char *daySwitch (int n) { assert(0 <= n && n <= 6); char *day; switch (n) { case 0: day = "Sun"; break; case 1: day = "Mon"; break; case 2: day = "Tue"; break; case 3: day = "Wed"; break; case 4: day = "Thur"; break; case 5: day = "Fri"; break; case 6: day = "Sat"; break; default: day = "???"; break; } return day; } <file_sep>// graph representation is hidden typedef struct GraphRep *Graph; typedef int Bool; typedef struct GraphRep { int nV; // #vertices int nE; // #edges Bool **edges; // matrix of booleans } GraphRep; // vertices denoted by integers 0..N-1 typedef int Vertex; int validV(Graph,Vertex); //validity check // edges are pairs of vertices (end-points) typedef struct { Vertex v; Vertex w; } Edge; Edge mkEdge(Graph, Vertex, Vertex); // operations on graphs Graph newGraph(int nV); // #vertices void insertE(Graph, Edge); void removeE(Graph, Edge); // returns #vertices & array of edges int edges(Graph, Edge *, int); Graph copy(Graph); void destroy(Graph); void show(Graph); <file_sep>/Implementation of a function that takes in a graph as its parameter //and then returns an array containing all the edges in the Graph, along //with the count of the number of edges. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "Graph.h" Edge *edges (Graph g, int *nE) { // Since we are not given the number of edges we must allocate the // maximum amount = v(v-1)/2 Edge *new = malloc(maxE(g)*sizeof(Edge)); for(int i = 0; i < nVertices(g); i++) { for(int j = (i + 1); j <nVertices(g); j++) { if(!matrix(i,j)) { new[i] = mkEdge(i,j); nE++; } } } return new; } Edge mkEdge(Vertex v, Vertex w) { Edge e = {v,w}; return e; } <file_sep>//Question 6. About Swaps #include <stdio.h> #include <stdlib.h> void swap(int *x, int *y); void SwapEl(int *a, int i, int k); int main(int argc, char *argv[]) { int x = 1; int y = 2; printf("Value of x is %d and y is %d\n", x, y); swap(&x,&y); printf("Value of x is %d and y is %d\n", x, y); //Array test int a[5]={1,2,3,4,5}; SwapEl(a,0,4); //&a[0] == a for(int i=0;i<5;i++) printf("%d-",a[i]); return EXIT_SUCCESS; } void swap(int *x, int *y) { int tmp; tmp = *x; *x = *y; *y = tmp; } void SwapEl(int *a, int i, int k) { //Assumption that i or j is no more than N-1 and >0 int tmp = a[i]; a[i]=a[k]; a[k]=tmp; } <file_sep>//Construct a functon to sum the values in the list. //Implement using 1)while 2)for 3) recursion //This is just stub code, this will NOT compile //Using While loops int sumOfList(List l) { Node *curr = l; int sum = 0; while(curr->next != NULL) { sum += curr->value; curr = curr->next; } return sum; } //Using For loops int sumOfList(List l) { Node *curr; int sum = 0; for(Node *curr=l;curr->next != NULL; curr=curr->next) { sum +=curr->value; } return sum; } //Using recursion int sumOfList (List l) { if (l->next = NULL) return; else return l->value + sumOfList(l->next); } <file_sep>//Interface for List ADT used for week06 question 10 typedef struct ListNode *Link; typedef struct ListNode { int value; Link next; } ListNode; typedef Link List; #define head(L) (empty(L) ? -1 : (L)->value) #define tail(L) (empty(L) ? NULL : (L)->next) #define empty(L) ((L) == NULL) // display the value contained in a ListNode #define show(V) { printf("%d", (V)); } // create a new ListNode containing supplied value // prints error and exit()s if cant create a ListNode Link newNode(int value); void drop(List L); void Drop(List L); List copy(List); <file_sep>//Implementation of recursive function which removes a list //ie. go through list and free everything start from the last node #include <stdio.h> #include <stdlib.h> #include "List.h" void drop(List L) { /* if(L == NULL) return; else { Link curr = drop(curr->next); free(curr); } */ } // Problems with above implementation: // 1) this a void function so it shouldn't return something // 2) cannot initialise curr = drop() as drop is a void function that // (1) shouldn't return anything and (2) is not the same type as Link //Alternative method void Drop(List L) { // This function shouldn't have an effect an already empty lists // so we can just disclude them from the function so //Using the macro, we first check that the list is not empty if(!empty(L)) { drop(tail(L)); free(L); } // But what is the base case? How does this function terminate? // Answer: The function exits once it goes through all the code. So // once we have an empty list, if(!empty(L)) fails and then control // continues down the function until it reaches the closing bracket // and so the function closes. } <file_sep>//Interface for DFS (prints path taken) #include "GraphMatrix.h" void depthFirst(Graph g, Vertex V); <file_sep>//Quick Sort (Median of 3) //Implemented by <NAME> //Date: 11/11/2016 #include <stdio.h> #include <stdlib.h> #define swap(a,i,j) \ {int tmp; tmp = a[i]; a[i]=a[j]; a[j]=tmp;} int main (int argc, char *argv) { return EXIT_SUCCESS; } void setMedianOfThree(int a[], int lo, int hi) { if((hi-lo+1) < 3) return; //checks that there are at least 3 elements int mid = (lo+hi/2); //Rearrange the 3 locations so that lowest goes all the way to the //left and highest goes to the right. if (a[lo] > a[mid]) swap(a,lo,mid); if (a[lo] > a[hi]) swap(a,mid,hi); if (a[mid] > a[hi]) swap(a,lo,hi); //Ie. say we have an array a[]=2,1,3,6,4 //lo=0,hi=4,mid=2 the array is in the right order //but say we have a[]=6,4,5,1,2 //lo=0,hi=4,mid=2 //we want to arrange the elements of the array so that these are in //order so by using the processes above we can get //a[lo]=6,a[hi]=2,a[mid]=5 //since a[lo]>a[mid] we swap so //a[]=5,4,6,1,2 //since a[lo]>a[hi] we swap so //a[]=2,4,6,1,5 //since a[mid]>a[hi] we swap so //a[]=2,4,5,1,6 //Everything is now in the right place. } <file_sep>//Function to check whether the elements in an array occur in ascending order. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define cmp(x,y) (x > y) bool isSorted(int *a, int n); int main(int argc, char *argv[]) { int i[10]={1,2,3,4,5,6,7,8,9,10}; if((isSorted(i, 10))) printf("Sorted\n"); int j[5]={3,1,2,6,7}; if(!(isSorted(j,5))) printf("Not sorted\n"); return EXIT_SUCCESS; } bool isSorted(int *a, int n) { //Go through each element in the array and check that their neighbour //greater then the current item for(int i=0;i<n-1;i++) { if(cmp(a[i], a[i+1])) return false; } return true; } <file_sep>// Implementation for a function that counts the number of distinct // edges in a graph using an adjacency matrix representation #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "Graph.h" int nEdges(Graph g) { int nE; for(int i = 0; i < nVertices(g); i++) { //ignore stuff below leading diagonal for(int j = i+1; j < nVertices(g); j++) { if(matrix(i,j) == 1) nE++; } } return nE; } <file_sep>// Implementation of a function that computes the maximum branch length // of a tree ie. width of the tree. // The branch length of a BSTree is defined as the number of links (edges) on the longest path from the root to a leaf. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "Tree.h" int BSTreeMaxBranchLen(BSTree t) { if (t == NULL) return 0; else if (t->left == NULL && t->right == NULL) { return 0; } else { int l, r; l = return 1 + BSTreeMaxBranchLen(t->left); r = return 1 + BSTreeMaxBranchLen(t->right); } return cmp(l,r) ? l : r; } <file_sep>// Interface for Stack ADT typedef struct StackRep *Stack; typedef int Item; #define ItemCopy(it) (it) Stack newStack(); // creates a new empty Stack void dropStack(Stack); // free up memory used by stack void StackPush(Stack s, int n); // adds n to top of Stack s Item StackPop(Stack s); // removes and returns top of Stack Item StackIsEmpty(Stack s); // indicates whether zero items in Stack <file_sep>//Interface for List ADT (as given from week03 tute q4) #define less(x,y) (curr->value < curr->next->value) // a link is simply a pointer to a List node typedef struct ListNode *Link; typedef struct ListNode { int value; // a List node has an integer value Link next; // and a link to the rest of the list } ListNode; // a List is represented by a pointer to its first node typedef Link List; void append (List ls, Link node); Link NewNode (int n); List selectSort(List ls); <file_sep>//Implementation of Complex Number ADT //By <NAME> //Date: 10/11/2016 //Notable bugs: Printing of negative complex numbers works but not //what we had in mind. ie. we print 1 -1i instead of 1 - i. #include <stdio.h> #include <stdlib.h> #include "Complex.h" #include <assert.h> struct complexNumber { int Re; int Img; }; Complex complex_new(int Re, int Img) { Complex z = malloc(sizeof(Complex)); assert(z != NULL); //Set fields z->Re = Re; z->Img = Img; return z; } void complex_delete(Complex z) { if(z != NULL) free(z); } void complex_print(Complex z) { if (z->Img < 0) printf("%d %di\n", z->Re, z->Img); else printf("%d + %di\n", z->Re, z->Img); } Complex complex_add(Complex y, Complex z) { Complex x = malloc(sizeof(Complex)); assert(x != NULL); x->Re = y->Re + z->Re; x->Img = y->Img + z->Img; return x; } Complex complex_multiply(Complex y, Complex z) { Complex x = malloc(sizeof(Complex)); assert (x != NULL); x->Re = y->Re * z->Re; if(y->Img < 0 && z->Img < 0) { int y_Img = (~(y->Img)+1); int z_Img = (~(z->Img)+1); } x->Img = y->Img * z->Img; return x; } <file_sep>//Implementation of a function that takes in the original array, the //sorted array, and determines whether the sort was stable. //Solution from Jas. Not efficient, there is probably a better way to do //it. Time could be saved if we remembered each key value that had //already been checked, and then skipeed if we see it again. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct { int a; int b;} Item; int isStableSort(Item original[], Item sorted[], int lo, int hi) { int i, j, k, key; for(i = lo; i <= hi; i++) { key = sorted[i].a; j = i; k = 0; while (j <= hi && k <= hi) { // find next pair of items with (item.a == key) for(/*current_i*/; j <= hi; j++) if(sorted[j].a == key) break; for(/*current_k*/; k <= hi; k++) if(sorted[k].a == key) break; //check that they have the same item.b if(j <= hi && k <= hi) { if(sorted[j].b != sorted[k].b) return true; } } } return false; } <file_sep>//QuickSort Implementation //By <NAME> //Date: 11/11/2016 #include <stdio.h> #include <stdlib.h> #define less(x,y) (x < y) #define swap(a,j,i) \ {Item tmp; tmp = a[i]; a[i] = a[j]; a[j] = tmp;} typedef int Item; void quicksort(Item a[], int lo, int hi); int partition(Item a[], int lo, int hi); int main (int argc, char *argv[]) { Item a[]={20,15,25,18,22}; partition(a,0,4); for(int i = 0; i < 5; i++) printf("%d ", a[i]); printf("\n"); return EXIT_SUCCESS; } void quicksort(Item a[], int lo, int hi) { int i; if(hi < lo) return; i = partition(a, lo, hi); quicksort(a,lo,i-1); quicksort(a,i+1,hi); } int partition(Item a[], int lo, int hi) { Item v = a[lo]; //pivot printf("Pivot is %d\n", v); int i = lo+1, j = hi; printf("Initially i is %d and j is %d\n", i, j); printf("In the loop...\n"); for(;;) { for(int k = 0; k < 5; k++) printf("%d ",a[k]); printf("\n"); while(less(a[i],v) && i < j) { //Find value bigger than pivot i++; printf("i is now %d\n", i); } while(less(v, a[j]) && j > i) { //Find value smaller than pivot j--; printf("j is now %d\n", j); } if(i == j) break; swap(a,i,j); //Swap those two values around } printf("Now we have exited the main loop.\n"); j = less(a[i],v) ? i: i-1; printf("j is now %d\n", j); swap(a,lo,j); //Move the pivot so that it is behind the numbers that // it is smaller than (ie. the ones just sorted) return j; } <file_sep>// Interface for Graph ADT w/ Adjacency matrix for tute week07 q9 // Vertices denoted by integers 0..N-1 typedef struct GraphRep * Graph; typedef int Vertex; typedef struct edge Edge; // Edges are pairs of vertices (end-points) struct edge { Vertex v; Vertex w; }; typedef struct GraphRep { int nV; // #vertices int ** edges; // matrix of 0/1 values //int ** edges = edges[0][0] } GraphRe; // Macros #define nVertices(g) (g->nV) #define matrix(i,j) (g->edges[i][j]) #define maxE(g) (g->nV)*((g->nV) - 1)/2 int nEdges(Graph g); Edge *edges(Graph g, int *nE); //which could be used as .... // Edges *es; //array we make int n; //#edges es = edges(g, &n); Edge mkEdge(Vertex v, Vertex w); <file_sep>// Implementation of DFS Algorithm (non-recursive) #include <stdio.h> #include <stdlib.h> #include "DFS.h" #include "GraphMatrix.h" void depthFirst(Graph g, Vertex V) { int *visited = calloc(g->nV, sizeof(int)); Stack s = newStack(); StackPush(s,v); while (!StackIsEmpty) } <file_sep>//testList.c implementation to test List Insertion Sort // By <NAME> // Date: 12/11/2016 #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "List.h" int main (int argc, char *argv[]) { int a[10] = {10,9,8,7,6,5,4,3,2,1}; List newList = malloc(sizeof(ListNode)); newList->value = 10; newList->next = NULL; for(int i = 1; i < 10; i++) { Link newNode = NewNode(a[i]); append(newList, newNode); } for(Link curr = newList; curr->next != NULL; curr = curr->next) { printf("%d ", curr->value); } printf("\n"); selectSort(newList); for(Link curr = newList; curr->next != NULL; curr = curr->next) { printf("%d ", curr->value); } return EXIT_SUCCESS; } <file_sep>// Implementation of function that checks if graph has a euler tour #include <stdio.h> #include <stdlib.h> #include "Graph.h" bool hasEulerTour(Graph g) { // Check that the graph is connected if(isConnected(g)) { for(int i = 0; i < nEdges(g); i++) { int v = vertex(i); if(degree(v)%2 != 0) return false; } } return false; } int degree(Graph g, Vertex v) { // Go through adjacency list and count how many other vertices v is // connected to = # degrees VLink curr = g->edges[v]; int degrees; for( ; curr != NULL; curr = curr->next) { degrees++; } return degrees; } <file_sep>// Implementation of a recursive function which makes a copy of a list. #include <stdio.h> #include <stdlib.h> #include "List.h" List copy(List L) { // Two cases to consider: (1) the empty list (2) list with items in // it //(1) Empty list: When we have an empty, we just return NULL if(empty(L)) return NULL; //base case else { List listCopy = newNode(head(L)); //pointer to 1st node in list listCopy->next = copy(tail(L)); //recursive case to go through list //cannot use tail(L) in LHS as NULL case screws things up return listCopy; } } <file_sep>//Implementation of a List //By <NAME> //Date: 11/11/2016 // WIP: insertion method is crap #include <stdio.h> #include <stdlib.h> #include <assert.h> struct ListRep { int value; ListRep *head; ListRep *tail; ListRep *next; }SortedListRep; static struct ListNode { int value; ListRep *next; } *ListNode; ListNode newNode(int n) { ListNode n = malloc(sizeof(ListNode)); assert (n != NULL); n->value = 0; n->next = NULL; return n; } SortedList newList() { SortedList L = malloc(sizeof(SortedListRep)); assert(L != NULL); L->value = 0; L->head = NULL; L->tail = NULL; L->next = NULL; return L; } void ListInsert(SortedList L, int n) { ListNode n = newNode(n); if(n->value <= L->value) { n->next = L->head; L->head = n; } else if(n->value => L->value) { L->tail->next = n; L->tail = n; } else { ListNode curr = L->next; while(curr != NULL) { if (less(n,curr->value)) { } } } } <file_sep>// Implementation of a function that takes a Grapgh (adjacency matrix) // and returns a sorted array of Edges. #include <stdio.h> #include <stdlib.h> #include "sortedEdgeList.h" void sortedEdgeList(Graph g, Edge edges[]) { int nEdges = 0; for(int i = 0; i < g->nV; i++) { for(int j = i + 1; j < g->nW; j++) { if (g->adj[i][j] > 0) { edges[nEdges].s = i; edges[nEdges].t = j; edges[nEdges].w = g->adj[i][j]; nEdges++; } } } qsort(edges, nEdges, sizeof(Edge), &cmp); } int cmp(const void *a, const void *b) { Edge *ae = (Edge *)a;//This is an unnecessary step. Can just initialise Edge *be = (Edge *)b;// function using Edge * as parameters. return (ae->w - be->w); //But this way its more general } <file_sep>// Code to test nEdges.c // By <NAME> // <file_sep>// Interface for indexOf function written for tute week07 q12 typedef sruct GraphRep * Graph; typedef int Vertex; typedef struct edge Edge; typedef unsigned char Bool; struct edge { Vertex v, Vertex w; }; struct GraphRep { int nV; // # vertices int nE; // # edges Bool *edges; //array of booleans (0 or 1) }; <file_sep>// Test DFS and BFS on a graph for question 14 tute week07 #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "Stack.h" #include "DFS.h" #include "GraphMatrix.h" int main (int argc, char *argv[]) { Graph g = newGraph(8); Edge edge1 = mkEdge(g,0,1); Edge edge2 = mkEdge(g,1,2); Edge edge3 = mkEdge(g,1,3); Edge edge4 = mkEdge(g,1,4); Edge edge5 = mkEdge(g,2,3); Edge edge6 = mkEdge(g,2,5); Edge edge7 = mkEdge(g,3,4); Edge edge8 = mkEdge(g,3,5); Edge edge9 = mkEdge(g,5,6); Edge edge10 = mkEdge(g,5,7); insertE(g,edge1); insertE(g,edge2); insertE(g,edge3); insertE(g,edge4); insertE(g,edge5); insertE(g,edge6); insertE(g,edge7); insertE(g,edge8); insertE(g,edge9); insertE(g,edge10); depthFirst(g,0); return EXIT_SUCCESS; } <file_sep>// Implementation of a version of selection sort that builds a NEW // sorted list from an original unsorted linked list. // Original list is not modified during the sorting. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "List.h" Link clone (List ls); List selectSort(List ls) { List sorted_list = malloc(sizeof(ListNode)); List list_copy = clone(ls); //Selection sort Link i, min, curr = list_copy; for( ; curr != NULL; curr = curr->next) { min = curr; for(i = curr->next; i->next != NULL; curr = curr->next) {//find smallest if (less(curr,curr->next)) min = i; // value in list } append(sorted_list, min); } return sorted_list; } //Make a copy of the original list Link clone (List ls) { if(ls == NULL) return NULL; // base case Link result = malloc(sizeof(ListNode)); assert(result != NULL); result->value = ls->value; result->next = clone(ls->next); return result; } void append (List ls, Link node) { assert(ls != NULL); //If list is empty Link curr = ls; for(; curr->next != NULL; curr = curr->next); //Find end of list curr->next = node; node->next = NULL; } Link NewNode (int n) { Link node = malloc(sizeof(ListNode)); node->value = n; node->next = NULL; return node; } <file_sep>typedef struct { Vertex s; Vertex t; int w; } Edge; void sortedEdgeList(Graph g, Edge edges[]); int cmp(const void *a, const void *b); <file_sep>// Implementation to check whether a graph using an array of edges // implementation has an euler path #include <assert.h> int hasEulerPath(Graph g, Edge e[], int nE) { assert(g != NULL); int nOdd; for(int i = 0; i < nE; i++) { int degree; for(int j = 0; j < nE; j++) { if(e[j].v == i || e[j].w == i) degree++; } if(degree % 2 != 0) nOdd++; } return (nOdd == 2) ? 0 : 1; } <file_sep>// Interface to sorted list of integers ADT #define less(x,y) (n < curr->value) typedef struct SortedListRep *SortedList; // create a new empty list SortedList newList(); // insert a value into the list void ListInsert(SortedList,int); // length of list int ListLength(SortedList); // number of distinct values int ListDistinct(SortedList); // display a sorted list as "(x,y,z,...)" void showList(SortedList); <file_sep>//Test functions of List.c #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "List.c" int main (int argc, char *argv[]) { SortedList L; L = newList(); // showList(L) → () ListInsert(L,3); // showList(L) → (3) ListInsert(L,2); // showList(L) → (2,3) ListInsert(L,3); // showList(L) → (2,3,3) printf("%d",ListLength(L)); // prints 3 printf("%d",ListDistinct(L)); // prints 2 return EXIT_SUCCESS; } <file_sep>//Header file for complex number implementation typedef struct complexNumber *Complex; Complex complex_new(int Re, int Img); //Add two complex numbers together Complex complex_add(Complex y, Complex z); //Multiply two complex numbers together Complex complex_multiply(Complex y, Complex z); //Delete a complex number void complex_delete(Complex z); //Print a complex number to stdout void complex_print(Complex z); <file_sep>// Interface for Graph Adjacency List ADT #include <stdbool.h> #define nEdges(g) (g->nE) #define vertex(i) (g->edges[i]->v) typedef struct Vnode *VList; typedef struct Vnode *VLink; typedef struct Vnode { Vertex v; VLink next; }; typedef struct Graph { int nV; int nE; VList *edges; } *Graph; bool hasEulerTour(Graph g); bool isConnected(Graph g); int degree(Graph g, Vertex v); <file_sep>#include <stdio.h> #include <stdlib.h> #include "GraphMatrix.h" #include <assert.h> Graph newGraph(int nV) { assert(nV >= 0); int i, j; int **e = malloc(nV * sizeof(int *)); assert(e != NULL); for (i = 0; i < nV; i++) { e[i] = malloc(nV * sizeof(int)); assert(e[i] != NULL); for (j = 0; j < nV; j++) e[i][j] = 0; // FALSE } Graph g = malloc(sizeof(GraphRep)); assert(g != NULL); g->nV = nV; g->nE = 0; g->edges = e; return g; } void insertE(Graph g, Edge e) { assert(g != NULL); assert(validV(g,e.v) && validV(g,e.w)); if (g->edges[e.v][e.w]) return; g->edges[e.v][e.w] = 1; g->edges[e.w][e.v] = 1; g->nE++; } void removeE(Graph g, Edge e) { assert(g != NULL); assert(validV(g,e.v) && validV(g,e.w)); if (!g->edges[e.v][e.w]) return; g->edges[e.v][e.w] = 0; g->edges[e.w][e.v] = 0; g->nE--; } void show(Graph g) { assert(g != NULL); printf("V=%d, E=%d\n", g->nV, g->nE); int i, j; for (i = 0; i < g->nV; i++) { int nshown = 0; for (j = i+1; j < g->nV; j++) { if (g->edges[i][j] != 0) { printf("%d-%d ",i,j); nshown++; } } if (nshown > 0) printf("\n"); } } int edges(Graph g, Edge es[], int nE) { assert(g != NULL && es != NULL); assert(nE >= g->nE); int i, j, n = 0; for (i = 0; i < g->nV; i++) { for (j = i+1; j < g->nV; j++) { if (g->edges[i][j] != 0) { assert(n < nE); es[n++] = mkEdge(g,i,j); } } } return n; } <file_sep>// Implementation of a function that takes two vertices from an edge and // determines the corresponding index in the edges array which gold the // boolean value for this edge. #include <stdio.h> #include <stdlib.h> #include "indexOf.h" int indexOf(Vertex v, Vertex w) { assert(v != w); //no self-edges if (v > w) { Vertex tmp = v; v = w; w = tmp; } //Because we are storing // top right half of // matrix int i = v; int j = i + 1; int k = nV - j; } <file_sep>// Implementation of Stack ADT #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "Stack.h" typedef struct StackNode { Item value; struct StackNode *next; } StackNode; typedef struct StackRep { StackNode *top; // ptr to first node } StackRep; Stack newStack() { Stack s; s = malloc(sizeof(StackRep)); assert(s != NULL); s->top = NULL; return s; } void StackPush(Stack s, Item it) { StackNode *new = malloc(sizeof(StackNode)); assert(new != NULL); new->value = ItemCopy(it); new->next = s->top; s->top = new; } Item StackPop(Stack s) { Item n = s->top->value; StackNode *curr = s->top; s->top = s->top->next; free(curr); return n; } <file_sep>//test code for Complex ADT #include <stdio.h> #include <stdlib.h> #include "Complex.c" #include <assert.h> int main (int argc, char *argv[]) { printf("===== INITIALISING COMPLEX TEST =====\n"); Complex z = complex_new(1, 1); Complex y = complex_new(2,2); Complex e = complex_new(-2,-1); assert(z->Re == 1 && z->Img == 1); assert(y->Re == 2 && y->Img == 2); assert(e->Re == -2 && e->Img == -1); complex_print(z); complex_print(y); complex_print(e); printf("Creation of complex numbers passed.\n"); Complex a = complex_add(y, z); assert(a->Re == 3 && a->Img == 3); complex_print(a); printf("Addition of complex numbers pased.\n"); Complex b = complex_multiply(a,y); assert(b->Re == 6 && b->Img == 6); complex_print(b); Complex c = complex_new(-3,-4); Complex d = complex_multiply(c,c); assert(d->Re == 9 && d->Img == 16); complex_print(d); printf("Multiplication of complex numbers passed.\n"); printf("All tests passed! You are Awesome!\n"); return EXIT_SUCCESS; }
68e691998163f471ee486cd63b8bb354474cc2ad
[ "C" ]
39
C
martinlecs/1927_revision
5a2dd2dac8adc29ef1545e2ec4506f0d83b8b339
89345d9724bd729bbe0fbf3b09999875b8dd55bc
refs/heads/master
<file_sep>const errors = require('./errors') const badDigits = /[^0-9+ \(\)-\.]/ const extension = /^(?:\+?1[ .-]?)?(?:([0-9]{3})|\(([0-9]{3})\))[ .-]?([0-9]{3})[ .-]?([0-9]{4})(?:#|ext.?)([0-9]+)$/ const ideal = /^(?:\+?1[ .-]?)?(?:([0-9]{3})|\(([0-9]{3})\))[ .-]?([0-9]{3})[ .-]?([0-9]{4})$/ const validNonNumerals = /\+|\.|-| |\(|\)/g module.exports = exports = function standardize (str) { const extensionMatches = str.match(extension) if (extensionMatches) { throw new Error(errors[4].en) } const badDigitsMatches = str.match(badDigits) if (badDigitsMatches) { throw new Error(errors[2].en) } const onlyValid = str.replace(validNonNumerals, '') const expectedNbChars = (onlyValid[0] === '1' ? 11 : 10) if (onlyValid.length < expectedNbChars) { throw new Error(errors[3].en) } if (onlyValid.length > expectedNbChars) { throw new Error(errors[5].en) } const idealMatches = str.match(ideal) if (idealMatches) { const region = '+1' const area = idealMatches[1] || idealMatches[2] const prefix = idealMatches[3] const line = idealMatches[4] return `${region} (${area}) ${prefix}-${line}` } throw new Error(errors[1].en) } <file_sep># tel-input In this repo, I try to make a good client-side only phone number input field that can accept different valid formats for north-american phone numbers and warn about anything unexpected, preventing form submission in those cases. <file_sep>const standardize = require('../standardize') const accepted = require('../accepted') const rejected = require('../rejected') Object.keys(accepted).forEach((name) => { const useCase = accepted[name] test(name, () => { expect(standardize(useCase.input)).toBe(useCase.expected) }) }) Object.keys(rejected).forEach((name) => { const useCase = rejected[name] test(name, () => { expect(() => { standardize(useCase.input) }).toThrowError(new Error(useCase.errMsg)) }) }) <file_sep>module.exports = exports = { unseparated: '', spaces: ' ', dashes: '-', periods: '.' } <file_sep>const accepted = require('./accepted') const rejected = require('./rejected') console.log('Accepted', accepted) console.log('Rejected', rejected) <file_sep>const separators = require('./separators') const errors = require('./errors') const templates = { '11 digits': { input: '33_987_654_321', errCode: 5 }, '+11 digits': { input: '+33_987_654_321', errCode: 5 }, 'letters': { input: '514_987_NEWS', errCode: 2 }, '7 digits': { input: '987_6543', errCode: 3 }, '8 digits': { input: '1_987_6543', errCode: 3 }, '9 digits': { input: '1_2_987_6543', errCode: 3 }, 'wrong region': { input: '2_514_987-6543', errCode: 5 }, '+wrong region': { input: '+2_514_987-6543', errCode: 5 }, 'extension': { input: '514_987_6543#1234', errCode: 4 }, 'region+extension': { input: '1_514_987_6543#1234', errCode: 4 }, '+region+extension': { input: '+1_514_987_6543#1234', errCode: 4 }, 'long': { input: '12_345_678_9012', errCode: 5 }, '+long': { input: '+12_345_678_9012', errCode: 5 }, 'parens_mismatch': { input: '514)_987_6543', errCode: 1 }, 'parens_mismatch_2': { input: '1_(514_987_6543', errCode: 1 } } const rejected = Object.keys(templates).reduce((ret, key) => { const template = templates[key] Object.keys(separators).forEach((name) => { ret[`${key}_${name}`] = { input: template.input.replace(/_/g, separators[name]), errMsg: errors[template.errCode].en } }) return ret }, {}) module.exports = exports = rejected <file_sep>const separators = require('./separators') const expected = '+1 (514) 987-6543' const templates = { '10 digits': '514_987_6543', '11 digits': '1_514_987_6543', '+11 digits': '+1_514_987_6543', '10 digits_parens': '(514)_987_6543', '11 digits_parens': '1_(514)_987_6543', '+11 digits_parens': '+1_(514)_987_6543', '10 digits_mixed': '(514) 987_6543', '11 digits_mixed': '1 (514) 987_6543', '+11 digits_mixed': '+1 (514) 987_6543' } const accepted = Object.keys(templates).reduce((ret, key) => { const template = templates[key] Object.keys(separators).forEach((name) => { ret[`${key}_${name}`] = { input: template.replace(/_/g, separators[name]), expected } }) return ret }, {}) module.exports = exports = accepted
dbb8e23ec6dc4b2f149fd36de8bc6c7c9745702e
[ "JavaScript", "Markdown" ]
7
JavaScript
shawninder/tel-input
8cd46fdcb6a2fcde081447c2b68e5dbc7c8df9f1
36193b5add5ccab8a072a05ed7deb36eb5266e92
refs/heads/master
<repo_name>epeterik/react_country2<file_sep>/src/containers/blockMembership.js //app imports import React, { Component } from 'react'; import { connect } from "react-redux"; //css imports import '../ui-toolkit/css/nm-cx/main.css'; import '../css/custom.css'; //App Imports import { WaitSpinner } from '../components/waitSpinner'; import { getListEconomicBlockNations } from '../actions/actions'; import Country from './country'; class BlockMembership extends Component { constructor(props) { super(props); this.state = { errorText: '', showWaitSpinner: false } //bindings this.handleWaitSpinner = this.handleWaitSpinner.bind(this); this.handleError = this.handleError.bind(this); } handleWaitSpinner(displayTheWaitSpinner) { //console.log("Entering BlockMembership.handleWaitSpinner - Bool Value is: ", displayTheWaitSpinner); this.setState({showWaitSpinner: displayTheWaitSpinner}); //console.log("Leaving BlockMembership.handleWaitSpinner"); } handleError(errorEncountered) { //console.log("Entering BlockMembership.handleError"); //debug //update error state if an error was encountered during the axios call this.setState({errorText: errorEncountered}); //console.log("Leaving BlockMembership.handleError"); //debug } componentDidMount() { console.log("BlockMembership - componentDidMount"); //If sent to this page with no props (no :economicBlock) do not perform lookup (lookup will fail with no val) if (this.props.match.params.economicBlock.trim() !== "") { this.props.listOfEconBlockMembers(this.props.match.params.economicBlock, this.handleWaitSpinner, this.handleError); } } componentDidUpdate(prevProps) { //console.log("BlockMembership - componentDidUpdate - New Props:", prevProps, "Current Props: ", this.props); if (prevProps.match.params.economicBlock.trim() !== this.props.match.params.economicBlock.trim()) { //debug console.log("BlockMembership - Props changed from: ", prevProps.match.params.economicBlock, "to: ", this.props.match.params.economicBlock); //If sent to this page with no props (no :economicBlock) do not perform lookup (lookup will fail with no val) if (prevProps.match.params.economicBlock.trim() !== "") { this.props.listOfEconBlockMembers(this.props.match.params.economicBlock, this.handleWaitSpinner, this.handleError); } } } mapMyEconomicBlockCountriesToCard(countryObject, arrayIndex) { return ( <tr key={"blockMemberRowFor" + countryObject.name}> <td key={"blockMemberDataFor" + countryObject.name}> <Country blocCountryData={countryObject} canUntrack={false} key={"blockMemberCardFor" + countryObject.name} /> </td> </tr> ); } render() { //debug //console.log("BlockMembership Props: ", this.props); //comenting out as this triggers on every keystroke //Error handling, check to see if the notes array has been loaded if (this.props.match.params.economicBlock.length === 0) { return <div>No economic bloc to display, please select an economic bloc.</div> } return ( <div className="card padding-medium"> {this.state.showWaitSpinner ? <div className="text-center"> <h3>Loading with Economic Block Members</h3> <WaitSpinner /> <h4>Please be patient</h4> </div> : this.state.errorText.trim() !== "" ? <div> <h3 className="text-center errorEncountered">Economic Block Data Not Found :(</h3> </div> : <div> <h1 className="text-center">{this.props.match.params.economicBlock}</h1> <table className="table scrollable"> <tbody style={{height: "500px"}}> { this.props.economicBlockMembers.map(this.mapMyEconomicBlockCountriesToCard) } </tbody> </table> </div> } </div> ); //end return } //end render } //end NoteEntry const mapStateToProps = (state) => { return { economicBlockMembers: state.economicBlockMemberCountries }; }; const mapDispatchToProps = (dispatch) => { return { listOfEconBlockMembers: (economicBlockCountries, waitCallback, errorCallBack) => { dispatch(getListEconomicBlockNations(economicBlockCountries, waitCallback, errorCallBack)) } }; }; export default connect(mapStateToProps, mapDispatchToProps)(BlockMembership); <file_sep>/src/containers/country.js import React, { Component } from 'react'; import '../ui-toolkit/css/nm-cx/main.css'; import '../css/custom.css'; //package imports import { connect } from "react-redux"; import { Link } from 'react-router-dom'; //App Imports import { WaitSpinner } from '../components/waitSpinner'; import { setCountryAsTracked, setCountryAsUNtracked } from '../actions/actions'; class Country extends Component { constructor(props) { super(props); this.state = { errorText: '', showWaitSpinner: false } //bindings this.handleWaitSpinner = this.handleWaitSpinner.bind(this); this.handleError = this.handleError.bind(this); this.handleTrackCountryClick = this.handleTrackCountryClick.bind(this); this.trackedCountryFind = this.trackedCountryFind.bind(this); } handleWaitSpinner(displayTheWaitSpinner) { //console.log("Entering Country.handleWaitSpinner - Bool Value is: ", displayTheWaitSpinner); this.setState({showWaitSpinner: displayTheWaitSpinner}); //console.log("Leaving Country.handleWaitSpinner"); } handleError(errorEncountered) { //console.log("Entering Country.handleError"); //debug //update error state if an error was encountered during the axios call this.setState({errorText: errorEncountered}); //console.log("Leaving Country.handleError"); //debug } handleTrackCountryClick(countryData) { console.log("Entering handleTrackCountryClick"); this.props.trackCountry(countryData, this.handleWaitSpinner, this.handleError); console.log("Leaving handleTrackCountryClick"); } handleUNTrackCountryClick(countryIsTrackedObject) { console.log("Entering handleUNTrackCountryClick"); this.props.stopTrackingACountry(countryIsTrackedObject.id, this.handleWaitSpinner, this.handleError); console.log("Leaving handleUNTrackCountryClick"); } trackedCountryFind(countryDataObject) { //console.log("Entering trackedCountryFind"); //console.log(countryDataObject); //debug //console.log(this.props.blocCountryData); //debug //check if this country is in the tracked countries list return countryDataObject.alpha3Code === this.props.blocCountryData.alpha3Code ? true : false; } render() { //debug //console.log("Country Object Props: ", this.props); //comenting out as this triggers on every keystroke //store local value for easier typing let localCountryObject = this.props.blocCountryData; //lets check if this country is a tracked country let countryIsTracked = this.props.trackedCountries.find(this.trackedCountryFind); //console.log("trackedCountries value: ", countryIsTracked); //debug return ( <div className="card padding-medium" key={"countryObjectRenderCard" + localCountryObject.numericCode} > {this.state.showWaitSpinner ? <div className="text-center"> <h3>Logging Updated Country Tracking Status</h3> <WaitSpinner /> <h4>Please be patient</h4> </div> : <div> <div className="row"> <div className="small-3 columns tableDiv"> <img alt={localCountryObject.name + " flag"} src={localCountryObject.flag} height="150" width="255" border="1"/> </div> <div className="small-9 columns tableDiv"> <div className="row"> <div className="small-9 columns"> <div className="row"> <div className="small-3 columns"> Country Name: </div> <div className="small-9 columns"> <Link to={"/countries/" + localCountryObject.name}>{ localCountryObject.name }</Link> </div> </div> <div className="row"> <div className="small-3 columns"> Capital: </div> <div className="small-9 columns"> { localCountryObject.capital } </div> </div> <div className="row"> <div className="small-3 columns"> Population: </div> <div className="small-9 columns"> { localCountryObject.population.toLocaleString() } </div> </div> </div> <div className="small-3 columns"> {countryIsTracked === undefined ? <button className="button btn-cta success small" onClick={() => this.handleTrackCountryClick(localCountryObject)}>Track</button> : this.props.canUntrack ? <button className="button btn-cta warning small" onClick={() => this.handleUNTrackCountryClick(countryIsTracked)} disabled={!this.props.canUntrack}>Untrack</button> : <button className="button btn-cta warning small" onClick={() => alert("Please go to the Tracked Countries page to untrack this country.")} disabled={!this.props.canUntrack}>Tracked</button> } </div> </div> </div> </div> </div> } </div> ); //end return } //end render } //end NoteEntry const mapStateToProps = (state) => { return { trackedCountries: state.trackedCountriesList }; }; const mapDispatchToProps = (dispatch) => { return { trackCountry: (localCountryData, waitFlag, errorFunction) => { dispatch(setCountryAsTracked (localCountryData, waitFlag, errorFunction)) }, stopTrackingACountry: (deleteId, waitFlag, errorFunction) => { dispatch(setCountryAsUNtracked (deleteId, waitFlag, errorFunction)) } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Country);<file_sep>/src/actions/types.js export const UPDATE_TRACKED_COUNTRIES = "Update-Tracked-Countries"; export const UPDATE_ECONOMIC_BLOCK_COUNTRIES = "Update-Economic-Block-Countries"; export const UPDATE_TRACKED_COUNTRIES_LIST = "Update-Tracked-Countries-List";<file_sep>/src/containers/trackedCountries.js //app imports import React, { Component } from 'react'; import { connect } from "react-redux"; //css imports import '../ui-toolkit/css/nm-cx/main.css'; import '../css/custom.css'; //App Imports import { WaitSpinner } from '../components/waitSpinner'; import { getTrackedCountriesList } from '../actions/actions'; import Country from './country'; class TrackedCountries extends Component { constructor(props) { super(props); this.state = { errorText: '', showWaitSpinner: false } //bindings this.handleWaitSpinner = this.handleWaitSpinner.bind(this); this.handleError = this.handleError.bind(this); } handleWaitSpinner(displayTheWaitSpinner) { //console.log("Entering noteEntry.handleWaitSpinner - Bool Value is: ", displayTheWaitSpinner); this.setState({showWaitSpinner: displayTheWaitSpinner}); //console.log("Leaving noteEntry.handleWaitSpinner"); } handleError(errorEncountered) { //console.log("Entering noteEntry.handleError"); //debug //update error state if an error was encountered during the axios call this.setState({errorText: errorEncountered}); //console.log("Leaving noteEntry.handleError"); //debug } componentDidMount() { console.log("TrackedCountries - componentDidMount"); this.props.listOfTrackedCountries(this.handleWaitSpinner, this.handleError, true); } mapMyEconomicBlockCountries(countryObject, arrayIndex) { return ( <div key={"countryRow" + arrayIndex}>{countryObject.name}</div> ); } mapMyTrackedCountires(countryObject, arrayIndex) { return ( <tr key={"blockMemberRowFor" + countryObject.name}> <td key={"blockMemberDataFor" + countryObject.name}> <Country blocCountryData={countryObject} key={"TrackedCountries" + countryObject.name} canUntrack={true} /> </td> </tr> ); } sortTrackedCountries(firstCountry, secondCountry) { //console.log(firstCountry, secondCountry); //debug if (firstCountry.name <= secondCountry.name) return -1; else if (firstCountry.name === secondCountry.name) return 0; else return 1; } render() { //debug //console.log("TrackedCountries Props: ", this.props); //comenting out as this triggers on every keystroke //Error handling, check to see if the notes array has been loaded if (this.props.trackedCountriesData.length === 0) { return <div>No tracked countries to display.</div> } //console.log("Tracked countries before sort: ", this.props.trackedCountriesData); //debug let localSortedCountriesArray = this.props.trackedCountriesData.slice().sort(this.sortTrackedCountries); //console.log("Tracked Countries after sort: ", localSortedCountriesArray);//debug return ( <div className="card padding-medium"> {this.state.showWaitSpinner ? <div className="text-center"> <h3>Getting List of Tracked Countries</h3> <WaitSpinner /> <h4>Please be patient</h4> </div> : <div> <h1 className="text-center">{this.props.match.params.economicBlock}</h1> <table className="table scrollable"> <tbody style={{height: "500px"}}> { localSortedCountriesArray.map(this.mapMyTrackedCountires) } </tbody> </table> </div> } </div> ); //end return } //end render } //end NoteEntry const mapStateToProps = (state) => { return { trackedCountriesData: state.trackedCountries }; }; const mapDispatchToProps = (dispatch) => { return { listOfTrackedCountries: (waitFlag, errorFunction, lookupCountryData) => { dispatch(getTrackedCountriesList(waitFlag, errorFunction, lookupCountryData)) } }; }; export default connect(mapStateToProps, mapDispatchToProps)(TrackedCountries); <file_sep>/src/components/renderEconBlocks.js //package imports import React from 'react'; //CSS imports import '../ui-toolkit/css/nm-cx/main.css'; import '../css/custom.css'; //app imports import { ShowActiveSideBarListLinkWithTooltip } from './setActiveNavLinks'; //Block Details API Call to: https://restcountries.eu/rest/v2/regionalbloc/ const listOfBlocs = [{acronym: "EU", name: "European Union"}, {acronym: "EFTA", name: "European Free Trade Association"}, {acronym: "CARICOM", name: "Caribbean Community"}, {acronym: "PA", name: "Pacific Alliance"}, {acronym: "AU", name: "African Union"}, {acronym: "USAN", name: "Union of South American Nations"}, {acronym: "EEU", name: "Eurasian Economic Union"}, {acronym: "AL", name: "Arab League"}, {acronym: "ASEAN", name: "Association of Southeast Asian Nations"}, {acronym: "CAIS", name: "Central American Integration System"}, {acronym: "CEFTA", name: "Central European Free Trade Agreement"}, {acronym: "NAFTA", name: "North American Free Trade Agreement"}, {acronym: "SAARC", name: "South Asian Association for Regional Cooperation"} ]; //render links out as NM formatted sidebar links function mapListOfBlocksNavBarWithLINK(blocObject, arrayIndex) { return ( <ShowActiveSideBarListLinkWithTooltip label={blocObject.acronym} to={"/" + blocObject.acronym} activeOnlyWhenExact={true} arrayIndex={arrayIndex} key={"economicBlocsListItem" + arrayIndex} toolTipText={blocObject.name}/> ); } //return header with economic block array mapped as economic blocks export function EconomicBlockNavLinks() { return ( <div> <h6>Regional Blocks</h6> { listOfBlocs.map(mapListOfBlocksNavBarWithLINK) } </div> ) }
07366b8481bd891bafcb3d969485e7f57b0b1ed6
[ "JavaScript" ]
5
JavaScript
epeterik/react_country2
1233aa2ed12d48bc588a8c45146e2a54bad07f25
a3f549bba25881ca50cec037ad58641dec64fc92
refs/heads/main
<repo_name>adityamahamuni/cpp<file_sep>/DS/LinkedList/DoublyLinkedList.h #pragma once #ifndef _DOUBLYLINKEDLIST_H_ #define _DOUBLYLINKEDLIST_H_ #include<iostream> #include<exception> class DoublyLinkedListException : virtual public std::exception { std::string msg; public: DoublyLinkedListException(std::string msg) : msg(msg) {} virtual ~DoublyLinkedListException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> class DNode { public: DNode<T>* prev; T data; DNode<T>* next; }; template <class T> class DoublyLinkedList { private: DNode<T>* head; public: DoublyLinkedList() : head(nullptr) {} ~DoublyLinkedList() {} friend std::ostream& operator<<(std::ostream& str, DoublyLinkedList& data) { data.display(str); return str; } int size() { int count = 0; if (head == nullptr) return 0; else { DNode<T>* temp = head; while (temp != nullptr) { count++; temp = temp->next; } } return count; } void addNode(const T val) { DNode<T>* newnode = new DNode<T>(); newnode->data = std::move(val); newnode->prev = nullptr; newnode->next = nullptr; if (head == nullptr) head = newnode; else { DNode<T>* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newnode; newnode->prev = temp; } } void insert(const T val, int pos = 0) { try { if (pos < 0 || pos > size()) throw(DoublyLinkedListException("Doubly LinkedList Exception: Index out of range.")); } catch (const DoublyLinkedListException& me) { std::cout << me.what() << std::endl; } DNode<T>* temp = new DNode<T>(); temp->data = std::move(val); DNode<T>* p; if (pos == 0) { temp->prev = head; temp->next = head; head = temp; } else if (pos > 0) { p = head; for (int i = 0; i < pos - 1 && p; i++) p = p->next; temp->prev = p; temp->next = p->next; p->next = temp; } } void push_back(const T val) { DNode<T>* newnode = new DNode<T>(); newnode->data = std::move(val); newnode->prev = nullptr; newnode->next = nullptr; if (head == nullptr) head = newnode; else { DNode<T>* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newnode; newnode->prev = temp; } } T remove(int pos = 0) { T x; try { if (pos < 0 || pos > size()) throw(DoublyLinkedListException("Doubly LinkedList Exception: Index out of range.")); } catch (const DoublyLinkedListException& me) { std::cout << me.what() << std::endl; } DNode<T>* p = nullptr; DNode<T>* temp = head; if (pos == 0) { head = head->next; x = temp->data; delete temp; return x; } else if (pos > 0) { p = head; for (int i = 0; i <= pos - 1 && p; i++) { temp = p; p = p->next; } temp->prev = p; temp->next = p->next; x = temp->data; delete p; return x; } return NULL; } void display(std::ostream& str = std::cout) { if (head == nullptr) std::cout << "List is empty" << std::endl; else { DNode<T>* temp = head; while (temp) { str << temp->data << " "; temp = temp->next; } str << std::endl; } } }; #endif // !_DOUBLYLINKEDLIST_H_ <file_sep>/DS/Queue/main.cpp #include<iostream> #include"Queue.h" int main() { std::cout << " *******Integer Queue******** " << std::endl; Queue<int> q(10); if (q.isEmpty()) std::cout << "Queue is Empty." << std::endl; q.enqueue(5); q.enqueue(9); q.enqueue(10); std::cout << "Elements of Queue : " << std::endl; q.display(); std::cout << "Removed Element : " << q.dequeue() << std::endl; std::cout << "Elements of Queue : " << std::endl; q.display(); std::cout << " *******Char Queue******** " << std::endl; Queue<char> qStr(10); if (qStr.isEmpty()) std::cout << "Queue is Empty." << std::endl; qStr.enqueue('A'); qStr.enqueue('B'); qStr.enqueue('C'); std::cout << "Elements of Queue : " << std::endl; qStr.display(); std::cout << "Removed Element : " << qStr.dequeue() << std::endl; std::cout << "Elements of Queue : " << std::endl; qStr.display(); std::cout << " *******Double Queue******** " << std::endl; Queue<double> qDb(10); if (qDb.isEmpty()) std::cout << "Queue is Empty." << std::endl; qDb.enqueue(20.2331); qDb.enqueue(1231.12312); qDb.enqueue(3241.332); std::cout << "Elements of Queue : " << std::endl; qDb.display(); std::cout << "Removed Element : " << qDb.dequeue() << std::endl; std::cout << "Elements of Queue : " << std::endl; qDb.display(); std::cout << " *********Queue using Stacks************* " << std::endl; QueueStk<int> qStk(10); qStk.enqueue(10); qStk.enqueue(20); qStk.enqueue(30); std::cout << "Elements of Queue : " << std::endl; qStk.display(); std::cout << "Removed Element : " << qStk.dequeue() << std::endl; std::cout << "Removed Element : " << qStk.dequeue() << std::endl; std::cout << "Elements of Queue : " << std::endl; qStk.display(); return 0; }<file_sep>/OpenGL/OpenGL-Dot/hello_dot.cpp // In this tutorial we will see the usage of vertex buffer objects(VBOs) for the first time. // As the name implies, they are used to store vertices. // The objects that exist in the 3D world you are trying to visualize, be it monsters, castles or a simple revolving cube, // are always built by connecting together a group of vertices.VBOs are the most efficient way to load vertices into the GPU. // They are buffers that can be stored in video memoryand provide the shortest access time to the GPU so they are definitely recommended. #include<GL/glew.h> #include <GLFW/glfw3.h> #include<iostream> #include "math_3d.h" int main() { // Here we initialize GLEW and check for any errors. This must be done after GLUT has been initialized. GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res)); return 1; } // We create an array of one Vector3f structures (this type is defined in math_3d.h) and initialize XYZ to be zero. // This will make the dot appear at the middle of the screen. Vector3f Vertices[1]; Vertices[0] = Vector3f(0.0f, 0.0f, 0.0f); // We allocate a GLuint in the global part of the program to store the handle of the vertex buffer object. // You will see later that most (if not all) OpenGL objects are accessed via a variable of GLuint type. GLuint VBO; // OpenGL defines several glGen* functions for generating objects of various types. // They often take two parameters - the first one specifies the number of objects you want to create and // the second is the address of an array of GLuints to store the handles that the driver allocates // for you (make sure the array is large enough to handle your request!). // Future calls to this function will not generate the same object handles unless you delete them first with glDeleteBuffers. // Note that at this point you don't specify what you intend to do with the buffers so they can be regarded as "generic". // This is the job of the next function. glGenBuffers(1, &VBO); // OpenGL has a rather unique way of using handles. In many APIs the handle is simply passed to any relevant function // and the action is taken on that handle. In OpenGL we bind the handle to a target name and then execute commands on that target. // These commmands affect the bounded handle until another one is bound in its stead or the call above takes zero as the handle. // The target GL_ARRAY_BUFFER means that the buffer will contain an array of vertices. // Another useful target is GL_ELEMENT_ARRAY_BUFFER which means that the buffer contains the indices of the vertices in another buffer. glBindBuffer(GL_ARRAY_BUFFER, VBO); // After binding our object we fill it with data. The call above takes the target name (same as what we used for binding), // the size of the data in bytes, address of the array of vertices and a flag that indicates the usage pattern for this data. // Since we are not going to change the buffer contents we specify GL_STATIC_DRAW. The opposite will be GL_DYNAMIC_DRAW. // While this is only a hint to OpenGL it is a good thing to give some thought as to the proper flag to use. // The driver can rely on it for optimization heuristics (such as what is the best place in memory to store the buffer). glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); // In the shaders tutorial you will see that vertex attributes used in the shader (position, normal, etc) // have an index mapped to them that enable you to create the binding between the data in the C/C++ program and // the attribute name inside the shader. In addition you must also enable each vertex attribute index. // In this tutorial we are not yet using any shader but the vertex position we have loaded into the buffer is treated as // vertex attribute index 0 in the fixed function pipeline (which becomes active when there is no shader bound). // You must enable each vertex attribute or else the data will not be accessible by the pipeline. glEnableVertexAttribArray(0); // Here we bind our buffer again as we prepare for making the draw call. // In this small program we only have one vertex buffer so making this call every frame is redundent but // in more complex programs there are multiple buffers to store your various models and you must update the pipeline // state with the buffer you intend to use. glBindBuffer(GL_ARRAY_BUFFER, VBO); /* This call tells the pipeline how to interpret the data inside the buffer. The first parameter specifies the index of the attribute. In our case we know that it is zero by default but when we start using shaders we will either need to explicitly set the index in the shader or query it. The second parameter is the number of components in the attribute (3 for X, Y and Z). The third parameter is the data type of each component. The next parameter indicates whether we want our attribute to be normalized before it is used in the pipeline. It our case we want the data to pass un-changed. The fifth parameter (called the 'stride') is the number of bytes between two instances of that attribute in the buffer. When there is only one attribute (e.g. the buffer contains only vertex positions) and the data is tightly packed we pass the value zero. If we have an array of structures that contain a position and normal (each one is a vector of 3 floats) we will pass the size of the structure in bytes (6 * 4 = 24). The last parameter is useful in the case of the previous example. We need to specify the offset inside the structure where the pipeline will find our attribute. In the case of the structure with the position and normal the offset of the position is zero while the offset of the normal is 12. */ glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); // Finally, we make the call to draw the geometry. All the commands that we've seen so far are important but they only // set the stage for the draw command. This is where the GPU really starts to work. // It will now combine the parameters of the draw call with the state that was built up to this point and render the results to the screen. glDrawArrays(GL_POINTS, 0, 1); glDisableVertexAttribArray(0); return 0; }<file_sep>/DS/STL/Sets_Container.cpp #include<set> #include<iostream> class Human { friend std::ostream& operator<<(std::ostream& os, const Human& p); std::string name; int age; public: Human() :name{"Unknown"}, age{0}{} Human(std::string, int age):name{name}, age{age}{} bool operator<(const Human& rhs) const { return this->age < rhs.age; } bool operator==(const Human& rhs) const { return (this->name == rhs.name && this->age == rhs.age); } }; std::ostream& operator<<(std::ostream& os, const Human& p) { os << p.name << " : " << p.age; return os; } template <typename T> void display_set(const std::set<T>& t) { std::cout << "[ "; for (const auto& elem : t) { std::cout << elem << " "; } std::cout << " ]" << std::endl; } void test_one() { std::cout << "\n Test1 ==========================" << std::endl; std::set<int> s1{ 1,4,3,5,2 }; display_set(s1); s1 = { 1,2,3,1,1,2,2,3,3,4,5 }; display_set(s1); s1.insert(0); s1.insert(10); display_set(s1); if (s1.count(10)) std::cout << "10 is in the set" << std::endl; else std::cout << "10 is not in the set!" << std::endl; auto it = s1.find(5); if (it != s1.end()) std::cout << "Found: " << *it << std::endl; s1.clear(); display_set(s1); } void test_two() { std::cout << "\n Test2 ==========================" << std::endl; std::set<Human> stooges{ {"Adi", 21}, {"aditya", 21} }; display_set(stooges); stooges.emplace("<NAME>", 22); display_set(stooges); stooges.emplace("adi", 22); display_set(stooges); auto it = stooges.find(Human{ "adi", 22 }); if (it != stooges.end()) stooges.erase(it); display_set(stooges); it = stooges.find(Human("XXXX", 22)); if (it != stooges.end()) stooges.erase(it); display_set(stooges); } /* int main() { test_one(); test_two(); return 0; }*/<file_sep>/DS/LinkedList/Node.h #pragma once #ifndef _NODE_H_ #define _NODE_H_ template <class T> class Node { public: T data; Node<T>* next; }; #endif // !_NODE_H_ <file_sep>/DS/Trees/main.cpp #include<iostream> #include"Trees.h" int main() { std::cout << " ************* Binary Search Tree************ " << std::endl; BinarySearchTree<int> tree; tree.insert(20); tree.insert(10); tree.insert(25); tree.insert(30); tree.insert(15); std::cout << "Elements of Binary Search Tree : (inorder traversal) " << std::endl; tree.display(); std::cout << "Elements of Binary Search Tree : (pre-order traversal) " << std::endl; tree.preorder(); std::cout << "Elements of Binary Search Tree : (post-order traversal) " << std::endl; tree.postorder(); std::cout << "Elements of Binary Search Tree : (level-order traversal) " << std::endl; tree.levelorder(); tree.search(10); tree.remove(20); std::cout << "Elements of Binary Search Tree : " << std::endl; tree.display(); tree.remove(25); std::cout << "Elements of Binary Search Tree : " << std::endl; tree.display(); tree.remove(30); std::cout << "Elements of Binary Search Tree : " << std::endl; tree.display(); std::cout << "\n ************* AVL Tree************ " << std::endl; AVLTree<int> avltree; avltree.insert(10); avltree.insert(20); avltree.insert(30); avltree.insert(25); avltree.insert(28); avltree.insert(27); avltree.insert(5); std::cout << "\nElements of AVL Tree (inorder traversal) : " << std::endl; avltree.display(); std::cout << "\nElements of AVL Tree (pre-order traversal) : " << std::endl; avltree.preorder(); std::cout << "\nElements of AVL Tree (post-order traversal) : " << std::endl; avltree.postorder(); std::cout << "Removed Data : " << avltree.remove(5) << std::endl; std::cout << "\nElements of AVL Tree (inorder traversal) : " << std::endl; avltree.display(); std::cout << "\n ******** LL Rotation of AVL Tree *********** " << std::endl; AVLTree<int> llRotate; llRotate.insert(10); llRotate.insert(20); llRotate.insert(30); llRotate.insert(25); llRotate.insert(28); llRotate.insert(27); llRotate.insert(5); std::cout << "\nElements of AVL Tree : " << std::endl; llRotate.display(); std::cout << "\n ******** LR Rotation of AVL Tree *********** " << std::endl; AVLTree<int> lrRotate; lrRotate.insert(30); lrRotate.insert(10); lrRotate.insert(20); std::cout << "\nElements of AVL Tree (inorder traversal) : " << std::endl; lrRotate.display(); std::cout << "\n ******** RR Rotation of AVL Tree *********** " << std::endl; AVLTree<int> rrRotate; rrRotate.insert(10); rrRotate.insert(20); rrRotate.insert(50); std::cout << "\nElements of AVL Tree (inorder traversal) : " << std::endl; rrRotate.display(); std::cout << "\n ******** RL Rotation of AVL Tree *********** " << std::endl; AVLTree<int> rlRotate; rlRotate.insert(10); rlRotate.insert(30); rlRotate.insert(20); std::cout << "\nElements of AVL Tree (inorder traversal) : " << std::endl; rlRotate.display(); return 0; }<file_sep>/DS/Queue/Queue.h #pragma once #ifndef _QUEUE_H_ #define _QUEUE_H_ #include<iostream> #include<exception> #include"Stack.h" class QueueException : virtual public std::exception { std::string msg; public: QueueException(std::string msg) : msg(msg) {} virtual ~QueueException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> class Queue { private: int size; int front; int rear; T* qArr; public: Queue() : size(-1), front(0), rear(0) {} Queue(int size) : size(size), front(0), rear(0) { qArr = new T[size]; } bool isFull() { return (rear == (size - 1)); } bool isEmpty() { return (front == rear); } void enqueue(T data) { try { if (isFull()) throw(QueueException("Queue is Full.")); else { qArr[rear++] = std::move(data); } } catch (const QueueException& me) { std::cout << me.what() << std::endl; } } T dequeue() { try { if (isEmpty()) { throw(QueueException("Queue is Empty.")); return NULL; } else { T temp; temp = qArr[front++]; return temp; } } catch (const QueueException& me) { std::cout << me.what() << std::endl; } } void display() { for (int i = front; i < rear; i++) { std::cout << qArr[i] << " "; } std::cout << std::endl; } ~Queue() { delete[] qArr; } }; template <class T> class QueueStk { private: int size; Stack<T> enqeueStk = Stack<T>(size); Stack<T> deqeueStk = Stack<T>(size); public: QueueStk() : size(-1) {} QueueStk(int size) : size(size) {} void enqueue(T data) { enqeueStk.push(data); } T dequeue() { if (deqeueStk.isEmpty()) while (!(enqeueStk.isEmpty())) deqeueStk.push(enqeueStk.pop()); return deqeueStk.pop(); } void display() { deqeueStk.display(); enqeueStk.display(); } }; #endif // !_QUEUE_H_ <file_sep>/DS/Matrix/Matrix.h #pragma once #include<iostream> #include<cmath> #include<math.h> #include<vector> #include<tuple> #include<exception> class MatrixException : virtual public std::exception{ std::string msg; public: MatrixException(std::string msg) : msg(msg){} virtual ~MatrixException() throw(){} virtual const char* what() const throw() { return msg.c_str(); } }; //template <class T> class Matrix2D { private: unsigned col_size; unsigned row_size; std::vector<std::vector<double>> Mat; public: Matrix2D() : row_size(0), col_size(0), Mat({}) {}; Matrix2D(unsigned row, unsigned col): row_size(row), col_size(col) { Mat.resize(row_size, std::vector<double>(col_size, 0)); } Matrix2D(unsigned row, unsigned col, double value) : row_size(row), col_size(col) { Mat.resize(row_size, std::vector<double>(col_size, value)); } void display() const; std::tuple<int, int> size() { return { this->row_size, this->col_size }; } int rows() const { return this->row_size; } int cols() const { return this->col_size; } Matrix2D operator + (const Matrix2D& ); Matrix2D operator + (double); Matrix2D add(const Matrix2D& ); Matrix2D operator - (const Matrix2D& ); Matrix2D operator - (double); Matrix2D subtract(const Matrix2D&); Matrix2D operator * (const Matrix2D& ); Matrix2D operator * (double); Matrix2D operator / (double); void zeros(int , int ); void ones(int , int ); Matrix2D transpose(); Matrix2D dot(Matrix2D); Matrix2D cross(Matrix2D); double determinant(); Matrix2D inverse(); ~Matrix2D() {}; }; <file_sep>/DS/Matrix/Matrix.cpp #include"Matrix.h" void Matrix2D::display() const { std::cout << "[\n"; for (unsigned i = 0; i < row_size; i++) { std::cout << " [ "; for (unsigned j = 0; j < col_size; j++) { std::cout << Mat[i][j] << " "; } std::cout << " ]\n"; } std::cout << "]\n"; } Matrix2D Matrix2D::operator+(const Matrix2D& obj) { Matrix2D Res(row_size, col_size, 0.0); try { if ((row_size == obj.row_size) && (col_size == obj.col_size)) { for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] + obj.Mat[i][j]; } else { throw(MatrixException("Matrices are not of the same size.")); } } catch (const MatrixException& me) { std::cout << me.what() << std::endl; } return Res; } Matrix2D Matrix2D::add(const Matrix2D& B) { Matrix2D Res(row_size, col_size, 0.0); try { if ((row_size == B.row_size) && (col_size == B.col_size)) { for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] + B.Mat[i][j]; } else { throw(MatrixException("Matrices are not of the same size.")); } } catch (const MatrixException& me) { std::cout << me.what() << std::endl; } return Res; } Matrix2D Matrix2D::operator + (double scalar) { Matrix2D Res(row_size, col_size, 0.0); for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] + scalar; return Res; } Matrix2D Matrix2D::operator-(const Matrix2D& obj) { Matrix2D Res(row_size, col_size, 0.0); try { if ((row_size == obj.row_size) && (col_size == obj.col_size)) { for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] - obj.Mat[i][j]; } else { throw(MatrixException("Matrices are not of the same size.")); } } catch (const MatrixException& me) { std::cout << me.what() << std::endl; } return Res; } Matrix2D Matrix2D::subtract(const Matrix2D& B) { Matrix2D Res(row_size, col_size, 0.0); try { if ((row_size == B.row_size) && (col_size == B.col_size)) { for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] - B.Mat[i][j]; } else { throw(MatrixException("Matrices are not of the same size.")); } } catch (const MatrixException& me) { std::cout << me.what() << std::endl; } return Res; } Matrix2D Matrix2D::operator - (double scalar) { Matrix2D Res(row_size, col_size, 0.0); for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] - scalar; return Res; } Matrix2D Matrix2D::operator * (double scalar) { Matrix2D Res(row_size, col_size, 0.0); for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] * scalar; return Res; } Matrix2D Matrix2D::operator / (double scalar) { Matrix2D Res(row_size, col_size, 0.0); for (unsigned i = 0; i < row_size; i++) for (unsigned j = 0; j < col_size; j++) Res.Mat[i][j] = this->Mat[i][j] / scalar; return Res; } void Matrix2D::zeros(int row, int col) { Mat.clear(); Mat.resize(row); for (unsigned i = 0; i < Mat.size(); i++) { Mat[i].resize(col, 0); } } void Matrix2D::ones(int row, int col) { Mat.clear(); Mat.resize(row); for (unsigned i = 0; i < Mat.size(); i++) { Mat[i].resize(col, 1); } } Matrix2D Matrix2D::transpose() { Matrix2D Transpose(row_size, col_size, 0.0); for (unsigned i = 0; i < col_size; i++) for (unsigned j = 0; j < row_size; j++) Transpose.Mat[i][j] = this->Mat[j][i]; return Transpose; }<file_sep>/DS/ArrayADT/main.cpp #include "ArrayADT.cpp" int main() { Array<int> arr1(20); arr1.Insert(0, 3); arr1.Insert(1, 6); arr1.Insert(2, 8); arr1.Insert(3, 8); arr1.Insert(4, 10); arr1.Insert(5, 12); arr1.Insert(6, 15); arr1.Insert(7, 15); arr1.Insert(8, 15); arr1.Insert(9, 20); //arr1.displayArr(); arr1.findDuplicates(); } <file_sep>/DS/Matrix/Polynomial.h #pragma once #ifndef _POLYNOMIAL_H_ #define _POLYNOMIAL_H_ #include<iostream> template <class T> class Term { T coeff; T exp; }; template <class T> class Polynomial { private: int n; Term<T>* terms; public: friend std::istream& operator>>(std::istream& is, Polynomial<T>& p); friend std::ostream& operator<<(std::ostream& os, const Polynomial<T> p); Polynomial<T> operator+(const Polynomial<T> p); }; #endif // !_POLYNOMIAL_H_ <file_sep>/DS/Trees/Trees.h #pragma once #ifndef _TREES_H_ #define _TREES_H_ #include<iostream> #include<exception> #include"Queue.h" enum NODE_CHILD { L, R }; class TreeException : virtual public std::exception { std::string msg; public: TreeException(std::string msg) : msg(msg) {} virtual ~TreeException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> struct node { int data; node<T>* left; node<T>* right; }; template <class T> class BinarySearchTree { public: node<T>* root; BinarySearchTree() : root(nullptr) {} node<T>* createEmpty(node<T>* nodePtr) { if (nodePtr == nullptr) { return NULL; } else { createEmpty(nodePtr->left); createEmpty(nodePtr->right); delete nodePtr; } return NULL; } node<T>* insert(T data, node<T>* nodePtr) { if (nodePtr == nullptr) { nodePtr = new node<T>; nodePtr->data = std::move(data); nodePtr->left = nodePtr->right = nullptr; } else if (data < nodePtr->data) { nodePtr->left = insert(data, nodePtr->left); } else if (data > nodePtr->data) { nodePtr->right = insert(data, nodePtr->right); } return nodePtr; } void insert(T data) { root = insert(data, root); } void inorder(node<T>* nodePtr) { if (nodePtr == nullptr) return; inorder(nodePtr->left); std::cout << nodePtr->data << " "; inorder(nodePtr->right); } void inorder() { inorder(root); std::cout << std::endl; } void preorder(node<T>* nodePtr) { if (nodePtr == nullptr) return; std::cout << nodePtr->data << " "; preorder(nodePtr->left); preorder(nodePtr->right); } void preorder() { preorder(root); std::cout << std::endl; } void postorder(node<T>* nodePtr) { if (nodePtr == nullptr) return; postorder(nodePtr->left); postorder(nodePtr->right); std::cout << nodePtr->data << " "; } void postorder() { postorder(root); std::cout << std::endl; } void levelorder(node<T> * nodePtr) { Queue<node<T>*> q(100); std::cout << root->data << " "; q.enqueue(nodePtr); while (!q.isEmpty()) { nodePtr = q.dequeue(); if (nodePtr->left) { std::cout << nodePtr->left->data << " "; q.enqueue(nodePtr->left); } if (nodePtr->right) { std::cout << nodePtr->right->data << " "; q.enqueue(nodePtr->right); } } } void levelorder() { levelorder(root); std::cout << std::endl; } void display() { inorder(root); std::cout << std::endl; } node<T>* min(node<T>* nodePtr) { if (nodePtr == nullptr) return NULL; else if (nodePtr->left == nullptr) return nodePtr; else return min(nodePtr->left); } node<T>* max(node<T>* nodePtr) { if (nodePtr == nullptr) return NULL; else if (nodePtr->right == nullptr) return nodePtr; else return max(nodePtr->right); } node<T>* remove(T data, node<T>* nodePtr) { node<T>* temp; if (nodePtr == nullptr) return NULL; else if (data < nodePtr->data) nodePtr->left = remove(data, nodePtr->left); else if (data > nodePtr->data) nodePtr->right = remove(data, nodePtr->right); else if (nodePtr->left && nodePtr->right) { temp = min(nodePtr->right); nodePtr->data = temp->data; nodePtr->right = remove(nodePtr->data, nodePtr->right); } else { temp = nodePtr; if (nodePtr->left == nullptr) nodePtr = nodePtr->right; else if (nodePtr->right == nullptr) nodePtr = nodePtr->left; delete temp; } return nodePtr; } void remove(T data) { root = remove(data, root); } bool search(T data, node<T>* nodePTr) { if (nodePTr == nullptr) return false; else { if (data == nodePTr->data) return true; else if (data < nodePTr->data) return search(data, nodePTr->left); else if (data > nodePTr->data) return search(data, nodePTr->right); } return false; } void search(T data) { if (search(data, root)) std::cout << "Element " << data << " found in the Binary Search Tree." << std::endl; else std::cout << "Element " << data << " not found in the Binary Search Tree." << std::endl; } ~BinarySearchTree() { createEmpty(root); } }; /* AVL Tree: balance factor = height of left subtree - height of right subtree {-1, 0, 1} if |hl-hr| <= 1 balanced tree if |hl-hr| > 1 imbalanced tree */ template <class T> struct avlNode { T data; int height; avlNode* left; avlNode* right; }; template <class T> class AVLTree { public: avlNode<T>* root; AVLTree() : root(nullptr){} int nodeHeight(avlNode<T>* nodePtr) { int hLeft, hRight; hLeft = nodePtr && nodePtr->left ? nodePtr->left->height : 0; hRight = nodePtr && nodePtr->right ? nodePtr->right->height : 0; return hLeft > hRight ? hLeft + 1 : hRight + 1; } int balanceFactor(avlNode<T>* nodePtr) { int hLeft, hRight; hLeft = nodePtr && nodePtr->left ? nodePtr->left->height : 0; hRight = nodePtr && nodePtr->right ? nodePtr->right->height : 0; return hLeft - hRight; } avlNode<T>* LLRotation(avlNode<T>* nodePtr) { avlNode<T>* leftChildNode = nodePtr->left; avlNode<T>* rightChildNode = leftChildNode->right; leftChildNode->right = nodePtr; nodePtr->left = rightChildNode; nodePtr->height = nodeHeight(nodePtr); leftChildNode->height = nodeHeight(leftChildNode); if (root == nodePtr) root = leftChildNode; return leftChildNode; } avlNode<T>* LRRotation(avlNode<T>* nodePtr) { avlNode<T>* leftChildNode = nodePtr->left; avlNode<T>* rightChildNode = leftChildNode->right; leftChildNode->right = rightChildNode->left; nodePtr->left = rightChildNode->right; rightChildNode->left = leftChildNode; rightChildNode->right = nodePtr; leftChildNode->height = nodeHeight(leftChildNode); nodePtr->height = nodeHeight(nodePtr); rightChildNode->height = nodeHeight(rightChildNode); if (root == nodePtr) root = rightChildNode; return rightChildNode; } avlNode<T>* RRRotation(avlNode<T>* nodePtr) { avlNode<T>* rightChildNode = nodePtr->right; avlNode<T>* leftChildNode = rightChildNode->left; rightChildNode->left = nodePtr; nodePtr->right = leftChildNode; nodePtr->height = nodeHeight(nodePtr); rightChildNode->height = nodeHeight(rightChildNode); if (root == nodePtr) root = rightChildNode; return rightChildNode; } avlNode<T>* RLRotation(avlNode<T>* nodePtr) { avlNode<T>* rightChildNode = nodePtr->right; avlNode<T>* leftChildNode = rightChildNode->left; rightChildNode->left = leftChildNode->right; nodePtr->right = leftChildNode->left; leftChildNode->right = rightChildNode; leftChildNode->left = nodePtr; rightChildNode->height = nodeHeight(rightChildNode); nodePtr->height = nodeHeight(nodePtr); leftChildNode->height = nodeHeight(leftChildNode); if (root == nodePtr) root = leftChildNode; return leftChildNode; } avlNode<T>* insert(T data, avlNode<T>* nodePtr) { if (nodePtr == nullptr) { nodePtr = new avlNode<T>; nodePtr->data = std::move(data); nodePtr->height = 1; nodePtr->left = nodePtr->right = nullptr; } else if (data < nodePtr->data) { nodePtr->left = insert(data, nodePtr->left); } else if (data > nodePtr->data) { nodePtr->right = insert(data, nodePtr->right); } nodePtr->height = nodeHeight(nodePtr); if (balanceFactor(nodePtr) == 2 && balanceFactor(nodePtr->left) == 1) return LLRotation(nodePtr); else if(balanceFactor(nodePtr) == 2 && balanceFactor(nodePtr->left) == -1) return LRRotation(nodePtr); else if (balanceFactor(nodePtr) == -2 && balanceFactor(nodePtr->right) == -1) return RRRotation(nodePtr); else if (balanceFactor(nodePtr) == -2 && balanceFactor(nodePtr->right) == 1) return RLRotation(nodePtr); return nodePtr; } void insert(T data) { root = insert(data, root); } avlNode<T>* remove(T data, avlNode<T>* nodePtr) { if (nodePtr == nullptr) { return nullptr; } if (nodePtr->left == nullptr && nodePtr->right == nullptr) { if (nodePtr == root) root = nullptr; delete nodePtr; return nullptr; } if (data < nodePtr->data) nodePtr->left = remove(data, nodePtr->left); else if (data > nodePtr->data) nodePtr->right = remove(data, nodePtr->right); else { avlNode<T>* temp; if (nodeHeight(nodePtr->left) > nodeHeight(nodePtr->right)) { while (nodePtr && nodePtr->right != nullptr) nodePtr = nodePtr->right; temp = nodePtr->left; nodePtr->data = temp->data; nodePtr->left = remove(temp->data, nodePtr->left); } else { while (nodePtr && nodePtr->left != nullptr) nodePtr = nodePtr->left; temp = nodePtr->right; nodePtr->data = temp->data; nodePtr->right = remove(temp->data, nodePtr->right); } } nodePtr->height = nodeHeight(nodePtr); // Balancing the Tree // L1 Roatation if (balanceFactor(nodePtr) == 2 && balanceFactor(nodePtr->left) == 1) return LLRotation(nodePtr); // L-1 Rotation else if (balanceFactor(nodePtr) == 2 && balanceFactor(nodePtr->left) == -1) return LRRotation(nodePtr); // R-1 Rotation else if (balanceFactor(nodePtr) == -2 && balanceFactor(nodePtr->right) == -1) return RRRotation(nodePtr); // R1 Rotation else if (balanceFactor(nodePtr) == -2 && balanceFactor(nodePtr->right) == 1) return RLRotation(nodePtr); // L0 Rotation else if (balanceFactor(nodePtr) == 2 && balanceFactor(nodePtr->left) == 0) return LLRotation(nodePtr); // R0 Rotation else if (balanceFactor(nodePtr) == -2 && balanceFactor(nodePtr->right) == 0) return RRRotation(nodePtr); return nodePtr; } avlNode<T>* remove(T data) { return remove(data, root); } void inorder(avlNode<T>* nodePtr) { if (nodePtr == nullptr) return; inorder(nodePtr->left); std::cout << nodePtr->data << " "; inorder(nodePtr->right); } void inorder() { inorder(root); std::cout << std::endl; } void display() { inorder(root); std::cout << std::endl; } void preorder(avlNode<T>* nodePtr) { if (nodePtr == nullptr) return; std::cout << nodePtr->data << " "; preorder(nodePtr->left); preorder(nodePtr->right); } void preorder() { preorder(root); std::cout << std::endl; } void postorder(avlNode<T>* nodePtr) { if (nodePtr == nullptr) return; postorder(nodePtr->left); postorder(nodePtr->right); std::cout << nodePtr->data << " "; } void postorder() { postorder(root); std::cout << std::endl; } }; #endif // !_TREES_H_ <file_sep>/DS/Stack/Stack.h #pragma once #ifndef _STACK_H_ #define _STACK_H_ #include<iostream> #include<exception> class StackException : virtual public std::exception { std::string msg; public: StackException(std::string msg) : msg(msg) {} virtual ~StackException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> class Stack { private: int size; int top; T* stackArr; public: Stack() : top(-1) {} Stack(int size) : size(size), top(-1) { stackArr = new T[size]; } bool isEmpty() { if (top == -1) return true; return false; } bool isFull() { if (top == (size - 1)) return true; return false; } void push(T data) { try { if (isFull()) throw(StackException("Stack is Full.")); else { stackArr[++top] = data; } } catch (const StackException& me) { std::cout << me.what() << std::endl; } } T pop() { try { if (isEmpty()) { throw(StackException("Stack is Empty.")); return NULL; } else { T elem = stackArr[top]; top--; return elem; } } catch (const StackException& me) { std::cout << me.what() << std::endl; } } T peek() { try { if (isEmpty()) { throw(StackException("Stack is Empty.")); return NULL; } else { return stackArr[top]; } } catch (const StackException& me) { std::cout << me.what() << std::endl; } } void display() { for (int i = 0; i <= top; i++) { std::cout << stackArr[i] << " "; } std::cout << std::endl; } ~Stack() { delete[] stackArr; } }; #endif // !_STACK_H_ <file_sep>/DS/ArrayADT/Readme.txt # Challenges # Find Missing Element in Sorted Array ## Finding single missing element in an Array 1. Using summation formula - O(n) a. Sum = n * (n+1) / 2 b. find the sum of all elements in the array c. return the difference between Summation and sum of all elements in the array. 2. Using Indices - O(n) l = first element h = last element n = number of elements in the array diff = l - first index(0) for i:=0 to n-1: if A[i] - i != diff: return diff+i; ## Finding Multiple missing elements in an Array 1. Using Indices - O(n) l = first element h = last element n = number of elements in the array diff = l - first index(0) for i:=0 to n-1: if A[i] - i != diff: while (diff < A[i] - 1): print(i+diff); diff++; # Find Duplicates in Sorted Array A = {3, 6, 8, 8, 10, 12, 15, 15, 15, 20} n = number of elements lastDuplicate = 0; for i:=0 to n: if A[i] == A[i+1] and if lastDuplicate != A[i]: display A[i]; lastDuplicate := A[i]; ## Counting Duplicates - n = number of elements lastDuplicate = 0; for i:=0 to n-1: if A[i] == A[i+1] j = j+1; while (A[j] == A[i]): j++; print(j-1 + "number is appearing" + j-i + "times."); i = j-1; if lastDuplicate != A[i]: display A[i]; lastDuplicate := A[i]; ## Find Duplicates in Sorted Array using Hashing - O(n) A = {3, 6, 8, 8, 10, 12, 15, 15, 15, 20} H = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - 20 elements for i:= 0 to n-1: H[A[i]]++; for i:= 0 to max: if H[i] > 1: print(i + "number is appearing " + H[i] + "times."); ## Find Duplicates in Unsorted Array A = {8, 3, 6, 4, 6, 5, 6, 8, 2, 7} # Find a pair with sum k ## General Method - O(n^2) A = {6, 3, 8, 10, 16, 7, 5, 2, 9, 14} a + b = k for i:=0 to n-1: for j:=i+1 to n: if A[i] + A[j] == k: print(A[j], A[j]); ## Hashing - O(n) A = {6, 3, 8, 10, 16, 7, 5, 2, 9, 14} H = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} for i:=0 to n: if H[k-A[i]] != 0: print(A[i], k-A[i]); H[A[i]]++; # Find a pair with sum k in Sorted Array A = {1, 3, 4, 5, 6, 8, 9, 10, 12, 14} i:=0, j:=n-1 while i<j: if A[i] + A[j] == k: print(A[i], A[j]); i++; j--; else if A[i] + A[j] < k: i++; else: j--; # Find Max and Min in one sweep - O(n) A = {5, 8, 3, 9, 6, 2, 10, 7, -1, 4} min := A[0]; max := A[0]; for i:=0 to n: if A[i] < min: min := A[i] else if A[i] > max: max := A[i] <file_sep>/DS/ArrayADT/ArrayADT.cpp #include "ArrayADT.h" template<class T> void Array<T>::displayArr() { std::cout << "Elements are : \n"; for (int i = 0; i <length; i++) { std::cout << A[i] << " "; } std::cout << "\n"; } template<class T> void Array<T>::Append(T x) { if (length < size) A[length++] = x; } template<class T> void Array<T>::Insert(int index, T x) { int i; if (index >= 0 && index <= length) { for (i = length; i > index; i--) A[i] = A[i - 1]; A[index] = x; length++; } else { std::cout << "Index Invalid.\n"; } } template<class T> T Array<T>::Delete(int index) { int i, temp; if (index >= 0 && index <= length) { temp = A[index]; for (i = index; i < length - 1; i++) A[i] = A[i + 1]; length--; return temp; } else { std::cout << "Index Invalid.\n"; } return 0; } template<class T> int Array<T>::LinearSearch(int key) { int i = 0; for (i = 0; i < length; i++) { if (A[i] == key) return i; } return -1; } template<class T> int Array<T>::BinarySearch(int key) { int low = 0; int high = length - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (key == A[mid]) return mid; else if (key < A[mid]) high = mid - 1; else if (key > A[mid]) low = mid + 1; } return -1; } template<class T> int Array<T>::get(int index) { if (index >= 0 && index < length) return A[index]; else { std::cout << "Index Out of Bounds.\n"; return -1; } } template<class T> void Array<T>::set(int index, T x) { if (index >= 0 && index < length) A[index] = x; else { std::cout << "Index Out of Bounds.\n"; } } template<class T> int Array<T>::Max() { int i = 0, max = A[0]; for (i = 1; i < length; i++) if (A[i] > max) max = A[i]; return max; } template<class T> int Array<T>::Min() { int i = 0, min = A[0]; for (i = 1; i < length; i++) if (A[i] < min) min = A[i]; return min; } template<class T> int Array<T>::Sum() { int total = 0, i = 0; for (i = 0; i < length; i++) total += A[i]; return total; } template<class T> float Array<T>::Avg() { int total = 0; total = Sum(); return total / length; } template<class T> void Array<T>::Reverse() { int i = 0, j = 0; int temp = 0; for (i = 0, j = length - 1; i < j; i++, j--) { temp = A[i]; A[i] = A[j]; A[j] = temp; } displayArr(); } template<class T> bool Array<T>::isSorted() { int i = 0; for (i = 0; i < length - 1; i++) if (A[i] > A[i + 1]) return false; return true; } template<class T> Array<T>* Array<T>::Merge(Array<T> arr2) { int i = 0, j = 0, k = 0; Array* arr3 = new Array(length+arr2.length); while (i < length && j < arr2.length) { if (A[i] < arr2.A[j]) arr3->A[k++] = A[i++]; else arr3->A[k++] = arr2.A[j++]; } for (; i < length; i++) arr3->A[k++] = A[i]; for (; j < arr2.length; j++) arr3->A[k++] = arr2.A[j]; arr3->length = length + arr2.length; return arr3; } template<class T> void Array<T>::findDuplicates() { Array<int> H = new Array<int>(Max()); for (int i = 0; i < H.length; i++) { H.A[i] = 0; std::cout << H.A[i] << "\t"; } std::cout << std::endl; for (int i = 0; i < length; i++) { H.A[A[i]]++; } /* for (int i = 0; i < H->length; i++) if (H->A[i] > 1) std::cout << "The Number " << i << "is appearing " << H->A[i] << " times!\n"; */ }<file_sep>/DS/Matrix/Polynomial.cpp #include"Polynomial.h" template <class T> std::istream& operator >> (std::istream& is, Polynomial<T>& p) { int i = 0; std::cout << "Number of terms : "; std::cin >> p.n; p->terms = new Term<T>[p.n * sizeof(Term<T>)]; std::cout << "\nEnter Terms : \n"; for (i = 0; i < p.n; i++) std::cin << p->terms[i].coeff << p->terms[i].exp; return is; } template <class T> std::ostream& operator << (std::ostream& os, const Polynomial<T> p) { int i = 0; for (i = 0; i < p.n; i++) std::cout << p.terms[i].coeff << "^" << p.terms[i].exp; std::cout << std::endl; return os; } template <class T> Polynomial<T> Polynomial<T>::operator+(const Polynomial<T> p) { int i = 0, j = 0, k = 0; Polynomial<T>* sum; sum = new Polynomial<T>[sizeof(Polynomial)]; sum->terms = new Term<T>[(n + p->n) * sizeof(Term)]; while (i < n && j < p->n) { if (terms[i].exp > p.terms[j].exp) sum->terms[k++] = terms[i++]; else if (terms[i].exp < p.terms[j].exp) sum->terms[k++] = p.terms[j++]; else { sum->terms[k].exp = terms[i].exp; sum->terms[k++].coeff = terms[i++].coeff + p.terms[j++].coeff; } } for (; i < n; i++) sum->terms[k++] = terms; for (; j < p.n; j++) sum->terms[k++] = p.terms; sum->n = k; return sum; }<file_sep>/DS/Matrix/SparseMatrix.cpp #include"SparseMatrix.h" void SparseMatrix::read() { std::cout << "Enter Non-Zero Elements: \n"; for (int i = 0; i < num; i++) { std::cin >> ele[i].i >> ele[i].j >> ele[i].x; } } void SparseMatrix::display() const{ int k = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (ele[k].i == i && ele[k].j == j) std::cout << ele[k++].x << " "; else std::cout << "0 "; } std::cout << std::endl; } } std::istream& operator >> (std::istream& is, SparseMatrix& s) { std::cout << "Enter Non-Zero Elements: \n"; for (int i = 0; i < s.num; i++) { std::cin >> s.ele[i].i >> s.ele[i].j >> s.ele[i].x; } return is; } std::ostream& operator << (std::ostream& os, const SparseMatrix& s) { int k = 0; for (int i = 0; i < s.m; i++) { for (int j = 0; j < s.n; j++) { if (s.ele[k].i == i && s.ele[k].j == j) std::cout << s.ele[k++].x << " "; else std::cout << "0 "; } std::cout << std::endl; } return os; } SparseMatrix SparseMatrix::operator+(const SparseMatrix& s) { int i = 0, j = 0, k = 0; if (m != s.m || n != s.n) exit ; SparseMatrix* sum = new SparseMatrix(m, n, num + s.num); while (i < num && j < s.num) { if (ele[i].i < s.ele[j].i) sum->ele[k++] = ele[i++]; else if(ele[i].i > s.ele[j].i) sum->ele[k++] = s.ele[j++]; else { if (ele[i].j < s.ele[j].j) sum->ele[k++] = ele[i++]; else if (ele[i].j > s.ele[j].j) sum->ele[k++] = s.ele[j++]; else { sum->ele[k] = ele[i]; sum->ele[k++].x = ele[i++].x + s.ele[j++].x; } } } for (; i < num; i++) sum->ele[k++] = ele[i]; for (; j < s.num; j++) sum->ele[k++] = s.ele[j]; sum->num = k; return *sum; }<file_sep>/DS/STL/List_Forward_List.cpp #include<iostream> #include<list> #include<algorithm> #include<iterator> class Person { friend std::ostream& operator<<(std::ostream& os, const Person& p); std::string name; int age; public: Person(): name{"Unknown"}, age{0}{} Person(std::string name, int age): name{name}, age{age}{} bool operator<(const Person& rhs) const { return this->age < rhs.age; } bool operator==(const Person& rhs) const { return (this->name == rhs.name && this->age == rhs.age); } }; std::ostream& operator<<(std::ostream& os, const Person& p) { os << p.name << " : " << p.age; return os; } template <typename T> void show(const std::list<T>& l) { std::cout << "[ "; for (const auto& elem : l) { std::cout << elem << " "; } std::cout << " ]" << std::endl; } void one() { std::cout << "\n Test1 ==============================" << std::endl; std::list<int> l{ 1, 2, 3, 4, 5 }; show(l); std::list<std::string> l1; l1.push_back("Back"); l1.push_front("Front"); show(l1); std::list<int> l2; l2 = { 1,2,3,4,5,6,7,8,9,10 }; show(l2); std::list<int> l3(10, 100); show(l3); } void two() { std::cout << "\n Test2 ==============================" << std::endl; std::list<int> l{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; show(l); std::cout << "Size: " << l.size() << std::endl; std::cout << "Front: " << l.front() << std::endl; std::cout << "Back: " << l.back() << std::endl; l.clear(); show(l); std::cout << "Size: " << l.size() << std::endl; } void three() { std::cout << "\n Test3 ==============================" << std::endl; std::list<int> l{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; show(l); l.resize(5); show(l); l.resize(10); show(l); std::list<Person> persons; persons.resize(5); show(persons); } void four() { std::cout << "\n Test4 ==============================" << std::endl; std::list<int> l{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; show(l); auto it = std::find(l.begin(), l.end(), 5); if (it != l.end()) l.insert(it, 100); show(l); std::list<int> l2{ 1000, 2000, 3000 }; l.insert(it, l2.begin(), l2.end()); show(l); std::advance(it, -4); l.erase(it); show(l); } void five() { std::cout << "\n Test5 ==============================" << std::endl; std::list<Person> p; show(p); } /* int main() { one(); two(); three(); four(); five(); return 0; } */<file_sep>/DS/LinkedList/LinkedList.h #pragma once #ifndef _LINKEDLIST_H_ #define _LINKEDLIST_H_ #include<iostream> #include<exception> #include"Node.h" class LinkedListException : virtual public std::exception { std::string msg; public: LinkedListException(std::string msg) : msg(msg) {} virtual ~LinkedListException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> class LinkedList { private: Node<T>* head; Node<T>* last; public: LinkedList() : head(nullptr), last(nullptr) {} LinkedList(T data) { addNode(data); } ~LinkedList() {} friend std::ostream& operator<<(std::ostream& str, LinkedList& data) { data.display(str); return str; } LinkedList<T>& operator +(LinkedList& other) { if (head == nullptr) { return other; } else if (other.head == nullptr) { return *this; } else { LinkedList<T> result; result.head = head; Node<T>* temp = result.head; while (temp->next != nullptr) temp = temp->next; temp->next = other.head; while (temp->next != nullptr) temp = temp->next; temp->next = nullptr; result.last = temp; return result; } } LinkedList<T>& concatenate(LinkedList& other) { return head + other; } void addNode(const T data) { Node<T>* newnode = new Node<T>(); newnode->data = std::move(data); newnode->next = nullptr; if (head == nullptr) head = newnode; else { Node<T>* temp = head; while (temp->next != nullptr) temp = temp->next; temp->next = newnode; } last = newnode; } int size() { int count = 0; if (head == nullptr) return 0; else { Node<T>* temp = head; while (temp != nullptr) { count++; temp = temp->next; } } return count; } int sum() { int total = 0; if (head == nullptr) return 0; else { Node<T>* temp = head; while (temp != nullptr) { total = total + temp->data; temp = temp->next; } } return total; } int max() { int MAX = -32678; if (head == nullptr) return 0; else { Node<T>* temp = head; while (temp != nullptr) { if (MAX < temp->data) MAX = temp->data; temp = temp->next; } } return MAX; } T LinearSearch(T key) { if (head == nullptr) return 0; else { Node<T>* temp = head; while (temp != nullptr) { if (temp->data == key) return temp->data; temp = temp->next; } } return NULL; } void display(std::ostream& str = std::cout) const { if (head == nullptr) std::cout << "List is empty!\n"; else { Node<T>* temp = head; while (temp != nullptr) { str << temp->data << " "; temp = temp->next; } std::cout << "\n"; } } void insert(T val, int pos = 0) { try { if (pos < 0 || pos > size()) throw(LinkedListException("LinkedList Exception: Index out of range.")); } catch (const LinkedListException& me) { std::cout << me.what() << std::endl; } Node<T>* temp =new Node<T>(); temp->data = std::move(val); Node<T>* p; if (pos == 0) { temp->next = head; head = temp; } else if (pos > 0){ p = head; for (int i = 0; i < pos - 1 && p; i++) { p = p->next; } temp->next = p->next; p->next = temp; } } void push_back(T data) { Node<T>* temp = new Node<T>(); temp->data = std::move(data); temp->next = nullptr; if (head == nullptr) head = last = temp; else { last->next = temp; last = temp; } } T remove(int pos = 0) { T x; try { if (pos < 0 || pos > size()) throw(LinkedListException("LinkedList Exception: Index out of range.")); } catch (const LinkedListException& me) { std::cout << me.what() << std::endl; } Node<T>* p = nullptr; Node<T>* temp = head; if (pos == 0) { head = head->next; x = temp->data; delete temp; return x; } else if (pos > 0) { p = head; for (int i = 0; i <= pos - 1 && p; i++) { temp = p; p = p->next; } temp->next = p->next; x = temp->data; delete p; return x; } return NULL; } bool isSorted() { if (head == nullptr) { std::cout << "List is empty!\n"; return false; } else { Node<T>* temp = head; T x = NULL; while (temp != nullptr) { if (temp->data < x) { return false; } x = temp->data; temp = temp->next; } } return true; } void removeDuplicates() { try { if (isSorted()) { Node<T>* temp = head; Node<T>* p = head->next; while (p != nullptr) { if (temp->data != p->data) { temp = p; p = p->next; } else { temp->next = p->next; delete p; p = temp->next; } } } else { throw(LinkedListException("LinkedList Exception: LinkedList is not Sorted.")); } } catch (const LinkedListException& me) { std::cout << me.what() << std::endl; } } }; #endif // !_LINKEDLIST_H_<file_sep>/DS/LinkedList/CircularLinkedList.h #pragma once #ifndef _CIRCULARLINKEDLIST_H_ #define _CIRCULARLINKEDLIST_H_ #include<iostream> #include<exception> #include"Node.h" class CircularLinkedListException : virtual public std::exception { std::string msg; public: CircularLinkedListException(std::string msg) : msg(msg) {} virtual ~CircularLinkedListException() throw() {} virtual const char* what() const throw() { return msg.c_str(); } }; template <class T> class CircularLinkedList { private: Node<T>* head; Node<T>* last; public: CircularLinkedList() : head(nullptr) { last = head; } ~CircularLinkedList() {} void addNode(const T val) { Node<T>* newnode = new Node<T>(); newnode->data = std::move(val); newnode->next = head; if (head == nullptr) { newnode->next = newnode; head = newnode; } else { Node<T>* temp = head; while (temp->next != head) temp = temp->next; temp->next = newnode; } last = newnode; last->next = head; } void insert(T val, int pos = 0) { try { if (pos < 0 || pos > size()) throw(CircularLinkedListException("Circular LinkedList Exception: Index out of range.")); } catch (const CircularLinkedListException& me) { std::cout << me.what() << std::endl; } Node<T>* temp = new Node<T>(); temp->data = std::move(val); Node<T>* p; if (pos == 0) { temp->next = head; head = temp; } else if(pos > 0) { p = head; for (int i = 0; i < pos - 1 && p; i++) p = p->next; temp->next = p->next; p->next = temp; } } T remove(int pos = 0) { T x; try { if (pos < 0 || pos > size()) throw(CircularLinkedListException("Circular LinkedList Exception: Index out of range.")); } catch (const CircularLinkedListException& me) { std::cout << me.what() << std::endl; } Node<T>* temp = head; Node<T>* p = nullptr; if (pos == 0) { head = head->next; x = temp->data; delete temp; return x; } else if(pos > 0) { p = head; for (int i = 0; i < pos - 1 && p; i++) { temp = p; p = p->next; } temp->next = p->next; x = temp->data; delete p; return x; } return NULL; } void display() { Node<T>* temp = head; try { if (head == nullptr) { throw(CircularLinkedListException("Circular LinkedList Exception: No elements in the List.")); } else { do { std::cout << temp->data << " "; temp = temp->next; } while (temp->next != head); std::cout << temp->data << std::endl; } } catch (const CircularLinkedListException& me) { std::cout << me.what() << std::endl; } } int size() { int count = 1; if (head == nullptr) { return 0; } else { Node<T>* temp = head; do { count++; temp = temp->next; } while (temp->next != head); } return count; } }; #endif // !_CIRCULARLINKEDLIST_H_<file_sep>/DS/Matrix/main.cpp #include<iostream> #include<stdio.h> #include<vector> #include"Matrix.h" #include"SparseMatrix.h" #include"Polynomial.h" int main() { SparseMatrix s1(5, 5, 5); SparseMatrix s2(5, 5, 5); std::cin >> s1; std::cin >> s2; SparseMatrix sum = s1 + s2; std::cout << "First Matrix : \n" << s1 << std::endl; std::cout << "Second Matrix : \n" << s2 << std::endl; std::cout << "Sum Matrix : \n" << sum << std::endl; Polynomial<int> p1; std::cin >> p1; std::cout << p1; return 0; } <file_sep>/DS/ArrayADT/ArrayCImpl.cpp #include<stdio.h> #include<stdlib.h> struct Array { int A[20]; int size; int length; }; void displayArr(struct Array arr) { int i; printf("Elements are : \n"); for (i = 0; i < arr.length; i++) { printf("%d ", arr.A[i]); } printf("\n"); } void Append(struct Array* arr, int x) { if (arr->length < arr->size) arr->A[arr->length++] = x; } void Insert(struct Array* arr, int index, int x) { int i; if (index >= 0 && index <= arr->length) { for (i = arr->length; i > index; i--) arr->A[i] = arr->A[i - 1]; arr->A[index] = x; arr->length++; } else { printf("Index Invalid.\n"); } } int Delete(struct Array* arr, int index) { int i, temp; if (index >= 0 && index <= arr->length) { temp = arr->A[index]; for (i = index; i < arr->length - 1; i++) arr->A[i] = arr->A[i + 1]; arr->length--; return temp; } else { printf("Index Invalid.\n"); } return 0; } int LinearSearch(struct Array* arr, int elem) { int i = 0; for (i = 0; i < arr->length; i++) { if (arr->A[i] == elem) return i; } return -1; } int BinarySearch(struct Array* arr, int key) { int low = 0; int high = arr->length - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (key == arr->A[mid]) return mid; else if (key < arr->A[mid]) high = mid - 1; else if (key > arr->A[mid]) low = mid + 1; } return -1; } int BinarySearchRecursive(struct Array* arr, int low, int high, int key) { int mid = 0; if (low <= high) { mid = (low + high) / 2; if (key == arr->A[mid]) return mid; else if (key < arr->A[mid]) { return BinarySearchRecursive(arr, low, mid - 1, key); } else if (key > arr->A[mid]) return BinarySearchRecursive(arr, mid + 1, high, key); } return -1; } int getElement(struct Array arr, int index) { if (index >= 0 && index < arr.length) return arr.A[index]; else { printf("Index out of Bounds.\n"); return -1; } } void setElement(struct Array* arr, int index, int x) { if (index >= 0 && index < arr->length) arr->A[index] = x; else { printf("Index out of Bounds.\n"); } } int max(struct Array arr) { int i = 0, max = arr.A[0]; for (i = 1; i < arr.length; i++) if (arr.A[i] > max) max = arr.A[i]; return max; } int min(struct Array arr) { int i = 0, min = arr.A[0]; for (i = 1; i < arr.length; i++) if (arr.A[i] < min) min = arr.A[i]; return min; } int sum(struct Array arr) { int total = 0, i = 0; for (i = 0; i < arr.length; i++) total += arr.A[i]; return total; } float avg(struct Array arr) { float total = 0; total = static_cast<float>(sum(arr)); return total / arr.length; } void ReverseArray(struct Array* arr) { int i = 0, j = 0; int temp = 0; for (i = 0, j = arr->length - 1; i < j; i++, j--) { temp = arr->A[i]; arr->A[i] = arr->A[j]; arr->A[j] = temp; } printf("Reversed Array :- \n"); displayArr(*arr); } void LeftRotation(struct Array* arr) { int i = 0; int temp = arr->A[0]; for (i = 0; i < arr->length; i++) { arr->A[i] = arr->A[i + 1]; } arr->A[arr->length - 1] = temp; } void RightRotation(struct Array* arr) { int i = 0; int temp = arr->A[arr->length - 1]; for (i = arr->length - 1; i >= 0; i--) { arr->A[i] = arr->A[i - 1]; } arr->A[0] = temp; } bool isSorted(struct Array arr) { int i = 0; for (i = 0; i < arr.length - 1; i++) { if (arr.A[i] > arr.A[i + 1]) return false; } return true; } struct Array* Merge(struct Array* arr1, struct Array* arr2) { int i = 0, j = 0, k = 0; struct Array* arr3 = (struct Array*)malloc(sizeof(struct Array)); while (i < arr1->length && j < arr2->length) { if (arr1->A[i] < arr2->A[j]) arr3->A[k++] = arr1->A[i++]; else arr3->A[k++] = arr2->A[j++]; } for (; i < arr1->length; i++) arr3->A[k++] = arr1->A[i]; for (; j < arr2->length; j++) arr3->A[k++] = arr2->A[j]; arr3->length = arr1->length + arr2->length; arr3->size = 10; return arr3; } <file_sep>/DS/STL/Vector_Container.cpp #include<iostream> #include<algorithm> #include<vector> /* class Person { friend std::ostream& operator<<(std::ostream& os, const Person& p); std::string name; int age; public: Person() = default; Person(std::string name, int age) : name(name), age(age){} bool operator<(const Person& rhs)const { return this->age < rhs.age; } bool operator==(const Person& rhs) const { return (this->name == rhs.name && this->age == rhs.age); } }; std::ostream& operator<<(std::ostream& os, const Person& p) { os << p.name << ":" << p.age; return os; } void display2(const std::vector<int>& vec) { std::cout << "[ "; std::for_each(vec.begin(), vec.end(), [](int x) {std::cout << x << " "; }); std::cout << " ]" << std::endl; } // Template function to display any vector template <typename T> void display_t(const std::vector<T>& vec) { std::cout << "[ "; for (const auto& elem : vec) std::cout << elem << " "; std::cout << " ]"<<std::endl; } void test_first() { std::cout << "\nTest1=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 }; display_t(vec); std::vector<int> vec1{ 10, 100 }; display_t(vec1); } void test_second() { std::cout << "\nTest2=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 }; display_t(vec); std::cout << "Vec Size: " << vec.size() << std::endl; std::cout << "Vec Max Size: " << vec.max_size() << std::endl; std::cout << "Vec Capacity: " << vec.capacity() << std::endl; vec.push_back(6); display_t(vec); std::cout << "Vec Size: " << vec.size() << std::endl; std::cout << "Vec Max Size: " << vec.max_size() << std::endl; std::cout << "Vec Capacity: " << vec.capacity() << std::endl; vec.shrink_to_fit(); display_t(vec); std::cout << "Vec Size: " << vec.size() << std::endl; std::cout << "Vec Max Size: " << vec.max_size() << std::endl; std::cout << "Vec Capacity: " << vec.capacity() << std::endl; vec.reserve(100); display_t(vec); std::cout << "Vec Size: " << vec.size() << std::endl; std::cout << "Vec Max Size: " << vec.max_size() << std::endl; std::cout << "Vec Capacity: " << vec.capacity() << std::endl; } void test_third() { std::cout << "\nTest3=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 }; display_t(vec); vec[0] = 100; vec.at(1) = 200; display_t(vec); } void test_four() { std::cout << "\nTest4=====================" << std::endl; std::vector<Person> stooges; Person p1{ "Aditya", 21 }; display_t(stooges); stooges.push_back(p1); display_t(stooges); stooges.push_back(Person{ "Aditya", 21 }); display_t(stooges); stooges.emplace_back("<NAME>", 22); display_t(stooges); } void test_five() { std::cout << "\nTest5=====================" << std::endl; std::vector<Person> stooges{ {"Adi", 21}, {"aditya", 22} }; display_t(stooges); std::cout << "\nFront" << stooges.front() << std::endl; std::cout << "\nBack" << stooges.back() <<std::endl; stooges.pop_back(); display_t(stooges); } void test_six() { std::cout << "\nTest5=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 }; display_t(vec); vec.clear(); display_t(vec); vec = { 1,2,3,4,5,6,7,8,9,10 }; display_t(vec); vec.erase(vec.begin(), vec.begin() + 2); display_t(vec); vec = { 1,2,3,4,5,6,7,8,9,10 }; // erase all even numbers auto it = vec.begin(); while (it != vec.end()) { if (*it % 2 == 0) vec.erase(it); else it++; } display_t(vec); } int main() { test_first(); test_second(); test_third(); test_four(); test_five(); test_six(); return 0; }*/<file_sep>/DS/Matrix/SparseMatrix.h #pragma once #ifndef _SPARSEMATRIX_H_ #define _SPARSEMATRIX_H_ #include<iostream> #include<vector> class Element { public: int i; int j; int x; }; class SparseMatrix { private: int m; int n; int num; Element *ele; public: SparseMatrix(int m, int n, int num) : m(m), n(n), num(num) { ele = new Element[this->num]; }; ~SparseMatrix() { delete[] ele; } void read(); void display() const; friend std::istream& operator >> (std::istream& is, SparseMatrix& s); friend std::ostream& operator << (std::ostream& os, const SparseMatrix& s); SparseMatrix operator+(const SparseMatrix& ); }; #endif // !_SPARSEMATRIX_H_<file_sep>/DS/Stack/main.cpp #include<iostream> #include"Stack.h" bool parenthesisMatch(std::string str) { Stack<char> stk(str.length()); for (auto& ch : str) { if (ch == '(' || ch == '[' || ch == '{') stk.push(ch); else if (ch == ')' || ch == ']' || ch == '}') { if (stk.isEmpty()) return false; else { char c; c = stk.pop(); if ((c == '(' && ch != ')') || (c == '[' && ch != ']') || (c == '{' && ch != '}')) return false; } } } if (stk.isEmpty()) return true; return false; } int main() { Stack<int> st(5); if (st.isEmpty()) std::cout << "Stack is Empty" << std::endl; st.push(10); st.push(30); st.push(50); std::cout << "Elements in the Stack : " << std::endl; st.display(); std::cout << "Element Removed : " << st.pop() << std::endl; st.display(); std::cout << "Top Element : " << st.peek() << std::endl; st.push(70); st.push(90); if (st.isFull()) std::cout << "Stack is Full." << std::endl; std::string par = "{[([A-] * [A+b]) \ e}"; if (parenthesisMatch(par)) std::cout << "Parenthesis are in Proper Order." << std::endl; else std::cout << "Parenthesis are not in proper order." << std::endl; return 0; }<file_sep>/DS/STL/Iterator.cpp #include<iostream> #include<vector> #include<set> #include<map> #include<list> /* // display any vector of integers using range-based for loop void display(const std::vector<int>& vec) { std::cout << "[ "; for (auto const& i : vec) { std::cout << i << " "; } std::cout << "]" << std::endl; } void test1() { std::cout << "\n===========================" << std::endl; std::vector<int> nums1{ 1, 2, 3, 4, 5 }; auto it = nums1.begin(); std::cout << *it << std::endl; it++; std::cout << *it << std::endl; it += 2; std::cout << *it << std::endl; it -= 2; std::cout << *it << std::endl; it = nums1.end() - 1; std::cout << *it << std::endl; } void test2() { std::cout << "\n=====================" << std::endl; // display all vector elements using an iterator std::vector<int> nums1{ 1, 2, 3, 4, 5 }; std::vector<int>::iterator it = nums1.begin(); while (it != nums1.end()) { //std::cout << *it << std::endl; *it = 0; it++; } display(nums1); } void test3() { // Using a const iterator std::cout<< "\n=====================" << std::endl; std::vector<int> nums1{ 1, 2, 3, 4, 5 }; std::vector<int>::const_iterator it = nums1.begin(); // auto it1 = nums1.cbegin(); while (it != nums1.end()) { std::cout << *it << std::endl; it++; } while (it != nums1.end()) { //*it = 0; // compiler error - read only it++; } } void test4() { //more iterators // using a reverse iterator std::cout << "\n=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 }; auto it1 = vec.rbegin(); while (it1 != vec.rend()) { std::cout << *it1 << std::endl; it1++; } //const reverse iterator over a list std::list<std::string> name{ "aditya", "Adi", "Mahamuni" }; auto it2 = name.crbegin(); std::cout << *it2 << std::endl; it2++; std::cout << *it2 << std::endl; // Iterator over a map std::map<std::string, std::string> fav{ {"adi", "C++"}, {"Aditya", "Linux"}, {"Adi", "Python"} }; auto it3 = fav.begin(); while (it3 != fav.end()) { std::cout << it3->first << " : " << it3->second << std::endl; it3++; } } void test5() { // Iterate over a sibset of a container std::cout << "\n=====================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10 }; auto start = vec.begin() + 2; auto finish = vec.end() - 3; while (start !=finish) { std::cout << *start << std::endl; start++; } } int main() { test1(); test2(); test3(); test4(); test5(); return 0; }*/<file_sep>/DS/STL/Deque_Container.cpp #include<iostream> #include<deque> #include<vector> #include<algorithm> #include <iterator> //template funtion to display any deque template <typename T> void disp(const std::deque<T>& d) { std::cout << "[ "; for (const auto& item : d) std::cout << item << " "; std::cout << " ]" << std::endl; } void test_1() { std::cout << "\nTest1 ===========================" << std::endl; std::deque<int> d{ 1, 2, 3, 4, 5 }; disp(d); d = { 2, 4, 5, 6 }; disp(d); std::deque<int> d1(10, 100 ); disp(d1); d[0] = 100; d.at(1) = 200; disp(d); } void test_2() { std::cout << "\nTest2 ===========================" << std::endl; std::deque<int> d{ 0,0,0 }; disp(d); d.push_back(10); d.push_back(20); disp(d); d.push_front(100); d.push_front(200); disp(d); std::cout << "Front: " << d.front() << std::endl; std::cout << "Back: " << d.back() << std::endl; std::cout << "Size: " << d.size() << std::endl; d.pop_back(); d.pop_front(); disp(d); } void test_3() { // Insert all even numbers into the back of a deque and all odd numbers to the front std::cout << "\nTest3 ===========================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::deque<int> d; for (const auto& item : vec) { if (item % 2 == 0) d.push_back(item); else d.push_front(item); } disp(d); } void test_4() { std::cout << "\nTest4 ===========================" << std::endl; // Push front vs back ordering std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::deque<int> d; for (const auto& item : vec) { d.push_front(item); } disp(d); d.clear(); for (const auto& item : vec) { d.push_back(item); } disp(d); } void test_5() { std::cout << "\nTest5 ===========================" << std::endl; std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::deque<int> d; std::copy(vec.begin(), vec.end(), std::front_inserter(d)); disp(d); d.clear(); std::copy(vec.begin(), vec.end(), std::back_inserter(d)); disp(d); } /* int main() { test_1(); test_2(); test_3(); test_4(); test_5(); return 0; }*/<file_sep>/DS/LinkedList/main.cpp #include<iostream> #include"LinkedList.h" #include"CircularLinkedList.h" #include"DoublyLinkedList.h" int main(int argc, const char* argv[]) { std::cout << "********* Singly Linked List ***************" << std::endl; LinkedList<int> list; list.addNode(100); list.addNode(200); list.addNode(300); list.addNode(400); //list.insert(700, 0); list.push_back(800); list.push_back(900); list.push_back(900); int x = 0; list.display(); x = list.remove(1); std::cout << x << " - Element removed from the list" << std::endl; list.display(); std::cout << "Size of Linked List : " << list.size() << std::endl; std::cout << "Sum of Elements of Linked List : " << list.sum() << std::endl; std::cout << "Max : " << list.max() << std::endl; if (list.LinearSearch(100) != NULL) { std::cout << "Linear Search found element " << std::endl; } else { std::cout << "Element not found in the List." << std::endl; } if (list.isSorted()) { std::cout << "List is Sorted!! " << std::endl; } else { std::cout << "List is not Sorted!!" << std::endl; } std::cout << "Before removing Duplicates!" << std::endl; list.display(); list.removeDuplicates(); std::cout << "After removing Duplicates!" << std::endl; list.display(); std::cout << "\nConcatenate Linked Lists" << std::endl; LinkedList<int> list2; list2.addNode(1000); list2.addNode(1100); list2.addNode(1200); LinkedList<int> concateList; concateList = list + list2; concateList.display(); std::cout << "\n********* Circular Linked List ***************" << std::endl; CircularLinkedList<int> clist1; clist1.addNode(100); clist1.addNode(2); clist1.addNode(500); clist1.insert(50, 1); clist1.display(); std::cout << "Size of List : " << clist1.size() << std::endl; clist1.remove(3); clist1.display(); std::cout << "\n********* Doubly Linked List ***************" << std::endl; DoublyLinkedList<int> dlist; dlist.addNode(500); dlist.addNode(700); dlist.addNode(25); dlist.insert(50, 2); dlist.insert(70, 1); dlist.display(); std::cout << "Size of List : " << dlist.size() << std::endl; dlist.remove(1); dlist.display(); dlist.push_back(20); dlist.display(); return 0; }<file_sep>/DS/ArrayADT/ArrayADT.h #pragma once #include<iostream> #include<stdio.h> #include<stdlib.h> template<class T> class Array { private: T* A; int size; int length; public: Array() { size = 10; length = 0; A = new T[size]; } Array(int sz) { size = sz; length = 0; A = new T[size]; } ~Array() { delete[]A; } void displayArr(); void Append(T x); void Insert(int index, T x); T Delete(int index); int LinearSearch(int key); int BinarySearch(int key); int get(int index); void set(int index, T x); int Max(); int Min(); int Sum(); float Avg(); void Reverse(); bool isSorted(); Array<T>* Merge(Array<T> arr2); void findDuplicates(); };
a9df30ea420802a48a53a3173ef91eda5f957b24
[ "Text", "C++" ]
29
C++
adityamahamuni/cpp
0da46038fce6c49e59bf635c84531a29f167b7bd
7ad72721604fe4d3e499e3ab0d31e8270c9a1cd1
refs/heads/master
<file_sep>#!/bin/bash jira_project_name="EB3AND" jira_url="https://alterplay.atlassian.net" jira_token="<KEY>" from_status="Team Review" to_status="Ready for QA" slack_webhoock="<KEY>" custom_jira_value="6" custom_jira_field="customfield_11360" changelogpath="changelog.txt" if [ -z "$jira_project_name" ]; then echo "Jira Project Name is required." usage fi if [ -z "$jira_url" ]; then echo "Jira Url is required." usage fi if [ -z "$jira_token" ]; then echo "Jira token is required." usage fi if [ -z "$from_status" ]; then echo "Status of tasks for deployment is required." usage fi if [ -z "$custom_jira_field" ]; then echo "custom_jira_field is empty" usage fi if [ -z "$custom_jira_value" ]; then echo "custom_jira_value is empty." usage fi length=${#jira_project_name} cred="<EMAIL>:$jira_token" token=`echo -n $cred | base64` query=$(jq -n \ --arg jql "project = $jira_project_name AND status = '$from_status'" \ '{ jql: $jql, startAt: 0, maxResults: 200, fields: [ "id" ], fieldsByKeys: false }' ); echo "Query to be executed in Jira: $query" tasks_to_close=$(curl -s \ -H "Content-Type: application/json" \ -H "Authorization: Basic $token" \ --request POST \ --data "$query" \ "$jira_url/rest/api/2/search" | jq -r '.issues[].key' ) change_log="" echo "Tasks to transition: $tasks_to_close" for task in ${tasks_to_close} do echo "Transitioning $task" if [[ -ne "$custom_jira_field" && -ne "$custom_jira_value" ]]; then echo "Setting $custom_jira_field of $task to $custom_jira_value" query=$(jq -n \ --arg c_value "$custom_jira_value" \ --arg c_name "$custom_jira_field" \ '{ "fields": { ($c_name) : { "value": $c_value } } }' ); curl \ -H "Content-Type: application/json" \ -H "Authorization: Basic $token" \ --request PUT \ --data "$query" \ "$jira_url/rest/api/2/issue/$task" fi task_title=$(curl \ -H "Content-Type: application/json" \ -H "Authorization: Basic $token" \ --request GET \ "$jira_url/rest/api/2/issue/$task" | jq -r '.fields.summary') change_log="$change_log"$'\n'"$task_title" transition_id=$(curl -s \ -H "Authorization: Basic $token" \ "$jira_url/rest/api/2/issue/$task/transitions" | jq -r --arg t "$to_status" '.transitions[] | select( .to.name == $t ) | .id' ) echo "ids: $transition_id" if [ -n "$transition_id" ]; then echo "Transitioning $task to $to_status" query=$(jq -n \ --arg ti $transition_id \ '{ transition: { id: $ti } }' ); echo "query: $query" curl \ -H "Content-Type: application/json" \ -H "Authorization: Basic $token" \ --request POST \ --data "$query" \ "$jira_url/rest/api/2/issue/$task/transitions" else echo "No matching transitions from status '$from_status' to '$to_status' for $task" fi done release_message="Next build resolves following issues \n\`\`\`\n" for task in ${tasks_to_close} do release_message="$release_message$jira_url/browse/$task\n" done release_message="$release_message\n\`\`\` " release_message="\"$release_message\"" slack_query=$(jq -n --argjson message "$release_message" '{text:$message}'); echo "======" echo "$change_log" echo "$change_log" > $changelogpath echo "query $slack_query" echo $(curl -X POST -H "Content-type: application/json" --data "$slack_query" $slack_webhoock)
b0a244ac9fe0e427dc95af063840d15a5aa53b88
[ "Shell" ]
1
Shell
frakc/jira-move-task
806627ec9d31a995875f72aa3905b47c6364c3e3
f6f2b268dae46731763616e6e7157d5ec84a90d4
refs/heads/main
<repo_name>vib1307/angular-ssr-project<file_sep>/src/app/launch-programs/launch-programs.component.ts import { Component, OnInit } from '@angular/core'; import { AppService } from '../app.service'; @Component({ selector: 'app-launch-programs', templateUrl: './launch-programs.component.html', styleUrls: ['./launch-programs.component.css'] }) export class LaunchProgramsComponent implements OnInit { launchYears = ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']; launchDataArray = []; isLoading = false; launchYearSelectedIndex: number; showFilter = false; constructor(private appService: AppService) { } ngOnInit(): void { this.getAllLaunches(); } getAllLaunches(): any { this.isLoading = true; this.appService.getAllLaunches() .subscribe((response: any) => { // console.log(response); this.launchDataArray = response; this.isLoading = false; }, err => { console.log(err); this.isLoading = false; }) } filterLaunchPrograms(index: number, year: string): any { // console.log(index, year); this.getFilteredLaunches(year); this.launchYearSelectedIndex = index; this.showFilter = true; } getFilteredLaunches(year: string): any { this.appService.getLaunchesByYear(year) .subscribe((response: any) => { // console.log(response); this.launchDataArray = response; }, err => { console.log(err); }) } clearFilter(): void { this.getAllLaunches(); this.launchYearSelectedIndex = null; this.showFilter = false; } } <file_sep>/src/app/launch-details-card/launch-details-card.component.spec.ts import { ComponentFixture, TestBed } from '@angular/core/testing'; import { LaunchDetailsCardComponent } from './launch-details-card.component'; describe('LaunchDetailsCardComponent', () => { let component: LaunchDetailsCardComponent; let fixture: ComponentFixture<LaunchDetailsCardComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ LaunchDetailsCardComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(LaunchDetailsCardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
9296bd568bec9febc512e3a6554ffd1eca070f17
[ "TypeScript" ]
2
TypeScript
vib1307/angular-ssr-project
90cb0e23144c87f4bfaba0e78a1a6512e2ec28da
21dc3e53254bff81c2a25632ba44c09f42f91b2d
refs/heads/master
<file_sep>using Assets.Scripts; using UnityEngine; /// <summary> /// Dragable Menu /// </summary> public class ConnectionSettings : GUIDraggableObject { private string m_Name; private int m_Value; // May have this for tracking menu numbers or some such // Holds cass to call private ConnectToDb _connectToDb; // Override constructor for use with the correct class public ConnectionSettings(string name, int value, ConnectToDb connectToDb, Vector2 position, Vector2 size) : base(position, size) { m_Name = name; m_Value = value; _connectToDb = connectToDb; } /// <summary> /// Override that gets called from the On_GUI() method. /// </summary> public override void DrawMenuObject() { Rect drawRect = new Rect(Position.x, Position.y, Size.x, Size.y), dragRect; GUILayout.BeginArea(drawRect, GUI.skin.GetStyle("Box")); GUILayout.Label(m_Name, GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); dragRect = GUILayoutUtility.GetLastRect(); dragRect = new Rect(dragRect.x + Position.x, dragRect.y + Position.y, dragRect.width, dragRect.height); if (Dragging) { GUILayout.Label(string.Format("Position X: {0} | Y: {1}", Position.x, Position.y), GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); // TODO: Save these values to a log when the finished draging the menu. It should then load those values when the software starts } // Custom code for each class goes into the below method MenuElement(); GUILayout.EndArea(); Drag(dragRect); } /// <summary> /// This is what will be called to draw up the custom menu for this class. /// </summary> public void MenuElement() { GUILayout.Label(string.Format("Server Address: {0}", _connectToDb.Host), GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); GUILayout.Label(string.Format("Server Port: {0}", _connectToDb.Port), GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); GUILayout.Label(string.Format("Connecting as: {0}", _connectToDb.User), GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); GUILayout.Label(string.Format("Connection Status: {0}", _connectToDb.ConnectionStatus), GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); // It's one of those......Need to remeber what these type of statments are called. GUI.backgroundColor = _connectToDb.BtnStatus == "Disconnect" ? Color.red : Color.green; if (GUILayout.Button(_connectToDb.BtnStatus)) { _connectToDb.ConnectionToDb();// TODO: May want this to be static class at some point? } } } <file_sep>using UnityEngine; using System.Collections; /// <summary> /// This class apears to be handling the draging and droping portion /// Polymorphism, Up-casting and Down-casting /// http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx /// </summary> public class GUIDraggableObject { private Vector2 m_DragStart; // Constructor public GUIDraggableObject (Vector2 position, Vector2 size) { Position = position; Size = size; } #region Autoproperties public bool Dragging { get; private set; } public Vector2 Position { get; set; } public Vector2 Size { get; set; } #endregion public void Drag (Rect draggingRect) { if (Event.current.type == EventType.MouseUp) { Dragging = false; } else if (Event.current.type == EventType.MouseDown && draggingRect.Contains (Event.current.mousePosition)) { Dragging = true; m_DragStart = Event.current.mousePosition - Position; Event.current.Use(); } if (Dragging) { Position = Event.current.mousePosition - m_DragStart; } } public virtual void DrawMenuObject() { Debug.Log("OnGUI is being called from the GUIDraggableObjects Class"); Debug.Log("This should be overriden in the child class"); } }<file_sep>using System; using Npgsql; using UnityEngine; using System.Data; // For reference // http://www.codeproject.com/Articles/30989/Using-PostgreSQL-in-your-C-NET-application-An-intr // http://forum.unity3d.com/threads/9051-Test-Connect-Script-to-PostgreSQL-Server // http://forum.unity3d.com/threads/7373-using-Npgsql-dll-to-access-PostgreSQL-server // http://forum.unity3d.com/threads/139887-Data-does-not-exist-in-the-namespace-System // Information about connections and transactions. Please review it in detail. // http://stackoverflow.com/questions/11517342/when-to-open-close-connection-to-database namespace Assets.Scripts { public class ConnectToDb { #region Fields public bool StorePassword; public NpgsqlConnection conn; // Create connection object private NpgsqlCommand dbcmd; // Create objected used for issueing db comands #endregion #region Properties // Auto Properties public string Host { get; private set; } public string DBname { get; private set; } public string User { get; private set; } public string Password { get; private set; } public string BtnStatus { get; private set; } public string ConnectionString { get; private set; } public string ConnectionStatus { get { return conn.State.ToString(); } } public int Port { get; private set; } /// <summary> /// Create a link to the static property in Terminal Window for use in this class. /// </summary> internal string Terminal { get { return TerminalWindow.Terminal; } set { TerminalWindow.Terminal = value; } } #endregion // TODO: Put this shit in a config file public ConnectToDb() { Host = "192.168.56.101";// db.schemaverse.com Port = 5432; DBname = "schemaverse"; User = "mrfreeman"; Password = "<PASSWORD>"; BtnStatus = "Connect"; // Setup connection string ConnectionString = string.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", Host, Port, User, Password, DBname); // Initialize a connection (socket)? conn = new NpgsqlConnection(ConnectionString); } public void GetSelectData(string [] fields, string table) { #region Create Select String from params // Grab paramiters and create a SELECT statement to string cmdText = "SELECT"; int arryLen = fields.Length;// caching the array length for optimization for (int i = 0; i < arryLen-1; i++) { cmdText += " " + fields[i] + ","; } // Grabs the last item in the array and then specify table to pull data FROM cmdText += fields[arryLen-1] + " " + "FROM" + " " + table; Terminal = cmdText; // Output what we have so there is feed back from the button #endregion dbcmd.CommandText = cmdText;//"SELECT username, balance, fuel_reserve FROM my_player"; var reader = dbcmd.ExecuteReader(); string outputTest = "| "; while (reader.Read()) { //Terminal = string.Format("Username: {0}, Balance: {1}, Fuel Reserve: {2}", reader["username"], reader["balance"], reader["fuel_reserve"]); for (int i = 0; i < arryLen; i++) { string temp = fields[i]; outputTest += Utilities.TitleCase(temp) + " : " + reader[fields[i]] + " | "; } Terminal = outputTest; } // clean up reader.Close(); reader = null; } // SELECT id, name, location, mine_limit, conqueror_id FROM planets WHERE conqueror_id=GET_PLAYER_ID(SESSION_USER); public void ConnectionToDb() { // Using try to wrap the db connection open and close process. try { if (conn.State == ConnectionState.Closed) { Terminal = "Connecting....."; conn.Open(); Terminal = "Success open postgreSQL connection."; BtnStatus = "Disconnect"; // Initialize object command interface dbcmd = conn.CreateCommand(); } else { dbcmd.Dispose(); conn.Close(); //conn = null; Terminal = "Connection should be closed"; dbcmd = null; BtnStatus = "Connect"; } } catch (Exception msg) { // something went wrong, and you wanna know why Debug.LogError(msg.ToString()); Terminal = msg.ToString(); throw; } } private void QuitApplication() { if (dbcmd != null) { dbcmd.Dispose(); dbcmd = null; } if (conn != null) { conn.Close(); conn = null; } BtnStatus = "Connect"; Application.Quit(); // This won't work in the editor. Only in build } } }<file_sep>using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class MyEditorWindow : EditorWindow { private List< DataObject > m_Data = new List< DataObject > (); private bool doRepaint = false; private Rect dropTargetRect = new Rect (10.0f, 10.0f, 30.0f, 30.0f); public MyEditorWindow () { m_Data.Add (new DataObject ("One", 1, new Vector2 (20.0f * Random.Range (1.0f, 10.0f), 20.0f * Random.Range (1.0f, 10.0f)),new Vector2(20.0f * Random.Range (1.0f, 10.0f), 20.0f * Random.Range (1.0f, 10.0f)))); m_Data.Add(new DataObject("Two", 2, new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)), new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)))); m_Data.Add(new DataObject("Three", 3, new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)), new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)))); m_Data.Add(new DataObject("Four", 4, new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)), new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)))); m_Data.Add(new DataObject("Five", 5, new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)), new Vector2(20.0f * Random.Range(1.0f, 10.0f), 20.0f * Random.Range(1.0f, 10.0f)))); } [MenuItem ("Window/MyEditorWindow")] public static void Launch () { GetWindow (typeof (MyEditorWindow)).Show (); } public void Update () { if (doRepaint) { Repaint (); } } public void OnGUI () { DataObject toFront, dropDead; bool previousState, flipRepaint; Color color; GUI.Box(dropTargetRect, "Die"); toFront = dropDead = null; doRepaint = false; flipRepaint = false; foreach (DataObject data in m_Data) { previousState = data.Dragging; color = GUI.color; if (previousState) { GUI.color = dropTargetRect.Contains (Event.current.mousePosition) ? Color.red : color; } data.OnGUI (); GUI.color = color; if (data.Dragging) { doRepaint = true; if (m_Data.IndexOf (data) != m_Data.Count - 1) { toFront = data; } } else if (previousState) { flipRepaint = true; if (dropTargetRect.Contains (Event.current.mousePosition)) { dropDead = data; } } } if (toFront != null) // Move an object to front if needed { m_Data.Remove (toFront); m_Data.Add (toFront); } if (dropDead != null) // Destroy an object if needed { m_Data.Remove (dropDead); } if (flipRepaint) // If some object just stopped being dragged, we should repaing for the state change { Repaint (); } } }<file_sep>using System.Data; using UnityEngine; namespace Assets.Scripts { public class BasicGUIOLD : MonoBehaviour { // Creates an instance of the ConnectToDb class for use in this class. This works because the ConnectToDb // does not inherit from the MonoBehavior class. Unity no liky that shit. ConnectToDb _connectToDb = new ConnectToDb(); private void OnGUI() { //// Make a background box for config menu //GUI.Box(new Rect(10, 48, 256, 256), "Connection Settings"); //// Connection Settings //// Pixels from left side of screen, Pixels from top left of screen, button width, button height GUI.Label(new Rect(35, 75, 256, 30), string.Format("Server Address: {0}", _connectToDb.Host)); GUI.Label(new Rect(35, 95, 256, 30), string.Format("Server Port: {0}", _connectToDb.Port)); GUI.Label(new Rect(35, 115, 256, 30), string.Format("Connecting As: {0}", _connectToDb.User)); GUI.Label(new Rect(35, 135, 256, 30), string.Format("Connection Status: {0}", _connectToDb.ConnectionStatus)); if (GUI.Button(new Rect(64, 168, 128, 30), _connectToDb.BtnStatus)) { _connectToDb.ConnectionToDb(); } //// Not working quite right ATM ////if (GUI.Button(new Rect(64, 208, 128, 30), "Quit Application")) { QuitApplication(); } //// Only Display these buttons if there is an active connection //if (_connectToDb.conn.State != ConnectionState.Open) return; //// Make a background box for config menu //GUI.Box(new Rect(Screen.width - 266, 48, 256, 512), "Commands"); //if (GUI.Button(new Rect(Screen.width - 266, 248, 128, 30), "Stats")) //{ // _connectToDb.GetSelectData(); //} } } }<file_sep>using System; using Assets.Scripts; using UnityEngine; /// <summary> /// Dragable Menu /// </summary> public class DraggableMenuTemplate : GUIDraggableObject { private string m_Name; private int m_Value; // May have this for tracking menu numbers or some such // Holds cass to call private ConnectToDb _connectToDb; // Override constructor for use with the correct class public DraggableMenuTemplate(string name, int value, ConnectToDb connectToDb, Vector2 position, Vector2 size) : base(position, size) { m_Name = name; m_Value = value; _connectToDb = connectToDb; } /// <summary> /// Override that gets called from the On_GUI() method. /// </summary> public override void DrawMenuObject() { Rect drawRect = new Rect(Position.x, Position.y, Size.x, Size.y), dragRect; GUILayout.BeginArea(drawRect, GUI.skin.GetStyle("Box")); GUILayout.Label(m_Name, GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); dragRect = GUILayoutUtility.GetLastRect(); dragRect = new Rect(dragRect.x + Position.x, dragRect.y + Position.y, dragRect.width, dragRect.height); if (Dragging) { GUILayout.Label(string.Format("Position X: {0} | Y: {1}", Position.x, Position.y)); // TODO: Save these values to a log when the finished draging the menu. It should then load those values when the software starts } //else if (GUILayout.Button ("Yes!")) //{ // Debug.Log ("Yes. It is " + m_Value + "!"); //} // Custom code for each class goes into the below method MenuElement(); GUILayout.EndArea(); Drag(dragRect); } /// <summary> /// This is what will be called to draw up the custom menu for this class. /// </summary> public void MenuElement() { throw new NotImplementedException("Class Not customized yet!"); } } <file_sep>using Assets.Scripts; using UnityEngine; using System.Collections; public class DataObject : GUIDraggableObject // This class just has the capability of being dragged in GUI - it could be any type of generic data class // This would be your dragable object { private string m_Name; private int m_Value; // Holds cass to call private ConnectionSettings _connectionSettings; // This is here to keep current compatablity with the MyEditor version of the calling class public DataObject(string name, int value, Vector2 position, Vector2 size) : base(position, size) { m_Name = name; m_Value = value; } // Override constructor for use with the correct class public DataObject(string name, int value, ConnectionSettings connectionSettings, Vector2 position, Vector2 size) : base(position, size) { m_Name = name; m_Value = value; _connectionSettings = connectionSettings; } public void OnGUI () { Rect drawRect = new Rect (Position.x, Position.y, Size.x, Size.y), dragRect; GUILayout.BeginArea (drawRect, GUI.skin.GetStyle ("Box")); GUILayout.Label (m_Name, GUI.skin.GetStyle ("Box"), GUILayout.ExpandWidth (true)); dragRect = GUILayoutUtility.GetLastRect (); dragRect = new Rect (dragRect.x + Position.x, dragRect.y + Position.y, dragRect.width, dragRect.height); #region Put custom code here //_connectionSettings.MenuElement(); #endregion if (Dragging) { GUILayout.Label (string.Format("Position X: {0} | Y: {1}",Position.x,Position.y)); // TODO: Save these values to a log when the finished draging the menu. It should then load those values when the software starts } //else if (GUILayout.Button ("Yes!")) //{ // Debug.Log ("Yes. It is " + m_Value + "!"); //} GUILayout.EndArea (); Drag (dragRect); } }<file_sep>SELECT last_value FROM tic_seq;<file_sep>using Assets.Scripts; using UnityEngine; using System.Collections; using System.Collections.Generic; public class BasicGUI : MonoBehaviour { /// <summary> /// Changed this from DataObject to GUIDraggableObject parent to keep a list of different child objects/classes /// It would be better to create an interface if I need to access properties and make changes. /// http://stackoverflow.com/questions/11354620/creating-a-generic-list-of-objects-in-c-sharp /// Polymorphism, Up-casting and Down-casting /// http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx /// </summary> private List<GUIDraggableObject> m_Data = new List<GUIDraggableObject>(); private Rect dropTargetRect = new Rect (Screen.width-50.0f, Screen.height-50.0f, 40.0f, 40.0f); // Creates an instance of the ConnectToDb class for use in this class. ConnectToDb _connectToDb = new ConnectToDb(); void Awake () { int sw = Screen.width; int sh = Screen.height; // Initialize all the menu objects TODO: These defaults should be loaded from a config file. Also, changes should be saved to same config. m_Data.Add(new ConnectionSettings("Connection Settings", 1, _connectToDb, new Vector2(10f, 10f), new Vector2(256f, 166f))); m_Data.Add(new BasicCommands("Basic Commands", 2, _connectToDb, new Vector2(sw - 266f, 10f), new Vector2(256f, 166f))); m_Data.Add(new TerminalWindow("Terminal Window", 3, _connectToDb, new Vector2(sw /2 - 256, sh - 206f), new Vector2(512f, 196f))); } public void OnGUI () { // DataObject toFront, dropDead; GUIDraggableObject toFront, dropDead; Color color; GUI.Box(dropTargetRect, "X"); toFront = dropDead = null; // Draw each object in the list foreach (var data in m_Data) { color = GUI.color; if (data.Dragging) { GUI.color = dropTargetRect.Contains (Event.current.mousePosition) ? Color.red : color; } // Call the OnGUI function in each DataObject in m_Data. This is where the magic happens data.DrawMenuObject(); GUI.color = color; if (data.Dragging) { if (m_Data.IndexOf (data) != m_Data.Count - 1) { toFront = data; } } } if (toFront != null) // Move an object to front if needed { m_Data.Remove(toFront); m_Data.Add(toFront); } } }<file_sep>using System; using System.Data; using Assets.Scripts; using UnityEngine; /// <summary> /// Dragable Menu /// </summary> public class BasicCommands : GUIDraggableObject { private string m_Name; private int m_Value; // May have this for tracking menu numbers or some such // Holds cass to call private ConnectToDb _connectToDb; // Override constructor for use with the correct class public BasicCommands(string name, int value, ConnectToDb connectToDb, Vector2 position, Vector2 size) : base(position, size) { m_Name = name; m_Value = value; _connectToDb = connectToDb; } /// <summary> /// Override that gets called from the On_GUI() method. /// </summary> public override void DrawMenuObject() { Rect drawRect = new Rect(Position.x, Position.y, Size.x, Size.y), dragRect; GUILayout.BeginArea(drawRect, GUI.skin.GetStyle("Box")); GUILayout.Label(m_Name, GUI.skin.GetStyle("Box"), GUILayout.ExpandWidth(true)); dragRect = GUILayoutUtility.GetLastRect(); dragRect = new Rect(dragRect.x + Position.x, dragRect.y + Position.y, dragRect.width, dragRect.height); if (Dragging) { GUILayout.Label(string.Format("Position X: {0} | Y: {1}", Position.x, Position.y)); // TODO: Save these values to a log when the finished draging the menu. It should then load those values when the software starts } // Custom code for each class goes into the below method MenuElement(); GUILayout.EndArea(); Drag(dragRect); } /// <summary> /// This is what will be called to draw up the custom menu for this class. /// </summary> public void MenuElement() { // Only Display these buttons if there is an active connection // TODO: Uncomment this when ready for use // if (_connectToDb.conn.State != ConnectionState.Open) return; // May want to set this up with GUI.enable // Right Side Menu GUI.backgroundColor = Color.yellow; // Setting this for safe buttons GUILayout.BeginArea(new Rect(5, 40, Size.x / 2 -5, Size.y-10)); // Make a background box for config menu //GUI.Button(new Rect(10, 10, 128, 10), "Stats"); // This works with in the area but you got to line stuff up if (GUILayout.Button("Stats")) { if (_connectToDb != null) _connectToDb.GetSelectData(new[] {"username", "balance", "fuel_reserve"},"my_player"); } GUILayout.EndArea(); } } <file_sep>using System; using System.Globalization; namespace Assets.Scripts { #region Contructs // By putting this here, it's available to any class as it's not in a class but the namespace // This is a structure. TODO: See if this wouldn't be better served being in the classes that use it. public struct Vector2Int // Doing this instead of the unity one as it would return a float { public int x; public int y; public Vector2Int(int width, int height) { x = width; y = height; } } public class Utilities { #endregion #region Fields private static Random _random; // For use with TileCase() private static TextInfo TextInfo = new CultureInfo("en-US", false).TextInfo; #endregion #region Constructors public Utilities() { _random = new Random(); // Could pass an int seed through this if i wanted to. } #endregion #region Properties #endregion #region Methods // A nice trick to make it easier to pick random items from an array // This is a generic method, it should take any array and return a result public T RandArray<T>(T[] array) { return array[_random.Next(0, array.Length)]; } // Basic clamp function; Provided under the CPOL See http://www.codeproject.com/Articles/23323/A-Generic-Clamp-Function-for-C for details // Another generic method, was static but could not unit test it that way? public T Clamp<T>(T value, T min, T max) where T : IComparable<T> { T result = value; if (value.CompareTo(max) > 0) result = max; if (value.CompareTo(min) < 0) result = min; return result; } #endregion /// <summary> /// Will output: string is string to titlecase: String Is String /// </summary> /// <param name="_string"></param> /// <returns></returns> public static string TitleCase(string _string) { // Changes a string to titlecase. return (TextInfo.ToTitleCase(_string)); } } }
78593fd861f86cf69a33b9f02301c9fcf535e85c
[ "C#", "SQL" ]
11
C#
P4r4d0x42/Schemaverse-FE
d2576732a8fbe5b9da1caa2ec295a9528c1c9b7d
10b809cf46a33ab2ff9de6cc1075ec8bc69f4301
refs/heads/master
<file_sep>package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.hardware.ColorSensor; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables; import android.graphics.Color; @Autonomous(name="黑珍珠号-自动程序", group="1820") public class Black_Pearl_Autonomous extends LinearOpMode { private Servo ballArm; private Servo ballHand; private DcMotor leftFront; private DcMotor leftBack; private DcMotor rightFront; private DcMotor rightBack; private DcMotor frontDrive; private ColorSensor sensorRGB; //Vuforia instances/objects private VuforiaLocalizer PhoneCameraInterface; private VuforiaLocalizer.Parameters param; private VuforiaTrackables relicTrackable; private VuforiaTrackable relicTemplate; private RelicRecoveryVuMark Img; private enum COLOR{RED,BLUE} private float hsvValues[] = {0F,0F,0F}; private ElapsedTime runtime = new ElapsedTime(); private int chooseMode(){ while(true){ if(gamepad2.y){ telemetry.addData("机器的起始位置","蓝1"); telemetry.update(); return 1; }if(gamepad2.a){ telemetry.addData("机器的起始位置","蓝2"); telemetry.update(); return 2; }if(gamepad2.dpad_up){ telemetry.addData("机器的起始位置","红1"); telemetry.update(); return 3; }if(gamepad2.dpad_down){ telemetry.addData("机器的起始位置","红2"); telemetry.update(); return 4; }else{ telemetry.addData("请选择机器的起始位置","等待选择…"); telemetry.update(); } } } private void Init(){ ballArm = hardwareMap.get( Servo.class , "ball_arm" ); ballHand = hardwareMap.get( Servo.class , "ball_hand"); sensorRGB = hardwareMap.colorSensor.get("sensor_color"); leftFront = hardwareMap.get( DcMotor.class , "leftFront" ); leftBack = hardwareMap.get( DcMotor.class , "leftBack" ); rightFront = hardwareMap.get( DcMotor.class , "rightFront" ); rightBack = hardwareMap.get( DcMotor.class , "rightBack" ); frontDrive = hardwareMap.get( DcMotor.class , "front_drive" ); //设定电机初始状态为解除刹车 leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); } private void InitVuforia(){ int cameraID = hardwareMap.appContext.getResources().getIdentifier( "cameraMonitorViewId" , "id" , hardwareMap.appContext.getPackageName() ); param = new VuforiaLocalizer.Parameters(cameraID); //This serial number is a magic number XD (magic number such as 19260817 :P) param.vuforiaLicenseKey = "<KEY>"; param.cameraDirection = VuforiaLocalizer.CameraDirection.BACK; this.PhoneCameraInterface = ClassFactory.createVuforiaLocalizer(param); relicTrackable = this.PhoneCameraInterface.loadTrackablesFromAsset("RelicVuMark"); relicTemplate = relicTrackable.get(0); relicTrackable.activate(); Img = RelicRecoveryVuMark.UNKNOWN; } private void encoderDrive(double rightPower,int rightTarget, double aStartDis,double aEndDis, double timeoutS){ int newRightTarget; int rightStart; double minPower=0.03; double RATE; double DIR=rightTarget>0?1.0:-1.0; if(opModeIsActive()) { rightStart = rightBack.getCurrentPosition(); newRightTarget = rightStart + rightTarget; runtime.reset(); while(opModeIsActive() && runtime.seconds() < timeoutS && Math.abs(rightBack.getCurrentPosition()-rightStart)<=Math.abs(rightTarget) ){ if( Math.abs(rightBack.getCurrentPosition()-rightStart) <= (int)aStartDis){ RATE = Math.sqrt((double)Math.abs(rightBack.getCurrentPosition()-rightStart)/aStartDis); minPower=0.1; }else if( Math.abs(rightBack.getCurrentPosition()-newRightTarget) <= (int)aEndDis){ RATE = (double)Math.abs(rightBack.getCurrentPosition()-newRightTarget)/aEndDis; minPower=0.02; }else RATE = 1.0; rightBack.setPower(DIR*Math.max(RATE*rightPower,minPower)); rightFront.setPower(DIR*Math.max(RATE*rightPower,minPower)); leftFront.setPower(-DIR*Math.max(RATE*rightPower,minPower)); leftBack.setPower(-DIR*Math.max(RATE*rightPower,minPower)); telemetry.addData("【前后】编码器","起始:%d,当前:%d,目标:%d", rightStart,rightBack.getCurrentPosition(),newRightTarget); telemetry.addData("当前","系数:%.2f,右轮功率:%.2f",RATE,DIR*Math.max(RATE*rightPower,minPower)); telemetry.update(); }if(!opModeIsActive())return; rightBack.setPower(0); rightFront.setPower(0); leftFront.setPower(0); leftBack.setPower(0); sleep(250); } } private void encoderTurn(double rightPower,int Target,double timeoutS){ if(!opModeIsActive())return; Target *= 2; int DIR=Target>0?1:-1; int Start = rightBack.getCurrentPosition()+leftFront.getCurrentPosition(); runtime.reset(); while( opModeIsActive() && Math.abs(rightBack.getCurrentPosition()+ leftFront.getCurrentPosition()-Start)<=Math.abs(Target) && runtime.seconds()<=timeoutS){ rightBack.setPower(DIR*rightPower); rightFront.setPower(DIR*rightPower); leftBack.setPower(DIR*rightPower); leftFront.setPower(DIR*rightPower); } rightBack.setPower(0); rightFront.setPower(0); leftFront.setPower(0); leftBack.setPower(0); sleep(250); } private void timerDrive(double leftPower , double rightPower , double timeoutS){ runtime.reset(); while(opModeIsActive()&&runtime.seconds() < timeoutS){ leftFront.setPower(leftPower); leftBack.setPower(leftPower); rightFront.setPower(rightPower); rightBack.setPower(rightPower); } } private int runVuforia(double sleepS,double timeoutS){ runtime.reset(); while( opModeIsActive() && runtime.seconds()<timeoutS ){ Img = RelicRecoveryVuMark.from(relicTemplate); //timeoutS秒钟无结果则跳过 if( Img == RelicRecoveryVuMark.LEFT ){ telemetry.addData( "图像识别" , "左" ); telemetry.update(); if(runtime.seconds()>sleepS)return 0; }else if( Img == RelicRecoveryVuMark.CENTER ){ telemetry.addData( "图像识别" , "中" ); telemetry.update(); if(runtime.seconds()>sleepS)return 1; }else if( Img == RelicRecoveryVuMark.RIGHT ){ telemetry.addData( "图像识别" , "右" ); telemetry.update(); if(runtime.seconds()>sleepS)return 2; }else{ telemetry.addData("图像识别","正在识别中……"); telemetry.update(); } }if( Img == RelicRecoveryVuMark.UNKNOWN ){ telemetry.addData("图像识别","3秒没有结果,强制使用中方案"); telemetry.update(); return 1; } return 1; } private void HitBall(COLOR color,double timeoutS){ runtime.reset(); while(opModeIsActive()){ Color.RGBToHSV ((sensorRGB.red() * 255) / 800, (sensorRGB.green() * 255) / 800, (sensorRGB.blue() * 255) / 800, hsvValues); telemetry.addData("识别到的颜色(A,R,G,B)","(%d,%d,%d,%d)", sensorRGB.alpha(), sensorRGB.red(), sensorRGB.green(), sensorRGB.blue()); telemetry.addData("Hue的值", hsvValues[0]); telemetry.update(); if(hsvValues[0]>350 || hsvValues[0]<31){ //红色球 telemetry.addData("Hue的值", hsvValues[0]); telemetry.addData("识别到的颜色为","红色"); telemetry.update(); if(color==COLOR.RED)ballHand.setPosition(0.85);//打掉红色球 if(color==COLOR.BLUE)ballHand.setPosition(0.15);//打掉蓝色球 sleep(1000); ballArm.setPosition(0.12); //收起 break; }else if(hsvValues[0]>170 && hsvValues[0]<220){ //蓝色球 telemetry.addData("Hue的值", hsvValues[0]); telemetry.addData("识别到的颜色为","蓝色"); telemetry.update(); if(color==COLOR.RED)ballHand.setPosition(0.15);//打掉红色球 if(color==COLOR.BLUE)ballHand.setPosition(0.85);//打掉蓝色球 sleep(1000); ballArm.setPosition(0.12); //收起 break; }else if(runtime.seconds()>=timeoutS){ //Cannot have analysis of ball color telemetry.addData("Hue的值", hsvValues[0]); telemetry.addData("颜色识别","超过2秒没有结果,跳过"); telemetry.update(); ballArm.setPosition(0.12); break; } } } private void Blue1(int Dist){ HitBall(COLOR.RED,2); if(!opModeIsActive())return; timerDrive(0.3,-0.3,1.0); timerDrive(0.0,0.0,0.3); timerDrive(-0.2,0.2,1.4); timerDrive(0.0,0.0,0.2); timerDrive(0.1,-0.1,0.3); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); int runDistance = 1800; if(Dist==0)runDistance-=900; if(Dist==2)runDistance+=900; encoderDrive(0.40,-runDistance,500,500,5); encoderTurn(0.2,-2400,5); encoderDrive(0.30,900,400,400,4); frontDrive.setPower(-0.8); sleep(800); frontDrive.setPower(0); encoderDrive(0.25,-1000,200,500,8); encoderTurn(0.35,-4750,8); timerDrive(0.25,-0.25,0.8); timerDrive(0,0,0.4); timerDrive(-0.2,0.2,0.25); } private void Blue2(int Dist){ HitBall(COLOR.RED,2); if(!opModeIsActive())return; timerDrive(0.3,-0.3,1.0); timerDrive(0.0,0.0,0.3); timerDrive(-0.2,0.2,1.4); timerDrive(0.0,0.0,0.2); timerDrive(0.1,-0.1,0.3); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); int runDistance = 1100; if(Dist==0)runDistance-=920; if(Dist==2)runDistance+=920; encoderDrive(0.2,-800,50,50,8); encoderTurn(0.2,-2400,5); encoderDrive(0.3,-runDistance,50,50,8); encoderTurn(0.2,-2400,5); encoderDrive(0.30,750,200,200,4); frontDrive.setPower(-0.8); sleep(800); frontDrive.setPower(0); encoderDrive(0.25,-800,200,500,8); encoderTurn(0.35,-4750,8); timerDrive(0.25,-0.25,0.9); timerDrive(0,0,0.4); timerDrive(-0.2,0.2,0.25); } private void Red1(int Dist){ HitBall(COLOR.BLUE,2); if(!opModeIsActive())return; timerDrive(-0.3,0.3,1.0); timerDrive(0.0,0.0,0.3); timerDrive(0.2,-0.2,1.4); timerDrive(0.0,0.0,0.2); timerDrive(-0.1,0.1,0.3); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); int runDistance = 1990; if(Dist==0)runDistance+=900; if(Dist==2)runDistance-=900; encoderDrive(0.40,runDistance,500,500,5); encoderTurn(0.2,-2400,5); encoderDrive(0.30,750,300,300,4); frontDrive.setPower(-0.8); sleep(800); frontDrive.setPower(0); encoderDrive(0.25,-1000,200,500,8); encoderTurn(0.35,-4750,8); timerDrive(0.25,-0.25,0.8); timerDrive(0,0,0.4); timerDrive(-0.2,0.2,0.25); } private void Red2(int Dist){ HitBall(COLOR.BLUE,2); if(!opModeIsActive())return; timerDrive(-0.3,0.3,1.0); timerDrive(0.0,0.0,0.3); timerDrive(0.2,-0.2,1.4); timerDrive(0.0,0.0,0.2); timerDrive(-0.1,0.1,0.3); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); int runDistance = 1500; if(Dist==0)runDistance+=900; if(Dist==2)runDistance-=900; encoderDrive(0.2,800,50,50,8); encoderTurn(0.2,-2400,5); encoderDrive(0.3,-runDistance,50,50,8); encoderTurn(0.2,2400,5); encoderDrive(0.30,300,120,120,4); frontDrive.setPower(-0.8); sleep(800); frontDrive.setPower(0); encoderDrive(0.25,-800,200,500,8); encoderTurn(0.35,-4750,8); timerDrive(0.25,-0.25,0.9); timerDrive(0,0,0.4); timerDrive(-0.2,0.2,0.25); } @Override public void runOpMode() { int mode = chooseMode(); //等待手柄选择起始位置并返回 Init(); //初始化hardwareMap InitVuforia(); //加载Vuforia telemetry.addData("初始化完毕","可以开始"); telemetry.update(); waitForStart(); //等待按下开始键 ballHand.setPosition(0.48); //放下拨球摆杆 ballArm.setPosition (0.90); //放下拨球摆杆 int ImgResult=runVuforia(0.8,3);//执行图像识别并返回结果 if(!opModeIsActive())return;//防止程序无法退出 //根据机器起始平衡板、图像识别结果执行对应程序 if(mode==1)Blue1(ImgResult); if(mode==2)Blue2(ImgResult); if(mode==3)Red1(ImgResult); if(mode==4)Red2(ImgResult); //确保机器停下 rightBack.setPower(0); rightFront.setPower(0); leftFront.setPower(0); leftBack.setPower(0); } }<file_sep># FTC-2018-TEAM1820 Team 1820's code during the FTC 2017 - 2018 season from Zhengzhou No.1 Middle School. For more details, please browse the [Technical Binder (工程日志)](/工程日志X-1-com.pdf). The code was last used in the final competition on June 3rd, 2018. ## News report: [我校心智机器人社团斩获“启迪奖”和“冠军联盟队长奖”两项最高荣誉 - 郑州市第一中学](http://www.zzyz.com.cn/xndt/xnxw/04/18814.shtml) [FIRST中国机器人大会郑州一中机器人战队再创佳绩 - 郑州市第一中学](http://www.zzyz.com.cn/xndt/xnxw/06/18796.shtml) ![合照](/photos/DSC09103.jpg)
2ccb4d8f0447f9367266525bec48c818bfd98b14
[ "Markdown", "Java" ]
2
Java
RoboBachelor/FTC-2018-TEAM1820
0759507af841a21d965707e2484f80f3502b6a19
c349cb0da72f7286112d87ddbdf6d866680b83f2
refs/heads/master
<file_sep>package com.boavista.jobbatch.step; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.boavista.jobbatch.dominio.ProdutoCliente; import com.boavista.jobbatch.job.reader.ProdutoReaderConfig; @Configuration public class produtoClienteStepConfig { private static final Logger logger = LoggerFactory.getLogger(produtoClienteStepConfig.class); @Autowired public StepBuilderFactory stepBuilderFactory; @Bean public Step produtoClienteStep( ItemReader<ProdutoCliente> produtoClienteReader, ItemWriter<ProdutoCliente> produtoClienteWriter) { return stepBuilderFactory .get("produtoClienteStep") .<ProdutoCliente, ProdutoCliente>chunk(1) .reader(produtoClienteReader) .writer(produtoClienteWriter) .build(); } } <file_sep>spring.datasource.jdbcUrl=jdbc:mysql://localhost:3306/spring_batch?useUnicode=true?characterEncoding=UTF-8?useTimezone=true&serverTimezone=UTC spring.datasource.username=user spring.datasource.password=<PASSWORD> app.datasource.jdbcUrl=jdbc:mysql://localhost:3306/migracao_dados?useUnicode=true?characterEncoding=UTF-8?useTimezone=true&serverTimezone=UTC app.datasource.username=user app.datasource.password=<PASSWORD> spring.batch.initialize-schema=always
d63179168f4b4bc7fa6054d9ea4d79befdde6dbf
[ "Java", "INI" ]
2
Java
Airlon/SpringBatchMonitoracao
0533522859457b1d0e37dc4f5c964f14726ac05a
bb5f140b338712d16ad769969be601ab4219bd90
refs/heads/master
<file_sep># KeyboardCoverDemo # KeyboardCoverDemo <file_sep>package com.stingerzou.keyboardcoverdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ScrollView; import java.net.DatagramPacket; public class MainActivity extends AppCompatActivity { private ScrollView mScrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mScrollView = findViewById(R.id.scrollView); final KeyboardStatusDetector keyboardStatusDetector = new KeyboardStatusDetector(); keyboardStatusDetector .registerActivity(this) .setVisibilityListener(new KeyboardStatusDetector.KeyboardVisibilityListener() { @Override public void onVisibilityChanged(boolean keyboardVisible, final View view) { if (keyboardVisible) { mScrollView.post(new Runnable() { @Override public void run() { if (keyboardStatusDetector.isViewUnderKeyBoard(view, dp2px(50))) { mScrollView.smoothScrollBy(0, dp2px(50)); } } }); } } }); } public int dp2px(float dipValue) { final float scale = getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } }
aa7bf29dee661685f71bb8c1d667cb576a6b935d
[ "Markdown", "Java" ]
2
Markdown
stingerzou/KeyboardCoverDemo
839b7298acac1d871cfabf3b280bf65168ff8672
cef80b2114a0941fe245477aa516c6967537eef3
refs/heads/master
<repo_name>timothyjeffcoat/semanticbits<file_sep>/data/sample_sql.sql -- sample sql (should see 2 rows) select ae.id, ae.safety_report_id, p.patient_age, p.patient_sex , d.medicinal_product, r.meddra_primary_term from adverse_events ae join patients p on p.adverse_event_id = ae.id left join patient_drugs pd on pd.patient_id = p.id join drugs d on d.id = pd.drug_id left join patient_reactions pr on pr.patient_id = p.id join reactions r on r.id = pr.reaction_id where ae.safety_report_id = '4719690-9';<file_sep>/db/models/Patient.js const db = require('../sequelize'); const Drug = require('./Drug'); const Patient = db.sequelize.define('patient', { firstName: { type: db.Sequelize.STRING }, lastName: { type: db.Sequelize.STRING }, age: { type: db.Sequelize.INTEGER } }); Patient.belongsToMany(Drug, { through: 'patient_drugs', as: 'drugs' }); module.exports = Patient;<file_sep>/INTERVIEW.md ### Summary Original code from https://github.com/semanticbits/interview-api I interviewed for a Senior Backend Node.js position. I was given 3 different coding exerices. I have listed them below. My personal opinion is that these exercises are an adequate set of tests. I did not receive an offer. My failure was either they did not like the fact I have side projects. Or it might be because I failed the exercises. I personally feel like these exercises are very easy. My failure is coding in front of other people. I find coding in front of other people to be distracting and stressful. #### First test Get an array of all people in the Marvel organization, with no duplicate last names, sorted by id, and add a name field that is a combination of firstName + lastName ```javascript const data = [{ id: 3, firstName: 'Tony', lastName: 'Stark', organization: 'Marvel' }, { id: 1, firstName: 'Bruce', lastName: 'Banner', organization: 'Marvel' }, { id: 2, firstName: 'Bruce', lastName: 'Wayne', organization: 'DC' }, { id: 5, firstName: 'Clark', lastName: 'Kent', organization: 'DC' }, { id: 4, firstName: 'John', lastName: 'Stark', organization: 'Marvel' }]; ``` #### The second test Is to determine the values of the variables i and name. Put a comment with the value next to each line that has a console.log ```javascript 'use strict'; const i = 44; (function() { var i = 22; var name = undefined; var self = this; function a() { console.log('#1 =>', i); for (let i = 0; i < 5; i++) { console.log('#2 =>', i); } console.log('#3 =>', i); } function b() { var i; console.log('#4 =>', i); for (var i = 0; i < 5; i++) { console.log('#5 =>', i); } console.log('#6 =>', i); if (name ==='marcus') { var j = 55; var salary = "100K"; } console.log('#j =>', j); } console.log('#7 =>', i); name = 'marcus'; a(); b(); })(); console.log('#8 =>', i); ``` ### Third test This test is actually related to this project. Be sure to validate that you can start the project and go to localhost:9000/patients to list data. Given the index.js file below that is an Node.js/Express.js code snippet do the following: 1. Make sure you can list the patients by localhost:9000/patients 2. Make sure you fix the problem with localhost:9000/patients/1 3. Paginate the GET request for localhost:9000/patients so it looks like something like localhost:9000/patients?offset=5&list=5 this returns a set of 5 records offset by the first 5. You can uncomment the sequelize code in the method to make the correction. ```javascript const router = require('express').Router(); const { Patient, Drug, PatientDrug, sequelize } = require('../../db'); let patients = [ { id: 1, first_name: 'John', last_name: 'Doe' }, { id: 2, first_name: 'Jane', last_name: 'Doe' } ]; router.get('/', async (req, res) => { // const data = await Patient.findAll({ // include: [{ // model: Drug, // as: 'drugs', // through: { // model: PatientDrug, // attributes: [], // } // }], // limit: 25 // }); // const data = await sequelize.query('select * from patients'); res.json({ patients }); }); router.post('/', function(req, res) { const id = Math.random() * 100000; const data = Object.assign({}, req.body, {id: id}); patients.push(data); res.json({ patient: data }); }); router.get('/:id', function(req, res) { res.json({ person: patients.find(function(patient) { return (patient.id === req.params.id); }) }); }); router.put('/:id', function(req, res) { const data = Object.assign({}, req.body); const index = patients.findIndex(function(patient) { return (patient.id === req.params.id); }); if (index === -1) { res.json({}); } else { patients.splice(index, 1, data); res.json({ patient: data }); } }); router.delete('/:id', function(req, res) { res.json({ patient: patients.filter(function(patient) { return (patient.id !== req.params.id); }) }); }); module.exports = router; ``` <file_sep>/routes/patients/index.js const router = require('express').Router(); const { Patient, Drug, PatientDrug, sequelize } = require('../../db'); let patients = [ { id: 1, first_name: 'John', last_name: 'Doe' }, { id: 2, first_name: 'Jane', last_name: 'Doe' } ]; router.get('/', async (req, res) => { // const data = await Patient.findAll({ // include: [{ // model: Drug, // as: 'drugs', // through: { // model: PatientDrug, // attributes: [], // } // }], // limit: 25 // }); // const data = await sequelize.query('select * from patients'); res.json({ patients }); }); router.post('/', function(req, res) { const id = Math.random() * 100000; const data = Object.assign({}, req.body, {id: id}); patients.push(data); res.json({ patient: data }); }); router.get('/:id', function(req, res) { res.json({ person: patients.find(function(patient) { return (patient.id === req.params.id); }) }); }); router.put('/:id', function(req, res) { const data = Object.assign({}, req.body); const index = patients.findIndex(function(patient) { return (patient.id === req.params.id); }); if (index === -1) { res.json({}); } else { patients.splice(index, 1, data); res.json({ patient: data }); } }); router.delete('/:id', function(req, res) { res.json({ patient: patients.filter(function(patient) { return (patient.id !== req.params.id); }) }); }); module.exports = router; <file_sep>/data/adverse_events_ddl.sql DROP TABLE PATIENT_REACTIONS; DROP TABLE PATIENT_DRUGS; DROP TABLE PATIENTS; DROP TABLE ADVERSE_EVENTS; DROP TABLE DRUGS; DROP TABLE REACTIONS; CREATE TABLE ADVERSE_EVENTS ( ID INTEGER PRIMARY KEY, safety_report_id character varying(15) NOT NULL, receive_date date NOT NULL, receipt_date date NOT NULL, company_numb character varying(100) ); CREATE TABLE DRUGS ( id integer primary key, medicinal_product character varying(250) unique NOT NULL, drug_indication character varying(250) NOT NULL, drug_dosage_text character varying(250), drug_authorization_numb character varying(100) ); CREATE TABLE PATIENTS ( id integer primary key, patient_age character varying(20) not null, patient_sex character not null ); create table REACTIONS ( ID INTEGER PRIMARY KEY, MEDDRA_PRIMARY_TERM CHARACTER VARYING(300) UNIQUE NOT NULL ); CREATE TABLE PATIENT_REACTIONS ( PATIENT_ID INTEGER REFERENCES PATIENTS(ID), REACTION_ID INTEGER REFERENCES REACTIONS(ID) ); CREATE TABLE PATIENT_DRUGS ( PATIENT_ID INTEGER REFERENCES PATIENTS(ID), DRUG_ID INTEGER REFERENCES DRUGS(ID) ); ALTER TABLE PATIENTS ADD COLUMN adverse_event_id integer; <file_sep>/README.md `npm start` will auto install modules and start the api ### Summary Take a look at the INTERVIEW.md file. It explains the details of this project. <file_sep>/db/models/PatientDrug.js const db = require('../sequelize'); const PatientDrug = db.sequelize.define('patient_drug', { patientId: { type: db.Sequelize.INTEGER }, drugId: { type: db.Sequelize.INTEGER } }, { timestamps: false }); module.exports = PatientDrug;<file_sep>/db/models/Drug.js const db = require('../sequelize'); // const Patient = require('./Patient'); const Drug = db.sequelize.define('drug', { name: { type: db.Sequelize.STRING }, details: { type: db.Sequelize.STRING } }); module.exports = Drug;
b61653cc996f67cb8baf396c4d13ada2af0f8ee2
[ "JavaScript", "SQL", "Markdown" ]
8
SQL
timothyjeffcoat/semanticbits
15627587e342f2e4acc42f85ca4fca28914727db
8a88174d98613264e46c2a6d9391b7128e2f69cd
refs/heads/master
<repo_name>souravsaha/I-REX<file_sep>/src/main/java/lucdeb/commands/SearchCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import static common.CommonVariables.FIELD_ID; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import lucdeb.LucDebObjects; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.queryparser.flexible.core.QueryNodeException; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.util.BytesRef; /** * * @author dwaipayan */ public class SearchCommand extends Commands { public SearchCommand(LucDebObjects lucivObjects) { super(lucivObjects, "search"); } @Override public String help() { return "search - search a collection with a query and retrieval model\n" + usage(); } @Override public String usage() { return "search - <query-terms> [<number of expansion terms> (defaulut 10)]"; } @Override public void execute(String[] args, PrintStream out) throws IOException { // + Options options = new Options(); Option queryOption = new Option("q", "queryTerms", true, "Query Terms"); queryOption.setRequired(true); options.addOption(queryOption); Option retModelOption = new Option("r", "retrievalParams", true, "Retrieval Models with params"); retModelOption.setRequired(false); options.addOption(retModelOption); Option rankOption = new Option("k", "rank", false, "Rank of the retrieved documents"); rankOption.setRequired(false); options.addOption(rankOption); Option scoreOption = new Option("s", "score", false, "Score of the retrieved documents"); scoreOption.setRequired(false); options.addOption(scoreOption); Option doclenOption = new Option("dl", "doclen", false, "Length of the retrieved documents"); doclenOption.setRequired(false); options.addOption(doclenOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); return; } String queryTerms = cmd.getOptionValue("queryTerms").trim(); String retrievalParams = cmd.getOptionValue("retrievalParams"); // - boolean rankFlag = cmd.hasOption("k"); boolean scoreFlag = cmd.hasOption("s"); boolean doclenFlag = cmd.hasOption("dl"); String searchField; ScoreDoc[] hits; TopDocs topDocs; int numDocs = 10; // System.out.println(rankFlag + " "+ scoreFlag+ " "+ doclenFlag); String param1="", param2= "", param3 = ""; searchField = lucdebObjects.getSearchField(); IndexSearcher indexSearcher = lucdebObjects.getIndexSearcher(); if(null != retrievalParams) { String retModel = cmd.getOptionValue("retrievalParams").trim(); System.out.println(retModel); String[] params = retModel.split("\\s+"); if(!lucdebObjects.isKnownRetFunc(params[0])) { out.println("Unknown retrieval model: " + retModel +"\n" + "Available retrieval models: " + lucdebObjects.retFuncMap.keySet()); return; } switch(params[0]) { case "lmjm": param1 = params[1]; break; case "lmdir": param1 = params[1]; break; case "bm25": param1 = params[1]; param2 = params[2]; break; case "dfr": param1 = params[1]; param2 = params[2]; param3 = params[3]; break; default: // TODO break; } SimilarityFunctions simFunc = new SimilarityFunctions(params[0], param1, param2, param3); indexSearcher.setSimilarity(simFunc); } indexSearcher.setSimilarity(new BM25Similarity()); TopScoreDocCollector collector = TopScoreDocCollector.create(numDocs); Query luceneQuery; try { luceneQuery = lucdebObjects.getAnalyzedQuery(queryTerms, searchField); } catch (QueryNodeException ex) { out.println("Error analysing the query. Returning..."); return; } indexSearcher.search(luceneQuery, collector); topDocs = collector.topDocs(); hits = topDocs.scoreDocs; int hits_length = hits.length; if(hits == null||hits_length==0) { System.out.println("Nothing found"); return; } ArrayList<String> searchOutput = new ArrayList<>(); for (int i = 0; i < hits_length; ++i) { int luceneDocId = hits[i].doc; Document d = indexSearcher.doc(luceneDocId); String singleDocInfo = d.get(FIELD_ID); singleDocInfo += rankFlag ? "\t"+i : ""; singleDocInfo += scoreFlag ? "\t"+hits[i].score : ""; singleDocInfo += doclenFlag ? "\t"+getDocLength(hits[i].doc) : ""; searchOutput.add(singleDocInfo); } /*if(scoreFlag) { for (int i = 0; i < hits_length; ++i) { searchOutput.set(i, searchOutput.get(i)+"\t"+hits[i].score); } } if(doclenFlag) { for (int i = 0; i < hits_length; ++i) { searchOutput.set(i, searchOutput.get(i)+"\t"+getDocLength(hits[i].doc)); } }*/ for (String temp : searchOutput) { System.out.println(temp); } } // REPEATED function: already implemented elsewhere public int getDocLength(int luceneDocid) throws IOException { IndexReader indexReader = lucdebObjects.getIndexReader(); String fieldName = lucdebObjects.getSearchField(); // Term vector for this document and field, or null if term vectors were not indexed Terms terms = indexReader.getTermVector(luceneDocid, fieldName); if(null == terms) { System.out.println("Term vector null: ("+luceneDocid + ":"+ fieldName+")"); return -1; } TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; //* for each word in the document int docSize = 0; while((byteRef = iterator.next()) != null) { String term = new String(byteRef.bytes, byteRef.offset, byteRef.length); long tf = iterator.totalTermFreq(); // tf of 't' docSize += tf; } return docSize; } } <file_sep>/src/main/java/lucdeb/commands/dfr/AfterEffectB.java package lucdeb.commands.dfr; import org.apache.lucene.search.similarities.BasicStats; import org.apache.lucene.search.Explanation; /** * Model of the information gain based on the ratio of two Bernoulli processes. * @lucene.experimental */ public class AfterEffectB extends AfterEffect { /** Sole constructor: parameter-free */ public AfterEffectB() {} @Override public final float score(BasicStats stats, float tfn) { long F = stats.getTotalTermFreq()+1; long n = stats.getDocFreq()+1; return (F + 1) / (n * (tfn + 1)); } @Override public final Explanation explain(BasicStats stats, float tfn) { return Explanation.match( score(stats, tfn), getClass().getSimpleName() + ", computed from: ", Explanation.match(tfn, "tfn"), Explanation.match(stats.getTotalTermFreq(), "totalTermFreq"), Explanation.match(stats.getDocFreq(), "docFreq")); } @Override public String toString() { return "B"; } } <file_sep>/README.md # I-REX I-REX: A Lucene Plugin for EXplainable IR ## Installation Steps ### Web Service: Generate war file and deploy to your Tomcat or any other web server engine. Make sure to restart the server to see any necessary changes. Create the war file from Eclipse, command line, maven and then place it(i-rex.war) to $CATALINA_HOME/webapps/ (for Tomcat). ### Command Line: ## Citing ``` @inproceedings{Roy:2019:ILP:3357384.3357859, author = {<NAME> <NAME> <NAME> <NAME> <NAME>}, title = {I-REX: A Lucene Plugin for EXplainable IR}, booktitle = {Proceedings of the 28th ACM International Conference on Information and Knowledge Management}, series = {CIKM '19}, year = {2019}, isbn = {978-1-4503-6976-3}, location = {Beijing, China}, pages = {2949--2952}, numpages = {4}, url = {http://doi.acm.org/10.1145/3357384.3357859}, doi = {10.1145/3357384.3357859}, acmid = {3357859}, publisher = {ACM}, address = {New York, NY, USA}, keywords = {debugger, explainable ir}, } ``` <file_sep>/src/main/java/lucdeb/commands/dfr/NormalizationZ.java package lucdeb.commands.dfr; import org.apache.lucene.search.similarities.BasicStats; /** * Pareto-Zipf Normalization * @lucene.experimental */ public class NormalizationZ extends Normalization { final float z; /** * Calls {@link #NormalizationZ(float) NormalizationZ(0.3)} */ public NormalizationZ() { this(0.30F); } /** * Creates NormalizationZ with the supplied parameter <code>z</code>. * @param z represents <code>A/(A+1)</code> where <code>A</code> * measures the specificity of the language. */ public NormalizationZ(float z) { this.z = z; } @Override public float tfn(BasicStats stats, float tf, float len) { return (float)(tf * Math.pow(stats.getAvgFieldLength() / len, z)); } @Override public String toString() { return "Z(" + z + ")"; } /** * Returns the parameter <code>z</code> * @see #NormalizationZ(float) */ public float getZ() { return z; } } <file_sep>/src/main/java/lucdeb/commands/ExplainDefaultCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; import org.apache.lucene.queryparser.flexible.core.QueryNodeException; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; /** * * @author dwaipayan */ public class ExplainDefaultCommand extends Commands { String docid; String query; int luceneDocid; public ExplainDefaultCommand(LucDebObjects lucivObjects) { super(lucivObjects, "explain2"); } @Override public String help() { return "Returns an Explanation that describes how doc scored against query."; } @Override public void execute(String[] args, PrintStream out) throws IOException { if (args.length < 2) { out.println("Usage: " + usage()); return; } StringBuilder buf = new StringBuilder(); for(int i=0; i<args.length-1; i++) buf.append(args[i]).append(" "); docid = args[args.length-1]; query = buf.toString(); out.println(query + " : " + docid); try { luceneDocid = lucdebObjects.getLuceneDocid(docid); if(luceneDocid == -1) { return; } } catch (Exception ex) { } Query luceneQuery; try { luceneQuery = lucdebObjects.getAnalyzedQuery(query, "content"); IndexSearcher indexSearcher = lucdebObjects.getIndexSearcher(); System.out.println(luceneQuery.toString()); Explanation expln = indexSearcher.explain(luceneQuery, luceneDocid); out.println(expln.toString()); // out.println(Arrays.toString(expln.getDetails())); } catch (QueryNodeException ex) { out.println("QueryNodeException in ExplainCommand.execute();\n" + ex); } } @Override public String usage() { return "explain2 <query-terms> <doc>"; } } <file_sep>/src/main/java/lucdeb/commands/CollectionFrequencyCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; /** * * @author dwaipayan */ public class CollectionFrequencyCommand extends Commands { static String cmdName = "cf"; String fieldName; String term; public CollectionFrequencyCommand(LucDebObjects lucivObjects) { super(lucivObjects, cmdName); } @Override public String help() { return cmdName + " - Collection Frequency\n" + usage(); } @Override public void execute(String[] args, PrintStream out) throws IOException { Options options = new Options(); Option modelOption = new Option("t", "term", true, "Term to get the collection frequency"); modelOption.setRequired(true); options.addOption(modelOption); options.addOption("f","fieldName", true, "Field name in which collection frequency will be computed" ); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); return; } term = cmd.getOptionValue("term"); String fieldNameValue = cmd.getOptionValue("fieldName"); if(null != fieldNameValue) fieldName = fieldNameValue; else { fieldName = lucdebObjects.getSearchField(); } /* if (args.length != 1 && args.length != 2) { out.println(help()); return; } // Parsing the arguments term = args[0]; if (args.length == 2 ) fieldName = args[1]; else fieldName = lucdebObjects.getSearchField(); */ IndexReader indexReader = lucdebObjects.getIndexReader(); Term termInstance = new Term(fieldName, term); long termFreq = indexReader.totalTermFreq(termInstance); // CF: Returns the total number of occurrences of term across all documents (the sum of the freq() for each doc that has this term). out.println("Collection Frequency of " + term + "is : " + termFreq); } @Override public String usage() { return cmdName + " <term> [ <field-name> ]"; } } <file_sep>/src/main/java/lucdeb/commands/QuitLucDeb.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; /** * * @author dwaipayan */ public class QuitLucDeb extends Commands { public QuitLucDeb(LucDebObjects lucivObjects) { super(lucivObjects, "quit"); } @Override public String help() { return "Quit LucIV."; } @Override public String usage() { return "quit"; } @Override public void execute(String[] args, PrintStream out) throws IOException { out.flush(); lucdebObjects.closeAll(); System.exit(0); } } <file_sep>/src/main/java/org/sourav/lucDeb/resources/CollectionFrequencyResource.java package org.sourav.lucDeb.resources; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.JSONP; import lucdeb.LucDeb; @Path("/cf") public class CollectionFrequencyResource { @POST @Produces(MediaType.TEXT_PLAIN) public Response getCollectionFrequency(@FormParam("term") String term, @FormParam("fieldName") String fieldName) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); LucDeb lucdeb; try { lucdeb = new LucDeb("/user1/faculty/cvpr/irlab/collections/indexed/trec678"); String args = "-t "+ term + (fieldName.length()> 0 ? "-f "+ fieldName : ""); lucdeb.executeCommand("cf", args.split(" "), System.out); } catch (Exception e) { //e.printStackTrace(); System.out.println("File not found!!"); } System.out.flush(); System.setOut(old); String cf = baos.toString(); return Response.ok(cf) .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS") .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build(); } } <file_sep>/src/main/java/lucdeb/commands/dfr/BasicModelBE.java package lucdeb.commands.dfr; import org.apache.lucene.search.similarities.BasicStats; import static org.apache.lucene.search.similarities.SimilarityBase.log2; /** * Limiting form of the Bose-Einstein model. The formula used in Lucene differs * slightly from the one in the original paper: {@code F} is increased by {@code tfn+1} * and {@code N} is increased by {@code F} * @lucene.experimental * NOTE: in some corner cases this model may give poor performance with Normalizations that * return large values for {@code tfn} such as NormalizationH3. Consider using the * geometric approximation ({@link BasicModelG}) instead, which provides the same relevance * but with less practical problems. */ public class BasicModelBE extends BasicModel { /** Sole constructor: parameter-free */ public BasicModelBE() {} @Override public final float score(BasicStats stats, float tfn) { double F = stats.getTotalTermFreq() + 1 + tfn; // approximation only holds true when F << N, so we use N += F double N = F + stats.getNumberOfDocuments(); return (float)(-log2((N - 1) * Math.E) + f(N + F - 1, N + F - tfn - 2) - f(F, F - tfn)); } /** The <em>f</em> helper function defined for <em>B<sub>E</sub></em>. */ private final double f(double n, double m) { return (m + 0.5) * log2(n / m) + (n - m) * log2(n); } @Override public String toString() { return "Be"; } } <file_sep>/src/main/java/org/sourav/lucDeb/resources/InputParam.java package org.sourav.lucDeb.resources; public class InputParam { String index; String term; String fieldName; public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } public String getHaru() { return term; } public void setTerm(String term) { this.term = term; } public String toString() { return "Index : "+ index + "Term : "+ term + "FieldName: " + fieldName; } } <file_sep>/src/main/java/lucdeb/commands/TermFrequencyNameCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; /** * * @author dwaipayan */ public class TermFrequencyNameCommand extends Commands { String fieldName; int luceneDocid; String docid; String term; public TermFrequencyNameCommand(LucDebObjects lucivObjects) { super(lucivObjects, "tfn"); } @Override public String help() { return "tfn - Term Frequency of a term in document with docid\n" + usage(); } @Override public void execute(String[] args, PrintStream out) throws IOException { if (args.length != 2 && args.length != 3) { out.println(help()); return; } // Parsing the arguments term = args[0]; docid = args[1]; if (args.length == 3 ) fieldName = args[2]; else fieldName = lucdebObjects.getSearchField(); try { luceneDocid = lucdebObjects.getLuceneDocid(docid); if(luceneDocid < 0) throw (new IllegalArgumentException("")); IndexReader indexReader = lucdebObjects.getIndexReader(); // t vector for this document and field, or null if t vectors were not indexed Terms terms = indexReader.getTermVector(luceneDocid, fieldName); if(null == terms) { out.println(0); } TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; //* for each word in the document long termFreq = -1; while((byteRef = iterator.next()) != null) { String token = new String(byteRef.bytes, byteRef.offset, byteRef.length); if(token.equalsIgnoreCase(this.term)) { termFreq = iterator.totalTermFreq(); // tf of 't' break; } } out.println(termFreq); } catch (Exception ex) { } } @Override public String usage() { return "tfn <term> <docid> [<field-name>]"; } } <file_sep>/src/main/java/lucdeb/LucDeb.java // TODO: change 'content' to something more generic package lucdeb; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lucdeb.commands.Commands; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * * @author dwaipayan */ public class LucDeb { String indexPath; File indexFile; Boolean boolIndexExists; IndexReader indexReader; LucDebObjects lucdebObjects; public LucDeb(String indexPath) throws IOException, Exception { lucdebObjects = new LucDebObjects(indexPath); } public void openIndex(String indexPath) throws IOException { // +++ index path setting this.indexPath = indexPath; indexFile = new File(indexPath); Directory indexDir = FSDirectory.open(indexFile.toPath()); if (!DirectoryReader.indexExists(indexDir)) { System.err.println("Index doesn't exists in "+indexPath); boolIndexExists = false; System.exit(1); } // --- index path set /* setting IndexReader */ indexReader = DirectoryReader.open(FSDirectory.open(indexFile.toPath())); System.out.println("Index opened successfully."); } public static void usage() { String usage = "java LucIV <index-path>"; System.out.println(usage); } public void runLucIV() throws IOException { while(true) { String command = lucdebObjects.readCommand(); if (command == null || command.isEmpty()) continue; command = command.trim(); // + puts the command line argument from LucDeb command line to appropriate arrays List<String> tokens = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean insideQuote = false; for (char c : command.toCharArray()) { if (c == '"') insideQuote = !insideQuote; if (c == ' ' && !insideQuote) {//when space is not inside quote split.. tokens.add(sb.toString().replace("\"", "")); //token is ready, lets add it to list sb.delete(0, sb.length()); //and reset StringBuilder`s content } else sb.append(c);//else add character to token } //lets not forget about last token that doesn't have space after it tokens.add(sb.toString().replace("\"", "")); String[] parts=tokens.toArray(new String[0]); // - puts the command line argument from LucDeb command line to appropriate arrays if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); executeCommand(cmd, cmdArgs, System.out); } } } public void executeCommand(String cmdName, String[] args, PrintStream out) throws IOException { Commands cmd = lucdebObjects.getCommand(cmdName); if(null == cmd) { out.println(cmdName + ": Command not found"); return; } cmd.execute(args, out); } /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException, Exception { LucDeb lucdeb; if(args.length != 1) { usage(); // for test running args = new String[1]; args[0] = "/store/collections/indexed/wt10g-2field.index"; args[0] = "/store/collections/indexed/trec678"; lucdeb = new LucDeb(args[0]); // lucdeb.executeCommand("explain2", "xyzzzz young group company FT922-7489".split(" "), System.out); // lucdeb.executeCommand("explain", "\"xyzzzz young group company\" \"FT922-7489\"".split(" "), System.out); // lucdeb.executeCommand("stats", "".split(" "), System.out); // lucdeb.executeCommand("stats", "".split(" "), System.out); lucdeb.executeCommand("vocab", "".split(" "), System.out); // lucdeb.executeCommand("rank", "What is a Bengals cat\tWTX095-B05-124 WTX095-B05-119\tlmjm 0.4\tbm25 0.2 0.75".split("\t"), System.out); System.exit(0); } lucdeb = new LucDeb(args[0]); lucdeb.runLucIV(); // lucdeb.executeCommand("stats", "".split(" "), System.out); // lucdeb.executeCommand("man", "docid".split(" "), System.out); // lucdeb.executeCommand("help", "".split(" "), System.out); // lucdeb.executeCommand("setfield", "content".split(" "), System.out); // lucdeb.executeCommand("explain", "xyzzzz young group company FT922-7489".split(" "), System.out); // lucdeb.executeCommand("man", "stats".split(" "), System.out); // lucdeb.executeCommand("dv", "content 216038".split(" "), System.out); // lucdeb.executeCommand("dvn", "content WTX001-B06-78".split(" "), System.out); // lucdeb.executeCommand("dvn", "content FT922-7489".split(" "), System.out); // explain "international organized crime" "FBIS4-46734 FBIS3-24145" lmdir 1000 // docterm "FBIS4-46734 FBIS3-24145" "lmdir 1000" // rank "What is a Bengals cat" "WTX095-B05-124 WTX095-B05-119" "lmjm 0.4" "bm25 0.2 0.75" } } <file_sep>/src/main/java/common/CommonMethods.java package common; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.util.BytesRef; /** * * @author dwaipayan */ public class CommonMethods { /** * Returns a string-buffer in the TREC-res format for the passed queryId * @param queryId * @param hits * @param searcher * @param runName * @return * @throws IOException */ static final public StringBuffer writeTrecResFileFormat(String queryId, ScoreDoc[] hits, IndexSearcher searcher, String runName) throws IOException { StringBuffer resBuffer = new StringBuffer(); int hits_length = hits.length; for (int i = 0; i < hits_length; ++i) { int luceneDocId = hits[i].doc; Document d = searcher.doc(luceneDocId); resBuffer.append(queryId).append("\tQ0\t"). append(d.get("docid")).append("\t"). append((i)).append("\t"). append(hits[i].score).append("\t"). append(runName).append("\n"); } return resBuffer; } /** * Analyzes 'text', using 'analyzer', to be stored in 'fieldName'. * @param analyzer The analyzer to be used for analyzing the text * @param text The text to be analyzed * @param fieldName The name of the field in which the text is going to be stored * @return The analyzed text as StringBuffer * @throws IOException */ public static StringBuffer analyzeText(Analyzer analyzer, String text, String fieldName) throws IOException { // +++ For replacing characters- ':','_' Map<String, String> replacements = new HashMap<String, String>() {{ put(":", " "); put("_", " "); }}; // create the pattern joining the keys with '|' String regExp = ":|_"; Pattern p = Pattern.compile(regExp); // --- For replacing characters- ':','_' StringBuffer temp; Matcher m; StringBuffer tokenizedContentBuff; TokenStream stream; CharTermAttribute termAtt; // +++ For replacing characters- ':','_' temp = new StringBuffer(); m = p.matcher(text); while (m.find()) { String value = replacements.get(m.group(0)); if(value != null) m.appendReplacement(temp, value); } m.appendTail(temp); text = temp.toString(); // --- For replacing characters- ':','_' tokenizedContentBuff = new StringBuffer(); stream = analyzer.tokenStream(fieldName, new StringReader(text)); termAtt = stream.addAttribute(CharTermAttribute.class); stream.reset(); while (stream.incrementToken()) { String term = termAtt.toString(); if(!term.equals("nbsp") && !term.equals("amp")) tokenizedContentBuff.append(term).append(" "); } stream.end(); stream.close(); return tokenizedContentBuff; } /** * Analyzes 'text', using 'analyzer', to be stored in a dummy field. * @param analyzer * @param text * @return * @throws IOException */ public static StringBuffer analyzeText(Analyzer analyzer, String text) throws IOException { StringBuffer temp; Matcher m; StringBuffer tokenizedContentBuff; TokenStream stream; CharTermAttribute termAtt; tokenizedContentBuff = new StringBuffer(); stream = analyzer.tokenStream("dummy_field", new StringReader(text)); termAtt = stream.addAttribute(CharTermAttribute.class); stream.reset(); while (stream.incrementToken()) { String term = termAtt.toString(); tokenizedContentBuff.append(term).append(" "); } stream.end(); stream.close(); return tokenizedContentBuff; } static boolean isNumeric(String term) { int len = term.length(); for (int i = 0; i < len; i++) { char ch = term.charAt(i); if (Character.isDigit(ch)) return true; } return false; } /** * Analyzes 'text', using 'analyzer', to be stored in a dummy field. * @param analyzer * @param text * @return * @throws IOException */ public static StringBuffer analyzeTextRemoveNum(Analyzer analyzer, String text) throws IOException { StringBuffer temp; Matcher m; StringBuffer tokenizedContentBuff; TokenStream stream; CharTermAttribute termAtt; tokenizedContentBuff = new StringBuffer(); stream = analyzer.tokenStream("dummy_field", new StringReader(text)); termAtt = stream.addAttribute(CharTermAttribute.class); stream.reset(); while (stream.incrementToken()) { String term = termAtt.toString(); if(!isNumeric(term)) tokenizedContentBuff.append(term).append(" "); } stream.end(); stream.close(); return tokenizedContentBuff; } public static long getDocLength(IndexReader indexReader, String fieldName, int luceneDocid) throws IOException { Terms terms = indexReader.getTermVector(luceneDocid, fieldName); if(null == terms) { System.err.println("Error: Term vector null: "+luceneDocid); System.exit(1); } System.out.println("unique-term-count " + terms.size()); TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; //* for each word in the document long docSize = 0; while((byteRef = iterator.next()) != null) { String term = new String(byteRef.bytes, byteRef.offset, byteRef.length); long tf = iterator.totalTermFreq(); // tf of 't' // System.out.println(term+" "+tf); // int docFreq = indexReader.docFreq(new Term(fieldName, term)); // df of 't' // long cf = indexReader.totalTermFreq(new Term(fieldName, term)); // tf of 't' // System.out.println(term+": cf: "+cf + " : df: " + docFreq); docSize += tf; } // System.out.println("doc-size: " + docSize); return docSize; } // for unit testing public static void main(String[] args) throws IOException { CommonMethods obj = new CommonMethods(); } } <file_sep>/src/main/java/lucdeb/commands/TermStats.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.util.Comparator; /** * * @author Dwaipayan */ public class TermStats { String term; long cf; long df; float idf; float tf; float collectionProbability; float score; public void setTerm(String term) {this.term = term;} public void setCF(long cf) {this.cf = cf;} public void setDF(long df) {this.df = df;} public void setIDF(float idf) {this.idf = idf;} public void setTF(float tf) {this.tf = tf;} public void setCollProba(float collProba) {this.collectionProbability = collProba;} public void setScore(float score) {this.score = score;} } class sortByTermScore implements Comparator<TermStats> { @Override public int compare(TermStats a, TermStats b) { return a.score<b.score?1:a.score==b.score?0:-1; } }<file_sep>/src/main/java/lucdeb/commands/HelpCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; import java.util.Map; import lucdeb.LucDebObjects; /** * * @author dwaipayan */ public class HelpCommand extends Commands{ public HelpCommand(LucDebObjects lucivObjects) { super(lucivObjects, "help"); } @Override public String help() { return "Prints all the commands with their utility"; } @Override public void execute(String[] args, PrintStream out) throws IOException { Map<String, Commands> cmdMap = lucdebObjects.getCommandMap(); Collection<Commands> allCommands = cmdMap.values(); for (Commands cmd : allCommands) { out.println(cmd.getName() + " - " + cmd.help()); } } @Override public String usage() { return "help"; } } <file_sep>/src/main/java/lucdeb/commands/DocVectorNameCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; /** * * @author dwaipayan */ public class DocVectorNameCommand extends Commands { String fieldName; String docid; int luceneDocid; public DocVectorNameCommand(LucDebObjects lucivObjects) { super(lucivObjects, "dvn"); } @Override public String help() { return usage(); } @Override public void execute(String[] args, PrintStream out) throws IOException { if (args.length != 1 && args.length != 2) { out.println(help()); return; } // Parsing the arguments docid = args[0]; if (args.length == 2 ) fieldName = args[1]; else fieldName = lucdebObjects.getSearchField(); try { luceneDocid = lucdebObjects.getLuceneDocid(docid); } catch (Exception ex) { out.println("Error while getting luceneDocid"); } if(luceneDocid < 0) { return; } IndexReader indexReader = lucdebObjects.getIndexReader(); // Term vector for this document and field, or null if term vectors were not indexed Terms terms = indexReader.getTermVector(luceneDocid, fieldName); if(null == terms) { out.println("Error: Term vector null: "+luceneDocid); return; } System.out.println("unique-term-count " + terms.size()); TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; //* for each word in the document int docSize = 0; while((byteRef = iterator.next()) != null) { String term = new String(byteRef.bytes, byteRef.offset, byteRef.length); long tf = iterator.totalTermFreq(); // tf of 't' out.println(term+" "+tf); // int docFreq = indexReader.docFreq(new Term(fieldName, term)); // df of 't' // long cf = indexReader.totalTermFreq(new Term(fieldName, term)); // tf of 't' // System.out.println(term+": cf: "+cf + " : df: " + docFreq); docSize += tf; } out.println("doc-size: " + docSize); } @Override public String usage() { return "dvn <docid> [<field-name>]"; } } <file_sep>/src/main/java/lucdeb/commands/CustomLMJMSim.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import common.DocumentVector; import java.util.List; import java.util.Locale; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.similarities.BasicStats; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import org.apache.lucene.search.similarities.LMSimilarity; /** * * @author dwaipayan */ public class CustomLMJMSim extends LMSimilarity { /** The &lambda; parameter. */ private final float lambda; DocumentVector dv; /** Instantiates with the specified collectionModel and &lambda; parameter. */ public CustomLMJMSim(CollectionModel collectionModel, float lambda) { super(collectionModel); this.lambda = lambda; } /** Instantiates with the specified &lambda; parameter. */ public CustomLMJMSim(float lambda) { this.lambda = lambda; } public void setDocVector(DocumentVector dv) { this.dv = dv; } @Override protected float score(BasicStats stats, float freq, float docLen) { return stats.getTotalBoost() * (float)Math.log(1 + ((1 - lambda) * freq / docLen) / (lambda * ((LMStats)stats).getCollectionProbability())); } // protected float score() { // float scr = 0; // scr = // (float)Math.log(1 + // ((1-lambda) * dv.getTf(term, dv) / dv.getDocSize()) / // (lambda * dv.getCollectionProbability(term, reader, fieldName)) // ; // return scr; // } /** Returns the &lambda; parameter. */ public float getLambda() { return lambda; } @Override public String getName() { return String.format(Locale.ROOT, "Jelinek-Mercer(%f)", getLambda()); } /** * * @param subs * @param stats * @param doc * @param freq * @param docLen */ @Override protected void explain(List<Explanation> subs, BasicStats stats, int doc, float freq, float docLen) { //System.out.println("\nHere in CustomeLMJM.Explain()"); //System.out.println("getAvgFieldLength: "+stats.getAvgFieldLength()); //System.out.println("getDocFreq: "+stats.getDocFreq()); //System.out.println("getNumberOfDocuments: "+stats.getNumberOfDocuments()); //System.out.println("getNumberOfFieldTokens: "+stats.getNumberOfFieldTokens()); //System.out.println("getTotalBoost: "+stats.getTotalBoost()); //System.out.println("getTotalTermFreq: "+ stats.getTotalTermFreq()); //System.out.println("docLen: " + docLen); //System.out.println("getValueForNormalization" + stats.getValueForNormalization()); // following two are used for CollectionProba. computation. // System.out.println("getTotalTermFreq: "+ stats.getTotalTermFreq()); // System.out.println("getNumberOfFieldTokens: "+stats.getNumberOfFieldTokens()); float collectionProbability = (float)stats.getTotalTermFreq() / (float)stats.getNumberOfFieldTokens(); float score = (float) Math.log(1 + ((1-lambda)*freq) / (lambda * docLen * collectionProbability)); // System.out.println("CollectionProbability: " + collectionProbability); // if (stats.getTotalBoost() != 1.0f) { // subs.add(Explanation.match(stats.getTotalBoost(), "boost")); // } // subs.add(Explanation.match(lambda, "lambda")); // super.explain(subs, stats, doc, freq, docLen); // System.out.println("freq\tdocLen\tcoll-Proba\tscore"); System.out.println("("+freq + "\t" + docLen + "\t" + collectionProbability + "\t" + score + ")"); // System.out.println("Freq: " + freq); // System.out.println("DocLen: " + docLen); } } <file_sep>/src/main/java/lucdeb/commands/SetRetrievalModelCommand.java package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; //import org.apache.lucene.search.TopScoreDocCollector; import lucdeb.LucDebObjects; import org.apache.commons.cli.*; /** * * @author souravsaha * */ public class SetRetrievalModelCommand extends Commands{ public SetRetrievalModelCommand(LucDebObjects lucDebObject) { super(lucDebObject, "setRetModel"); } @Override public String help() { return "Set the retrieval model online"; } @Override public String usage() { return "setRetrieval <-m Models> <-p Params...> "; } @Override public void execute(String[] args, PrintStream out) throws IOException { // tokenize // call to my setRetrieval method Options options = new Options(); Option modelOption = new Option("m", "model", true, "Model name"); modelOption.setRequired(true); options.addOption(modelOption); Option paramOption = new Option("p", "parameter", true, "List of parameters"); paramOption.setRequired(true); options.addOption(paramOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); return; } String modelName = cmd.getOptionValue("model"); String allParams = cmd.getOptionValue("parameter"); out.println(modelName); out.println(allParams); String param1="", param2= "", param3 = ""; String[] params = allParams.split(" "); switch(modelName) { case "lmjm": param1 = params[0]; break; case "lmdir": param1 = params[0]; break; case "bm25": param1 = params[0]; param2 = params[1]; break; case "dfr": param1 = params[0]; param2 = params[1]; param3 = params[2]; break; default: // TODO break; } lucdebObjects.setRetreivalParameter(modelName,param1, param2, param3); System.out.println("Retrieval Model changed to "+ modelName); } } <file_sep>/src/main/java/lucdeb/commands/Postings.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lucdeb.LucDebObjects; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.util.BytesRef; /** * * @author Dwaipayan */ public class Postings extends Commands{ static String cmdName = "pl"; String fieldName; String term; public Postings(LucDebObjects lucivObjects) { super(lucivObjects, cmdName); } @Override public String help() { return cmdName + " - prints the posting list of a given term\n" + usage(); } @Override public String usage() { return cmdName + " <term> [ <field-name> ]"; } @Override public void execute(String[] args, PrintStream out) throws IOException { if (args.length != 1 && args.length != 2) { out.println(help()); return; } // Parsing the arguments term = args[0]; if (args.length == 2 ) fieldName = args[1]; else fieldName = lucdebObjects.getSearchField(); // + List<PostingValues> postingsLists = new ArrayList<>(); IndexReader indexReader = lucdebObjects.getIndexReader(); List<LeafReaderContext> leaves = indexReader.leaves(); int docBase = 0; PostingsEnum postings = null; // for each occurrences for (LeafReaderContext leaf : leaves) { LeafReader atomicReader = leaf.reader(); Terms terms = atomicReader.terms(fieldName); if (terms == null){ continue; } if (terms != null && term != null) { TermsEnum termsEnum = terms.iterator(); if (termsEnum.seekExact(new BytesRef(term))) { postings = termsEnum.postings(postings, PostingsEnum.FREQS); int docid; while((docid = postings.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS){ int tf = postings.freq(); // out.println("docid: "+(docid+docBase)+", tf: "+tf); postingsLists.add(new PostingValues(docid+docBase, tf)); } } } docBase += atomicReader.maxDoc(); } Collections.sort(postingsLists, new sortByTermTF()); // for (PostingValues pv : postingsLists) { // System.out.println(pv.luceneDocid + " " + pv.tf); // } ArrayList<String> list; list = new ArrayList<>(); for(PostingValues pv : postingsLists) { String s = pv.toString(); // System.out.println(s); list.add(s); /* if(s.equals("315394 1")) list.add("\033[37;41;1m"+s+"\033[0;0;1m"); else list.add("\033[0;0;1m"+s); */ } out.println(String.join("\n", list)); //lucdebObjects.printPagination(list); // - } } <file_sep>/src/main/java/lucdeb/commands/StatsCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.List; import lucdeb.LucDebObjects; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.Terms; /** * * @author dwaipayan */ public class StatsCommand extends Commands { HashMap<String,Boolean> isSetStats; /** * * @param lucivObjects */ public StatsCommand(LucDebObjects lucivObjects) { super(lucivObjects, "stats"); isSetStats = new HashMap<>(); } /** * * @param args * @param out * @throws IOException */ @Override public void execute(String[] args, PrintStream out) throws IOException{ out.println("Number of docs: " + lucdebObjects.numDocs); out.println("Number of fields: " + lucdebObjects.numFields); int fcount = 0; for (Object[] finfo : lucdebObjects.fields.values()) { FieldInfo fieldInfo = (FieldInfo) finfo[0]; String fieldName = fieldInfo.name; out.println("=== Field "+ ++fcount + ": "+fieldInfo.name+" ==="); out.println("Field name:\t\t" + fieldInfo.name); out.println("Term vectors stored:\t" + fieldInfo.hasVectors()); if(null == (isSetStats.get(fieldName))) // if not already computed setStats(finfo, out); //else // System.out.println("already computed"); List<Long> counts = lucdebObjects.getTermCounts(fieldName); out.println("Unique term count:\t" + counts.get(0)); out.println("Total term count:\t" + counts.get(1) + "\n"); } } /** * * @param info * @param out * @throws IOException */ public void setStats(Object[] info, PrintStream out) throws IOException { FieldInfo fieldInfo = (FieldInfo) info[0]; String fieldName = fieldInfo.name; List<Terms> termList = (List<Terms>) info[1]; if (termList != null) { long numTerms = 0L; long sumTotalTermFreq = 0L; try{ for (Terms t : termList) { if (t != null) { numTerms += t.size(); sumTotalTermFreq += t.getSumTotalTermFreq(); } } } catch(IOException ex) { System.err.println("IOException in Stats.prettyPrint()"); System.err.println(ex); } if (numTerms < 0) numTerms = -1; if (sumTotalTermFreq < 0) sumTotalTermFreq = -1; // (fieldName, uniqTermCount, totalTermCount) lucdebObjects.setTermCounts(fieldName, numTerms, sumTotalTermFreq); } isSetStats.put(fieldName, true); } @Override public String help() { return "stats - show the basic stats of the index"; } @Override public String usage() { return "stats"; } } <file_sep>/src/main/java/lucdeb/commands/dfr/NormalizationH1.java package lucdeb.commands.dfr; import org.apache.lucene.search.similarities.BasicStats; /** * Normalization model that assumes a uniform distribution of the term frequency. * <p>While this model is parameterless in the * <a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.742"> * original article</a>, <a href="http://dl.acm.org/citation.cfm?id=1835490"> * information-based models</a> (see {@link IBSimilarity}) introduced a * multiplying factor. * The default value for the {@code c} parameter is {@code 1}.</p> * @lucene.experimental */ public class NormalizationH1 extends Normalization { private final float c; /** * Creates NormalizationH1 with the supplied parameter <code>c</code>. * @param c hyper-parameter that controls the term frequency * normalization with respect to the document length. */ public NormalizationH1(float c) { this.c = c; } /** * Calls {@link #NormalizationH1(float) NormalizationH1(1)} */ public NormalizationH1() { this(1); } @Override public final float tfn(BasicStats stats, float tf, float len) { return tf * stats.getAvgFieldLength() / len; } @Override public String toString() { return "1"; } /** * Returns the <code>c</code> parameter. * @see #NormalizationH1(float) */ public float getC() { return c; } } <file_sep>/src/main/java/lucdeb/commands/TermFrequencyCommand.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lucdeb.commands; import java.io.IOException; import java.io.PrintStream; import lucdeb.LucDebObjects; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; /** * * @author dwaipayan */ public class TermFrequencyCommand extends Commands { String fieldName; int luceneDocid; String term; public TermFrequencyCommand(LucDebObjects lucivObjects) { super(lucivObjects, "tf"); } @Override public String help() { return "tf - Term Frequency\n" + usage(); } @Override public void execute(String[] args, PrintStream out) throws IOException { Options options = new Options(); Option modelOption = new Option("i", "luceneDocId", true, "Lucene Doc Id"); // modelOption = Option.builder("i").longOpt("luceneDocId").desc("Lucene Doc Id").hasArg(true).build(); modelOption.setRequired(false); options.addOption(modelOption); Option paramOption = new Option("n", "docName", true, "Document Name"); paramOption.setRequired(false); options.addOption(paramOption); options.addOption("f", "fieldName", true, "Field name in which collection frequency will be computed" ); Option queryOption = new Option("q", "queryTerms", true, "Query Terms"); queryOption.setRequired(true); options.addOption(queryOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); return; } String queryTermsValue = cmd.getOptionValue("queryTerms"); String luceneDocIdNum = cmd.getOptionValue("luceneDocId"); String docNameValue = cmd.getOptionValue("docName"); if(cmd.hasOption("i")) { // Parsing the arguments try { luceneDocid = Integer.parseInt(luceneDocIdNum.trim()); } catch(NumberFormatException ex) { out.println("error reading docid; expected integers."); } } else if(cmd.hasOption("n")) { try { //out.println(docNameValue); luceneDocid = lucdebObjects.getLuceneDocid(docNameValue.trim()); } catch (Exception ex) { out.println("Error while getting luceneDocid"); } if(luceneDocid < 0) { return; } } else return; if(luceneDocid < 0 || luceneDocid > lucdebObjects.getNumDocs()) { out.println(luceneDocid + ": not in the docid range (0 - " + lucdebObjects.getNumDocs() + ")"); return; } String fieldNameValue = cmd.getOptionValue("fieldName"); if(null != fieldNameValue) fieldName = fieldNameValue; else { fieldName = lucdebObjects.getSearchField(); } IndexReader indexReader = lucdebObjects.getIndexReader(); // t vector for this document and field, or null if t vectors were not indexed Terms terms = indexReader.getTermVector(luceneDocid, fieldName); if(null == terms) { } TermsEnum iterator = terms.iterator(); BytesRef byteRef = null; //* for each word in the document long termFreq = -1; while((byteRef = iterator.next()) != null) { String token = new String(byteRef.bytes, byteRef.offset, byteRef.length); if(token.equalsIgnoreCase(queryTermsValue)) { termFreq = iterator.totalTermFreq(); // tf of 't' break; } } out.println("Term Frequency of " + queryTermsValue + " = " + termFreq); //System.out.println("DocSize: "+docSize); } @Override public String usage() { return "tf <term> <lucene-docid> [<field-name>]"; } } <file_sep>/src/main/java/lucdeb/commands/qe/RelevanceBasedLanguageModel.java /** * RM3: Complete; * Relevance Based Language Model with query mix. * References: * 1. Relevance Based Language Model - <NAME> - SIGIR-2001 * 2. UMass at TREC 2004: Novelty and HARD - <NAME> - TREC-2004 */ package lucdeb.commands.qe; import java.io.File; import java.io.IOException; import java.util.HashMap; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import common.TRECQueryParser; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import lucdeb.LucDebObjects; import org.apache.lucene.queryparser.flexible.core.QueryNodeException; import org.apache.lucene.search.similarities.AfterEffectB; import org.apache.lucene.search.similarities.BasicModelIF; import org.apache.lucene.search.similarities.DFRSimilarity; import org.apache.lucene.search.similarities.NormalizationH2; /** * * @author dwaipayan */ public class RelevanceBasedLanguageModel { String indexPath; String queryPath; // path of the query file File queryFile; // the query file String stopFilePath; IndexReader indexReader; IndexSearcher indexSearcher; int numHits; // number of document to retrieveWithExpansionTermsFromFile String queryStr; Query luceneQuery; File indexFile; // place where the index is stored // Analyzer analyzer; // the analyzer boolean boolIndexExists; // boolean flag to indicate whether the index exists or not String fieldToSearch; // the field in the index to be searched String fieldForFeedback; // field, to be used for feedback TRECQueryParser trecQueryparser; int simFuncChoice; float param1, param2; long vocSize; // vocabulary size RLM rlm; Boolean feedbackFromFile; HashMap<String, TopDocs> allTopDocsFromFileHashMap; // For feedback from file, to contain all topdocs from file // +++ TRF String qrelPath; boolean trf; // true or false depending on whether True Relevance Feedback is choosen HashMap<String, TopDocs> allRelDocsFromQrelHashMap; // For TRF, to contain all true rel. docs. // --- TRF int numFeedbackTerms;// number of feedback terms int numFeedbackDocs; // number of feedback documents float QMIX; PrintStream out; public RelevanceBasedLanguageModel(LucDebObjects lucivObjects, String queryStr, int numExpTerms, PrintStream out) throws IOException, QueryNodeException { // +++++ setting the analyzer with English Analyzer with Smart stopword list // stopFilePath = lucivObjects.stopwordPath; // EnglishAnalyzerWithSmartStopword engAnalyzer = new EnglishAnalyzerWithSmartStopword(stopFilePath); // analyzer = engAnalyzer.setAndGetEnglishAnalyzerWithSmartStopword(); // ----- analyzer set: analyzer fieldToSearch = lucivObjects.getSearchField(); fieldForFeedback = lucivObjects.getSearchField(); /* index path set */ /* setting indexReader and indexSearcher */ indexReader = lucivObjects.getIndexReader(); indexSearcher = lucivObjects.getIndexSearcher(); /* indexReader and searher set */ this.queryStr = queryStr; luceneQuery = lucivObjects.getAnalyzedQuery(queryStr); // numFeedbackTerms = number of top terms to select numFeedbackTerms = numExpTerms; // numFeedbackDocs = number of top documents to select numFeedbackDocs = 20; numHits = numFeedbackDocs; rlm = new RLM(this); this.out = out; } /** * Sets indexSearcher.setSimilarity() with parameter(s) * @param choice similarity function selection flag * @param param1 similarity function parameter 1 * @param param2 similarity function parameter 2 */ private void setSimilarityFunction(int choice, float param1, float param2) { switch(choice) { case 0: indexSearcher.setSimilarity(new DefaultSimilarity()); System.out.println("Similarity function set to DefaultSimilarity"); break; case 1: indexSearcher.setSimilarity(new BM25Similarity(param1, param2)); System.out.println("Similarity function set to BM25Similarity" + " with parameters: " + param1 + " " + param2); break; case 2: indexSearcher.setSimilarity(new LMJelinekMercerSimilarity(param1)); System.out.println("Similarity function set to LMJelinekMercerSimilarity" + " with parameter: " + param1); break; case 3: indexSearcher.setSimilarity(new LMDirichletSimilarity(param1)); System.out.println("Similarity function set to LMDirichletSimilarity" + " with parameter: " + param1); break; case 4: indexSearcher.setSimilarity(new DFRSimilarity(new BasicModelIF(), new AfterEffectB(), new NormalizationH2())); System.out.println("Similarity function set to DFRSimilarity with default parameters"); break; } } // ends setSimilarityFunction() public void retrieveAll() throws Exception { ScoreDoc[] hits; TopDocs topDocs; TopScoreDocCollector collector; HashMap<String, String> queryTerms = new HashMap<>(); collector = TopScoreDocCollector.create(numHits); out.println("Initial query: " + luceneQuery.toString(fieldToSearch)); for(String queryTerm : luceneQuery.toString(fieldToSearch).split(" ")) queryTerms.put(queryTerm, queryTerm); // performing the search indexSearcher.search(luceneQuery, collector); topDocs = collector.topDocs(); rlm.setFeedbackStats(topDocs, luceneQuery.toString(fieldToSearch).split(" "), this); /** * HashMap of P(w|R) for 'numFeedbackTerms' terms with top P(w|R) among each w in R, * keyed by the term with P(w|R) as the value. */ HashMap<String, WordProbability> hashmap_PwGivenR; hashmap_PwGivenR = rlm.RM1(topDocs); //hashmap_PwGivenR = rlm.RM3(query, topDocs); Set<String> keySet = hashmap_PwGivenR.keySet(); List<String> keyList = new ArrayList<>(keySet); int listSize = keyList.size(); int qterms = 0; for (int i = 0; i < Math.min(listSize, numFeedbackTerms)+qterms; i++) { String expansionTerm = keyList.get(i); if(queryTerms.containsKey(expansionTerm)) qterms ++; else out.println(keyList.get(i)); } } // ends retrieveAll } <file_sep>/src/main/java/lucdeb/commands/DiffCommand.java package lucdeb.commands; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.*; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import lucdeb.LucDebObjects; import treceval.Qrel; /** * @author souravsaha * */ public class DiffCommand extends Commands{ public DiffCommand(LucDebObjects lucivObjects) { super(lucivObjects, "diff"); } @Override public String help() { return usage(); } @Override public String usage() { return "diff <-f1> <-1st res file> <-f2 > <-2nd res file>"; } @Override public void execute(String[] args, PrintStream out) throws IOException { Options options = new Options(); Option resFileOption1 = new Option("f1", "resfile1", true, "Name of the 1st res file"); resFileOption1.setRequired(true); options.addOption(resFileOption1); Option resFileOption2 = new Option("f2", "resFile2", true, "Name of the 2nd res file"); resFileOption2.setRequired(false); options.addOption(resFileOption2); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); return; } String resFileName1 = cmd.getOptionValue("resFile1"); String resFileName2 = cmd.getOptionValue("resFile2"); if(cmd.hasOption("f1") && cmd.hasOption("f2")) { // throw if s1 and s2 not found Scanner s1 = new Scanner(new File("/Users/souravsaha/Downloads/"+resFileName1)); Scanner s2 = new Scanner(new File("/Users/souravsaha/Downloads/"+resFileName2)); LinkedHashMap<LinkedHashMap<String, String>, String[]> qidDocScoreMap1 = new LinkedHashMap<LinkedHashMap<String, String>, String[]>(); LinkedHashMap<LinkedHashMap<String, String>, String[]> qidDocScoreMap2 = new LinkedHashMap<LinkedHashMap<String, String>, String[]>(); while (s1.hasNext()) { String qID = s1.next(); s1.next(); String docID = s1.next(); String rank = s1.next(); String score = s1.next(); s1.next(); LinkedHashMap<String,String> queryDocMap1 = new LinkedHashMap<String,String>(); queryDocMap1.put(qID, docID); qidDocScoreMap1.put(queryDocMap1, new String[] {rank, score}); } while (s2.hasNext()) { String qID = s2.next(); s2.next(); String docID = s2.next(); String rank = s2.next(); String score = s2.next(); s2.next(); LinkedHashMap<String,String> queryDocMap2 = new LinkedHashMap<String,String>(); queryDocMap2.put(qID, docID); qidDocScoreMap2.put(queryDocMap2, new String[] {rank, score}); } out.println("QID" + "\t" + "DOCID" + "R1" + "\t" + "SIM1" + "\t" + "R2" + "\t" + "SIM2" + "\t" + "RANK-DIFF" + "\t" + "REL"); for (Map.Entry<LinkedHashMap<String, String>, String[]> entry : qidDocScoreMap1.entrySet()) { LinkedHashMap<String, String> qIDdocIDMap = entry.getKey(); String[] rankScore = entry.getValue(); out.print(qIDdocIDMap.entrySet().iterator().next().getKey()); // qid out.print(qIDdocIDMap.entrySet().iterator().next().getValue()); // docid out.print(rankScore[0] + "\t" + rankScore[1]); // rank1, score1 String[] rankScore2 =null; if(qidDocScoreMap2.get(qIDdocIDMap)!=null) { rankScore2 = qidDocScoreMap2.get(qIDdocIDMap); out.print(rankScore2[0] + "\t" + rankScore2[1]); // rank2, score2 } else out.print("NOT FOUND" + "\t"+ "NOT FOUND"); int rankDiff; Integer rank1 = Integer.valueOf(rankScore[0]); Integer rank2 = Integer.valueOf(rankScore2[0]); rankDiff = (rank1 > rank2) ? (rank1 - rank2) : (rank1 - rank2); out.print(String.valueOf(rankDiff)); out.print(Qrel.getQrel().getQueryRelevance().get(qIDdocIDMap)); // relevant or not } } else { out.println("less than 2 res files found."); return; } } }
f171ff30d4899303984202e76ba8823ca69f415c
[ "Markdown", "Java" ]
24
Java
souravsaha/I-REX
d3d5a9bd4208314374fd54ed607b9e268310574e
2b4a24182bb561f47fe4f2a7bd3a12def03c4417
refs/heads/main
<repo_name>Siddhant128-bit/Nayve-Bayes-Classification<file_sep>/main.py import pandas as pd import re data_set=pd.read_csv('spam.csv') data_set['Message']=data_set['Message'].str.replace('\W',' ') data_set['Message']=data_set['Message'].str.lower() data_set['Message']=data_set['Message'].str.split() vocabulary=[] for message in data_set['Message']: #go through each message in the list for word in message: vocabulary.append(word) vocabulary=list(set(vocabulary)) #converting the list into set and converting it to list again so that repeated text will not be repeated #this part is essentially creating a new dataframe which has words and their count respectively words_count_per_message={unique_word: [0]*len(data_set['Message']) for unique_word in vocabulary } for index,message in enumerate(data_set['Message']): for words in message: words_count_per_message[word][index]+=1 word_counts=pd.DataFrame(words_count_per_message) #must rewatch the above code again its kind of confusing. data_set_clean=pd.concat([data_set,word_counts],axis=1) #print(data_set_clean) #formula using P(spam|w1,w2,w3......)=P(spam)*sum i from 1 to n (P(wi|spam)) and p(w/spam)=(Nw|spam +alpha)/(Nspam+alpha*Nvocabulary) # Isolating spam and ham messages first spam_messages = data_set_clean[data_set_clean['Label'] == 'spam'] ham_messages = data_set_clean[data_set_clean['Label'] == 'ham'] # P(spam) and P(ham) p_spam = len(spam_messages) / len(data_set_clean) p_ham = len(ham_messages) / len(data_set_clean) # N_spam n_words_per_spam_message = spam_messages['Message'].apply(len) n_spam = n_words_per_spam_message.sum() # N_ham n_words_per_ham_message = ham_messages['Message'].apply(len) n_ham = n_words_per_ham_message.sum() # N_Vocabulary n_vocabulary = len(vocabulary) # Laplace smoothing alpha = 1 # Initiate parameters parameters_spam = {unique_word:0 for unique_word in vocabulary} parameters_ham = {unique_word:0 for unique_word in vocabulary} # Calculate parameters for word in vocabulary: n_word_given_spam = spam_messages[word].sum() # spam_messages already defined p_word_given_spam = (n_word_given_spam + alpha) / (n_spam + alpha*n_vocabulary) parameters_spam[word] = p_word_given_spam n_word_given_ham = ham_messages[word].sum() # ham_messages already defined p_word_given_ham = (n_word_given_ham + alpha) / (n_ham + alpha*n_vocabulary) parameters_ham[word] = p_word_given_ham def test_model(): while True: message=str(input('Enter the message in Roman Nepali: ')) message=re.sub('\W',' ',message) if message=='exit': break else: message=message.lower().split() p_spam_given_message=p_spam p_ham_given_message=p_ham for word in message: if word in parameters_spam: p_spam_given_message*=parameters_spam[word] if word in parameters_ham: p_ham_given_message*=parameters_ham[word] print('P(spam|message): ',p_spam_given_message) print('P(ham|message): ',p_ham_given_message) if p_ham_given_message > p_spam_given_message: print('Label: ham') elif p_ham_given_message < p_spam_given_message: print('Label: spam') else: print('Equal proabilities, have a human classify this!') test_model() <file_sep>/main_sklearn.py import pandas as pd from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn.metrics import accuracy_score from sklearn.feature_extraction.text import CountVectorizer import string from nltk.corpus import stopwords enc = preprocessing.LabelEncoder() dataset=pd.read_csv('spam.csv') input_x=dataset['Message'].values output_y=dataset['Label'].values #enc.fit(input_x) #input_x = enc.transform(input_x) vectorizer=CountVectorizer() input_x = vectorizer.fit_transform(input_x) #input_x=input_x.reshape(-1,1) #output_y=output_y.reshape(-1,1) X_train,X_test,Y_train,Y_test=train_test_split(input_x,output_y) nb=MultinomialNB() nb.fit(X_train,Y_train) pred=nb.predict(X_test) print(accuracy_score(pred,Y_test)) def input_process(text): translator = str.maketrans('', '', string.punctuation) nopunc = text.translate(translator) words = [word for word in nopunc.split() if word.lower() not in stopwords.words('english')] return ' '.join(words) Z=str(input('Enter the message to test: ')) new_x=vectorizer.transform([input_process(Z)]) #print(new_x) print(nb.predict(new_x))
53900769780b3830a42cf67c764339edcd1dd5ab
[ "Python" ]
2
Python
Siddhant128-bit/Nayve-Bayes-Classification
b65c41c9b971bcec35b338e43418e896d6084b57
4f9a78397724a24e54389ad4d30e5795ed8e4880
refs/heads/master
<repo_name>anshuman73/2016-CBSE-Grade-12-Results<file_sep>/Result Extractor.py """ Copyright 2016, <NAME> (anshuman73) 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. """ from selenium import webdriver import os from time import time from bs4 import BeautifulSoup import sqlite3 def parser(html): data = dict() marks_table_index = list() marks = list() soup = BeautifulSoup(html, 'html.parser') parsed_tables = soup.findAll('table')[:2] basic_data_table = parsed_tables[0] basic_data_tr = basic_data_table.findAll('tr') for rows in basic_data_tr: columns = rows.findAll('td') data[''.join(columns[0].findAll(text=True)).strip()] = ''.join(columns[1].findAll(text=True)).strip() result_data_table = parsed_tables[1] result_data_tr = result_data_table.findAll('tr') for codes in result_data_tr[0].findAll('td'): marks_table_index.append(''.join(codes.findAll(text=True)).strip()) marks_table_subjects = result_data_tr[1:-1] for subject_tr in marks_table_subjects: if len(subject_tr.findAll('td')) > 1: subject_marks = {} for index, sub_details in enumerate(subject_tr.findAll('td')): subject_marks[marks_table_index[index]] = ''.join(sub_details.findAll(text=True)).strip() marks.append(subject_marks) raw_result = ''.join(result_data_tr[-1].findAll('td')[1].findAll(text=True)).strip() result = raw_result[raw_result.find('Result:') + len('Result:'): raw_result.rfind(':')].strip() data['marks'] = marks data['final_result'] = result return data def main(): database_conn = sqlite3.connect('database.sqlite') cursor = database_conn.cursor() cursor.executescript(''' DROP TABLE IF EXISTS Records; DROP TABLE IF EXISTS Marks; CREATE TABLE Records ( Roll_Number INTEGER PRIMARY KEY, Name TEXT, Father_Name TEXT, Mother_Name TEXT, Final_Result TEXT, Number_of_subjects INTEGER ); CREATE TABLE Marks ( Roll_Number INTEGER, Subject_Code TEXT, Subject_Name TEXT, Theory_Marks INTEGER, Practical_Marks INTEGER, Total_Marks INTEGER, Grade TEXT ) ''') school_code = raw_input('Enter the School Code: ') lower_limit = int(raw_input('Enter the lower limit of roll no. to check: ')) upper_limit = int(raw_input('Enter the upper limit of roll no. to check: ')) choice = raw_input('Go headless ? (y/n) ').lower() if choice == 'y': driver = webdriver.PhantomJS(os.getcwd() + '/' + 'phantomjs.exe') elif choice == 'n': driver = webdriver.Chrome(os.getcwd() + '/' + 'chromedriver.exe') else: print 'Wrong input, going headless...' driver = webdriver.PhantomJS(os.getcwd() + '/' + 'phantomjs.exe') driver.get('http://cbseresults.nic.in/class12/cbse1216.htm') st = time() count = 0 for roll_no in range(lower_limit, upper_limit + 1): try: reg_no_element = driver.find_element_by_name('regno') school_code_element = driver.find_element_by_name('schcode') submit_button = driver.find_element_by_xpath("//input[@type='submit']") reg_no_element.clear() reg_no_element.send_keys(roll_no) school_code_element.clear() school_code_element.send_keys(school_code) submit_button.click() html = ''.join(driver.page_source.encode('utf8').split('\n')[67:]) data = parser(html) cursor.execute('INSERT INTO Records (Roll_Number, Name, Father_Name, Mother_Name, Final_Result, Number_of_subjects) ' 'VALUES (?, ?, ?, ?, ?, ?)', (data['Roll No:'], data['Name:'], data['Father\'s Name:'], data['Mother\'s Name:'], data['final_result'], len(data['marks']), )) for subject in data['marks']: cursor.execute('INSERT INTO Marks (Roll_Number, Subject_Code, Subject_Name, Theory_Marks, ' 'Practical_Marks, Total_Marks, Grade) VALUES (?, ?, ?, ?, ?, ?, ?)', (data['Roll No:'], subject['SUB CODE'], subject['SUB NAME'], subject['THEORY'], subject['PRACTICAL'], subject['MARKS'], subject['GRADE'], )) print 'Processed Roll No.', roll_no count += 1 if count % 50 == 0: print '\n50 records in RAM, saving to database to avoid loss of data...\n' database_conn.commit() except Exception as error: print 'Roll No.', roll_no, 'threw an error, leaving it.' print error driver.back() print '\n\nLog: \n' print count, 'valid records downloaded, saving everything to database...' database_conn.commit() database_conn.close() print '\nClosing the Simulated Browser' driver.close() print '\nSimulated browser closed.\n' print '\nFinished processing everything.\n' print '\nTook', time() - st, 'seconds for execution for processing', count, 'valid records' raw_input('Press any Key to exit: ') if __name__ == '__main__': main() <file_sep>/README.md # CBSE 2016 12th Grade Result Crawler A script to find results of 12th Boards using selenium implementation on headless browser. Works by brute forcing the roll numbers of a specific range. Requires school code. Attached .exe to run out of the box. **Please note you need the all the .exe(s) in one folder.** The other two are for the simulated browsers. Saves all the extracted data into 2 tables in SQLITE, namely 'Records' and 'Marks'. 'Records' stores all the basic data like roll number, identity, etc. 'Marks' stores marks of each roll number for each subject in different rows along with breakup of the marks. Data isn't normalized perfectly, SQLITE probably wasn't a good idea to go with. MongoDB would have been a better choice for such a nested data structure. Went with SQLITE due to lack of time and care. This was mostly a bet. It isn't like its unusable, just requires a bit of SQL knowledge. Join and select statements should do the job pretty nicely. Contact me for more. **Please note I am not in favour of anyone taking this code and calling it their own without any sort of acknowledgement. A lot of hardwork went into this. See the License for more**<file_sep>/parsing trials/parser trial.py from bs4 import BeautifulSoup html = open('lol.html', 'r').readlines()[67:] html = ''.join(html) def parser(html): data = dict() marks_table_index = list() marks = list() soup = BeautifulSoup(html, 'html.parser') parsed_tables = soup.findAll('table')[:2] basic_data_table = parsed_tables[0] basic_data_tr = basic_data_table.findAll('tr') for rows in basic_data_tr: columns = rows.findAll('td') data[''.join(columns[0].findAll(text=True)).strip()] = ''.join(columns[1].findAll(text=True)).strip() result_data_table = parsed_tables[1] result_data_tr = result_data_table.findAll('tr') for codes in result_data_tr[0].findAll('td'): marks_table_index.append(''.join(codes.findAll(text=True)).strip()) marks_table_subjects = result_data_tr[1:-1] for subject_tr in marks_table_subjects: if len(subject_tr.findAll('td')) > 1: subject_marks = {} for index, sub_details in enumerate(subject_tr.findAll('td')): subject_marks[marks_table_index[index]] = ''.join(sub_details.findAll(text=True)).strip() marks.append(subject_marks) raw_result = ''.join(result_data_tr[-1].findAll('td')[1].findAll(text=True)).strip() result = raw_result[raw_result.find('Result:') + len('Result:'): raw_result.rfind(':')].strip() data['marks'] = marks data['final_result'] = result return data print parser(html)
382f01aa992e34d2ba63f3050ccbdc703feb1729
[ "Markdown", "Python" ]
3
Python
anshuman73/2016-CBSE-Grade-12-Results
0f2927ac837d18a5ce2d5a70bb8def397e70b4bd
0731e476489ae16ed01fa02b9e856ab4d5c0c6b3
refs/heads/main
<file_sep>import { useState } from 'react'; import './assets/App.css'; import data from "./data" function App() { const [number,setNumber] = useState(0); const [text,setText] = useState([]); const [copy , setCopy] = useState(false); const handleSubmit = (event) => { event.preventDefault(); setText(data.slice(0,number)); } const checkValue = (event) => { let value = event.target.value ; if(value > data.length){ value = data.length } if(value <= 0){ value = 0 } setNumber(Number(value)) setCopy(false) } const copyToClipBoard = () => { const input = document.querySelector(".hidden-input").value; navigator.clipboard.writeText(input); setCopy(true) } let buttonStatus = "btn-secondary" ; copy ? buttonStatus = "btn-success" : buttonStatus = "btn-secondary" ; return ( <main className="container-fluid App d-flex flex-column justify-content-center align-items-center h-100"> <h2 className="title d-flex justify-content-center align-items-center w-100 mb-5"> Lorem Ipsum Maker </h2> <section className="input-box d-flex justify-content-center align-items-center mb-5"> <form onSubmit={e=>handleSubmit(e)} className="input-form d-flex w-100 justify-content-center align-items-center"> <label htmlFor="number" className="input-desc m-0">number of paragraphs : </label> <input className="paragraph-number" type="number" id="number" name="number" value={number} onChange={(e)=>checkValue(e)}/> <button className="input-btn btn btn-secondary" type="submit"> Generate </button> </form> { text.length > 0 ? <button className={`btn btn-secondary copy-btn ${buttonStatus}` } onClick={copyToClipBoard}> copy to clipboard </button> : "" } </section> <section className="paragraphs-container d-flex flex-column w-100 justify-content-center align-items-center "> <input className="hidden-input" type="hidden" value={text.join(" <br> ")}/> { text.map((value,index)=>{ return( <p key={index} className="lorem-item"> {value} </p> ) }) } </section> </main> ); } export default App; <file_sep># reactMini_8_loremIpsum This is a lorem ipsum generator that created with React.
79ef52857971cf2c81fc7c9eca89c45ab624546a
[ "JavaScript", "Markdown" ]
2
JavaScript
hadiraz/reactMini_8_loremIpsum
84f9c8c63145bfcb980eee52d89fdd2d7f1e11df
81c474720f6c16638681c00df45b25bf06705197
refs/heads/master
<file_sep>import re import time import os import requests import argparse from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class MusicDownloader(object): AVAILABLE_SITE = ['kugou', 'qq','kuwo'] # AVAILABLE_SITE = ['qq'] URL_REGEX = re.compile(r'https?://\w+.([\w\d]+).com') DEFAULT_SONG_NAME = "千千阙歌" PLAY_TAB_TAG = ['试听', '播放', '正在','单曲'] STORAGE_PATH = './downloads' def __init__(self, *args, **kwargs): self.browser = webdriver.Chrome() self.wait = WebDriverWait(self.browser,10) self.url = kwargs.get('url') self.song_name = kwargs.get('name', MusicDownloader.DEFAULT_SONG_NAME) if not os.path.exists(MusicDownloader.STORAGE_PATH): os.makedirs(MusicDownloader.STORAGE_PATH) def search(self, **kwargs): ''' 百度搜索歌曲 ''' self.browser.get('https://www.baidu.com') self.song_name = kwargs.get('name') or self.song_name kw_input = self.browser.find_element_by_css_selector("#kw") kw_input.send_keys(self.song_name) search_btn = self.browser.find_element_by_css_selector("#su") search_btn.click() i = 1 # # 调试用,因为每次返回的web不是同一个,有些会出现bug # flag = input() # while not flag: # self.browser.refresh() # flag = input() # time.sleep(0.5) # tabs = self.browser.find_elements_by_xpath('//ul[@class="c-tabs-nav-more"]/li[@music-data]') tabs = self.wait.until(EC.presence_of_all_elements_located((By.XPATH,('//ul[@class="c-tabs-nav-more"]/li[@music-data]')))) for source in tabs: self.site_name = source.get_attribute('music-data').split('.')[1] if self.site_name in MusicDownloader.AVAILABLE_SITE: if i>1: source.click() break i += 1 if i > len(tabs): raise Exception("Not supported" % self.song_name) # 表格的情况 try: div = self.wait.until(EC.presence_of_element_located((By.XPATH,'//div[contains(@class,"c-tabs-content")][{}]'.format(i)))) except NoSuchElementException as e: song = self.browser.find_element_by_xpath( '//a[contains(text(),"在线试听")]') try: song = div.find_element_by_xpath( 'table[@class="c-table op-musicsongs-songs"]/tbody/tr[2]/td[4]/a') except NoSuchElementException: song = div.find_element_by_xpath('//a[contains(text(),"在线试听")]') song.click() def switch_play_tab(self): ''' 切换chrome的标签页 ''' if self.site_name == 'qq': time.sleep(3) for window in self.browser.window_handles[::-1]: self.browser.switch_to_window(window) title = self.browser.title for tag in MusicDownloader.PLAY_TAB_TAG: if tag in title: url = self.browser.current_url m = MusicDownloader.URL_REGEX.match(url) if m: self.site_name = m.group(1) return def extract_page(self, page_url=None): """ 从页面中提取url """ if page_url: self.browser.get(page_url) if 'kugou' == self.site_name: # 等待js加载 time.sleep(0.5) audio = self.browser.find_element_by_css_selector('audio#myAudio') singer = ','.join(map(lambda elem: elem.text,self.browser.find_elements_by_xpath('//p[contains(@class,singerName)]/a')[1:])) self.song_name = '%s - %s' %(self.browser.find_element_by_xpath( '//span[@id="songName"]').text,singer) self.url = audio.get_attribute('src') elif 'qq' == self.site_name: time.sleep(1) print(self.browser.current_url) try: self.song_name = '%s - %s' % (self.browser.find_element_by_xpath( '//*[@id="sim_song_info"]/a[1]').text, self.browser.find_element_by_xpath('//*[@id="sim_song_info"]/a[2]').text) except NoSuchElementException: pass self.url = self.browser.find_element_by_xpath( '//*[@id="h5audio_media"]').get_attribute('src') elif 'kuwo' == self.site_name: song_id = 'Music_'+self.browser.current_url.split('?')[0].split('/')[-1] self.url = 'http://antiserver.kuwo.cn/anti.s?format=aac|mp3&rid='+song_id+'&type=convert_url&response=res' self.song_name = ' - '.join(self.browser.title.split('-')[:2]) else: raise Exception("Site not supported") def download(self, audio_url=None): """ 根据页面解析的url下载音频 """ self.url = audio_url or self.url rsp = requests.get(self.url) if 200 == rsp.status_code: path = os.path.join(MusicDownloader.STORAGE_PATH,self.song_name+'.mp3') with open(path, 'wb') as f: f.write(rsp.content) def run(self,name='爱的供养'): try: self.search(name=name) except Exception as e: print(e) return self.switch_play_tab() self.extract_page() self.download() def close(self): self.browser.quit() if __name__ == '__main__': ''' 测试 ''' parser = argparse.ArgumentParser() parser.add_argument('-n','--name',help='Input the song name you want to search') parser.add_argument('-f','--file',help='Specify the path of song list') parser.add_argument('-l','--link',help='Specify the link of the song') args = parser.parse_args() md = MusicDownloader() if args.file: with open(args.file.strip()) as f: for name in f.readlines(): md.run(name) elif args.name: md.run(args.name) elif args.link: md.extract_page(page_url=args.link) md.download() md.close()
87fc26e0079e7bedbb0d81262177e333217a88e5
[ "Python" ]
1
Python
Johnny4Fun/song_downloader
a2531743022d00016e2d388f5398858f5f0dcd39
f8049fcf86c8e0ddf61cb8af9056c6bb8b276dac
refs/heads/master
<file_sep>import React from 'react'; export default function Migration() { return <div>Migration</div>; } <file_sep>using System; using System.Text; namespace dotnet_migration_toolkit.Services { public class PathModel { public string path { get; set; } } } <file_sep>import { combineReducers } from 'redux'; import { GENERATE_REPORT, CLEAR_REPORT, SEARCH_NUGET, SEARCH_NUGET_PACKAGES, } from '../actions/types'; const reducer = (state = null, action) => { switch (action.type) { case GENERATE_REPORT: { const { path, data, reportType } = action.payload; // console.log(data, path); if (reportType === 'html') return { ...state, projectPath: path, report: data }; if (reportType === 'json') return { ...state, projectPath: path, jsonReport: data }; if (reportType === 'excel') return { ...state, projectPath: path, excelReport: true }; return { ...state }; } case CLEAR_REPORT: { return null; } case SEARCH_NUGET: { if (state.nugetRes) state.nugetRes.push(action.payload); else { state.nugetRes = []; state.nugetRes.push(action.payload); } return { ...state }; } case SEARCH_NUGET_PACKAGES: { return { ...state, nugetPackageList: action.payload }; } default: return { ...state }; } }; export default combineReducers({ app: reducer, }); <file_sep>using dotnet_migration_toolkit.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace dotnet_migration_toolkit { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "dotnet_migration_toolkit", Version = "v1" }); }); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); //To allow access with any headers corsBuilder.AllowAnyMethod(); //Using HTTP Post or Get or other HTTP Methods corsBuilder.AllowAnyOrigin(); //To allow access for applications of any origin //To restrict the access from specific domain //corsBuilder.WithOrigins("https://domain:port"); // corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders("content-desposition"); services.AddCors(options => { options.AddPolicy("CorsPolicy", corsBuilder.Build()); }); services.AddSingleton<IMigrationService, MigrationService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "dotnet_migration_toolkit v1")); } app.UseCors("CorsPolicy"); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import { Paper, Typography, Button } from '@material-ui/core'; import { connect } from 'react-redux'; import useStyles from '../utils/styles'; const IFrame = ({ report }) => { const classes = useStyles(); return report ? ( <> <Button component={Link} to="/report" color="secondary"> Go Back &larr; </Button> <Paper className={classes.iFrameContainer} variant="outlined"> <iframe srcDoc={report} title="report output" className={classes.reportIFrame} /> </Paper> </> ) : ( <Paper className="loader"> <Typography color="secondary" variant="h5" style={{ display: 'block' }}> Generating Report </Typography> <br /> <div className="lds-facebook"> <div /> <div /> <div /> </div> </Paper> ); }; const mapStateToProps = state => { const { app: { report }, } = state; return { report, }; }; export default connect(mapStateToProps)(IFrame); <file_sep>export const GENERATE_REPORT = 'GENERATE_REPORT'; export const CLEAR_REPORT = 'CLEAR_REPORT'; export const SEARCH_NUGET = 'SEARCH_NUGET'; export const SEARCH_NUGET_PACKAGES = 'SEARCH_NUGET_PACKAGES'; <file_sep>import axios from 'axios'; import { GENERATE_REPORT, CLEAR_REPORT, SEARCH_NUGET, SEARCH_NUGET_PACKAGES, } from './types'; export const generateReport = (path, reportType) => async dispatch => { const { data } = await axios.post( `http://localhost:5000/api/v1/analyze/${reportType}`, { path, } ); dispatch({ type: GENERATE_REPORT, payload: { data, path, reportType } }); }; // https://localhost:44302 export const clearStore = () => { return { type: CLEAR_REPORT, }; }; export const nugetSearch = (searchTerm, assemblyName) => async dispatch => { const { data } = await axios.get(`https://azuresearch-usnc.nuget.org/query`, { params: { q: searchTerm, prerelease: false, packageType: 'dependency', }, }); // if (!nugetRes) { // nugetRes = []; // nugetRes.push(data.data[0]); // } return dispatch({ type: SEARCH_NUGET, payload: { searchRes: data.data[0], assemblyName }, }); }; export const searchNugetPackages = searchTerm => async dispatch => { const { data } = await axios.get(`https://azuresearch-usnc.nuget.org/query`, { params: { q: searchTerm, prerelease: false, packageType: 'dependency', }, }); return dispatch({ type: SEARCH_NUGET_PACKAGES, payload: data.data, }); }; <file_sep>using dotnet_migration_toolkit.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace dotnet_migration_toolkit.Controllers { [Route("api/v1/")] [ApiController] public class MigrationController : ControllerBase { private readonly IMigrationService _migrationService; public MigrationController(IMigrationService migrationService) { _migrationService = migrationService; } #region Controller Methods [HttpPost] [Route("analyze/json")] public async Task<IActionResult> GetJSONReport([FromBody] PathModel pathModel) { var resString = await _migrationService.GetReport(pathModel.path, "json"); return Ok(resString); } [HttpPost] [Route("analyze/html")] public async Task<IActionResult> GetHTMLReport([FromBody] PathModel pathModel) { var resString = await _migrationService.GetReport(pathModel.path, "html"); return Ok(resString); } [HttpPost] [Route("analyze/excel")] public async Task<IActionResult> GetExcelReport([FromBody] PathModel pathModel) { var resString = await _migrationService.GetReport(pathModel.path, "excel"); return Ok("Success"); } [HttpPost] [Route("analyze/dgml")] public async Task<IActionResult> GetDGMLReport([FromBody] PathModel pathModel) { var resString = await _migrationService.GetReport(pathModel.path, "dgml"); return Ok(resString); } #endregion } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace dotnet_migration_toolkit.Services { public interface IMigrationService { public Task<string> GetReport(string path, string reportType); } public class MigrationService : IMigrationService { #region service methods public async Task<string> GetReport(string path, string reportType) { //if (reportType.ToLower() == "xlsx") //{ // reportType = "excel"; //} if (reportType.ToLower() == "html" && File.Exists(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.html")) { File.Delete(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.html"); } if (reportType.ToLower() == "json" && File.Exists(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.json")) { File.Delete(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.json"); } if (reportType.ToLower() == "dgml" && File.Exists(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.dgml")) { File.Delete(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.dgml"); } using (var process = new Process()) { process.StartInfo.FileName = @$"{Environment.CurrentDirectory}\ApiPort\ApiPort.exe"; // relative path. absolute path works too. if (reportType != "excel") process.StartInfo.Arguments = $"analyze -r {reportType} -f {path}"; else { var downloadPath = path; if (path.Contains(".dll")) { downloadPath = path.Split(".dll")[0]; } process.StartInfo.Arguments = $"analyze -r {reportType} -f {path} -o {downloadPath}\\ExcelReport.xlsx"; } process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += (sender, data) => Console.WriteLine(data.Data); process.ErrorDataReceived += (sender, data) => Console.WriteLine(data.Data); Console.WriteLine("starting"); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); var exited = process.WaitForExit(1000 * 30); // Waiting for the file generation for 30 seconds Console.WriteLine($"exit {exited}"); } if (reportType == "excel") { return "ok"; } var data = File.ReadAllText(@$"{Environment.CurrentDirectory}\ApiPortAnalysis.{reportType}"); var response = data; if (reportType.ToLower() == "json") { var dataObject = JObject.Parse(data); if (!path.Contains("dll")) { var solFilePath = Directory.GetFiles(path, "*.sln"); if (solFilePath.Length > 0) { var solFileLines = File.ReadAllLines(@$"{solFilePath[0]}"); var projList = new ArrayList(); foreach (var line in solFileLines) { if (line.Contains("csproj")) { var projName = line.Split("\\")[1].Split(",")[0]; projList.Add(projName); } } JArray array = new JArray(); for (int i = 0; i < projList.Count; i++) { array.Add(projList[i]); } dataObject["SubProjects"] = array; } } response = dataObject.ToString(); } return response; } #endregion } } <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import { ThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import 'fontsource-roboto'; import reducer from './reducers'; import App from './components/App'; const theme = createMuiTheme({ palette: { primary: { light: '#3a9ce8', main: '#0984e3', dark: '#0876cc', contrastText: '#fff', }, secondary: { light: '#ef706e', main: '#eb4d4b', dark: '#d34543', contrastText: '#fff', }, }, }); const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk))); ReactDOM.render( <Provider store={store}> <ThemeProvider theme={theme}> <App /> </ThemeProvider> </Provider>, document.querySelector('#root') ); <file_sep>import React, { useState } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import Header from './Header'; import Footer from './Footer'; import FileUpload from './FileUpload'; import Report from './Report'; import IFrame from './IFrame'; import Estimation from './Estimation'; import Migration from './Migration'; import SearchNuGet from './SearchNuGet'; const App = () => { const [tabValue, setTabValue] = useState(0); return ( <div> <BrowserRouter> <Header tabValue={tabValue} setTabValue={setTabValue} /> <Route exact path="/"> <FileUpload /> </Route> <Route exact path="/report"> <Report /> </Route> <Route exact path="/report/html"> <IFrame /> </Route> <Route exact path="/estimation"> <Estimation /> </Route> <Route exact path="/migration"> <Migration /> </Route> <Route exact path="/search-nuget"> <SearchNuGet /> </Route> <Footer /> </BrowserRouter> </div> ); }; export default App;
342f1c6bf733b729f867d1f6abcc89c6aa70b3f1
[ "JavaScript", "C#" ]
11
JavaScript
theonly1me/dotnet-migration-toolkit-ui
be95efa6800dd1d209949b61790880c804d43816
5803d6736c3844931ac90ac59eeafa4db64ece95
refs/heads/master
<file_sep>package com.riseapps.marusyaobjloader.model.material; import java.util.Arrays; public class TextureOptionModel { private TextureType type; private float sharpness; private float brightness; private float contrast; private float[] originOffset; private float[] scale; private float[] turbulence; private boolean clamp; private char imfchan; private boolean blendU; private boolean blendV; private float bumpMultiplier; private String colorspace; public TextureOptionModel() { } public TextureType getType() { return type; } public float getSharpness() { return sharpness; } public float getBrightness() { return brightness; } public float getContrast() { return contrast; } public float[] getOriginOffset() { return originOffset; } public float[] getScale() { return scale; } public float[] getTurbulence() { return turbulence; } public boolean isClamp() { return clamp; } public char getImfchan() { return imfchan; } public boolean isBlendU() { return blendU; } public boolean isBlendV() { return blendV; } public float getBumpMultiplier() { return bumpMultiplier; } public String getColorspace() { return colorspace; } @Override public String toString() { return "TextureOptionModel{" + "type=" + type + ", sharpness=" + sharpness + ", brightness=" + brightness + ", contrast=" + contrast + ", originOffset=" + Arrays.toString(originOffset) + ", scale=" + Arrays.toString(scale) + ", turbulence=" + Arrays.toString(turbulence) + ", clamp=" + clamp + ", imfchan='" + imfchan + '\'' + ", blendU=" + blendU + ", blendV=" + blendV + ", bumpMultiplier=" + bumpMultiplier + ", colorspace='" + colorspace + '\'' + '}'; } }<file_sep>cmake_minimum_required(VERSION 3.6.0) add_library(obj_loader_jni SHARED obj_loader_jni.cpp) target_link_libraries(obj_loader_jni android log)<file_sep>package com.riseapps.objloaderjni; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private static int READ_EXTERNAL_STORAGE_REQUEST_CODE = 322; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.am_load_3d_model).setOnClickListener((view) -> ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE)); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { ResultActivity.start(this); } else { finish(); } } }<file_sep>package com.riseapps.objloaderjni; import com.riseapps.marusyaobjloader.model.ResultModel; public interface ProgressListener { void preLoad(); void onFinish(ResultModel resultModel, long time); void onError(String error); } <file_sep>include ':app', ':marusyaobjloader' <file_sep>#define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <jni.h> #include <android/log.h> #include <chrono> #define LOG_TAG "MarusyaObjLoader" const int VERTICES_NUM_COMPONENTS = 3; const int NORMALS_NUM_COMPONENTS = 3; const int TEX_COORDS_NUM_COMPONENTS = 2; bool print_log = true; typedef struct { jclass j_result_model_class; jmethodID j_result_model_constructor; jfieldID j_shape_models_field_id; jfieldID j_material_models_field_id; jfieldID j_warn_field_id; jfieldID j_error_field_id; } RESULT_MODEL_JNI; typedef struct { jclass j_shape_model_class; jmethodID j_shape_model_constructor; jfieldID j_name_field_id; jfieldID j_mesh_model_field_id; } SHAPE_MODEL_JNI; typedef struct { jclass j_mesh_model_class; jmethodID j_mesh_model_constructor; jfieldID j_vertices_field_id; jfieldID j_indices_field_id; jfieldID j_vertices_size_field_id; jfieldID j_normals_size_field_id; jfieldID j_texcoords_size_field_id; } MESH_MODEL_JNI; typedef struct { jclass j_material_model_class; jmethodID j_material_model_constructor; jfieldID j_name_field_id; jfieldID j_ambient_field_id; jfieldID j_diffuse_field_id; jfieldID j_specular_field_id; jfieldID j_transmittance_field_id; jfieldID j_emission_field_id; jfieldID j_shininess_field_id; jfieldID j_ior_field_id; jfieldID j_dissolve_field_id; jfieldID j_illum_field_id; jfieldID j_dummy_field_id; jfieldID j_ambient_texname_field_id; jfieldID j_diffuse_texname_field_id; jfieldID j_specular_texname_field_id; jfieldID j_specular_highlight_texname_field_id; jfieldID j_bump_texname_field_id; jfieldID j_displacement_texname_field_id; jfieldID j_alpha_texname_field_id; jfieldID j_reflection_texname_field_id; jfieldID j_ambient_texopt_field_id; jfieldID j_diffuse_texopt_field_id; jfieldID j_specular_texopt_field_id; jfieldID j_specular_highlight_texopt_field_id; jfieldID j_bump_texopt_field_id; jfieldID j_displacement_texopt_field_id; jfieldID j_alpha_texopt_field_id; jfieldID j_reflection_texopt_field_id; jfieldID j_roughness_field_id; jfieldID j_metallic_field_id; jfieldID j_sheen_field_id; jfieldID j_clearcoat_thickness_field_id; jfieldID j_clearcoat_roughness_field_id; jfieldID j_anisotropy_field_id; jfieldID j_anisotropy_rotation_field_id; jfieldID j_pad0_field_id; jfieldID j_roughness_texname_field_id; jfieldID j_metallic_texname_field_id; jfieldID j_sheen_texname_field_id; jfieldID j_emissive_texname_field_id; jfieldID j_normal_texname_field_id; jfieldID j_roughness_texopt_field_id; jfieldID j_metallic_texopt_field_id; jfieldID j_sheen_texopt_field_id; jfieldID j_emissive_texopt_field_id; jfieldID j_normal_texopt_field_id; jfieldID j_pad2_field_id; jfieldID j_unknown_parameter_field_id; } MATERIAL_MODEL_JNI; typedef struct { jclass j_texture_option_model_class; jmethodID j_texture_option_model_constructor; jfieldID j_type_field_id; jfieldID j_sharpness_field_id; jfieldID j_brightness_field_id; jfieldID j_contrast_field_id; jfieldID j_origin_offset_field_id; jfieldID j_scale_field_id; jfieldID j_turbulence_field_id; jfieldID j_clamp_field_id; jfieldID j_imfchan_field_id; jfieldID j_blend_u_field_id; jfieldID j_blend_v_field_id; jfieldID j_bump_multiplier_field_id; jfieldID j_colorspace_field_id; } TEXTURE_OPTION_MODEL_JNI; typedef struct { jclass j_texture_type_class; jfieldID j_texture_type_none_field_id; jfieldID j_texture_type_sphere_field_id; jfieldID j_texture_type_cube_top_field_id; jfieldID j_texture_type_cube_bottom_field_id; jfieldID j_texture_type_cube_front_field_id; jfieldID j_texture_type_cube_back_field_id; jfieldID j_texture_type_cube_left_field_id; jfieldID j_texture_type_cube_right_field_id; } TEXTURE_TYPE_JNI; typedef struct { jclass j_hash_map_class; jmethodID j_hash_map_constructor; jmethodID j_hash_map_put; } HASH_MAP_JNI; RESULT_MODEL_JNI * result_model_jni = nullptr; SHAPE_MODEL_JNI * shape_model_jni = nullptr; MESH_MODEL_JNI * mesh_model_jni = nullptr; MATERIAL_MODEL_JNI * material_model_jni = nullptr; TEXTURE_OPTION_MODEL_JNI * texture_option_model_jni = nullptr; TEXTURE_TYPE_JNI * texture_type_jni = nullptr; HASH_MAP_JNI * hash_map_jni = nullptr; void LoadResultModelJNIDetails(JNIEnv * env) { result_model_jni = new RESULT_MODEL_JNI; result_model_jni->j_result_model_class = env->FindClass("com/riseapps/marusyaobjloader/model/ResultModel"); result_model_jni->j_result_model_constructor = env->GetMethodID(result_model_jni->j_result_model_class, "<init>", "()V"); result_model_jni->j_shape_models_field_id = env->GetFieldID(result_model_jni->j_result_model_class, "shapeModels", "[Lcom/riseapps/marusyaobjloader/model/mesh/ShapeModel;"); result_model_jni->j_material_models_field_id = env->GetFieldID(result_model_jni->j_result_model_class, "materialModels", "[Lcom/riseapps/marusyaobjloader/model/material/MaterialModel;"); result_model_jni->j_warn_field_id = env->GetFieldID(result_model_jni->j_result_model_class, "warn", "Ljava/lang/String;"); result_model_jni->j_error_field_id = env->GetFieldID(result_model_jni->j_result_model_class, "error", "Ljava/lang/String;"); } void LoadShapeModelJNIDetails(JNIEnv * env) { shape_model_jni = new SHAPE_MODEL_JNI; shape_model_jni->j_shape_model_class = env->FindClass("com/riseapps/marusyaobjloader/model/mesh/ShapeModel"); shape_model_jni->j_shape_model_constructor = env->GetMethodID(shape_model_jni->j_shape_model_class, "<init>", "()V"); shape_model_jni->j_name_field_id = env->GetFieldID(shape_model_jni->j_shape_model_class, "name", "Ljava/lang/String;"); shape_model_jni->j_mesh_model_field_id = env->GetFieldID(shape_model_jni->j_shape_model_class, "meshModel", "Lcom/riseapps/marusyaobjloader/model/mesh/MeshModel;"); } void LoadMeshModelJNIDetails(JNIEnv * env) { mesh_model_jni = new MESH_MODEL_JNI; mesh_model_jni->j_mesh_model_class = env->FindClass("com/riseapps/marusyaobjloader/model/mesh/MeshModel"); mesh_model_jni->j_mesh_model_constructor = env->GetMethodID(mesh_model_jni->j_mesh_model_class, "<init>", "()V"); mesh_model_jni->j_vertices_field_id = env->GetFieldID(mesh_model_jni->j_mesh_model_class, "vertices", "[F"); mesh_model_jni->j_indices_field_id = env->GetFieldID(mesh_model_jni->j_mesh_model_class, "indices", "[I"); mesh_model_jni->j_vertices_size_field_id = env->GetFieldID(mesh_model_jni->j_mesh_model_class, "verticesSize", "J"); mesh_model_jni->j_normals_size_field_id = env->GetFieldID(mesh_model_jni->j_mesh_model_class, "normalsSize", "J"); mesh_model_jni->j_texcoords_size_field_id = env->GetFieldID(mesh_model_jni->j_mesh_model_class, "texcoordsSize", "J"); } void LoadMaterialModelJNIDetails(JNIEnv * env) { material_model_jni = new MATERIAL_MODEL_JNI; material_model_jni->j_material_model_class = env->FindClass("com/riseapps/marusyaobjloader/model/material/MaterialModel"); material_model_jni->j_material_model_constructor = env->GetMethodID(material_model_jni->j_material_model_class, "<init>", "()V"); material_model_jni->j_name_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "name", "Ljava/lang/String;"); material_model_jni->j_ambient_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "ambient", "[F"); material_model_jni->j_diffuse_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "diffuse", "[F"); material_model_jni->j_specular_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "specular", "[F"); material_model_jni->j_transmittance_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "transmittance", "[F"); material_model_jni->j_emission_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "emission", "[F"); material_model_jni->j_shininess_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "shininess", "F"); material_model_jni->j_ior_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "ior", "F"); material_model_jni->j_dissolve_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "dissolve", "F"); material_model_jni->j_illum_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "illum", "I"); material_model_jni->j_dummy_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "dummy", "I"); material_model_jni->j_ambient_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "ambientTexname", "Ljava/lang/String;"); material_model_jni->j_diffuse_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "diffuseTexname", "Ljava/lang/String;"); material_model_jni->j_specular_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "specularTexname", "Ljava/lang/String;"); material_model_jni->j_specular_highlight_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "specularHighlightTexname", "Ljava/lang/String;"); material_model_jni->j_bump_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "bumpTexname", "Ljava/lang/String;"); material_model_jni->j_displacement_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "displacementTexname", "Ljava/lang/String;"); material_model_jni->j_alpha_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "alphaTexname", "Ljava/lang/String;"); material_model_jni->j_reflection_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "reflectionTexname", "Ljava/lang/String;"); material_model_jni->j_ambient_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "ambientTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_diffuse_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "diffuseTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_specular_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "specularTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_specular_highlight_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "specularHighlightTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_bump_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "bumpTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_displacement_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "displacementTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_alpha_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "alphaTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_reflection_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "reflectionTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_roughness_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "roughness", "F"); material_model_jni->j_metallic_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "metallic", "F"); material_model_jni->j_sheen_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "sheen", "F"); material_model_jni->j_clearcoat_thickness_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "clearcoatThickness", "F"); material_model_jni->j_clearcoat_roughness_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "clearcoatRoughness", "F"); material_model_jni->j_anisotropy_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "anisotropy", "F"); material_model_jni->j_anisotropy_rotation_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "anisotropyRotation", "F"); material_model_jni->j_pad0_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "pad0", "F"); material_model_jni->j_roughness_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "roughnessTexname", "Ljava/lang/String;"); material_model_jni->j_metallic_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "metallicTexname", "Ljava/lang/String;"); material_model_jni->j_sheen_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "sheenTexname", "Ljava/lang/String;"); material_model_jni->j_emissive_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "emissiveTexname", "Ljava/lang/String;"); material_model_jni->j_normal_texname_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "normalTexname", "Ljava/lang/String;"); material_model_jni->j_roughness_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "roughnessTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_metallic_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "metallicTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_sheen_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "sheenTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_emissive_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "emissiveTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_normal_texopt_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "normalTexopt", "Lcom/riseapps/marusyaobjloader/model/material/TextureOptionModel;"); material_model_jni->j_pad2_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "pad2", "I"); material_model_jni->j_unknown_parameter_field_id = env->GetFieldID(material_model_jni->j_material_model_class, "unknownParameter", "Ljava/util/HashMap;"); } void LoadTextureOptionModelJNIDetails(JNIEnv * env) { texture_option_model_jni = new TEXTURE_OPTION_MODEL_JNI; texture_option_model_jni->j_texture_option_model_class = env->FindClass("com/riseapps/marusyaobjloader/model/material/TextureOptionModel"); texture_option_model_jni->j_texture_option_model_constructor = env->GetMethodID(texture_option_model_jni->j_texture_option_model_class, "<init>", "()V"); texture_option_model_jni->j_type_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "type", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_option_model_jni->j_sharpness_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "sharpness", "F"); texture_option_model_jni->j_brightness_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "brightness", "F"); texture_option_model_jni->j_contrast_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "contrast", "F"); texture_option_model_jni->j_origin_offset_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "originOffset", "[F"); texture_option_model_jni->j_scale_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "scale", "[F"); texture_option_model_jni->j_turbulence_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "turbulence", "[F"); texture_option_model_jni->j_clamp_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "clamp", "Z"); texture_option_model_jni->j_imfchan_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "imfchan", "C"); texture_option_model_jni->j_blend_u_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "blendU", "Z"); texture_option_model_jni->j_blend_v_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "blendV", "Z"); texture_option_model_jni->j_bump_multiplier_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "bumpMultiplier", "F"); texture_option_model_jni->j_colorspace_field_id = env->GetFieldID(texture_option_model_jni->j_texture_option_model_class, "colorspace", "Ljava/lang/String;"); } void LoadTextureTypeJNIDetails(JNIEnv * env) { texture_type_jni = new TEXTURE_TYPE_JNI; texture_type_jni->j_texture_type_class = env->FindClass("com/riseapps/marusyaobjloader/model/material/TextureType"); texture_type_jni->j_texture_type_none_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_NONE", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_sphere_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_SPHERE", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_top_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_TOP", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_bottom_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_BOTTOM", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_front_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_FRONT", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_back_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_BACK", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_left_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_LEFT", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); texture_type_jni->j_texture_type_cube_right_field_id = env->GetStaticFieldID(texture_type_jni->j_texture_type_class, "TEXTURE_TYPE_CUBE_RIGHT", "Lcom/riseapps/marusyaobjloader/model/material/TextureType;"); } void LoadHashMapJNIDetails(JNIEnv *env) { hash_map_jni = new HASH_MAP_JNI; hash_map_jni->j_hash_map_class = env->FindClass("java/util/HashMap"); hash_map_jni->j_hash_map_constructor = env->GetMethodID(hash_map_jni->j_hash_map_class, "<init>", "(I)V"); hash_map_jni->j_hash_map_put = env->GetMethodID(hash_map_jni->j_hash_map_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); } void ReleaseJNIDetails() { if (result_model_jni != nullptr) { delete result_model_jni; result_model_jni = nullptr; } if (shape_model_jni != nullptr) { delete shape_model_jni; shape_model_jni = nullptr; } if (mesh_model_jni != nullptr) { delete mesh_model_jni; mesh_model_jni = nullptr; } if (texture_option_model_jni != nullptr) { delete texture_option_model_jni; texture_option_model_jni = nullptr; } if (texture_type_jni != nullptr) { delete texture_type_jni; texture_type_jni = nullptr; } if (hash_map_jni != nullptr) { delete hash_map_jni; hash_map_jni = nullptr; } } void LoadJNIDetails(JNIEnv * env) { LoadResultModelJNIDetails(env); LoadShapeModelJNIDetails(env); LoadMeshModelJNIDetails(env); LoadMaterialModelJNIDetails(env); LoadTextureOptionModelJNIDetails(env); LoadTextureTypeJNIDetails(env); LoadHashMapJNIDetails(env); } std::string GetBaseDir(const std::string &filepath) { if (filepath.find_last_of("/\\") != std::string::npos) { return filepath.substr(0, filepath.find_last_of("/\\")) + "/"; } else { return ""; } } jobject GenerateResultModelDueToError(JNIEnv * env, const std::string &err) { jobject j_result_model = env->NewObject(result_model_jni->j_result_model_class, result_model_jni->j_result_model_constructor); jstring j_error = env->NewStringUTF(err.c_str()); env->SetObjectField(j_result_model, result_model_jni->j_error_field_id, j_error); return j_result_model; } void GenerateShapeModels(JNIEnv * env, jobject &j_result_model, const tinyobj::attrib_t &attrib, const std::vector<tinyobj::shape_t> &shapes, const jfloat normalize_coefficient, const jboolean flip_texcoords) { jobjectArray shape_models = env->NewObjectArray((jsize) shapes.size(), shape_model_jni->j_shape_model_class, nullptr); for (size_t s = 0; s < shapes.size(); s++) { jobject j_shape_model = env->NewObject(shape_model_jni->j_shape_model_class, shape_model_jni->j_shape_model_constructor); jobject j_mesh_model = env->NewObject(mesh_model_jni->j_mesh_model_class, mesh_model_jni->j_mesh_model_constructor); // vertices tinyobj::shape_t shape = shapes[s]; unsigned long vertices_size = (!attrib.vertices.empty() ? shape.mesh.indices.size() * VERTICES_NUM_COMPONENTS : 0) + (!attrib.normals.empty() ? shape.mesh.indices.size() * NORMALS_NUM_COMPONENTS : 0) + (!attrib.texcoords.empty() ? shape.mesh.indices.size() * TEX_COORDS_NUM_COMPONENTS : 0); jfloatArray vertices_array = env->NewFloatArray((jsize) vertices_size); jboolean is_copy_vertices; jfloat *body_vertices = env->GetFloatArrayElements(vertices_array, &is_copy_vertices); // indices jintArray indices_array = env->NewIntArray((jsize) shape.mesh.indices.size()); jboolean is_copy_indices; jint *body_indices = env->GetIntArrayElements(indices_array, &is_copy_indices); size_t vertices_count = 0; size_t index_offset = 0; for (size_t f = 0; f < shape.mesh.num_face_vertices.size(); f++) { int fv = shape.mesh.num_face_vertices[f]; for (size_t v = 0; v < fv; v++) { tinyobj::index_t idx = shape.mesh.indices[index_offset + v]; for (size_t vn = 0; vn < VERTICES_NUM_COMPONENTS; vn++) { tinyobj::real_t vertex = attrib.vertices[VERTICES_NUM_COMPONENTS * idx.vertex_index + vn]; body_vertices[vertices_count] = vertex / normalize_coefficient; vertices_count++; } if (!attrib.normals.empty()) { for (size_t nn = 0; nn < NORMALS_NUM_COMPONENTS; nn++) { tinyobj::real_t normal = attrib.normals[NORMALS_NUM_COMPONENTS * idx.normal_index + nn]; body_vertices[vertices_count] = normal; vertices_count++; } } if (!attrib.texcoords.empty()) { for (size_t tcn = 0; tcn < TEX_COORDS_NUM_COMPONENTS; tcn++) { tinyobj::real_t tex_coord = attrib.texcoords[TEX_COORDS_NUM_COMPONENTS * idx.texcoord_index + tcn]; body_vertices[vertices_count] = flip_texcoords ? 1 - tex_coord : tex_coord; vertices_count++; } } } index_offset += fv; } for (size_t i = 0; i < shape.mesh.indices.size(); i++) { body_indices[i] = (jshort) i; } // mesh model env->SetFloatArrayRegion(vertices_array, 0, env->GetArrayLength(vertices_array), body_vertices); env->SetIntArrayRegion(indices_array, 0, env->GetArrayLength(indices_array), body_indices); // vertices field env->SetObjectField(j_mesh_model, mesh_model_jni->j_vertices_field_id, vertices_array); // indices field env->SetObjectField(j_mesh_model, mesh_model_jni->j_indices_field_id, indices_array); // vertices size field env->SetLongField(j_mesh_model, mesh_model_jni->j_vertices_size_field_id, shape.mesh.indices.size() * VERTICES_NUM_COMPONENTS); // normals size field env->SetLongField(j_mesh_model, mesh_model_jni->j_normals_size_field_id, shape.mesh.indices.size() * NORMALS_NUM_COMPONENTS); // texcoords size field env->SetLongField(j_mesh_model, mesh_model_jni->j_texcoords_size_field_id, shape.mesh.indices.size() * TEX_COORDS_NUM_COMPONENTS); // shape model // name field env->SetObjectField(j_shape_model, shape_model_jni->j_name_field_id, env->NewStringUTF(shape.name.c_str())); // mesh model field env->SetObjectField(j_shape_model, shape_model_jni->j_mesh_model_field_id, j_mesh_model); // shape model field env->SetObjectArrayElement(shape_models, (jsize) s, j_shape_model); } // shape models field env->SetObjectField(j_result_model, result_model_jni->j_shape_models_field_id, shape_models); } void SetMaterialAmbientField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jfloatArray j_ambient_array = env->NewFloatArray((jsize) sizeof(material.ambient) / sizeof(material.ambient[0])); jboolean is_copy_ambient; jfloat *body_ambient = env->GetFloatArrayElements(j_ambient_array, &is_copy_ambient); for (size_t i = 0; i < sizeof(material.ambient) / sizeof(material.ambient[0]); i++) { body_ambient[i] = material.ambient[i]; } env->SetFloatArrayRegion(j_ambient_array, 0, env->GetArrayLength(j_ambient_array), body_ambient); env->SetObjectField(j_material_model, material_model_jni->j_ambient_field_id, j_ambient_array); } void SetMaterialDiffuseField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jfloatArray j_diffuse_array = env->NewFloatArray((jsize) sizeof(material.diffuse) / sizeof(material.diffuse[0])); jboolean is_copy_diffuse; jfloat *body_diffuse = env->GetFloatArrayElements(j_diffuse_array, &is_copy_diffuse); for (size_t i = 0; i < sizeof(material.diffuse) / sizeof(material.diffuse[0]); i++) { body_diffuse[i] = material.diffuse[i]; } env->SetFloatArrayRegion(j_diffuse_array, 0, env->GetArrayLength(j_diffuse_array), body_diffuse); env->SetObjectField(j_material_model, material_model_jni->j_diffuse_field_id, j_diffuse_array); } void SetMaterialSpecularField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jfloatArray j_specular_array = env->NewFloatArray((jsize) sizeof(material.specular) / sizeof(material.specular[0])); jboolean is_copy_specular; jfloat *body_specular = env->GetFloatArrayElements(j_specular_array, &is_copy_specular); for (size_t i = 0; i < sizeof(material.specular) / sizeof(material.specular[0]); i++) { body_specular[i] = material.specular[i]; } env->SetFloatArrayRegion(j_specular_array, 0, env->GetArrayLength(j_specular_array), body_specular); env->SetObjectField(j_material_model, material_model_jni->j_specular_field_id, j_specular_array); } void SetMaterialTransmittanceField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jfloatArray j_transmittance_array = env->NewFloatArray((jsize) sizeof(material.transmittance) / sizeof(material.transmittance[0])); jboolean is_copy_transmittance; jfloat *body_transmittance = env->GetFloatArrayElements(j_transmittance_array, &is_copy_transmittance); for (size_t i = 0; i < sizeof(material.transmittance) / sizeof(material.transmittance[0]); i++) { body_transmittance[i] = material.transmittance[i]; } env->SetFloatArrayRegion(j_transmittance_array, 0, env->GetArrayLength(j_transmittance_array), body_transmittance); env->SetObjectField(j_material_model, material_model_jni->j_transmittance_field_id, j_transmittance_array); } void SetMaterialEmissionField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jfloatArray j_emission_array = env->NewFloatArray((jsize) sizeof(material.emission) / sizeof(material.emission[0])); jboolean is_copy_emission; jfloat *body_emission = env->GetFloatArrayElements(j_emission_array, &is_copy_emission); for (size_t i = 0; i < sizeof(material.emission) / sizeof(material.emission[0]); i++) { body_emission[i] = material.emission[i]; } env->SetFloatArrayRegion(j_emission_array, 0, env->GetArrayLength(j_emission_array), body_emission); env->SetObjectField(j_material_model, material_model_jni->j_emission_field_id, j_emission_array); } void SetMaterialShininessField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_shininess_field_id, material.shininess); } void SetMaterialIorField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_ior_field_id, material.ior); } void SetMaterialDissolveField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_dissolve_field_id, material.dissolve); } void SetMaterialIllumField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetIntField(j_material_model, material_model_jni->j_illum_field_id, material.illum); } void SetMaterialDummyField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetIntField(j_material_model, material_model_jni->j_dummy_field_id, material.dummy); } void SetMaterialAmbientTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_ambient_texname_field_id, env->NewStringUTF(material.ambient_texname.c_str())); } void SetMaterialDiffuseTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_diffuse_texname_field_id, env->NewStringUTF(material.diffuse_texname.c_str())); } void SetMaterialSpecularTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_specular_texname_field_id, env->NewStringUTF(material.specular_texname.c_str())); } void SetMaterialSpecularHighlightTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_specular_highlight_texname_field_id, env->NewStringUTF(material.specular_highlight_texname.c_str())); } void SetMaterialBumpTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_bump_texname_field_id, env->NewStringUTF(material.bump_texname.c_str())); } void SetMaterialDisplacementTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_displacement_texname_field_id, env->NewStringUTF(material.displacement_texname.c_str())); } void SetMaterialAlphaTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_alpha_texname_field_id, env->NewStringUTF(material.alpha_texname.c_str())); } void SetMaterialReflectionTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_reflection_texname_field_id, env->NewStringUTF(material.reflection_texname.c_str())); } void SetMaterialAmbientTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_ambient_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_ambient_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_ambient_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_ambient_texopt_model, texture_option_model_jni->j_type_field_id, j_ambient_texture_type); // sharpness field env->SetFloatField(j_ambient_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.ambient_texopt.sharpness); // brightness field env->SetFloatField(j_ambient_texopt_model, texture_option_model_jni->j_brightness_field_id, material.ambient_texopt.brightness); // contrast field env->SetFloatField(j_ambient_texopt_model, texture_option_model_jni->j_contrast_field_id, material.ambient_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.ambient_texopt.origin_offset) / sizeof(material.ambient_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.ambient_texopt.origin_offset) / sizeof(material.ambient_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.ambient_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_ambient_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.ambient_texopt.scale) / sizeof(material.ambient_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.ambient_texopt.scale) / sizeof(material.ambient_texopt.scale[0]); i++) { body_scale[i] = material.ambient_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_ambient_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.ambient_texopt.turbulence) / sizeof(material.ambient_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.ambient_texopt.turbulence) / sizeof(material.ambient_texopt.turbulence[0]); i++) { body_turbulence[i] = material.ambient_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_ambient_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_ambient_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.ambient_texopt.clamp); // imfchan field env->SetCharField(j_ambient_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.ambient_texopt.imfchan); // blendu field env->SetBooleanField(j_ambient_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.ambient_texopt.blendu); // blendv field env->SetBooleanField(j_ambient_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.ambient_texopt.blendv); // colorspace field env->SetObjectField(j_ambient_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.ambient_texopt.colorspace.c_str())); // ambient texopt field env->SetObjectField(j_material_model, material_model_jni->j_ambient_texopt_field_id, j_ambient_texopt_model); } void SetMaterialDiffuseTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_diffuse_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_diffuse_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_diffuse_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_diffuse_texopt_model, texture_option_model_jni->j_type_field_id, j_diffuse_texture_type); // sharpness field env->SetFloatField(j_diffuse_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.diffuse_texopt.sharpness); // brightness field env->SetFloatField(j_diffuse_texopt_model, texture_option_model_jni->j_brightness_field_id, material.diffuse_texopt.brightness); // contrast field env->SetFloatField(j_diffuse_texopt_model, texture_option_model_jni->j_contrast_field_id, material.diffuse_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.diffuse_texopt.origin_offset) / sizeof(material.diffuse_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.diffuse_texopt.origin_offset) / sizeof(material.diffuse_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.diffuse_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_diffuse_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.diffuse_texopt.scale) / sizeof(material.diffuse_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.diffuse_texopt.scale) / sizeof(material.diffuse_texopt.scale[0]); i++) { body_scale[i] = material.diffuse_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_diffuse_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.diffuse_texopt.turbulence) / sizeof(material.diffuse_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.diffuse_texopt.turbulence) / sizeof(material.diffuse_texopt.turbulence[0]); i++) { body_turbulence[i] = material.diffuse_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_diffuse_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_diffuse_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.diffuse_texopt.clamp); // imfchan field env->SetCharField(j_diffuse_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.diffuse_texopt.imfchan); // blendu field env->SetBooleanField(j_diffuse_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.diffuse_texopt.blendu); // blendv field env->SetBooleanField(j_diffuse_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.diffuse_texopt.blendv); // colorspace field env->SetObjectField(j_diffuse_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.diffuse_texopt.colorspace.c_str())); // diffuse texopt field env->SetObjectField(j_material_model, material_model_jni->j_diffuse_texopt_field_id, j_diffuse_texopt_model); } void SetMaterialSpecularTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_specular_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_specular_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_specular_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_specular_texopt_model, texture_option_model_jni->j_type_field_id, j_specular_texture_type); // sharpness field env->SetFloatField(j_specular_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.specular_texopt.sharpness); // brightness field env->SetFloatField(j_specular_texopt_model, texture_option_model_jni->j_brightness_field_id, material.specular_texopt.brightness); // contrast field env->SetFloatField(j_specular_texopt_model, texture_option_model_jni->j_contrast_field_id, material.specular_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.specular_texopt.origin_offset) / sizeof(material.specular_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.specular_texopt.origin_offset) / sizeof(material.specular_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.specular_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_specular_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.specular_texopt.scale) / sizeof(material.specular_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.specular_texopt.scale) / sizeof(material.specular_texopt.scale[0]); i++) { body_scale[i] = material.specular_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_specular_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.specular_texopt.turbulence) / sizeof(material.specular_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.specular_texopt.turbulence) / sizeof(material.specular_texopt.turbulence[0]); i++) { body_turbulence[i] = material.specular_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_specular_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_specular_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.specular_texopt.clamp); // imfchan field env->SetCharField(j_specular_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.specular_texopt.imfchan); // blendu field env->SetBooleanField(j_specular_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.specular_texopt.blendu); // blendv field env->SetBooleanField(j_specular_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.specular_texopt.blendv); // colorspace field env->SetObjectField(j_specular_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.specular_texopt.colorspace.c_str())); // specular texopt field env->SetObjectField(j_material_model, material_model_jni->j_specular_texopt_field_id, j_specular_texopt_model); } void SetMaterialSpecularHighlightTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_specular_highlight_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_specular_highlight_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_specular_highlight_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_specular_highlight_texopt_model, texture_option_model_jni->j_type_field_id, j_specular_highlight_texture_type); // sharpness field env->SetFloatField(j_specular_highlight_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.specular_highlight_texopt.sharpness); // brightness field env->SetFloatField(j_specular_highlight_texopt_model, texture_option_model_jni->j_brightness_field_id, material.specular_highlight_texopt.brightness); // contrast field env->SetFloatField(j_specular_highlight_texopt_model, texture_option_model_jni->j_contrast_field_id, material.specular_highlight_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.specular_highlight_texopt.origin_offset) / sizeof(material.specular_highlight_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.specular_highlight_texopt.origin_offset) / sizeof(material.specular_highlight_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.specular_highlight_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_specular_highlight_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.specular_highlight_texopt.scale) / sizeof(material.specular_highlight_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.specular_highlight_texopt.scale) / sizeof(material.specular_highlight_texopt.scale[0]); i++) { body_scale[i] = material.specular_highlight_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_specular_highlight_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.specular_highlight_texopt.turbulence) / sizeof(material.specular_highlight_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.specular_highlight_texopt.turbulence) / sizeof(material.specular_highlight_texopt.turbulence[0]); i++) { body_turbulence[i] = material.specular_highlight_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_specular_highlight_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_specular_highlight_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.specular_highlight_texopt.clamp); // imfchan field env->SetCharField(j_specular_highlight_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.specular_highlight_texopt.imfchan); // blendu field env->SetBooleanField(j_specular_highlight_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.specular_highlight_texopt.blendu); // blendv field env->SetBooleanField(j_specular_highlight_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.specular_highlight_texopt.blendv); // colorspace field env->SetObjectField(j_specular_highlight_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.specular_highlight_texopt.colorspace.c_str())); // specular highlight texopt field env->SetObjectField(j_material_model, material_model_jni->j_specular_highlight_texopt_field_id, j_specular_highlight_texopt_model); } void SetMaterialBumpTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_bump_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_bump_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_bump_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_bump_texopt_model, texture_option_model_jni->j_type_field_id, j_bump_texture_type); // sharpness field env->SetFloatField(j_bump_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.bump_texopt.sharpness); // brightness field env->SetFloatField(j_bump_texopt_model, texture_option_model_jni->j_brightness_field_id, material.bump_texopt.brightness); // contrast field env->SetFloatField(j_bump_texopt_model, texture_option_model_jni->j_contrast_field_id, material.bump_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.bump_texopt.origin_offset) / sizeof(material.bump_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.bump_texopt.origin_offset) / sizeof(material.bump_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.bump_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_bump_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.bump_texopt.scale) / sizeof(material.bump_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.bump_texopt.scale) / sizeof(material.bump_texopt.scale[0]); i++) { body_scale[i] = material.bump_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_bump_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.bump_texopt.turbulence) / sizeof(material.bump_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.bump_texopt.turbulence) / sizeof(material.bump_texopt.turbulence[0]); i++) { body_turbulence[i] = material.bump_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_bump_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_bump_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.bump_texopt.clamp); // imfchan field env->SetCharField(j_bump_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.bump_texopt.imfchan); // blendu field env->SetBooleanField(j_bump_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.bump_texopt.blendu); // blendv field env->SetBooleanField(j_bump_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.bump_texopt.blendv); // colorspace field env->SetObjectField(j_bump_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.bump_texopt.colorspace.c_str())); // bump texopt field env->SetObjectField(j_material_model, material_model_jni->j_bump_texopt_field_id, j_bump_texopt_model); } void SetMaterialDisplacementTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_displacement_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_displacement_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_displacement_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_displacement_texopt_model, texture_option_model_jni->j_type_field_id, j_displacement_texture_type); // sharpness field env->SetFloatField(j_displacement_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.displacement_texopt.sharpness); // brightness field env->SetFloatField(j_displacement_texopt_model, texture_option_model_jni->j_brightness_field_id, material.displacement_texopt.brightness); // contrast field env->SetFloatField(j_displacement_texopt_model, texture_option_model_jni->j_contrast_field_id, material.displacement_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.displacement_texopt.origin_offset) / sizeof(material.displacement_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.displacement_texopt.origin_offset) / sizeof(material.displacement_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.displacement_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_displacement_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.displacement_texopt.scale) / sizeof(material.displacement_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.displacement_texopt.scale) / sizeof(material.displacement_texopt.scale[0]); i++) { body_scale[i] = material.displacement_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_displacement_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.displacement_texopt.turbulence) / sizeof(material.displacement_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.displacement_texopt.turbulence) / sizeof(material.displacement_texopt.turbulence[0]); i++) { body_turbulence[i] = material.displacement_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_displacement_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_displacement_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.displacement_texopt.clamp); // imfchan field env->SetCharField(j_displacement_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.displacement_texopt.imfchan); // blendu field env->SetBooleanField(j_displacement_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.displacement_texopt.blendu); // blendv field env->SetBooleanField(j_displacement_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.displacement_texopt.blendv); // colorspace field env->SetObjectField(j_displacement_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.displacement_texopt.colorspace.c_str())); // displacement texopt field env->SetObjectField(j_material_model, material_model_jni->j_displacement_texopt_field_id, j_displacement_texopt_model); } void SetMaterialAlphaTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_alpha_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_alpha_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_alpha_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_alpha_texopt_model, texture_option_model_jni->j_type_field_id, j_alpha_texture_type); // sharpness field env->SetFloatField(j_alpha_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.alpha_texopt.sharpness); // brightness field env->SetFloatField(j_alpha_texopt_model, texture_option_model_jni->j_brightness_field_id, material.alpha_texopt.brightness); // contrast field env->SetFloatField(j_alpha_texopt_model, texture_option_model_jni->j_contrast_field_id, material.alpha_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.alpha_texopt.origin_offset) / sizeof(material.alpha_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.alpha_texopt.origin_offset) / sizeof(material.alpha_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.alpha_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_alpha_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.alpha_texopt.scale) / sizeof(material.alpha_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.alpha_texopt.scale) / sizeof(material.alpha_texopt.scale[0]); i++) { body_scale[i] = material.alpha_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_alpha_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.alpha_texopt.turbulence) / sizeof(material.alpha_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.alpha_texopt.turbulence) / sizeof(material.alpha_texopt.turbulence[0]); i++) { body_turbulence[i] = material.alpha_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_alpha_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_alpha_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.alpha_texopt.clamp); // imfchan field env->SetCharField(j_alpha_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.alpha_texopt.imfchan); // blendu field env->SetBooleanField(j_alpha_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.alpha_texopt.blendu); // blendv field env->SetBooleanField(j_alpha_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.alpha_texopt.blendv); // colorspace field env->SetObjectField(j_alpha_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.alpha_texopt.colorspace.c_str())); // alpha texopt field env->SetObjectField(j_material_model, material_model_jni->j_alpha_texopt_field_id, j_alpha_texopt_model); } void SetMaterialReflectionTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_reflection_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_reflection_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_reflection_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_reflection_texopt_model, texture_option_model_jni->j_type_field_id, j_reflection_texture_type); // sharpness field env->SetFloatField(j_reflection_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.reflection_texopt.sharpness); // brightness field env->SetFloatField(j_reflection_texopt_model, texture_option_model_jni->j_brightness_field_id, material.reflection_texopt.brightness); // contrast field env->SetFloatField(j_reflection_texopt_model, texture_option_model_jni->j_contrast_field_id, material.reflection_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.reflection_texopt.origin_offset) / sizeof(material.reflection_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.reflection_texopt.origin_offset) / sizeof(material.reflection_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.reflection_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_reflection_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.reflection_texopt.scale) / sizeof(material.reflection_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.reflection_texopt.scale) / sizeof(material.reflection_texopt.scale[0]); i++) { body_scale[i] = material.reflection_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_reflection_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.reflection_texopt.turbulence) / sizeof(material.reflection_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.reflection_texopt.turbulence) / sizeof(material.reflection_texopt.turbulence[0]); i++) { body_turbulence[i] = material.reflection_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_reflection_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_reflection_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.reflection_texopt.clamp); // imfchan field env->SetCharField(j_reflection_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.reflection_texopt.imfchan); // blendu field env->SetBooleanField(j_reflection_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.reflection_texopt.blendu); // blendv field env->SetBooleanField(j_reflection_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.reflection_texopt.blendv); // colorspace field env->SetObjectField(j_reflection_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.reflection_texopt.colorspace.c_str())); // reflection texopt field env->SetObjectField(j_material_model, material_model_jni->j_reflection_texopt_field_id, j_reflection_texopt_model); } void SetMaterialRoughnessField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_roughness_field_id, material.roughness); } void SetMaterialMetallicField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_metallic_field_id, material.metallic); } void SetMaterialSheenField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_sheen_field_id, material.sheen); } void SetMaterialClearcoatThicknessField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_clearcoat_thickness_field_id, material.clearcoat_thickness); } void SetMaterialClearcoatRoughnessField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_clearcoat_roughness_field_id, material.clearcoat_roughness); } void SetMaterialAnisotrophyField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_anisotropy_field_id, material.anisotropy); } void SetMaterialAnisotrophyRotationField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_anisotropy_rotation_field_id, material.anisotropy_rotation); } void SetMaterialPad0Field(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetFloatField(j_material_model, material_model_jni->j_pad0_field_id, material.pad0); } void SetMaterialRoughnessTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_roughness_texname_field_id, env->NewStringUTF(material.roughness_texname.c_str())); } void SetMaterialMetallicTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_metallic_texname_field_id, env->NewStringUTF(material.metallic_texname.c_str())); } void SetMaterialSheenTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_sheen_texname_field_id, env->NewStringUTF(material.sheen_texname.c_str())); } void SetMaterialEmissiveTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_emissive_texname_field_id, env->NewStringUTF(material.emissive_texname.c_str())); } void SetMaterialNormalTexnameField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetObjectField(j_material_model, material_model_jni->j_normal_texname_field_id, env->NewStringUTF(material.normal_texname.c_str())); } void SetMaterialRoughnessTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_roughness_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_roughness_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_roughness_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_roughness_texopt_model, texture_option_model_jni->j_type_field_id, j_roughness_texture_type); // sharpness field env->SetFloatField(j_roughness_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.roughness_texopt.sharpness); // brightness field env->SetFloatField(j_roughness_texopt_model, texture_option_model_jni->j_brightness_field_id, material.roughness_texopt.brightness); // contrast field env->SetFloatField(j_roughness_texopt_model, texture_option_model_jni->j_contrast_field_id, material.roughness_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.roughness_texopt.origin_offset) / sizeof(material.roughness_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.roughness_texopt.origin_offset) / sizeof(material.roughness_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.roughness_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_roughness_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.roughness_texopt.scale) / sizeof(material.roughness_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.roughness_texopt.scale) / sizeof(material.roughness_texopt.scale[0]); i++) { body_scale[i] = material.roughness_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_roughness_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.roughness_texopt.turbulence) / sizeof(material.roughness_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.roughness_texopt.turbulence) / sizeof(material.roughness_texopt.turbulence[0]); i++) { body_turbulence[i] = material.roughness_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_roughness_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_roughness_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.roughness_texopt.clamp); // imfchan field env->SetCharField(j_roughness_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.roughness_texopt.imfchan); // blendu field env->SetBooleanField(j_roughness_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.roughness_texopt.blendu); // blendv field env->SetBooleanField(j_roughness_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.roughness_texopt.blendv); // colorspace field env->SetObjectField(j_roughness_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.roughness_texopt.colorspace.c_str())); // roughness texopt field env->SetObjectField(j_material_model, material_model_jni->j_roughness_texopt_field_id, j_roughness_texopt_model); } void SetMaterialMetallicTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_metallic_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_metallic_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_metallic_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_metallic_texopt_model, texture_option_model_jni->j_type_field_id, j_metallic_texture_type); // sharpness field env->SetFloatField(j_metallic_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.metallic_texopt.sharpness); // brightness field env->SetFloatField(j_metallic_texopt_model, texture_option_model_jni->j_brightness_field_id, material.metallic_texopt.brightness); // contrast field env->SetFloatField(j_metallic_texopt_model, texture_option_model_jni->j_contrast_field_id, material.metallic_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.metallic_texopt.origin_offset) / sizeof(material.metallic_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.metallic_texopt.origin_offset) / sizeof(material.metallic_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.metallic_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_metallic_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.metallic_texopt.scale) / sizeof(material.metallic_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.metallic_texopt.scale) / sizeof(material.metallic_texopt.scale[0]); i++) { body_scale[i] = material.metallic_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_metallic_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.metallic_texopt.turbulence) / sizeof(material.metallic_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.metallic_texopt.turbulence) / sizeof(material.metallic_texopt.turbulence[0]); i++) { body_turbulence[i] = material.metallic_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_metallic_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_metallic_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.metallic_texopt.clamp); // imfchan field env->SetCharField(j_metallic_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.metallic_texopt.imfchan); // blendu field env->SetBooleanField(j_metallic_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.metallic_texopt.blendu); // blendv field env->SetBooleanField(j_metallic_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.metallic_texopt.blendv); // colorspace field env->SetObjectField(j_metallic_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.metallic_texopt.colorspace.c_str())); // metallic texopt field env->SetObjectField(j_material_model, material_model_jni->j_metallic_texopt_field_id, j_metallic_texopt_model); } void SetMaterialSheenTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_sheen_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_sheen_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_sheen_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_sheen_texopt_model, texture_option_model_jni->j_type_field_id, j_sheen_texture_type); // sharpness field env->SetFloatField(j_sheen_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.sheen_texopt.sharpness); // brightness field env->SetFloatField(j_sheen_texopt_model, texture_option_model_jni->j_brightness_field_id, material.sheen_texopt.brightness); // contrast field env->SetFloatField(j_sheen_texopt_model, texture_option_model_jni->j_contrast_field_id, material.sheen_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.sheen_texopt.origin_offset) / sizeof(material.sheen_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.sheen_texopt.origin_offset) / sizeof(material.sheen_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.sheen_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_sheen_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.sheen_texopt.scale) / sizeof(material.sheen_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.sheen_texopt.scale) / sizeof(material.sheen_texopt.scale[0]); i++) { body_scale[i] = material.sheen_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_sheen_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.sheen_texopt.turbulence) / sizeof(material.sheen_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.sheen_texopt.turbulence) / sizeof(material.sheen_texopt.turbulence[0]); i++) { body_turbulence[i] = material.sheen_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_sheen_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_sheen_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.sheen_texopt.clamp); // imfchan field env->SetCharField(j_sheen_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.sheen_texopt.imfchan); // blendu field env->SetBooleanField(j_sheen_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.sheen_texopt.blendu); // blendv field env->SetBooleanField(j_sheen_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.sheen_texopt.blendv); // colorspace field env->SetObjectField(j_sheen_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.sheen_texopt.colorspace.c_str())); // sheen texopt field env->SetObjectField(j_material_model, material_model_jni->j_sheen_texopt_field_id, j_sheen_texopt_model); } void SetMaterialEmissiveTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_emissive_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_emissive_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_emissive_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_emissive_texopt_model, texture_option_model_jni->j_type_field_id, j_emissive_texture_type); // sharpness field env->SetFloatField(j_emissive_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.emissive_texopt.sharpness); // brightness field env->SetFloatField(j_emissive_texopt_model, texture_option_model_jni->j_brightness_field_id, material.emissive_texopt.brightness); // contrast field env->SetFloatField(j_emissive_texopt_model, texture_option_model_jni->j_contrast_field_id, material.emissive_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.emissive_texopt.origin_offset) / sizeof(material.emissive_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.emissive_texopt.origin_offset) / sizeof(material.emissive_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.emissive_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_emissive_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.emissive_texopt.scale) / sizeof(material.emissive_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.emissive_texopt.scale) / sizeof(material.emissive_texopt.scale[0]); i++) { body_scale[i] = material.emissive_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_emissive_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.emissive_texopt.turbulence) / sizeof(material.emissive_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.emissive_texopt.turbulence) / sizeof(material.emissive_texopt.turbulence[0]); i++) { body_turbulence[i] = material.emissive_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_emissive_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_emissive_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.emissive_texopt.clamp); // imfchan field env->SetCharField(j_emissive_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.emissive_texopt.imfchan); // blendu field env->SetBooleanField(j_emissive_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.emissive_texopt.blendu); // blendv field env->SetBooleanField(j_emissive_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.emissive_texopt.blendv); // colorspace field env->SetObjectField(j_emissive_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.emissive_texopt.colorspace.c_str())); // emissive texopt field env->SetObjectField(j_material_model, material_model_jni->j_emissive_texopt_field_id, j_emissive_texopt_model); } void SetMaterialNormalTexoptField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_normal_texopt_model = env->NewObject(texture_option_model_jni->j_texture_option_model_class, texture_option_model_jni->j_texture_option_model_constructor); jobject j_normal_texture_type = nullptr; switch (material.ambient_texopt.type) { case tinyobj::texture_type_t::TEXTURE_TYPE_NONE: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_none_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_SPHERE: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_sphere_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_TOP: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_top_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BOTTOM: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_bottom_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_FRONT: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_front_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_BACK: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_back_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_LEFT: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_left_field_id); break; case tinyobj::texture_type_t::TEXTURE_TYPE_CUBE_RIGHT: j_normal_texture_type = env->GetStaticObjectField(texture_type_jni->j_texture_type_class, texture_type_jni->j_texture_type_cube_right_field_id); break; } // type field env->SetObjectField(j_normal_texopt_model, texture_option_model_jni->j_type_field_id, j_normal_texture_type); // sharpness field env->SetFloatField(j_normal_texopt_model, texture_option_model_jni->j_sharpness_field_id, material.normal_texopt.sharpness); // brightness field env->SetFloatField(j_normal_texopt_model, texture_option_model_jni->j_brightness_field_id, material.normal_texopt.brightness); // contrast field env->SetFloatField(j_normal_texopt_model, texture_option_model_jni->j_contrast_field_id, material.normal_texopt.contrast); // origin offset field jfloatArray j_origin_offset_array = env->NewFloatArray((jsize) sizeof(material.normal_texopt.origin_offset) / sizeof(material.normal_texopt.origin_offset[0])); jboolean is_copy_origin_offset; jfloat *body_origin_offset = env->GetFloatArrayElements(j_origin_offset_array, &is_copy_origin_offset); for (size_t i = 0; i < sizeof(material.normal_texopt.origin_offset) / sizeof(material.normal_texopt.origin_offset[0]); i++) { body_origin_offset[i] = material.normal_texopt.origin_offset[i]; } env->SetFloatArrayRegion(j_origin_offset_array, 0, env->GetArrayLength(j_origin_offset_array), body_origin_offset); env->SetObjectField(j_normal_texopt_model, texture_option_model_jni->j_origin_offset_field_id, j_origin_offset_array); // scale field jfloatArray j_scale_array = env->NewFloatArray((jsize) sizeof(material.normal_texopt.scale) / sizeof(material.normal_texopt.scale[0])); jboolean is_copy_scale; jfloat *body_scale = env->GetFloatArrayElements(j_scale_array, &is_copy_scale); for (size_t i = 0; i < sizeof(material.normal_texopt.scale) / sizeof(material.normal_texopt.scale[0]); i++) { body_scale[i] = material.normal_texopt.scale[i]; } env->SetFloatArrayRegion(j_scale_array, 0, env->GetArrayLength(j_scale_array), body_scale); env->SetObjectField(j_normal_texopt_model, texture_option_model_jni->j_scale_field_id, j_scale_array); // turbulence field jfloatArray j_turbulence_array = env->NewFloatArray((jsize) sizeof(material.normal_texopt.turbulence) / sizeof(material.normal_texopt.turbulence[0])); jboolean is_copy_turbulence; jfloat *body_turbulence = env->GetFloatArrayElements(j_turbulence_array, &is_copy_turbulence); for (size_t i = 0; i < sizeof(material.normal_texopt.turbulence) / sizeof(material.normal_texopt.turbulence[0]); i++) { body_turbulence[i] = material.normal_texopt.turbulence[i]; } env->SetFloatArrayRegion(j_turbulence_array, 0, env->GetArrayLength(j_turbulence_array), body_turbulence); env->SetObjectField(j_normal_texopt_model, texture_option_model_jni->j_turbulence_field_id, j_turbulence_array); // clamp field env->SetBooleanField(j_normal_texopt_model, texture_option_model_jni->j_clamp_field_id, (jboolean) material.normal_texopt.clamp); // imfchan field env->SetCharField(j_normal_texopt_model, texture_option_model_jni->j_imfchan_field_id, (jchar) material.normal_texopt.imfchan); // blendu field env->SetBooleanField(j_normal_texopt_model, texture_option_model_jni->j_blend_u_field_id, (jboolean) material.normal_texopt.blendu); // blendv field env->SetBooleanField(j_normal_texopt_model, texture_option_model_jni->j_blend_v_field_id, (jboolean) material.normal_texopt.blendv); // colorspace field env->SetObjectField(j_normal_texopt_model, texture_option_model_jni->j_colorspace_field_id, env->NewStringUTF(material.normal_texopt.colorspace.c_str())); // normal texopt field env->SetObjectField(j_material_model, material_model_jni->j_normal_texopt_field_id, j_normal_texopt_model); } void SetMaterialPad2Field(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { env->SetIntField(j_material_model, material_model_jni->j_pad2_field_id, material.pad2); } void SetMaterialUnknownParameterField(JNIEnv * env, jobject &j_material_model, const tinyobj::material_t &material) { jobject j_unknown_parameter = env->NewObject(hash_map_jni->j_hash_map_class, hash_map_jni->j_hash_map_constructor, material.unknown_parameter.size()); for (const auto &it : material.unknown_parameter) { env->CallObjectMethod(j_unknown_parameter, hash_map_jni->j_hash_map_put, env->NewStringUTF(it.first.c_str()), env->NewStringUTF(it.second.c_str())); } env->SetObjectField(j_material_model, material_model_jni->j_unknown_parameter_field_id, j_unknown_parameter); } void GenerateMaterialModels(JNIEnv * env, jobject &j_result_model, const std::vector<tinyobj::material_t> &materials) { jobjectArray material_models = env->NewObjectArray((jsize) materials.size(), material_model_jni->j_material_model_class, nullptr); for (size_t m = 0; m < materials.size(); m++) { jobject j_material_model = env->NewObject(material_model_jni->j_material_model_class, material_model_jni->j_material_model_constructor); tinyobj::material_t material = materials[m]; // material model env->SetObjectField(j_material_model, material_model_jni->j_name_field_id, env->NewStringUTF(material.name.c_str())); env->SetObjectArrayElement(material_models, (jsize) m, j_material_model); SetMaterialAmbientField(env, j_material_model, material); SetMaterialDiffuseField(env, j_material_model, material); SetMaterialSpecularField(env, j_material_model, material); SetMaterialTransmittanceField(env, j_material_model, material); SetMaterialEmissionField(env, j_material_model, material); SetMaterialShininessField(env, j_material_model, material); SetMaterialIorField(env, j_material_model, material); SetMaterialDissolveField(env, j_material_model, material); SetMaterialIllumField(env, j_material_model, material); SetMaterialDummyField(env, j_material_model, material); SetMaterialAmbientTexnameField(env, j_material_model, material); SetMaterialDiffuseTexnameField(env, j_material_model, material); SetMaterialSpecularTexnameField(env, j_material_model, material); SetMaterialSpecularHighlightTexnameField(env, j_material_model, material); SetMaterialBumpTexnameField(env, j_material_model, material); SetMaterialDisplacementTexnameField(env, j_material_model, material); SetMaterialAlphaTexnameField(env, j_material_model, material); SetMaterialReflectionTexnameField(env, j_material_model, material); SetMaterialAmbientTexoptField(env, j_material_model, material); SetMaterialDiffuseTexoptField(env, j_material_model, material); SetMaterialSpecularTexoptField(env, j_material_model, material); SetMaterialSpecularHighlightTexoptField(env, j_material_model, material); SetMaterialBumpTexoptField(env, j_material_model, material); SetMaterialDisplacementTexoptField(env, j_material_model, material); SetMaterialAlphaTexoptField(env, j_material_model, material); SetMaterialReflectionTexoptField(env, j_material_model, material); SetMaterialRoughnessField(env, j_material_model, material); SetMaterialMetallicField(env, j_material_model, material); SetMaterialSheenField(env, j_material_model, material); SetMaterialClearcoatThicknessField(env, j_material_model, material); SetMaterialClearcoatRoughnessField(env, j_material_model, material); SetMaterialAnisotrophyField(env, j_material_model, material); SetMaterialAnisotrophyRotationField(env, j_material_model, material); SetMaterialPad0Field(env, j_material_model, material); SetMaterialRoughnessTexnameField(env, j_material_model, material); SetMaterialMetallicTexnameField(env, j_material_model, material); SetMaterialSheenTexnameField(env, j_material_model, material); SetMaterialEmissiveTexnameField(env, j_material_model, material); SetMaterialNormalTexnameField(env, j_material_model, material); SetMaterialRoughnessTexoptField(env, j_material_model, material); SetMaterialMetallicTexoptField(env, j_material_model, material); SetMaterialSheenTexoptField(env, j_material_model, material); SetMaterialEmissiveTexoptField(env, j_material_model, material); SetMaterialNormalTexoptField(env, j_material_model, material); SetMaterialPad2Field(env, j_material_model, material); SetMaterialUnknownParameterField(env, j_material_model, material); } env->SetObjectField(j_result_model, result_model_jni->j_material_models_field_id, material_models); } void GenerateMessages(JNIEnv * env, jobject &j_result_model, const std::string &warn, const std::string &err) { // warn field env->SetObjectField(j_result_model, result_model_jni->j_warn_field_id, env->NewStringUTF(warn.c_str())); // error field env->SetObjectField(j_result_model, result_model_jni->j_error_field_id, env->NewStringUTF(err.c_str())); } template<typename... ArgTypes> void log(const char* pattern, ArgTypes... args) { if (print_log) { __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, pattern, args...); } } extern "C" JNIEXPORT jobject JNICALL Java_com_riseapps_marusyaobjloader_MarusyaObjLoaderImpl_nativeLoad(JNIEnv *env, jobject instance, jstring obj_path, jstring mtl_path, jfloat normalize_coefficient, jboolean flip_texcoord) { log("***********************************************************************************", NULL); std::chrono::time_point<std::chrono::high_resolution_clock> t_start, t_end; t_start = std::chrono::high_resolution_clock::now(); ReleaseJNIDetails(); LoadJNIDetails(env); // input files std::string obj_file_path = env->GetStringUTFChars(obj_path, (jboolean *) false); std::string mtl_file_path = env->GetStringUTFChars(mtl_path, (jboolean *) false); std::string mtl_base_dir = GetBaseDir(mtl_file_path); log("Start parsing -> obj: %s, mtl: %s", obj_file_path.c_str(), mtl_file_path.c_str()); // parsing tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string warn; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, obj_file_path.c_str(), mtl_base_dir.c_str()); // when error if (!err.empty() && !ret) { log("Error while parsing -> %s", err.c_str()); return GenerateResultModelDueToError(env, err); } log("End parsing -> %s", obj_file_path.c_str()); // print parse data log("shapes size -> %lu", shapes.size()); log("materials size -> %lu", materials.size()); log("vertices size -> %lu", attrib.vertices.size()); log("normals size -> %lu", attrib.normals.size()); log("texcoords size -> %lu", attrib.texcoords.size()); log("colors size -> %lu", attrib.colors.size()); unsigned long indicesSize = 0; for (auto &shape : shapes) { indicesSize += shape.mesh.indices.size(); } log("indices size -> %lu", indicesSize); // generate result model jobject j_result_model = env->NewObject(result_model_jni->j_result_model_class, result_model_jni->j_result_model_constructor); GenerateShapeModels(env, j_result_model, attrib, shapes, normalize_coefficient, flip_texcoord); GenerateMaterialModels(env, j_result_model, materials); GenerateMessages(env, j_result_model, warn, err); ReleaseJNIDetails(); t_end = std::chrono::high_resolution_clock::now(); log("Time to parse -> %ld ms", std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count()); log("***********************************************************************************", NULL); return j_result_model; } extern "C" JNIEXPORT void JNICALL Java_com_riseapps_marusyaobjloader_MarusyaObjLoaderImpl_nativeEnableLog(JNIEnv *env, jobject instance) { print_log = true; } extern "C" JNIEXPORT void JNICALL Java_com_riseapps_marusyaobjloader_MarusyaObjLoaderImpl_nativeDisableLog(JNIEnv *env, jobject instance) { print_log = false; }<file_sep>package com.riseapps.objloaderjni; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.riseapps.marusyaobjloader.MarusyaObjLoader; import com.riseapps.marusyaobjloader.MarusyaObjLoaderImpl; import com.riseapps.marusyaobjloader.model.ResultModel; import java.io.File; import java.io.FileNotFoundException; public class ResultActivity extends AppCompatActivity implements ProgressListener { private static final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "jni_test"); private static final File OBJ = new File(FILES_PATH, "luxury_house_interior.obj"); private static final File MTL = new File(FILES_PATH, "luxury_house_interior.mtl"); private TextView result; private ProgressBar progress; public static Intent getStartIntent(@NonNull Context context) { return new Intent(context, ResultActivity.class); } public static void start(@NonNull Context context) { context.startActivity(getStartIntent(context)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); result = findViewById(R.id.ar_result); progress = findViewById(R.id.ar_progress); load(); } @Override public void preLoad() { progress.setVisibility(View.VISIBLE); } @Override public void onFinish(ResultModel resultModel, long time) { progress.setVisibility(View.GONE); result.setText(String.format( "Result:\n\nOBJ -> %1s\n (%2s MB)\n\nMTL -> %3s (%4s MB)\n\nTIME -> %5s\n\nSHAPES SIZE -> %6s\n\nMATERIALS SIZE -> %7s", OBJ.getAbsolutePath(), OBJ.length() / 1024.0f / 1024.0f, MTL.getAbsolutePath(), MTL.length() / 1024.0f / 1024.0f, time, resultModel.getShapeModels().length, resultModel.getMaterialModels().length)); } @Override public void onError(String error) { result.setText(error); } private void load() { final Load3DModelAsyncTask load3DModelAsyncTask = new Load3DModelAsyncTask(); load3DModelAsyncTask.setProgressListener(this); load3DModelAsyncTask.execute(); } private static class Load3DModelAsyncTask extends AsyncTask<Void, Void, ResultModel> { private long time; private ProgressListener progressListener; public void setProgressListener(ProgressListener progressListener) { this.progressListener = progressListener; } @Override protected void onPreExecute() { super.onPreExecute(); if (progressListener != null) { progressListener.preLoad(); } } @Override protected ResultModel doInBackground(Void... params) { final long startTime = System.currentTimeMillis(); final MarusyaObjLoader marusyaObjLoader = new MarusyaObjLoaderImpl(); ResultModel resultModel = null; try { resultModel = marusyaObjLoader.load( OBJ, MTL, 1.0f, true); if (resultModel.getError() != null && !resultModel.getError().isEmpty() && progressListener != null) { progressListener.onError(resultModel.getError()); } } catch (FileNotFoundException e) { e.printStackTrace(); if (progressListener != null) { progressListener.onError(e.getMessage()); } } time = System.currentTimeMillis() - startTime; return resultModel; } @Override protected void onPostExecute(ResultModel result) { super.onPostExecute(result); if (progressListener != null) { progressListener.onFinish(result, time); } } } } <file_sep>MTL material format (Lightwave, OBJ) Excerpt from FILE FORMATS, Version 4.2 October 1995 Documentation created by: <NAME>, <NAME>, and <NAME> Copyright 1995 Alias|Wavefront, Inc. All rights reserved 5. Material Library File (.mtl) Material library files contain one or more material definitions, each of which includes the color, texture, and reflection map of individual materials. These are applied to the surfaces and vertices of objects. Material files are stored in ASCII format and have the .mtl extension. An .mtl file differs from other Alias|Wavefront property files, such as light and atmosphere files, in that it can contain more than one material definition (other files contain the definition of only one item). An .mtl file is typically organized as shown below. newmtl my_red Material color & illumination statements texture map statements reflection map statement newmtl my_blue Material color & illumination statements texture map statements reflection map statement newmtl my_green Material color & illumination statements texture map statements reflection map statement Figure 5-1. Typical organization of .mtl file Each material description in an .mtl file consists of the newmtl statement, which assigns a name to the material and designates the start of a material description. This statement is followed by the material color, texture map, and reflection map statements that describe the material. An .mtl file map contain many different material descriptions. After you specify a new material with the "newmtl" statement, you can enter the statements that describe the materials in any order. However, when the Property Editor writes an .mtl file, it puts the statements in a system-assigned order. In this chapter, the statements are described in the system-assigned order. Format The following is a sample format for a material definition in an .mtl file: Material name statement: newmtl my_mtl Material color and illumination statements: Ka 0.0435 0.0435 0.0435 Kd 0.1086 0.1086 0.1086 Ks 0.0000 0.0000 0.0000 Tf 0.9885 0.9885 0.9885 illum 6 d -halo 0.6600 Ns 10.0000 sharpness 60 Ni 1.19713 Texture map statements: map_Ka -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Kd -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ks -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ns -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps map_d -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps disp -s 1 1 .5 wisp.mps decal -s 1 1 1 -o 0 0 0 -mm 0 1 sand.mps bump -s 1 1 1 -o 0 0 0 -bm 1 sand.mpb Reflection map statement: refl -type sphere -mm 0 1 clouds.mpc Material Name The material name statement assigns a name to the material description. Syntax The folowing syntax describes the material name statement. newmtl name Specifies the start of a material description and assigns a name to the material. An .mtl file must have one newmtl statement at the start of each material description. "name" is the name of the material. Names may be any length but cannot include blanks. Underscores may be used in material names. Material color and illumination The statements in this section specify color, transparency, and reflectivity values. Syntax The following syntax describes the material color and illumination statements that apply to all .mtl files. Ka r g b Ka spectral file.rfl factor Ka xyz x y z To specify the ambient reflectivity of the current material, you can use the "Ka" statement, the "Ka spectral" statement, or the "Ka xyz" statement. Tip These statements are mutually exclusive. They cannot be used concurrently in the same material. Ka r g b The Ka statement specifies the ambient reflectivity using RGB values. "r g b" are the values for the red, green, and blue components of the color. The g and b arguments are optional. If only r is specified, then g, and b are assumed to be equal to r. The r g b values are normally in the range of 0.0 to 1.0. Values outside this range increase or decrease the relectivity accordingly. Ka spectral file.rfl factor The "Ka spectral" statement specifies the ambient reflectivity using a spectral curve. "file.rfl" is the name of the .rfl file. "factor" is an optional argument. "factor" is a multiplier for the values in the .rfl file and defaults to 1.0, if not specified. Ka xyz x y z The "Ka xyz" statement specifies the ambient reflectivity using CIEXYZ values. "x y z" are the values of the CIEXYZ color space. The y and z arguments are optional. If only x is specified, then y and z are assumed to be equal to x. The x y z values are normally in the range of 0 to 1. Values outside this range increase or decrease the reflectivity accordingly. Kd r g b Kd spectral file.rfl factor Kd xyz x y z To specify the diffuse reflectivity of the current material, you can use the "Kd" statement, the "Kd spectral" statement, or the "Kd xyz" statement. Tip These statements are mutually exclusive. They cannot be used concurrently in the same material. Kd r g b The Kd statement specifies the diffuse reflectivity using RGB values. "r g b" are the values for the red, green, and blue components of the atmosphere. The g and b arguments are optional. If only r is specified, then g, and b are assumed to be equal to r. The r g b values are normally in the range of 0.0 to 1.0. Values outside this range increase or decrease the relectivity accordingly. Kd spectral file.rfl factor The "Kd spectral" statement specifies the diffuse reflectivity using a spectral curve. "file.rfl" is the name of the .rfl file. "factor" is an optional argument. "factor" is a multiplier for the values in the .rfl file and defaults to 1.0, if not specified. Kd xyz x y z The "Kd xyz" statement specifies the diffuse reflectivity using CIEXYZ values. "x y z" are the values of the CIEXYZ color space. The y and z arguments are optional. If only x is specified, then y and z are assumed to be equal to x. The x y z values are normally in the range of 0 to 1. Values outside this range increase or decrease the reflectivity accordingly. Ks r g b Ks spectral file.rfl factor Ks xyz x y z To specify the specular reflectivity of the current material, you can use the "Ks" statement, the "Ks spectral" statement, or the "Ks xyz" statement. Tip These statements are mutually exclusive. They cannot be used concurrently in the same material. Ks r g b The Ks statement specifies the specular reflectivity using RGB values. "r g b" are the values for the red, green, and blue components of the atmosphere. The g and b arguments are optional. If only r is specified, then g, and b are assumed to be equal to r. The r g b values are normally in the range of 0.0 to 1.0. Values outside this range increase or decrease the relectivity accordingly. Ks spectral file.rfl factor The "Ks spectral" statement specifies the specular reflectivity using a spectral curve. "file.rfl" is the name of the .rfl file. "factor" is an optional argument. "factor" is a multiplier for the values in the .rfl file and defaults to 1.0, if not specified. Ks xyz x y z The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values. "x y z" are the values of the CIEXYZ color space. The y and z arguments are optional. If only x is specified, then y and z are assumed to be equal to x. The x y z values are normally in the range of 0 to 1. Values outside this range increase or decrease the reflectivity accordingly. Tf r g b Tf spectral file.rfl factor Tf xyz x y z To specify the transmission filter of the current material, you can use the "Tf" statement, the "Tf spectral" statement, or the "Tf xyz" statement. Any light passing through the object is filtered by the transmission filter, which only allows the specifiec colors to pass through. For example, Tf 0 1 0 allows all the green to pass through and filters out all the red and blue. Tip These statements are mutually exclusive. They cannot be used concurrently in the same material. Tf r g b The Tf statement specifies the transmission filter using RGB values. "r g b" are the values for the red, green, and blue components of the atmosphere. The g and b arguments are optional. If only r is specified, then g, and b are assumed to be equal to r. The r g b values are normally in the range of 0.0 to 1.0. Values outside this range increase or decrease the relectivity accordingly. Tf spectral file.rfl factor The "Tf spectral" statement specifies the transmission filterusing a spectral curve. "file.rfl" is the name of the .rfl file. "factor" is an optional argument. "factor" is a multiplier for the values in the .rfl file and defaults to 1.0, if not specified. Tf xyz x y z The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values. "x y z" are the values of the CIEXYZ color space. The y and z arguments are optional. If only x is specified, then y and z are assumed to be equal to x. The x y z values are normally in the range of 0 to 1. Values outside this range will increase or decrease the intensity of the light transmission accordingly. illum illum_# The "illum" statement specifies the illumination model to use in the material. Illumination models are mathematical equations that represent various material lighting and shading effects. "illum_#"can be a number from 0 to 10. The illumination models are summarized below; for complete descriptions see "Illumination models" on page 5-30. Illumination Properties that are turned on in the model Property Editor 0 Color on and Ambient off 1 Color on and Ambient on 2 Highlight on 3 Reflection on and Ray trace on 4 Transparency: Glass on Reflection: Ray trace on 5 Reflection: Fresnel on and Ray trace on 6 Transparency: Refraction on Reflection: Fresnel off and Ray trace on 7 Transparency: Refraction on Reflection: Fresnel on and Ray trace on 8 Reflection on and Ray trace off 9 Transparency: Glass on Reflection: Ray trace off 10 Casts shadows onto invisible surfaces d factor Specifies the dissolve for the current material. "factor" is the amount this material dissolves into the background. A factor of 1.0 is fully opaque. This is the default when a new material is created. A factor of 0.0 is fully dissolved (completely transparent). Unlike a real transparent material, the dissolve does not depend upon material thickness nor does it have any spectral character. Dissolve works on all illumination models. d -halo factor Specifies that a dissolve is dependent on the surface orientation relative to the viewer. For example, a sphere with the following dissolve, d -halo 0.0, will be fully dissolved at its center and will appear gradually more opaque toward its edge. "factor" is the minimum amount of dissolve applied to the material. The amount of dissolve will vary between 1.0 (fully opaque) and the specified "factor". The formula is: dissolve = 1.0 - (N*v)(1.0-factor) For a definition of terms, see "Illumination models" on page 5-30. Ns exponent Specifies the specular exponent for the current material. This defines the focus of the specular highlight. "exponent" is the value for the specular exponent. A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000. sharpness value Specifies the sharpness of the reflections from the local reflection map. If a material does not have a local reflection map defined in its material definition, sharpness will apply to the global reflection map defined in PreView. "value" can be a number from 0 to 1000. The default is 60. A high value results in a clear reflection of objects in the reflection map. Tip Sharpness values greater than 100 map introduce aliasing effects in flat surfaces that are viewed at a sharp angle Ni optical_density Specifies the optical density for the surface. This is also known as index of refraction. "optical_density" is the value for the optical density. The values can range from 0.001 to 10. A value of 1.0 means that light does not bend as it passes through an object. Increasing the optical_density increases the amount of bending. Glass has an index of refraction of about 1.5. Values of less than 1.0 produce bizarre results and are not recommended. Material texture map Texture map statements modify the material parameters of a surface by associating an image or texture file with material parameters that can be mapped. By modifying existing parameters instead of replacing them, texture maps provide great flexibility in changing the appearance of an object's surface. Image files and texture files can be used interchangeably. If you use an image file, that file is converted to a texture in memory and is discarded after rendering. Tip Using images instead of textures saves disk space and setup time, however, it introduces a small computational cost at the beginning of a render. The material parameters that can be modified by a texture map are: - Ka (color) - Kd (color) - Ks (color) - Ns (scalar) - d (scalar) In addition to the material parameters, the surface normal can be modified. Image file types You can link any image file type that is currently supported. Supported image file types are listed in the chapter "About Image" in the "Advanced Visualizer User's Guide". You can also use the "im_info - a" command to list Image file types, among other things. Texture file types The texture file types you can use are: - mip-mapped texture files (.mpc, .mps, .mpb) - compiled procedural texture files (.cxc, .cxs, .cxb) Mip-mapped texture files Mip-mapped texture files are created from images using the Create Textures panel in the Director or the "texture2D" program. There are three types of texture files: - color texture files (.mpc) - scalar texture files (.mps) - bump texture files (.mpb) Color textures. Color texture files are designated by an extension of ".mpc" in the filename, such as "chrome.mpc". Color textures modify the material color as follows: - Ka - material ambient is multiplied by the texture value - Kd - material diffuse is multiplied by the texture value - Ks - material specular is multiplied by the texture value Scalar textures. Scalar texture files are designated by an extension of ".mps" in the filename, such as "wisp.mps". Scalar textures modify the material scalar values as follows: - Ns - material specular exponent is multiplied by the texture value - d - material dissolve is multiplied by the texture value - decal - uses a scalar value to deform the surface of an object to create surface roughness Bump textures. Bump texture files are designated by an extension of ".mpb" in the filename, such as "sand.mpb". Bump textures modify surface normals. The image used for a bump texture represents the topology or height of the surface relative to the average surface. Dark areas are depressions and light areas are high points. The effect is like embossing the surface with the texture. Procedural texture files Procedural texture files use mathematical formulas to calculate sample values of the texture. The procedural texture file is compiled, stored, and accessed by the Image program when rendering. for more information see chapter 9, "Procedural Texture Files (.cxc, .cxb. and .cxs)". Syntax The following syntax describes the texture map statements that apply to .mtl files. These statements can be used alone or with any combination of options. The options and their arguments are inserted between the keyword and the "filename". map_Ka -options args filename Specifies that a color texture file or a color procedural texture file is applied to the ambient reflectivity of the material. During rendering, the "map_Ka" value is multiplied by the "Ka" value. "filename" is the name of a color texture file (.mpc), a color procedural texture file (.cxc), or an image file. Tip To make sure that the texture retains its original look, use the .rfl file "ident" as the underlying material. This applies to the "map_Ka", "map_Kd", and "map_Ks" statements. For more information on .rfl files, see chapter 8, "Spectral Curve File (.rfl)". The options for the "map_Ka" statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -cc on | off -clamp on | off -mm base gain -o u v w -s u v w -t u v w -texres value map_Kd -options args filename Specifies that a color texture file or color procedural texture file is linked to the diffuse reflectivity of the material. During rendering, the map_Kd value is multiplied by the Kd value. "filename" is the name of a color texture file (.mpc), a color procedural texture file (.cxc), or an image file. The options for the map_Kd statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -cc on | off -clamp on | off -mm base gain -o u v w -s u v w -t u v w -texres value map_Ks -options args filename Specifies that a color texture file or color procedural texture file is linked to the specular reflectivity of the material. During rendering, the map_Ks value is multiplied by the Ks value. "filename" is the name of a color texture file (.mpc), a color procedural texture file (.cxc), or an image file. The options for the map_Ks statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -cc on | off -clamp on | off -mm base gain -o u v w -s u v w -t u v w -texres value map_Ns -options args filename Specifies that a scalar texture file or scalar procedural texture file is linked to the specular exponent of the material. During rendering, the map_Ns value is multiplied by the Ns value. "filename" is the name of a scalar texture file (.mps), a scalar procedural texture file (.cxs), or an image file. The options for the map_Ns statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -clamp on | off -imfchan r | g | b | m | l | z -mm base gain -o u v w -s u v w -t u v w -texres value map_d -options args filename Specifies that a scalar texture file or scalar procedural texture file is linked to the dissolve of the material. During rendering, the map_d value is multiplied by the d value. "filename" is the name of a scalar texture file (.mps), a scalar procedural texture file (.cxs), or an image file. The options for the map_d statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -clamp on | off -imfchan r | g | b | m | l | z -mm base gain -o u v w -s u v w -t u v w -texres value map_aat on Turns on anti-aliasing of textures in this material without anti- aliasing all textures in the scene. If you wish to selectively anti-alias textures, first insert this statement in the material file. Then, when rendering with the Image panel, choose the anti-alias settings: "shadows", "reflections polygons", or "polygons only". If using Image from the command line, use the -aa or -os options. Do not use the -aat option. Image will anti-alias all textures in materials with the map_aat on statement, using the oversampling level you choose when you run Image. Textures in other materials will not be oversampled. You cannot set a different oversampling level individually for each material, nor can you anti-alias some textures in a material and not others. To anti-alias all textures in all materials, use the -aat option from the Image command line. If a material with "map_aat on" includes a reflection map, all textures in that reflection map will be anti-aliased as well. You will not see the effects of map_aat in the Property Editor. Tip Some .mpc textures map exhibit undesirable effects around the edges of smoothed objects. The "map_aat" statement will correct this. decal -options args filename Specifies that a scalar texture file or a scalar procedural texture file is used to selectively replace the material color with the texture color. "filename" is the name of a scalar texture file (.mps), a scalar procedural texture file (.cxs), or an image file. During rendering, the Ka, Kd, and Ks values and the map_Ka, map_Kd, and map_Ks values are blended according to the following formula: result_color=tex_color(tv)*decal(tv)+mtl_color*(1.0-decal(tv)) where tv is the texture vertex. "result_color" is the blended Ka, Kd, and Ks values. The options for the decal statement are listed below. These options are described in detail in "Options for texture map statements" on page 5-18. -blendu on | off -blendv on | off -clamp on | off -imfchan r | g | b | m | l | z -mm base gain -o u v w -s u v w -t u v w -texres value disp -options args filename Specifies that a scalar texture is used to deform the surface of an object, creating surface roughness. "filename" is the name of a scalar texture file (.mps), a bump procedural texture file (.cxb), or an image file. The options for the disp statement are listed below. These options are described in detail in "Options for texture map statements" on page 5- 18. -blendu on | off -blendv on | off -clamp on | off -imfchan r | g | b | m | l | z -mm base gain -o u v w -s u v w -t u v w -texres value bump -options args filename Specifies that a bump texture file or a bump procedural texture file is linked to the material. "filename" is the name of a bump texture file (.mpb), a bump procedural texture file (.cxb), or an image file. The options for the bump statement are listed below. These options are described in detail in "Options for texture map statements" on page 5- 18. -bm mult -clamp on | off -blendu on | off -blendv on | off -imfchan r | g | b | m | l | z -mm base gain -o u v w -s u v w -t u v w -texres value Options for texture map statements The following options and arguments can be used to modify the texture map statements. -blenu on | off The -blendu option turns texture blending in the horizontal direction (u direction) on or off. The default is on. -blenv on | off The -blendv option turns texture blending in the vertical direction (v direction) on or off. The default is on. -bm mult The -bm option specifies a bump multiplier. You can use it only with the "bump" statement. Values stored with the texture or procedural texture file are multiplied by this value before they are applied to the surface. "mult" is the value for the bump multiplier. It can be positive or negative. Extreme bump multipliers may cause odd visual results because only the surface normal is perturbed and the surface position does not change. For best results, use values between 0 and 1. -boost value The -boost option increases the sharpness, or clarity, of mip-mapped texture files -- that is, color (.mpc), scalar (.mps), and bump (.mpb) files. If you render animations with boost, you may experience some texture crawling. The effects of boost are seen when you render in Image or test render in Model or PreView; they aren't as noticeable in Property Editor. "value" is any non-negative floating point value representing the degree of increased clarity; the greater the value, the greater the clarity. You should start with a boost value of no more than 1 or 2 and increase the value as needed. Note that larger values have more potential to introduce texture crawling when animated. -cc on | off The -cc option turns on color correction for the texture. You can use it only with the color map statements: map_Ka, map_Kd, and map_Ks. -clamp on | off The -clamp option turns clamping on or off. When clamping is on, textures are restricted to 0-1 in the uvw range. The default is off. When clamping is turned on, one copy of the texture is mapped onto the surface, rather than repeating copies of the original texture across the surface of a polygon, which is the default. Outside of the origin texture, the underlying material is unchanged. A postage stamp on an envelope or a label on a can of soup is an example of a texture with clamping turned on. A tile floor or a sidewalk is an example of a texture with clamping turned off. Two-dimensional textures are clamped in the u and v dimensions; 3D procedural textures are clamped in the u, v, and w dimensions. -imfchan r | g | b | m | l | z The -imfchan option specifies the channel used to create a scalar or bump texture. Scalar textures are applied to: transparency specular exponent decal displacement The channel choices are: r specifies the red channel. g specifies the green channel. b specifies the blue channel. m specifies the matte channel. l specifies the luminance channel. z specifies the z-depth channel. The default for bump and scalar textures is "l" (luminance), unless you are building a decal. In that case, the default is "m" (matte). -mm base gain The -mm option modifies the range over which scalar or color texture values may vary. This has an effect only during rendering and does not change the file. "base" adds a base value to the texture values. A positive value makes everything brighter; a negative value makes everything dimmer. The default is 0; the range is unlimited. "gain" expands the range of the texture values. Increasing the number increases the contrast. The default is 1; the range is unlimited. -o u v w The -o option offsets the position of the texture map on the surface by shifting the position of the map origin. The default is 0, 0, 0. "u" is the value for the horizontal direction of the texture "v" is an optional argument. "v" is the value for the vertical direction of the texture. "w" is an optional argument. "w" is the value used for the depth of a 3D texture. -s u v w The -s option scales the size of the texture pattern on the textured surface by expanding or shrinking the pattern. The default is 1, 1, 1. "u" is the value for the horizontal direction of the texture "v" is an optional argument. "v" is the value for the vertical direction of the texture. "w" is an optional argument. "w" is a value used for the depth of a 3D texture. "w" is a value used for the amount of tessellation of the displacement map. -t u v w The -t option turns on turbulence for textures. Adding turbulence to a texture along a specified direction adds variance to the original image and allows a simple image to be repeated over a larger area without noticeable tiling effects. turbulence also lets you use a 2D image as if it were a solid texture, similar to 3D procedural textures like marble and granite. "u" is the value for the horizontal direction of the texture turbulence. "v" is an optional argument. "v" is the value for the vertical direction of the texture turbulence. "w" is an optional argument. "w" is a value used for the depth of the texture turbulence. By default, the turbulence for every texture map used in a material is uvw = (0,0,0). This means that no turbulence will be applied and the 2D texture will behave normally. Only when you raise the turbulence values above zero will you see the effects of turbulence. -texres resolution The -texres option specifies the resolution of texture created when an image is used. The default texture size is the largest power of two that does not exceed the original image size. If the source image is an exact power of 2, the texture cannot be built any larger. If the source image size is not an exact power of 2, you can specify that the texture be built at the next power of 2 greater than the source image size. The original image should be square, otherwise, it will be scaled to fit the closest square size that is not larger than the original. Scaling reduces sharpness. Material reflection map A reflection map is an environment that simulates reflections in specified objects. The environment is represented by a color texture file or procedural texture file that is mapped on the inside of an infinitely large, space. Reflection maps can be spherical or cubic. A spherical reflection map requires only one texture or image file, while a cubic reflection map requires six. Each material description can contain one reflection map statement that specifies a color texture file or a color procedural texture file to represent the environment. The material itself must be assigned an illumination model of 3 or greater. The reflection map statement in the .mtl file defines a local reflection map. That is, each material assigned to an object in a scene can have an individual reflection map. In PreView, you can assign a global reflection map to an object and specify the orientation of the reflection map. Rotating the reflection map creates the effect of animating reflections independently of object motion. When you replace a global reflection map with a local reflection map, the local reflection map inherits the transformation of the global reflection map. Syntax The following syntax statements describe the reflection map statement for .mtl files. refl -type sphere -options -args filename Specifies an infinitely large sphere that casts reflections onto the material. You specify one texture file. "filename" is the color texture file, color procedural texture file, or image file that will be mapped onto the inside of the shape. refl -type cube_side -options -args filenames Specifies an infinitely large sphere that casts reflections onto the material. You can specify different texture files for the "top", "bottom", "front", "back", "left", and "right" with the following statements: refl -type cube_top refl -type cube_bottom refl -type cube_front refl -type cube_back refl -type cube_left refl -type cube_right "filenames" are the color texture files, color procedural texture files, or image files that will be mapped onto the inside of the shape. The "refl" statements for sphere and cube can be used alone or with any combination of the following options. The options and their arguments are inserted between "refl" and "filename". -blendu on | off -blendv on | off -cc on | off -clamp on | off -mm base gain -o u v w -s u v w -t u v w -texres value The options for the reflection map statement are described in detail in "Options for texture map statements" on page 18. Examples 1 Neon green This is a bright green material. When applied to an object, it will remain bright green regardless of any lighting in the scene. newmtl neon_green Kd 0.0000 1.0000 0.0000 illum 0 2 Flat green This is a flat green material. newmtl flat_green Ka 0.0000 1.0000 0.0000 Kd 0.0000 1.0000 0.0000 illum 1 3 Dissolved green This is a flat green, partially dissolved material. newmtl diss_green Ka 0.0000 1.0000 0.0000 Kd 0.0000 1.0000 0.0000 d 0.8000 illum 1 4 Shiny green This is a shiny green material. When applied to an object, it shows a white specular highlight. newmtl shiny_green Ka 0.0000 1.0000 0.0000 Kd 0.0000 1.0000 0.0000 Ks 1.0000 1.0000 1.0000 Ns 200.0000 illum 1 5 Green mirror This is a reflective green material. When applied to an object, it reflects other objects in the same scene. newmtl green_mirror Ka 0.0000 1.0000 0.0000 Kd 0.0000 1.0000 0.0000 Ks 0.0000 1.0000 0.0000 Ns 200.0000 illum 3 6 Fake windshield This material approximates a glass surface. Is it almost completely transparent, but it shows reflections of other objects in the scene. It will not distort the image of objects seen through the material. newmtl fake_windsh Ka 0.0000 0.0000 0.0000 Kd 0.0000 0.0000 0.0000 Ks 0.9000 0.9000 0.9000 d 0.1000 Ns 200 illum 4 7 Fresnel blue This material exhibits an effect known as Fresnel reflection. When applied to an object, white fringes may appear where the object's surface is viewed at a glancing angle. newmtl fresnel_blu Ka 0.0000 0.0000 0.0000 Kd 0.0000 0.0000 0.0000 Ks 0.6180 0.8760 0.1430 Ns 200 illum 5 8 Real windshield This material accurately represents a glass surface. It filters of colorizes objects that are seen through it. Filtering is done according to the transmission color of the material. The material also distorts the image of objects according to its optical density. Note that the material is not dissolved and that its ambient, diffuse, and specular reflective colors have been set to black. Only the transmission color is non-black. newmtl real_windsh Ka 0.0000 0.0000 0.0000 Kd 0.0000 0.0000 0.0000 Ks 0.0000 0.0000 0.0000 Tf 1.0000 1.0000 1.0000 Ns 200 Ni 1.2000 illum 6 9 Fresnel windshield This material combines the effects in examples 7 and 8. newmtl fresnel_win Ka 0.0000 0.0000 1.0000 Kd 0.0000 0.0000 1.0000 Ks 0.6180 0.8760 0.1430 Tf 1.0000 1.0000 1.0000 Ns 200 Ni 1.2000 illum 7 10 Tin This material is based on spectral reflectance samples taken from an actual piece of tin. These samples are stored in a separate .rfl file that is referred to by name in the material. Spectral sample files (.rfl) can be used in any type of material as an alternative to RGB values. newmtl tin Ka spectral tin.rfl Kd spectral tin.rfl Ks spectral tin.rfl Ns 200 illum 3 11 Pine Wood This material includes a texture map of a pine pattern. The material color is set to "ident" to preserve the texture's true color. When applied to an object, this texture map will affect only the ambient and diffuse regions of that object's surface. The color information for the texture is stored in a separate .mpc file that is referred to in the material by its name, "pine.mpc". If you use different .mpc files for ambient and diffuse, you will get unrealistic results. newmtl pine_wood Ka spectral ident.rfl 1 Kd spectral ident.rfl 1 illum 1 map_Ka pine.mpc map_Kd pine.mpc 12 Bumpy leather This material includes a texture map of a leather pattern. The material color is set to "ident" to preserve the texture's true color. When applied to an object, it affects both the color of the object's surface and its apparent bumpiness. The color information for the texture is stored in a separate .mpc file that is referred to in the material by its name, "brown.mpc". The bump information is stored in a separate .mpb file that is referred to in the material by its name, "leath.mpb". The -bm option is used to raise the apparent height of the leather bumps. newmtl bumpy_leath Ka spectral ident.rfl 1 Kd spectral ident.rfl 1 Ks spectral ident.rfl 1 illum 2 map_Ka brown.mpc map_Kd brown.mpc map_Ks brown.mpc bump -bm 2.000 leath.mpb 13 Frosted window This material includes a texture map used to alter the opacity of an object's surface. The material color is set to "ident" to preserve the texture's true color. When applied to an object, the object becomes transparent in certain areas and opaque in others. The variation between opaque and transparent regions is controlled by scalar information stored in a separate .mps file that is referred to in the material by its name, "window.mps". The "-mm" option is used to shift and compress the range of opacity. newmtl frost_wind Ka 0.2 0.2 0.2 Kd 0.6 0.6 0.6 Ks 0.1 0.1 0.1 d 1 Ns 200 illum 2 map_d -mm 0.200 0.800 window.mps 14 Shifted logo This material includes a texture map which illustrates how a texture's origin may be shifted left/right (the "u" direction) or up/down (the "v" direction). The material color is set to "ident" to preserve the texture's true color. In this example, the original image of the logo is off-center to the left. To compensate, the texture's origin is shifted back to the right (the positive "u" direction) using the "-o" option to modify the origin. Ka spectral ident.rfl 1 Kd spectral ident.rfl 1 Ks spectral ident.rfl 1 illum 2 map_Ka -o 0.200 0.000 0.000 logo.mpc map_Kd -o 0.200 0.000 0.000 logo.mpc map_Ks -o 0.200 0.000 0.000 logo.mpc 15 Scaled logo This material includes a texture map showing how a texture may be scaled left or right (in the "u" direction) or up and down (in the "v" direction). The material color is set to "ident" to preserve the texture's true color. In this example, the original image of the logo is too small. To compensate, the texture is scaled slightly to the right (in the positive "u" direction) and up (in the positive "v" direction) using the "-s" option to modify the scale. Ka spectral ident.rfl 1 Kd spectral ident.rfl 1 Ks spectral ident.rfl 1 illum 2 map_Ka -s 1.200 1.200 0.000 logo.mpc map_Kd -s 1.200 1.200 0.000 logo.mpc map_Ks -s 1.200 1.200 0.000 logo.mpc 16 Chrome with spherical reflection map This illustrates a common use for local reflection maps (defined in a material). this material is highly reflective with no diffuse or ambient contribution. Its reflection map is an image with silver streaks that yields a chrome appearance when viewed as a reflection. ka 0 0 0 kd 0 0 0 ks .7 .7 .7 illum 1 refl -type sphere chrome.rla Illumination models The following list defines the terms and vectors that are used in the illumination model equations: Term Definition Ft Fresnel reflectance Ft Fresnel transmittance Ia ambient light I light intensity Ir intensity from reflected direction (reflection map and/or ray tracing) It intensity from transmitted direction Ka ambient reflectance Kd diffuse reflectance Ks specular reflectance Tf transmission filter Vector Definition H unit vector bisector between L and V L unit light vector N unit surface normal V unit view vector The illumination models are: 0 This is a constant color illumination model. The color is the specified Kd for the material. The formula is: color = Kd 1 This is a diffuse illumination model using Lambertian shading. The color includes an ambient constant term and a diffuse shading term for each light source. The formula is color = KaIa + Kd { SUM j=1..ls, (N * Lj)Ij } 2 This is a diffuse and specular illumination model using Lambertian shading and Blinn's interpretation of Phong's specular illumination model (BLIN77). The color includes an ambient constant term, and a diffuse and specular shading term for each light source. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks { SUM j=1..ls, ((H*Hj)^Ns)Ij } 3 This is a diffuse and specular illumination model with reflection using Lambertian shading, Blinn's interpretation of Phong's specular illumination model (BLIN77), and a reflection term similar to that in Whitted's illumination model (WHIT80). The color includes an ambient constant term and a diffuse and specular shading term for each light source. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij } + Ir) Ir = (intensity of reflection map) + (ray trace) 4 The diffuse and specular illumination model used to simulate glass is the same as illumination model 3. When using a very low dissolve (approximately 0.1), specular highlights from lights or reflections become imperceptible. Simulating glass requires an almost transparent object that still reflects strong highlights. The maximum of the average intensity of highlights and reflected lights is used to adjust the dissolve factor. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij } + Ir) 5 This is a diffuse and specular shading models similar to illumination model 3, except that reflection due to Fresnel effects is introduced into the equation. Fresnel reflection results from light striking a diffuse surface at a grazing or glancing angle. When light reflects at a grazing angle, the Ks value approaches 1.0 for all color samples. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij Fr(Lj*Hj,Ks,Ns)Ij} + Fr(N*V,Ks,Ns)Ir}) 6 This is a diffuse and specular illumination model similar to that used by Whitted (WHIT80) that allows rays to refract through a surface. The amount of refraction is based on optical density (Ni). The intensity of light that refracts is equal to 1.0 minus the value of Ks, and the resulting light is filtered by Tf (transmission filter) as it passes through the object. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij } + Ir) + (1.0 - Ks) TfIt 7 This illumination model is similar to illumination model 6, except that reflection and transmission due to Fresnel effects has been introduced to the equation. At grazing angles, more light is reflected and less light is refracted through the object. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij Fr(Lj*Hj,Ks,Ns)Ij} + Fr(N*V,Ks,Ns)Ir}) + (1.0 - Kx)Ft (N*V,(1.0-Ks),Ns)TfIt 8 This illumination model is similar to illumination model 3 without ray tracing. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij } + Ir) Ir = (intensity of reflection map) 9 This illumination model is similar to illumination model 4without ray tracing. The formula is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks ({ SUM j=1..ls, ((H*Hj)^Ns)Ij } + Ir) Ir = (intensity of reflection map) 10 This illumination model is used to cast shadows onto an invisible surface. This is most useful when compositing computer-generated imagery onto live action, since it allows shadows from rendered objects to be composited directly on top of video-grabbed images. The equation for computation of a shadowmatte is formulated as follows. color = Pixel color. The pixel color of a shadowmatte material is always black. color = black M = Matte channel value. This is the image channel which typically represents the opacity of the point on the surface. To store the shadow in the matte channel of the image, it is calculated as: M = 1 - W / P where: P = Unweighted sum. This is the sum of all S values for each light: P = S1 + S2 + S3 + ..... W = Weighted sum. This is the sum of all S values, each weighted by the visibility factor (Q) for the light: W = (S1 * Q1) + (S2 * Q2) + ..... Q = Visibility factor. This is the amount of light from a particular light source that reaches the point to be shaded, after traveling through all shadow objects between the light and the point on the surface. Q = 0 means no light reached the point to be shaded; it was blocked by shadow objects, thus casting a shadow. Q = 1 means that nothing blocked the light, and no shadow was cast. 0 < Q < 1 means that the light was partially blocked by objects that were partially dissolved. S = Summed brightness. This is the sum of the spectral sample intensities for a particular light. The samples are variable, but the default is 3: S = samp1 + samp2 + samp3. <file_sep>package com.riseapps.marusyaobjloader; import com.riseapps.marusyaobjloader.model.ResultModel; import java.io.File; import java.io.FileNotFoundException; public interface MarusyaObjLoader { ResultModel load(File obj, boolean flipTextureCoordinates) throws FileNotFoundException; ResultModel load(File obj, File mtl, boolean flipTextureCoordinates) throws FileNotFoundException; ResultModel load(File obj, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException; ResultModel load(File obj, File mtl, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException; void enableLog(); void disableLog(); }<file_sep>![](logo.jpg) # MarusyaObjLoader A small library for fast Wavefront .obj and .mtl files loading. As .obj parser was used this fantastic library [https://github.com/syoyo/tinyobjloader](https://github.com/syoyo/tinyobjloader) ## Getting Started These instructions will help you to install the package and use it. ### Installing Using gradle: ```gradle implementation 'com.riseapps.marusyaobjloader:marusyaobjloader:1.0.0' ``` Using maven: ```xml <dependency> <groupId>com.riseapps.marusyaobjloader</groupId> <artifactId>marusyaobjloader</artifactId> <version>1.0.0</version> <type>pom</type> </dependency> ``` Or download it as a file [here](https://github.com/dmitryusikriseapps/MarusyaObjLoader/releases) ### Usage Use this code for the minimum functionality: ```java import com.riseapps.marusyaobjloader.MarusyaObjLoader; import com.riseapps.marusyaobjloader.MarusyaObjLoaderImpl; import com.riseapps.marusyaobjloader.model.ResultModel; import java.io.File; import java.io.FileNotFoundException; private static final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "jni_test"); private static final File OBJ = new File(FILES_PATH, "luxury_house_interior.obj"); private static final File MTL = new File(FILES_PATH, "luxury_house_interior.mtl"); public void load() { final MarusyaObjLoader marusyaObjLoader = new MarusyaObjLoaderImpl(); ResultModel resultModel = null; try { resultModel = marusyaObjLoader.load( OBJ, MTL, 1.0f, true); } catch (FileNotFoundException e) { e.printStackTrace(); } } } ``` ## Example The full example of using is located [here](https://github.com/dmitryusikriseapps/MarusyaObjLoader/tree/master/app/src/main/java/com/riseapps/objloaderjni) ## Documentation ### Method ```java ResultModel load(File obj, boolean flipTextureCoordinates) throws FileNotFoundException; ``` #### Arguments obj - .obj file in a storage flipTextureCoordinates - reverse a texture or not #### Return ResultModel - an object which contains shapes, materials, error and warning messages ### Method ```java ResultModel load(File obj, File mtl, boolean flipTextureCoordinates) throws FileNotFoundException; ``` #### Arguments obj - .obj file in a storage mtl - .mtl file in a storage flipTextureCoordinates - reverse a texture or not #### Return ResultModel - an object which contains shapes, materials, error and warning messages ### Method ```java ResultModel load(File obj, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException; ``` #### Arguments obj - .obj file in a storage normalizeCoefficient - allows normalizing vertices flipTextureCoordinates - reverse a texture or not #### Return ResultModel - an object which contains shapes, materials, error and warning messages ### Method ```java ResultModel load(File obj, File mtl, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException; ``` #### Arguments obj - .obj file in a storage mtl - .mtl file in a storage normalizeCoefficient - allows normalizing vertices flipTextureCoordinates - reverse a texture or not #### Return ResultModel - an object which contains shapes, materials, error and warning messages ### Method ```java void enableLog(); ``` You will see a log like this: ``` D/MarusyaObjLoader: *********************************************************************************** D/MarusyaObjLoader: Start parsing -> obj: /storage/emulated/0/jni_test/luxury_house_interior.obj, mtl: /storage/emulated/0/jni_test/luxury_house_interior.mtl D/MarusyaObjLoader: End parsing -> /storage/emulated/0/jni_test/luxury_house_interior.obj D/MarusyaObjLoader: shapes size -> 116 D/MarusyaObjLoader: materials size -> 25 D/MarusyaObjLoader: vertices size -> 390021 D/MarusyaObjLoader: normals size -> 392763 D/MarusyaObjLoader: texcoords size -> 130796 D/MarusyaObjLoader: colors size -> 390021 D/MarusyaObjLoader: indices size -> 773121 D/MarusyaObjLoader: Time to parse -> 1364 ms D/MarusyaObjLoader: *********************************************************************************** ``` ### Method ```java void disableLog(); ``` ## Performance For the performance tests were read 50 3-D models of .obj format. It was done using pure Java and JNI. For pure Java was used this cool library [https://github.com/javagl/Obj](https://github.com/javagl/Obj). The table below shows gain in speed for devices with different power when reading 3-D models of .obj format using pure Java and JNI. | Device | File size versus read time | | :--- | :---: | | **Google Pixel 2** Qualcom Snapdragon 835 (4x2.35 GGz + 4x1.9 GGz), RAM 4 GB | ![](charts/google%20pixel%202.png) | | **Huawei HRY - LX1** HiSiliconKirin 710 (4x2.2 GGz + 4x1.7 GGz), RAM 3 GB) | ![](charts/huawei%20hry-lx1.png) | | **LGE Nexus 5X** Qualcom Snapdragon 808 (2x1.44 GGz + 2x1.82 GGz), RAM 2 GB) | ![](charts/lge%20nexus%205x.png) | | **Samsung SM - G930F** Samsung Exynos 9 Octa 8890 (8x2.3 GGz), RAM 4 GB) | ![](charts/samsung%20sm-g930f.png) | | **Samsung SM - N950F** Samsung Exynos 9 Octa 8895 (4x2.3 GGz + 4x1.7 ГГц), RAM 6 GB) | ![](charts/samsung%20sm-n950f.png) | | **Samsung SM - T820** Qualcomm Snapdragon 820 (2x2.15 GGz + 2x1.6 GGz), RAM 4 GB) | ![](charts/samsung%20sm-t820.png) | | **Xiaomi Mi A1** Qualcomm Snapdragon 625 (4x2.0 GGz), RAM 4 GB) | ![](charts/xiaomi%20mi%20a1.png) | | **Xiaomi Redmi Note 5** Qualcom Snapdragon 636 (8x1.8 GGz), RAM 3 GB) | ![](charts/xioami%20redmi%20note%205.png) | On average, the download speed using JNI is **4.71** times higher. ## License This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details. <file_sep>apply plugin: 'com.android.library' apply plugin: 'com.novoda.bintray-release' publish { def groupProjectID = 'com.riseapps.marusyaobjloader' def artifactProjectID = 'marusyaobjloader' def publishVersionID = '1.0.0' userOrg = 'dmitryusikriseapps' repoName = 'MarusyaObjLoader' groupId = groupProjectID artifactId = artifactProjectID publishVersion = publishVersionID desc = '' website = 'https://github.com/dmitryusikriseapps/MarusyaObjLoader' } android { compileSdkVersion 28 defaultConfig { minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" } externalNativeBuild { cmake { path "src/main/jni/CMakeLists.txt" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { }<file_sep>package com.riseapps.marusyaobjloader.model.material; import java.util.Arrays; import java.util.HashMap; public class MaterialModel { private String name; private float[] ambient; private float[] diffuse; private float[] specular; private float[] transmittance; private float[] emission; private float shininess; private float ior; private float dissolve; private int illum; private int dummy; private String ambientTexname; private String diffuseTexname; private String specularTexname; private String specularHighlightTexname; private String bumpTexname; private String displacementTexname; private String alphaTexname; private String reflectionTexname; private TextureOptionModel ambientTexopt; private TextureOptionModel diffuseTexopt; private TextureOptionModel specularTexopt; private TextureOptionModel specularHighlightTexopt; private TextureOptionModel bumpTexopt; private TextureOptionModel displacementTexopt; private TextureOptionModel alphaTexopt; private TextureOptionModel reflectionTexopt; private float roughness; private float metallic; private float sheen; private float clearcoatThickness; private float clearcoatRoughness; private float anisotropy; private float anisotropyRotation; private float pad0; private String roughnessTexname; private String metallicTexname; private String sheenTexname; private String emissiveTexname; private String normalTexname; private TextureOptionModel roughnessTexopt; private TextureOptionModel metallicTexopt; private TextureOptionModel sheenTexopt; private TextureOptionModel emissiveTexopt; private TextureOptionModel normalTexopt; private int pad2; private HashMap<String, String> unknownParameter; public MaterialModel() { } public String getName() { return name; } public float[] getAmbient() { return ambient; } public float[] getDiffuse() { return diffuse; } public float[] getSpecular() { return specular; } public float[] getTransmittance() { return transmittance; } public float[] getEmission() { return emission; } public float getShininess() { return shininess; } public float getIor() { return ior; } public float getDissolve() { return dissolve; } public int getIllum() { return illum; } public int getDummy() { return dummy; } public String getAmbientTexname() { return ambientTexname; } public String getDiffuseTexname() { return diffuseTexname; } public String getSpecularTexname() { return specularTexname; } public String getSpecularHighlightTexname() { return specularHighlightTexname; } public String getBumpTexname() { return bumpTexname; } public String getDisplacementTexname() { return displacementTexname; } public String getAlphaTexname() { return alphaTexname; } public String getReflectionTexname() { return reflectionTexname; } public TextureOptionModel getAmbientTexopt() { return ambientTexopt; } public TextureOptionModel getDiffuseTexopt() { return diffuseTexopt; } public TextureOptionModel getSpecularTexopt() { return specularTexopt; } public TextureOptionModel getSpecularHighlightTexopt() { return specularHighlightTexopt; } public TextureOptionModel getBumpTexopt() { return bumpTexopt; } public TextureOptionModel getDisplacementTexopt() { return displacementTexopt; } public TextureOptionModel getAlphaTexopt() { return alphaTexopt; } public TextureOptionModel getReflectionTexopt() { return reflectionTexopt; } public float getRoughness() { return roughness; } public float getMetallic() { return metallic; } public float getSheen() { return sheen; } public float getClearcoatThickness() { return clearcoatThickness; } public float getClearcoatRoughness() { return clearcoatRoughness; } public float getAnisotropy() { return anisotropy; } public float getAnisotropyRotation() { return anisotropyRotation; } public float getPad0() { return pad0; } public String getRoughnessTexname() { return roughnessTexname; } public String getMetallicTexname() { return metallicTexname; } public String getSheenTexname() { return sheenTexname; } public String getEmissiveTexname() { return emissiveTexname; } public String getNormalTexname() { return normalTexname; } public TextureOptionModel getRoughnessTexopt() { return roughnessTexopt; } public TextureOptionModel getMetallicTexopt() { return metallicTexopt; } public TextureOptionModel getSheenTexopt() { return sheenTexopt; } public TextureOptionModel getEmissiveTexopt() { return emissiveTexopt; } public TextureOptionModel getNormalTexopt() { return normalTexopt; } public int getPad2() { return pad2; } public HashMap<String, String> getUnknownParameter() { return unknownParameter; } @Override public String toString() { return "MaterialModel{" + "name='" + name + '\'' + ", ambient=" + Arrays.toString(ambient) + ", diffuse=" + Arrays.toString(diffuse) + ", specular=" + Arrays.toString(specular) + ", transmittance=" + Arrays.toString(transmittance) + ", emission=" + Arrays.toString(emission) + ", shininess=" + shininess + ", ior=" + ior + ", dissolve=" + dissolve + ", illum=" + illum + ", dummy=" + dummy + ", ambientTexname='" + ambientTexname + '\'' + ", diffuseTexname='" + diffuseTexname + '\'' + ", specularTexname='" + specularTexname + '\'' + ", specularHighlightTexname='" + specularHighlightTexname + '\'' + ", bumpTexname='" + bumpTexname + '\'' + ", displacementTexname='" + displacementTexname + '\'' + ", alphaTexname='" + alphaTexname + '\'' + ", reflectionTexname='" + reflectionTexname + '\'' + ", ambientTexopt=" + ambientTexopt.toString() + ", diffuseTexopt=" + diffuseTexopt.toString() + ", specularTexopt=" + specularTexopt.toString() + ", specularHighlightTexopt=" + specularHighlightTexopt.toString() + ", bumpTexopt=" + bumpTexopt.toString() + ", displacementTexopt=" + displacementTexopt.toString() + ", alphaTexopt=" + alphaTexopt.toString() + ", reflectionTexopt=" + reflectionTexopt.toString() + ", roughness=" + roughness + ", metallic=" + metallic + ", sheen=" + sheen + ", clearcoatThickness=" + clearcoatThickness + ", clearcoatRoughness=" + clearcoatRoughness + ", anisotropy=" + anisotropy + ", anisotropyRotation=" + anisotropyRotation + ", pad0=" + pad0 + ", roughnessTexname='" + roughnessTexname + '\'' + ", metallicTexname='" + metallicTexname + '\'' + ", sheenTexname='" + sheenTexname + '\'' + ", emissiveTexname='" + emissiveTexname + '\'' + ", normalTexname='" + normalTexname + '\'' + ", roughnessTexopt=" + roughnessTexopt.toString() + ", metallicTexopt=" + metallicTexopt.toString() + ", sheenTexopt=" + sheenTexopt.toString() + ", emissiveTexopt=" + emissiveTexopt.toString() + ", normalTexopt=" + normalTexopt.toString() + ", pad2=" + pad2 + ", unknownParameter=" + unknownParameter.toString() + '}'; } }<file_sep>package com.riseapps.marusyaobjloader; import com.riseapps.marusyaobjloader.model.ResultModel; import java.io.File; import java.io.FileNotFoundException; public class MarusyaObjLoaderImpl implements MarusyaObjLoader { static { System.loadLibrary("obj_loader_jni"); } @Override public ResultModel load(File obj, boolean flipTextureCoordinates) throws FileNotFoundException { if (obj == null) { throw new FileNotFoundException("The obj file is null"); } else if (!obj.exists()) { throw new FileNotFoundException(String.format("%s not found", obj.getAbsolutePath())); } return nativeLoad(obj.getAbsolutePath(), "", 1.0f, flipTextureCoordinates); } @Override public ResultModel load(File obj, File mtl, boolean flipTextureCoordinates) throws FileNotFoundException { if (obj == null) { throw new FileNotFoundException("The obj file is null"); } else if (mtl == null) { throw new FileNotFoundException("The mtl file is null"); } else if (!obj.exists()) { throw new FileNotFoundException(String.format("%s not found", obj.getAbsolutePath())); } else if (!mtl.exists()) { throw new FileNotFoundException(String.format("%s not found", mtl.getAbsolutePath())); } return nativeLoad(obj.getAbsolutePath(), mtl.getAbsolutePath(), 1.0f, flipTextureCoordinates); } @Override public ResultModel load(File obj, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException { if (obj == null) { throw new FileNotFoundException("The obj file is null"); } else if (!obj.exists()) { throw new FileNotFoundException(String.format("%s not found", obj.getAbsolutePath())); } return nativeLoad(obj.getAbsolutePath(), "", normalizeCoefficient, flipTextureCoordinates); } @Override public ResultModel load(File obj, File mtl, float normalizeCoefficient, boolean flipTextureCoordinates) throws FileNotFoundException { if (obj == null) { throw new FileNotFoundException("The obj file is null"); } else if (mtl == null) { throw new FileNotFoundException("The mtl file is null"); } else if (!obj.exists()) { throw new FileNotFoundException(String.format("%s not found", obj.getAbsolutePath())); } else if (!mtl.exists()) { throw new FileNotFoundException(String.format("%s not found", mtl.getAbsolutePath())); } return nativeLoad(obj.getAbsolutePath(), mtl.getAbsolutePath(), normalizeCoefficient, flipTextureCoordinates); } @Override public void enableLog() { nativeEnableLog(); } @Override public void disableLog() { nativeDisableLog(); } private native ResultModel nativeLoad(String objPath, String mtlPath, float normalizeCoefficient, boolean flipTextureCoordinates); private native void nativeEnableLog(); private native void nativeDisableLog(); }<file_sep>package com.riseapps.marusyaobjloader.model; import com.riseapps.marusyaobjloader.model.material.MaterialModel; import com.riseapps.marusyaobjloader.model.mesh.ShapeModel; import java.util.Arrays; public class ResultModel { private ShapeModel[] shapeModels; private MaterialModel[] materialModels; private String warn; private String error; public ResultModel() { } public ShapeModel[] getShapeModels() { return shapeModels; } public MaterialModel[] getMaterialModels() { return materialModels; } public String getWarn() { return warn; } public String getError() { return error; } @Override public String toString() { return "ResultModel{" + "shapeModels=" + Arrays.toString(shapeModels) + ", materialModels=" + Arrays.toString(materialModels) + ", warn='" + warn + '\'' + ", error='" + error + '\'' + '}'; } }
a44c6d32dcc8b0e91c8a3f3281f2bf770f426ea0
[ "CMake", "Markdown", "Gradle", "Java", "Python", "C++" ]
14
Java
dmitryusikriseapps/MarusyaObjLoader
9688ac83925253fc29a2a7e887866efde13218c0
d34c56dc980e15db3ecfa43e48296b6c32e0cc65
refs/heads/master
<repo_name>NicklasJensen/Cdio3Gruppe11<file_sep>/src/dtu/client/Menu.java package dtu.client; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class Menu { VerticalPanel vPanel = new VerticalPanel(); public void MenuView(){ //Buttons Button CreateOperator = new Button("Create Operator"); CreateOperator.addClickHandler(new ButtonClickHanlder()); Button UdpateOperator = new Button("Udpate Operator"); UdpateOperator.addClickHandler(new ButtonClickHanlder2()); Button DeleteOperator = new Button("Delete Operator"); DeleteOperator.addClickHandler(new ButtonClickHanlder3()); Button Exit = new Button("Exit"); Exit.addClickHandler(new ButtonClickHanlder4()); Button ShowList = new Button("Vis Liste"); ShowList.addClickHandler(new ButtonClickHandler5()); //Add to Panel vPanel.add(CreateOperator); vPanel.add(UdpateOperator); vPanel.add(DeleteOperator); vPanel.add(ShowList); vPanel.add(Exit); RootPanel.get().add(vPanel); } private class ButtonClickHanlder implements ClickHandler { @Override public void onClick(ClickEvent event) { CreateOpertaoer copr = new CreateOpertaoer(); vPanel.clear(); copr.onModuleLoad(); } } // this is code to show the box on the web private class ButtonClickHanlder2 implements ClickHandler { @Override public void onClick(ClickEvent event) { UpdateOperatoer uopr = new UpdateOperatoer(); vPanel.clear(); uopr.onModuleLoad(); } } // code for Delte in not finished!!!!!!!!! private class ButtonClickHanlder3 implements ClickHandler { @Override public void onClick(ClickEvent event) { } } // for Exit code private class ButtonClickHanlder4 implements ClickHandler { @Override public void onClick(ClickEvent event) { Login ShowLogin = new Login(); vPanel.clear(); ShowLogin.onModuleLoad(); } } private class ButtonClickHandler5 implements ClickHandler { @Override public void onClick(ClickEvent event) { vPanel.clear(); } } }<file_sep>/src/src/client/service/VaegtServiceClientImpl.java package src.client.service; import com.google.gwt.core.shared.GWT; import com.google.gwt.user.client.rpc.ServiceDefTarget; public class VaegtServiceClientImpl { // global reference to service endpoint public VaegtServiceAsync service; public VaegtServiceClientImpl(String url) { // Set RPC service end point this.service = GWT.create(VaegtService.class); ServiceDefTarget endpoint = (ServiceDefTarget) this.service; endpoint.setServiceEntryPoint(url); } }
da5afc281da8e163feccfa262f06f47165950d42
[ "Java" ]
2
Java
NicklasJensen/Cdio3Gruppe11
5df1f94c99168a015a9727e14b1eb58cded7374a
5dd16d7fce6f67bf821c88828ff45f2bc11b374c
refs/heads/master
<repo_name>surya-prakash-singh/-Moodi-CMS<file_sep>/admin/posts.php <?php include "includes/admin_header.php" ?> <div id="wrapper"> <!-- Navigation --> <?php include "includes/admin_navigation.php" ?> <div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Welcome to admin <small>Author</small> </h1> <table class="table table-bordered table-hover"> <thead> <tr> <th>Post ID</th> <th>Post Author</th> <th>Post Title</th> <th>Post Category ID</th> <th>Post Image</th> <th>Post Status</th> <th>Post Tags</th> <th>Post Comment</th> <th>Post Date</th> </tr> </thead> <tbody> <?php $query = "Select * from posts"; $select_posts = mysqli_query($connection,$query); while($row=mysqli_fetch_assoc($select_posts)){ $post_id = $row['post_id']; $post_author = $row['post_author']; $post_title = $row['post_title']; $post_category_id = $row['post_category_id']; $post_image = $row['post_image']; $post_status = $row['post_status']; $post_tags = $row['post_tags']; $post_comment_count = $row['post_comment_count']; $post_date = $row['post_date']; echo "<tr>"; echo "<td>$post_id </td>"; echo "<td>$post_author</td>"; echo "<td>$post_title</td>"; echo "<td>$post_category_id</td>"; echo "<td><img class='img-responsive' width=200px src='../images/$post_image'</td>"; echo "<td>$post_status</td>"; echo "<td> $post_tags</td>"; echo "<td>$post_comment_count</td>"; echo "<td> $post_date</td>"; echo "</tr>"; } ?> </tbody> </table> <!-- /#page-wrapper --> <?php include "includes/admin_footer.php" ?> <file_sep>/README.md # -Moodi-A Content Management Systems (CMS) CMSs are used for managing what actually appears on your website—what, when, where, how and by whom. A CMS is designed to allow non-technical staff with little or no programming skill to easily and quickly publish content to a website. Content is normally defined outside of the system (e.g. an HR policy or a news item) and the CMS is used to define the presentation of the content on the website. CMSs usually provide a range of features, including the capability to: define workflows and approvals archive old content immediately publish directly to the site contribute content directly into the CMS define when content appears on the site populate a database of all information on the site (i.e. a content repository or inventory) facilitate site search functions, navigation and a site map enforce site policy, standards, structure and design automatically index and meta tag content with keywords
0a3dcfdbef9929c19acdd47ece5832fb3eb01696
[ "Markdown", "PHP" ]
2
PHP
surya-prakash-singh/-Moodi-CMS
60c73299f5c0d7ea610af642998456ca8e2d4c66
4c79f77b6aa4a3412cbe23a18347719fc0146231
refs/heads/master
<repo_name>KevinAlvss/react-first-site<file_sep>/src/components/Title/index.js import React from 'react'; import './styles.css' function Title() { return ( <div id="title-container"> <h1><NAME></h1> <strong>Quem concorda respira</strong> </div> ); } export default Title;<file_sep>/src/components/Mensagem/index.js import React from 'react'; import './styles.css'; function Mensagem() { return ( <div id="mensagem-container"> <p>7873789 pessoas já ficaram lindas com ajuda do Kevin</p> </div> ); } export default Mensagem;<file_sep>/src/components/Buttons/index.js import React from 'react'; import './styles.css'; function Buttons() { return ( <div id="buttons-container"> <p> Venha ser lindo você também </p> <div id="buttons-content"> <button> <a href="#" >Ser Lindo</a> </button> <button> <a href="#" >Já sou</a> </button> <button> <a href="#">Ainda não</a> </button> </div> </div> ); } export default Buttons;
7d5bb82138c26631e00634098e4c6bd94a10e2d1
[ "JavaScript" ]
3
JavaScript
KevinAlvss/react-first-site
9474edf39a220aa16ce1ada188f3bbc5f6c2218c
d1284b440ce997b22343cc3d23568e1aa456187a
refs/heads/master
<file_sep>require 'socket' # Get sockets from stdlib server = TCPServer.open('0.0.0.0', 2000) # Socket to listen on all interaces at port 2000 loop { # Servers run forever Thread.start(server.accept) do |client| puts "Accepted connection from #{client.peeraddr}" 10.times do client.puts(Time.now.ctime) # Send the time to the client client.puts "Holding the connection. Wait a sec!" sleep(1) end client.puts "Closing the connection. Bye!" client.close # Disconnect from the client end }<file_sep># Usage: ruby client3.rb host port team require 'socket' # Sockets are in standard library hostname = ARGV[0] port = ARGV[1] team = ARGV[2] s = TCPSocket.open(hostname, port) s.puts team # send team name $stdout.puts s.gets # echo handshake in $stdout.flush $stdout.puts "The 'Enter' key is your button. Ctrl-C or Ctrl-D will disconnect." $stdout.flush while $stdin.gets # Read lines from the input, discarding input as we're only interested in the 'enter' s.puts team # send team name on enter end $stdout.puts "Disconnecting..." s.close # close the socket<file_sep>require 'thread' require 'socket' # Get sockets from stdlib host = '0.0.0.0' port = 2000 win = "control" win_sem = Mutex.new server = TCPServer.open(host, port) # Socket to listen on all interaces at port 2000 puts "Starting #{$0} to listen on port #{port}" loop { # Servers run forever Thread.start(server.accept) do |client| puts "Accepted connection from #{client.peeraddr}" team = client.gets.strip puts "Team name is #{team}" client.puts("Welcome team #{team}. You are connected.") client.flush while sent = client.gets win_sem.synchronize { if win == "control" || team == "control" then win = team puts "#{team} wins!" end } hit_time = Time.now puts "#{hit_time.strftime('%H:%M:%S.%L')} #{team}" end puts "#{team} has disconnected." client.close # Disconnect from the client end }<file_sep># Usage: ruby client3.rb host port team require 'socket' # Sockets are in standard library Shoes.app(title: "TeamButton") do hostname = "192.168.1.64" # ARGV[0] port = 2000 # ARGV[1] team = "shoes" # ARGV[2] stack { caption "Connection" flow { inscription "Hostname :", :width => 500, stroke: red @hostedit = edit_line @hostedit.text = hostname } flow { inscription "Port number: " @portedit = edit_line @portedit.text = port } flow { inscription "Team name:" @teamedit = edit_line @teamedit.text = team } } stack { @connect_button = button "Connect" @team_button = button "We know!", :height => 300 } @connect_button.click { @info = para "Setting up..." @info.text = "#{@hostedit.text}, #{port.to_s}, #{@teamedit.text}" @s = TCPSocket.open(@hostedit.text, port) @s.puts @teamedit.text # send team name handshake = @s.gets # receive handshake para handshake } @team_button.click { @s.puts team } end
612bc018d0f8384183e0c8b9a22b71ba4d5b8492
[ "Ruby" ]
4
Ruby
clivemjeffery/teambutton
c693ba8efa1c64c7c31281f08fc6a75b1dae4eed
eec8b3c96fa6815e2143e90c669b6765223220c5
refs/heads/master
<repo_name>DavidArchibald/ArchiveBot<file_sep>/reddit.go package main import ( "fmt" "net/http" "strconv" "sync" "time" "github.com/vartanbeno/go-reddit/reddit" ) // RedditConfig is the toml configuration for Reddit. type RedditConfig struct { Username string `toml:"username"` Password string `toml:"<PASSWORD>"` ClientID string `toml:"client_id"` ClientSecret string `toml:"client_secret"` RedirectURI string `toml:"redirect_uri"` UserAgent string `toml:"user_agent"` SearchLimit int `toml:"search_limit"` URL string `toml:"url"` } // Reddit is the structure for Reddit. type Reddit struct { *reddit.Client http *http.Client client *Client lock sync.Locker rateLimit *Limiter } // Limiter limits how often a can occur. type Limiter struct { currentRateLimit *RateLimit rateLimitDone chan struct{} } // RateLimit is a rate limit returned by Reddit. type RateLimit struct { time time.Time used int remaining int reset int resetTime time.Time } func (r *RateLimit) String() string { return fmt.Sprintf("used: %d, remaining: %d, reset: %d", r.used, r.remaining, r.reset) } // SubmissionData is the data Reddit's post listing returns. // A blank before, after, and zero children means either the post is deleted or the only one in the subreddit. type SubmissionData struct { Data struct { Children []struct { Data *reddit.Post } Before string `json:"before"` After string `json:"after"` } } // SubmissionsResponse is the response of a submission listing. type SubmissionsResponse struct { Submissions []*reddit.Post Next *reddit.ListOptions } // RedditSubredditPrefix is the prefix of a subreddit's name. const RedditSubredditPrefix = "/r/" // NewRedditClient creates a new Reddit client. func NewRedditClient(client *Client, config *Config) (*Reddit, error) { h := &http.Client{} r, err := reddit.NewClient(h, &reddit.Credentials{ ID: config.Reddit.ClientID, Secret: config.Reddit.ClientSecret, Username: config.Reddit.Username, Password: config.Reddit.Password, }) if err != nil { return nil, err } ticker := make(chan struct{}, 1) limiter := &Limiter{nil, ticker} return &Reddit{r, h, client, &sync.Mutex{}, limiter}, nil } // func authenticateInBrowser() { // url := authenticator.GetAuthenticationURL() // err := browser.OpenURL(url) // if err != nil { // fmt.Printf("Could not open browser: %s\nPlease open URL manually: %s\n", err, url) // } // http.HandleFunc("/") // http.ListenAndServe() // } // func (r *Reddit) getSubmissions(params reddit.ListOptions) (*SubmissionsResponse, *ContextError) { // c := r.client // isForwards := true // Synonymous with using after // searchDescriptor := "" // if params.Before != "" && params.After != "" { // err := NewContextError(errors.New("both before and after param is set"), []ContextParam{ // {"params", fmt.Sprint(params)}, // }) // c.dfatal(err) // return nil, err // } else if params.Before != "" { // isForwards = false // searchDescriptor = "before " + params.Before // } else if params.After != "" { // searchDescriptor = "after " + params.After // } else { // searchDescriptor = "from start" // } // c.Logger.Infof("Reading submissions %s.", searchDescriptor) // posts, _, err := r.Subreddit.NewPosts(ctx, c.Config.Subreddit.Name, &reddit.ListOptions{ // Limit: c.Config.Reddit.SearchLimit, // After: params.After, // Before: params.Before, // }) // err = c.checkSubmissions(posts, isForwards) // if err != nil { // return nil, NewContextlessError(err).Wrap("could not check submissions") // } // next := &reddit.ListOptions{} // *next = params // if params.Before != "" { // next.Before = posts.Before // if next.Before == "" { // next = nil // } // } else { // next.After = posts.After // if next.After == "" { // next = nil // } // } // return &SubmissionsResponse{posts.Posts, next}, nil // } // NewRateLimit constructs a rate limit from a response. func (r *Reddit) NewRateLimit(resp *http.Response) (*RateLimit, *ContextError) { headers := [...]string{"X-Ratelimit-Used", "X-Ratelimit-Remaining", "X-Ratelimit-Reset"} headerInts := [...]int{0, 0, 0} for i, header := range headers { headerString := resp.Header.Get(header) headerInt, err := strconv.Atoi(headerString) if err != nil { return nil, NewWrappedError("could not parse rate limit header", err, []ContextParam{ {header, headerString}, {"All Headers", fmt.Sprint(resp.Header)}, }) } headerInts[i] = headerInt } now := time.Now() used, remaining, reset := headerInts[0], headerInts[1], headerInts[2] resetTime := now.Add(time.Duration(reset) * time.Second) return &RateLimit{now, used, remaining, reset, resetTime}, nil } // SetRateLimit sets the rate limit if it is newer than the currently set one. func (r *Reddit) SetRateLimit(newLimit *RateLimit) { c := r.client c.Reddit.lock.Lock() defer c.Reddit.lock.Unlock() currentLimit := c.Reddit.RateLimit() if currentLimit == nil { c.Logger.Infof("First rate limit: %s", newLimit) c.Reddit.rateLimit.currentRateLimit = newLimit return } if currentLimit.time.Before(newLimit.time) { c.Reddit.rateLimit.currentRateLimit = newLimit } else { return } if newLimit.remaining == 0 { c.Logger.Infof("Used all limits approximately %d seconds until reset.", currentLimit.reset) } if currentLimit.remaining == 0 && newLimit.remaining != 0 { givenDuration := time.Duration(currentLimit.reset) realDuration := time.Now().Sub(currentLimit.time) difference := givenDuration - realDuration if difference > -1 && difference < 1 { c.Logger.Infof("Limits reset after %v.", realDuration) } else { c.Logger.Infof("Limits reset after %v (expected %v).", realDuration, givenDuration) } } } // RateLimit gets a copy of the rate limit. func (r *Reddit) RateLimit() *RateLimit { if r.rateLimit == nil || r.rateLimit.currentRateLimit == nil { return nil } currentLimit := &RateLimit{} *currentLimit = *r.rateLimit.currentRateLimit return currentLimit } // IsRateLimited checks to see if the process is rate limited. func (r *Reddit) IsRateLimited() bool { if r.rateLimit == nil || r.rateLimit.currentRateLimit != nil { return false } return time.Now().Before(r.rateLimit.currentRateLimit.resetTime) } <file_sep>/logger.go package main import ( "fmt" "os" "strings" "time" rotatelogs "github.com/lestrrat-go/file-rotatelogs" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // NewLogger creates a formatted logger to make it easier to read. func NewLogger(isProduction bool) (*zap.SugaredLogger, error) { var ( config zap.Config err error ) if isProduction { config = zap.NewDevelopmentConfig() } else { config = zap.NewProductionConfig() config.Encoding = "console" config.EncoderConfig = zap.NewDevelopmentEncoderConfig() } if err != nil { return nil, err } logFile := "./logs/ArchiveBot-%Y-%m-%d-%H.log" rotator, err := rotatelogs.New( logFile, rotatelogs.WithMaxAge(60*24*time.Hour), rotatelogs.WithRotationTime(time.Hour), ) if err != nil { return nil, err } w := zapcore.AddSync(rotator) fileCore := zapcore.NewCore( zapcore.NewConsoleEncoder(config.EncoderConfig), w, config.Level, ) toFile := zap.WrapCore(func(c zapcore.Core) zapcore.Core { return zapcore.NewTee(c, fileCore) }) logger, err := config.Build(toFile) if err != nil { return nil, err } return logger.Sugar(), nil } // log an error with added context if relevant. func (c *Client) log(err error) { ce, ok := err.(*ContextError) if ok { ce.LogError(c.Logger) } else { c.Logger.Error(err) } } // fatal is equivalent to log() followed by os.Exit(1) func (c *Client) fatal(err error) { if ce, ok := err.(*ContextError); ok { err = ce.Wrap("FATAL") } else { err = fmt.Errorf("FATAL: %w", err) } c.log(err) os.Exit(1) } // dfatal is fatal except it only exits in development mode. // This is used more often that might be expected as to keep the processes running. // Secondly, because there are many APIs that don't always behave consistently, issues may crop up without programmer error. func (c *Client) dfatal(err error) { if ce, ok := err.(*ContextError); ok { err = ce.Wrap("DEVELOPMENT FATAL") } else { err = fmt.Errorf("DEVELOPMENT FATAL: %w", err) } c.log(err) if !c.IsProduction { os.Exit(1) } } // dpanic panics only in development mode. func (c *Client) dpanic(v interface{}) { if c.IsProduction { panic(v) } else { c.Logger.Error("UNEXPECTED PANIC: %v", v) } } // ContextError is an error with additional debugging context. type ContextError struct { context []ContextParam contextKeys map[string]struct{} history []ContextError combinedWith []ContextError err error } // ContextParam is a contextual parameter. type ContextParam struct { key string value string } var _ error = &ContextError{} // NewContextlessError creates a ContextError with no context. This is essentially a no-op. func NewContextlessError(err error) *ContextError { return &ContextError{[]ContextParam{}, make(map[string]struct{}), nil, nil, err} } // NewWrappedError wraps the error and then adds context. func NewWrappedError(wrap string, err error, context []ContextParam) *ContextError { ce := NewContextError(err, context) ce.err = fmt.Errorf("%s: %w", wrap, err) return ce } // NewContextError creates a new contextual error. func NewContextError(err error, context []ContextParam) *ContextError { if ce, ok := err.(*ContextError); ok { if ce == nil { return &ContextError{context, make(map[string]struct{}), nil, nil, err} } temp := *ce for _, param := range context { if _, ok := ce.contextKeys[param.key]; ok { isSet := false // Replace an existing instance of context if one exists. Remove extras. for i, contextParam := range ce.context { if contextParam.key == param.key { if !isSet { temp.context[i] = param } else { temp.context = append(temp.context[:i], temp.context[i+1:]...) } } } if isSet { continue } } temp.context = append(temp.context, param) temp.contextKeys[param.key] = struct{}{} } temp.history = nil temp.history = append(ce.history, temp) return &temp } contextKeys := make(map[string]struct{}) for _, param := range context { contextKeys[param.key] = struct{}{} } return &ContextError{context, contextKeys, nil, nil, err} } // AddContext to an error. func (ce *ContextError) AddContext(key, value string) *ContextError { ce.context = append(ce.context, ContextParam{key, value}) ce.contextKeys[key] = struct{}{} return ce } // GetContext gets a contextual value. func (ce *ContextError) GetContext(key string) string { for _, v := range ce.context { if v.key == key { return v.value } } return "" } // RemoveContext removes a contextual value. func (ce *ContextError) RemoveContext(key string) *ContextError { if _, ok := ce.contextKeys[key]; !ok { return ce } for i, v := range ce.context { if v.key == key { ce.context = append(ce.context[:i], ce.context[i+1:]...) } } delete(ce.contextKeys, key) return ce } // Wrap this error, returning itself for chaining. func (ce *ContextError) Wrap(msg string) *ContextError { history := make([]ContextError, len(ce.history)) copy(ce.history, history) ce.history = nil ce.err = fmt.Errorf("%s: %w", msg, ce.err) ce.history = append(history, *ce) return ce } func (ce *ContextError) Error() string { return fmt.Sprint(ce.err) } func (ce *ContextError) Unwrap() error { if len(ce.history) != 0 { return ce.UnwrapContext() } return ce.err } // UnwrapContext unwraps a contextual error only. func (ce *ContextError) UnwrapContext() *ContextError { if len(ce.history) != 0 { err := ce.history[0] err.history = ce.history[1:] return &err } return nil } // Panic a contextual error. func (ce *ContextError) Panic(logger *zap.SugaredLogger) { ce.LogError(logger) panic(ce.err) } // LogError a contextual error. func (ce *ContextError) LogError(logger *zap.SugaredLogger) { logger.Error(ce.err) if context := ce.FormattedContext(logger); context != "" { logger.Info(context) } } // LogWarn outputs a contextual error as a warning. func (ce *ContextError) LogWarn(logger *zap.SugaredLogger) { logger.Warn(ce.err) if context := ce.FormattedContext(logger); context != "" { logger.Info(context) } } // FormattedContext logs the context at the info level. func (ce *ContextError) FormattedContext(logger *zap.SugaredLogger) string { if len(ce.context) == 0 || ce.context != nil { var context strings.Builder for _, value := range ce.context { context.WriteString(fmt.Sprintf("\n%s = %s", value.key, value.value)) } return context.String() } return "'" } <file_sep>/main.go package main import ( "time" ) func main() { client := NewClient("config.toml") defer client.Close() go func() { for !client.closed { nextSubmissions := client.ReadPushshiftSubmissions() readSubmissions(client, nextSubmissions) time.After(15 * time.Minute) } }() go analyzeSubmissions(client) go client.ReplyToInbox() client.Run() } func readSubmissions(client *Client, nextSubmissions func() ([]PushshiftSubmission, error)) { submissionsCount := 0 for { submissions, err := nextSubmissions() if err != nil { client.dfatal(err) break } if len(submissions) == 0 { break } if err := client.Redis.addSubmissions(submissions); err != nil { client.dfatal(err) break } addedSubmissions := len(submissions) submissionsCount += addedSubmissions firstSubmission := submissions[0] lastSubmission := submissions[addedSubmissions-1] client.Logger.Infof("Added %d Pushshift submissions: %s (epoch: %f) to %s (epoch: %f).", addedSubmissions, "t3_"+firstSubmission.ID, firstSubmission.DateCreated, "t3_"+lastSubmission.ID, lastSubmission.DateCreated) } client.Logger.Infof("Added %d Pushshift submissions.", submissionsCount) } func analyzeSubmissions(client *Client) { processName := "Analyze Submissions" for !client.closed { client.Processes.RoutineStart(processName) err := client.AnalyzeSubmissions() if err != nil { client.dfatal(err) } client.Processes.RoutineWait(processName) } } <file_sep>/pushshift.go package main import ( "bytes" "encoding/json" "errors" "fmt" "net/url" "time" ) // PushshiftSearch is a structure to traverse history through Pushshift. type PushshiftSearch struct { last *PushshiftSubmission done bool } // NewPushshiftSearch constructs a search . func NewPushshiftSearch(client *Client, config *Config) *PushshiftSearch { return &PushshiftSearch{} } // PushshiftData is the structure of the returned pushshift data type PushshiftData struct { Data []PushshiftSubmission `json:"data"` } // PushshiftSubmission is the extracted information from a Pushshift message. type PushshiftSubmission struct { PushshiftFields Raw map[string]interface{} } // PushshiftFields are the extracted fields of a submission. // reddit.Submission is not necessarily guaranteed to match and so is not used. type PushshiftFields struct { Permalink string `json:"permalink"` ID string `json:"id"` Title string `json:"title"` Ups int `json:"ups"` DateCreated float64 `json:"created_utc"` LinkFlairText string `json:"link_flair_text"` } // UnmarshalJSON from bytes. func (s *PushshiftSubmission) UnmarshalJSON(b []byte) error { var fields PushshiftFields if err := json.Unmarshal(b, &fields); err != nil { return NewContextError(err, []ContextParam{ {"responseData", fmt.Sprintf(`"%s"`, b)}, }) } var raw map[string]interface{} if err := json.Unmarshal(b, &raw); err != nil { return NewContextError(err, []ContextParam{ {"responseData", fmt.Sprintf(`"%s"`, b)}, }) } *s = PushshiftSubmission{fields, raw} return nil } // MarshalJSON turns into a submission into JSON. func (s PushshiftSubmission) MarshalJSON() ([]byte, error) { return json.Marshal(s.Raw) } // MarshalBinary turns the JSON string into raw bytes. func (s PushshiftSubmission) MarshalBinary() ([]byte, error) { var b bytes.Buffer if err := json.NewEncoder(&b).Encode(s.Raw); err != nil { return nil, err } return b.Bytes(), nil } // ErrSubmissionsRead is returned with ReadSubmissions has finished reading all submissions. var ErrSubmissionsRead = errors.New("all submissions read") // ErrMaySkipSubmissions is returned when submissions may be skipped. // This occurs when a request returns submissions starting and ending with the same epoch. // Because paging submissions is dependent on the epoch, if a page is filled with the same epoch . // For example, if the limit is 10 and there are 10 posts with the same epoch going to the next epoch var ErrMaySkipSubmissions = errors.New("submissions may be skipped") // ErrInvalidLimit occurs when the limit is invalid. var ErrInvalidLimit = errors.New("invalid limit") // ReadPushshiftSubmissions gets every submission with an appropriate delay between. func (c *Client) ReadPushshiftSubmissions() func() ([]PushshiftSubmission, error) { return func() ([]PushshiftSubmission, error) { history := c.PushshiftSearch config := c.Config submissions, err := c.ReadSubmissionBatch() if err != nil && !errors.Is(err, ErrSubmissionsRead) { return nil, err } if history.done && submissions == nil { return nil, nil } time.Sleep(time.Duration(config.Pushshift.Delay)) return submissions, nil } } // ReadSubmissionBatch reads a batch of submissions from Pushshift. // ReadSubmissionBatch will panic if given a limit less than 2. There is no known downside to putting the limit to the current maximum of 500, the minimum suggested is 10. // The length returned will be less than or equal to the limit, usually about the limit - 1 after the first request. This is to prevent submissions being skipped. // If the error is the sentinel error ErrSubmissionsRead, any submissions are still valid. Otherwise if a submission is returned with an error, it is unintended behavior. func (c *Client) ReadSubmissionBatch() ([]PushshiftSubmission, error) { history := c.PushshiftSearch config := c.Config if config.Subreddit.Limit <= 2 { c.Logger.DPanic( fmt.Errorf("expected limit to be at least 2, %w", ErrInvalidLimit), ) } if history.done { return nil, ErrSubmissionsRead } submissions, err := c.readSubmissionBatch() if err != nil { return submissions, err } lastBatch := &PushshiftSubmission{} if history.last != nil { *lastBatch = *history.last } for i, submission := range submissions { if i == len(submissions) { break } if submission.ID == lastBatch.ID { submissions = submissions[i+1:] break } } // When reading is done, none will be returned or only the submission as the search is made inclusive. if len(submissions) == 0 || (len(submissions) == 1 && submissions[0].ID == lastBatch.ID) { history.last = nil history.done = true return nil, NewContextlessError(ErrSubmissionsRead).Wrap("all submissions read") } lastIndex := len(submissions) - 1 lastSubmission := submissions[lastIndex] history.last = &lastSubmission if lastSubmission.DateCreated == lastBatch.DateCreated { // If this is reached the page is full of submissions of the same epoch. // This edge case is likely only relevant on low limits as it's unlikely the maximal limit of 500 with result in posts with the same epoch. // Reading is still valid if necessitated so this epoch is skipped. history.last.DateCreated++ return submissions, NewWrappedError("request returned all same epoch", ErrMaySkipSubmissions, []ContextParam{ {"epoch", fmt.Sprint(lastSubmission.DateCreated)}, }) } return submissions, nil } func (c *Client) readSubmissionBatch() ([]PushshiftSubmission, error) { h := c.PushshiftSearch config := c.Config name := url.QueryEscape(config.Subreddit.Name) requestURL := fmt.Sprintf("%s?subreddit=%s&limit=%d", config.Pushshift.URL, name, config.Subreddit.Limit) if h.last != nil { // Makes the request include the last recorded epoch, for the edge case of the last request ending with an epoch in which there are still more comments of the same epoch right after, outside the search limit. requestURL += fmt.Sprintf("&before=%d", int64(h.last.DateCreated)+1) } b, ce := c.doRequest("GET", requestURL, nil, nil) if ce != nil { return nil, ce.Wrap("reading failed") } var responseJSON PushshiftData if err := json.Unmarshal(b, &responseJSON); err != nil { return nil, NewContextError(err, []ContextParam{ {"requestURL", requestURL}, {"responseData", fmt.Sprintf(`"%s"`, b)}, }) } return responseJSON.Data, nil } <file_sep>/inbox.go package main import ( "errors" "fmt" "strings" "github.com/go-redis/redis/v8" "github.com/vartanbeno/go-reddit/reddit" ) // RedditMarkReadBatch is the number of comments that Reddit allows to be read at once. const RedditMarkReadBatch = 25 // Listing is the data a listing will return. type Listing struct { Data struct { Kind string `json:"kind"` Children []struct { Data ListingItem `json:"data"` } `json:"children"` } `json:"data"` Before string `json:"before,omitempty"` After string `json:"after,omitempty"` } // ListingItem is the combined information of different listing kinds. type ListingItem struct { Body string `json:"body"` *reddit.Post } // ReplyToInbox checks the inbox and replies to mentions. func (c *Client) ReplyToInbox() { processName := "Reply To Inbox" p := c.Processes for !c.closed { p.RoutineStart(processName) ce := c.replyToInbox() if ce != nil { c.dfatal(ce) } p.RoutineWait(processName) } } func (c *Client) replyToInbox() *ContextError { // TODO: make it actually iterate backwards. c.Logger.Infof("Reading inbox") comments, _, _, err := c.Reddit.Message.InboxUnread(ctx, &reddit.ListOptions{ Limit: 100, }) if err != nil { return NewContextlessError(err) } if len(comments.Messages) == 0 { c.Logger.Info("No new comments.") } var read []string for _, item := range comments.Messages { if strings.Contains(item.Text, "u/"+c.Config.Reddit.Username) { err := c.replyToComment(item) if err != nil { c.dfatal(err) continue } read = append(read, item.FullID) } else { c.Logger.Infof("Not a mention, skipping processing message (ID: %s).\nBody: %s", item.FullID, item.Text) } } return c.MarkAsRead(read) } // ErrCouldNotParse is the error given when a reply can't be parsed. var ErrCouldNotParse = errors.New("Could not parse") func (c *Client) replyToComment(l *reddit.Message) *ContextError { parts := strings.SplitN(l.Text, "u/"+c.Config.Reddit.Username, 2) if len(parts) == 1 { notParse := c.Config.Constants.CouldNotParse + c.Config.Constants.Footer c.reply(l, notParse) c.Logger.DPanic("Message has no mention in it!") return NewContextError(ErrCouldNotParse, []ContextParam{ {"Reply Author", l.Author}, {"Reply ID", l.FullID}, {"Reply Text", l.Text}, }) } mentionLine := parts[1] fields := strings.Fields(mentionLine) name := strings.ToLower(fields[0]) arguments := fields[1:] constants := c.Config.Constants switch name { case "help": return c.HelpCommand(l, arguments) case "find": fallthrough case "search": return c.SearchCommand(l, arguments) default: return c.reply(l, fmt.Sprintf(constants.CouldNotParse+constants.HelpBody, fmt.Sprintf("Unknown command `%s`.", name))) } } // HelpCommand is the . func (c *Client) HelpCommand(m *reddit.Message, arguments []string) *ContextError { constants := c.Config.Constants return c.reply(m, constants.HelpStart+constants.HelpBody) } // SearchCommand is the command to search through search terms. func (c *Client) SearchCommand(m *reddit.Message, arguments []string) *ContextError { constants := c.Config.Constants couldNotParse := constants.CouldNotParse + constants.HelpBody if len(arguments) == 0 { return c.reply(m, fmt.Sprint(couldNotParse, "I need more info to find you anything.")) } matches := c.Search.getTitleMatches(arguments[0]) var search string var flairArgument string if len(matches) == 0 { flairArgument = strings.Join(arguments, " ") } else { search = matches[0] flairArgument = strings.Join(arguments[1:], " ") } r := c.Redis var searchResults []redis.Z if search != "" { var ce *ContextError searchResults, ce = r.getZSet(RedisSearchPrefix + search) if ce != nil { return ce } } var flairs []redis.Z if flairArgument != "" { var ce *ContextError flairs, ce = r.getZSet(RedisFlairsPrefix + flairArgument) if ce != nil { return ce } } // The round trip time to do this in a loop would be too expensive to justify. Hopefully memory doesn't overflow. linkMap, err := c.Redis.HGetAll(ctx, RedisLinks).Result() if err != nil { return NewContextError(err, []ContextParam{ {"Redis Key", RedisLinks}, }) } // The round trip time to do this in a loop would be too expensive to justify. Hopefully memory doesn't overflow. submissions, err := c.Redis.HGetAll(ctx, RedisSubmissions).Result() if err != nil { return NewContextError(err, []ContextParam{ {"Redis Key", RedisLinks}, }) } var allResults []redis.Z if len(searchResults) != 0 && len(flairs) != 0 { allResults = c.ZIntersect(searchResults, flairs) } else if len(searchResults) != 0 { allResults = searchResults } else if len(flairs) != 0 { allResults = flairs } results := make([]redis.Z, 0, 25) i := 0 for _, result := range allResults { if i >= 25 { break } if _, ok := submissions[result.Member.(string)]; ok { results[i] = result i++ } } links := make([]string, 0, len(results)) for _, result := range results { member, ok := result.Member.(string) if !ok { c.dfatal(fmt.Errorf("Expected search and title results to only contain strings, instead received member of type %T with value %s and score %f", member, member, result.Score)) continue } links = append(links, "- "+linkMap[member]) } argumentString := strings.Join(arguments, " ") if len(links) == 0 { noResults := fmt.Sprintf(constants.NoResults, argumentString) return c.reply(m, noResults) } allLinks := strings.Join(links, "\n\n") foundResults := fmt.Sprintf(constants.FoundResults+"\n\n", argumentString) return c.reply(m, foundResults+allLinks+constants.Footer) } // ZIntersect gets the intersection of two sorted sets. func (c *Client) ZIntersect(a []redis.Z, b []redis.Z) []redis.Z { var larger []redis.Z var smaller []redis.Z if len(a) > len(b) { larger, smaller = a, b } else { larger, smaller = b, a } baseSet := make(map[redis.Z]struct{}, len(smaller)) for _, item := range smaller { baseSet[item] = struct{}{} } i := 0 keys := make([]redis.Z, len(smaller)) for _, item := range larger { if _, ok := baseSet[item]; ok { if i >= len(smaller) { break } keys[i] = item i++ } } return keys } func (c *Client) reply(m *reddit.Message, message string) *ContextError { _, _, err := c.Reddit.Comment.Submit(ctx, m.FullID, message) if err != nil { return NewWrappedError("replying to comment", err, []ContextParam{ {"Author Reply", m.Author}, {"Comment ID", m.FullID}, {"Body", message}, }) } return nil } // RedditMarkReadPayload is the payload Reddit requires to mark submissions as read. type RedditMarkReadPayload struct { ID string `json:"id"` } // MarkAsRead batches ids up to RedditMarkReadBatch and marks them as read. func (c *Client) MarkAsRead(ids []string) *ContextError { for len(ids) > 0 { idBatch := ids if len(ids) > RedditMarkReadBatch { idBatch = ids[:RedditMarkReadBatch] } if len(idBatch) == 1 { c.Logger.Infof("Marking id: %v as read.", idBatch[0]) } else { c.Logger.Infof("Marking ids: %v as read.", idBatch) } _, err := c.Reddit.Message.Read(ctx, idBatch...) if err != nil { return NewWrappedError("setting message read", err, []ContextParam{ {"ids", fmt.Sprint(idBatch)}, }) } processed := make([]interface{}, len(idBatch)) for i, id := range idBatch { processed[i] = id } if err := c.Redis.SAdd(ctx, RedisProcessed, processed...).Err(); err != nil { return NewWrappedError("could not add processed submissions to Redis", err, []ContextParam{ {"IDs", fmt.Sprint(idBatch)}, }) } ids = ids[len(idBatch):] } return nil } <file_sep>/processes.go package main import ( "sync" "time" ) // Processes control the type Processes struct { client *Client config *Config reserveLock sync.Locker reserved map[string]reservation nextReserve map[string]reservation ticker *time.Ticker routineTicker chan struct{} wg *sync.WaitGroup closeFuncs map[string]func() } // reservation holds the reserved API info calls. type reservation struct { reservation uint64 unused uint64 buffer uint64 } // NewProcesses creates a structure for managing processes. func NewProcesses(client *Client, config *Config) *Processes { var reserveLock *sync.Mutex reserved := make(map[string]reservation) nextReserve := make(map[string]reservation) ticker := time.NewTicker(config.Application.TickSpeed) routineTicker := make(chan struct{}) wg := &sync.WaitGroup{} closeFuncs := make(map[string]func()) return &Processes{client, config, reserveLock, reserved, nextReserve, ticker, routineTicker, wg, closeFuncs} } // Start begins the process loop. func (p *Processes) Start() { c := p.client timer := time.NewTicker(c.Config.Application.LoopDelay) go func() { for !c.closed { p.routineTicker <- struct{}{} p.wg.Wait() // The timer can be cancelled using this method, but should otherwise be equivalent to time.Sleep(...) timer.Reset(c.Config.Application.LoopDelay) <-timer.C for !c.closed && !c.Reddit.IsRateLimited() { <-p.Tick() } } }() for !c.closed { <-p.Tick() } p.ticker.Stop() <-p.Tick() timer.Reset(0) <-timer.C <-p.routineTicker close(p.routineTicker) } // OnClose adds a function called when a process closes. func (p *Processes) OnClose(processName string, closeFunc func()) { p.closeFuncs[processName] = closeFunc } // Close closes the process loop. func (p *Processes) Close() { p.client.closed = true <-p.routineTicker close(p.routineTicker) for _, closeFunc := range p.closeFuncs { closeFunc() } } // RoutineStart will begin a routine. func (p *Processes) RoutineStart(name string) { } // RoutineWait will block until the process may continue. func (p *Processes) RoutineWait(name string) { <-p.routineTicker } // RoutineCrash will handle a routine crashing. func (p *Processes) RoutineCrash(name string) { if err := recover(); err != nil { p.client.dpanic(err) } } // ReserveNextLoop is. func (p *Processes) ReserveNextLoop(name string, reservation uint64, buffer uint64) {} // Release will release any held limits func (p *Processes) Release(name string) {} // Tick returns the ticker for the tick speed. func (p *Processes) Tick() <-chan time.Time { return p.ticker.C } <file_sep>/client.go package main import ( "log" "go.uber.org/zap" ) // Client is the encapsulation of the relevant clients used. type Client struct { *Flags Logger *zap.SugaredLogger Config *Config Redis *Redis Reddit *Reddit Search *Search PushshiftSearch *PushshiftSearch Processes *Processes closed bool // Can only be set to true, once. } // Flags are the application flags, sourced from Config.Application, hoisted for convenience. type Flags struct { IsProduction bool } // NewClient creates the needed Client connections. func NewClient(configPath string) *Client { client := &Client{} config, err := OpenConfig(configPath) if err != nil { log.Fatalf("could not open config: %v", err) } flags := &Flags{config.Application.IsProduction} logger, err := NewLogger(flags.IsProduction) if err != nil { log.Fatal("could not creator logger: %w", err) } rdb, err := NewRedisClient(client, config) if err != nil { logger.Panicf("could not create Redis client: %v", err) } reddit, err := NewRedditClient(client, config) if err != nil { defer rdb.Close() logger.Panicf("could not create Reddit client: %v", err) } search, ce := NewSearch(client, config) if ce != nil { ce.Panic(logger) } pushshiftSearch := NewPushshiftSearch(client, config) processes := NewProcesses(client, config) return &Client{flags, logger, config, rdb, reddit, search, pushshiftSearch, processes, false} } // Close the client's functions. func (c *Client) Close() { c.Redis.Close() c.Logger.Sync() c.Processes.Close() } // Run is used to control the event loop until the client closes. func (c *Client) Run() { c.Processes.Start() } <file_sep>/search.go package main import ( "regexp" "time" "github.com/go-redis/redis/v8" ) // Search store information about the range of discovered information. // The marker anchor is set to the last traversed submission and is used to resume next iteration. It is ignored on startup to update newer posts faster. // The end anchor is the newest known locked submission. for which submissions can safely not be checked. This prevents the search from being forced to traverse every historical submission. type Search struct { client *Client config *Config Current *Anchor // The last processed submission. Start *Anchor // The start of currently recorded submissions. End *Anchor // The newest locked submission; statistics for posts will not update past this anchor. TraversedAll bool // Whether the entire history been traversed. If not, submissions after the end anchor will be analyzed. IsForwards bool // Whether the current anchor is traversing forwards or not. LockTime time.Duration // The amount of time a submission has until it is locked. Currently 60 days. MaxRequests int // The max requests a search iteration can have. -1 is infinite. } // ConstantsConfig is the search data. type ConstantsConfig struct { CouldNotParse string `toml:"could_not_parse"` HelpStart string `toml:"help_start"` HelpBody string `toml:"help_body"` NoResults string `toml:"no_results"` FoundResults string `toml:"found_results"` Footer string `toml:"footer"` Searches [][]string `toml:"searches"` } // NewSearch initializes all the information needed for a bidirectional search. // Search expects Redis to already be initalized. func NewSearch(client *Client, config *Config) (*Search, *ContextError) { anchorKeys := []string{RedisSearchCurrent, RedisSearchStart, RedisSearchEnd} anchors := make([]*Anchor, len(anchorKeys)) for i, anchorKey := range anchorKeys { anchor, ce := client.Redis.getAnchor(anchorKey) if ce != nil && ce.Unwrap().Error() != redis.Nil.Error() { return nil, ce } anchors[i] = anchor } // A lock occurs after 60 days. lock := 60 * (time.Duration(24) * time.Hour) return &Search{client, config, anchors[0], anchors[1], anchors[2], false, true, lock, 10}, nil } func (s *Search) getSubmissions() { } // GetLockUnix returns the Unix time when posts will become locked. func (s *Search) GetLockUnix() int64 { lockTime := time.Now().Add(-s.LockTime) return lockTime.Unix() } func (s *Search) getTitleMatches(title string) []string { var matches []string for _, searches := range s.config.Constants.Searches { canonical := searches[0] for _, search := range searches { expr := "(?i)\\b" + regexp.QuoteMeta(search) + "\\b" exp, err := regexp.Compile(expr) if err != nil { s.client.dfatal(err) break } if exp.MatchString(title) { matches = append(matches, canonical) break } } } return matches } <file_sep>/routine.go package main import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "path" "strconv" "strings" "github.com/go-redis/redis/v8" "github.com/vartanbeno/go-reddit/reddit" ) // AnalyzeSubmissions analyzes Reddit submissions. // The parameters Before, After, and Count params are handled in AnalyzeSubmissions. func (c Client) AnalyzeSubmissions() *ContextError { submissions, err := c.Redis.getHashMap(RedisAllSubmissions) if err != nil { if !c.IsProduction { return err } err.LogError(c.Logger) } submissions, err = c.analyzeRedditSubmissions(submissions) if err != nil { if !c.IsProduction { return err } err.LogError(c.Logger) } ids := make([]string, len(submissions)) i := 0 for submission := range submissions { ids[i] = submission i++ } var context []ContextParam if len(ids) <= 25 { context = []ContextParam{ {"ids", fmt.Sprint(ids)}, } } if len(ids) != 0 { err = NewContextError(errors.New("some submissions were not analyzed"), context) err.LogWarn(c.Logger) } return nil } // PostListing is a type PostListing struct { Data struct { Children []PushshiftSubmission `json:"children"` } `json:"data"` } func (c *Client) analyzeRedditSubmissions(submissionsMap map[string]string) (map[string]string, *ContextError) { totalSubmissions := 0 for len(submissionsMap) > 0 { ids := make([]string, 0, c.Config.Reddit.SearchLimit) removed := make(map[string]bool, c.Config.Reddit.SearchLimit) for _, submission := range submissionsMap { if len(ids) >= c.Config.Reddit.SearchLimit { break } ids = append(ids, submission) removed[submission] = true } c.Logger.Infof("Reading submission IDs: %v", ids) _, resp, err := c.Reddit.Listings.GetPosts(ctx, ids...) if err != nil { return submissionsMap, NewContextlessError(err) } l := &PostListing{} err = json.NewDecoder(resp.Body).Decode(l) if err != nil { return submissionsMap, NewContextlessError(err) } submissions := l.Data.Children err = c.Redis.addSubmissions(submissions) if err != nil { return submissionsMap, NewContextlessError(err) } submissionCount := len(submissions) totalSubmissions += submissionCount if submissionCount == 0 { break } for _, submission := range submissions { delete(submissionsMap, submission.ID) removed[submission.ID] = false } if ce := c.Redis.updateVotes(submissions); ce != nil { c.dfatal(ce) } if ce := c.Redis.setRemoved(submissions, removed); ce != nil { c.dfatal(ce) } } c.Logger.Infof("Read %d submissions.", totalSubmissions) return submissionsMap, nil } // func (c *Client) checkSubmissions(posts *reddit.Posts, isForwards bool) error { // // EDGE CASE: How to deal with <3 submissions? // if len(posts.Posts) == 0 { // // If you have reached the beginning or the end and are searching in that direction nothing to do. // if (posts.After == "" && isForwards) || (posts.Before == "" && !isForwards) { // return nil // } // } // r := c.Redis // var currentSubmission *reddit.Post // if isForwards { // lastSubmission := posts.Posts[len(posts.Posts)-1] // if lastSubmission.Created != nil { // c.Logger.Info("Time created not given for submission ID: %s (permalink: %s)", lastSubmission.FullID, lastSubmission.Permalink) // } else if c.Search.End == nil || lastSubmission.Created.Before(c.Search.End.Epoch) { // if ce := r.setAnchor(RedisSearchEnd, lastSubmission.FullID, *lastSubmission.Created); ce != nil { // c.dfatal(ce) // } // } // currentSubmission = lastSubmission // } else { // firstSubmission := posts.Posts[0] // if firstSubmission.Created == nil { // c.Logger.Info("Time created not given for submission ID: %s (permalink: %s)", firstSubmission.FullID, firstSubmission.Permalink) // } else if c.Search.Start == nil || !c.Search.Start.Epoch.Before(*firstSubmission.Created) { // if ce := r.setAnchor(RedisSearchStart, firstSubmission.FullID, *firstSubmission.Created); ce != nil { // c.dfatal(ce) // } // } // currentSubmission = firstSubmission // } // if currentSubmission.Created != nil { // if ce := r.setCurrentAnchor(RedisSearchCurrent, currentSubmission.FullID, *currentSubmission.Created, isForwards); ce != nil { // c.dfatal(ce) // } // } // return nil // } func (c *Client) makePath(route string, query url.Values) string { u, err := url.Parse(c.Config.Reddit.URL) if err != nil { panic(fmt.Errorf("invalid API URL: %s", c.Config.Reddit.URL)) } u.Path = path.Join(u.Path, route) u.RawQuery = query.Encode() return u.String() } func (c *Client) makePaths(parts []string, query url.Values) string { return c.makePath(path.Join(parts...), query) } func (c *Client) doRedditRequest(req *http.Request, v interface{}) (*reddit.Response, *ContextError) { resp, err := c.Reddit.Do(ctx, req, v) if err != nil { return nil, NewContextlessError(err) } return resp, nil } func (c *Client) doRequest(method, url string, body io.Reader, header http.Header) ([]byte, *ContextError) { getContext := func() []ContextParam { var bodyString string var err error if body != nil { var b []byte b, err = ioutil.ReadAll(body) bodyString = string(b) } else { bodyString = fmt.Sprint(body) } baseParams := []ContextParam{ {"Method", method}, {"Request URL", url}, } headerParam := ContextParam{"Header", fmt.Sprint(header)} if err == nil { return append(baseParams, ContextParam{"Body", bodyString}, headerParam) } return append(baseParams, ContextParam{"Body Read Error", fmt.Sprint(err)}, headerParam) } req, err := http.NewRequest(method, url, body) if err != nil { return nil, NewContextError(err, append( getContext(), ContextParam{"requestURL", url}, )) } req.Header = header resp, err := http.DefaultClient.Do(req) if err != nil { return nil, NewContextError(err, append( getContext(), ContextParam{"Request", fmt.Sprint(req)}, )) } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, NewContextError(err, append( getContext(), ContextParam{"Request", fmt.Sprint(req)}, ContextParam{"Response", fmt.Sprint(resp)}, )) } if resp.StatusCode == http.StatusTooManyRequests { if ce := c.doRateLimit(resp); ce != nil { return nil, NewContextError(ce, getContext()) } } else if resp.StatusCode != http.StatusOK { return nil, NewContextError(errors.New("not OK status"), append( getContext(), ContextParam{"Status", fmt.Sprint(resp.StatusCode)}, )) } return b, nil } func (c *Client) doRateLimit(resp *http.Response) *ContextError { r := c.Reddit rateLimit, ce := r.NewRateLimit(resp) if ce != nil { return ce } r.SetRateLimit(rateLimit) for !c.closed && !r.IsRateLimited() { <-c.Processes.Tick() } return nil } // Anchor represents a place in the search. type Anchor struct { FullID string Epoch reddit.Timestamp } func (r *Redis) getAnchor(anchorKey string) (*Anchor, *ContextError) { anchorString, err := r.Get(ctx, anchorKey).Result() if err != nil { if err.Error() == redis.Nil.Error() { return nil, NewContextlessError(err) } return nil, NewWrappedError(fmt.Sprintf("could not get %s", anchorKey), err, nil) } anchorParts := strings.Split(anchorString, RedisDelimiter) if len(anchorParts) != 2 { return nil, NewContextError(errors.New("anchor does not have 2 parts"), []ContextParam{ {"Anchor", anchorString}, {"Anchor Parts", fmt.Sprint(anchorParts)}, }) } fullID, epochString := anchorParts[0], anchorParts[1] if err := checkFullName(fullID); err != nil { return nil, err.AddContext("Anchor", anchorString) } timestamp := reddit.Timestamp{} if timestamp.UnmarshalJSON([]byte(epochString)); err != nil { return nil, NewContextError(err, []ContextParam{ {"Anchor", anchorString}, {"Epoch String", epochString}, }) } return &Anchor{fullID, timestamp}, nil } func checkFullName(fullID string) *ContextError { submissionPrefix := "t3_" // Rudimentary Reddit ID verification if !strings.HasPrefix(fullID, submissionPrefix) { return NewContextError(fmt.Errorf(`Expected fullname prefix "%s"`, submissionPrefix), []ContextParam{ {"Input ID", fullID}, }) } baseID := fullID[len(submissionPrefix):] i, err := strconv.ParseInt(baseID, 36, 64) if err != nil { return NewContextError(errors.New(`Could not parse submission ID as base 36 string`), []ContextParam{ {"Full Name Input", fullID}, {"Submission ID", baseID}, }) } if i < 0 { return NewContextError(errors.New("expected parsed Reddit ID to be positive"), []ContextParam{ {"Full Name Input", fullID}, {"Submission ID", baseID}, {"Submission ID Integer", fmt.Sprint(i)}, }) } if len(baseID) != 6 { return NewContextError(errors.New("expected Reddit ID of length 6"), []ContextParam{ {"Full Name Input", fullID}, {"Full Name Length", fmt.Sprint(len(fullID))}, {"Submission ID", baseID}, }) } return nil } <file_sep>/config.go package main import ( "fmt" "os" "time" "github.com/pelletier/go-toml" ) // Config is the toml config that houses all of ArchiveBot's information. type Config struct { Application Application `toml:"Application"` Subreddit Subreddit `toml:"Subreddit"` Pushshift Pushshift `toml:"Pushshift"` Redis RedisConfig `toml:"Redis"` Reddit RedditConfig `toml:"Reddit"` Constants ConstantsConfig `toml:"Constants"` } // Application is type Application struct { IsProduction bool `toml:"is_production"` LoopDelay time.Duration `toml:"loop_delay"` TickSpeed time.Duration `toml:"tick_speed"` } // Subreddit is the configuration for a subreddit. type Subreddit struct { Name string `toml:"name"` Limit int64 `toml:"search_limit"` } // Pushshift is the configuration for Pushshift. type Pushshift struct { URL string `toml:"url"` Delay int64 `toml:"delay"` } // RedisConfig configuration type RedisConfig struct { Addr string `toml:"addr"` Password string `toml:"<PASSWORD>"` DB int `toml:"db"` } // OpenConfig opens the configuration file. func OpenConfig(filename string) (*Config, error) { file, err := os.Open(filename) if err != nil { return nil, fmt.Errorf("cannot open config: %w", err) } defer file.Close() config := &Config{} if err := toml.NewDecoder(file).Decode(config); err != nil { return nil, fmt.Errorf("could not parse toml: %w", err) } return config, nil } <file_sep>/redis.go package main import ( "context" "fmt" "github.com/go-redis/redis/v8" "github.com/vartanbeno/go-reddit/reddit" ) // Reddit Search anchors. // RedisSearchCurrent is the current anchor key. const RedisSearchCurrent = "searchCurrent" // RedisSearchStart is the start anchor key. const RedisSearchStart = "searchStart" // RedisSearchEnd is the end anchor key. const RedisSearchEnd = "searchEnd" // Inbox Anchors // RedisInboxCurrent is the currently held listing item for iteration. const RedisInboxCurrent = "inboxCurrent" // RedisInboxStart is the first known listing item. const RedisInboxStart = "inboxStart" // Pushshift Anchors // RedisPushshiftStart is the epoch of the first scanned Pushshift data. const RedisPushshiftStart = "pushshiftStartEpoch" // RedisPushshiftEnd is the epoch of the last scanned Pushshift data. const RedisPushshiftEnd = "pushshiftEndEpoch" // RedisPushshiftTraversed is a boolean value for whether to check after RedisPushshiftEnd. const RedisPushshiftTraversed = "pushshiftTraversed" // RedisSearchIsForwards represents a boolean value for whether to traverse the current anchor forwards or backwards. const RedisSearchIsForwards = "searchForwards" // RedisDelimiter is the delimiter for fields. const RedisDelimiter = ":" // RedisSearchPrefix is the prefix for a search term corresponding to a set of submission IDs sorted by date created. const RedisSearchPrefix = "search" + RedisDelimiter // RedisUpvotes is the key for submission upvotes. const RedisUpvotes = "upvotes" // RedisFlairNames is a set of existing flairs const RedisFlairNames = "flairNames" // RedisFlairsPrefix is the prefix for a flair corresponding to a set of submission IDs sorted by date created. const RedisFlairsPrefix = "flairs" + RedisDelimiter // RedisAllSubmissions is a hash with keys of submission IDs to their JSON data. const RedisAllSubmissions = "allSubmissions" // RedisSubmissions is a hash with keys of not deleted submission IDs to their JSON data. const RedisSubmissions = "submissions" // RedisRemovedSubmissions is a hash with keys of deleted submission IDs to their JSON data. const RedisRemovedSubmissions = "removedSubmissions" // RedisLinks is a hash with keys of process full names to a link formatted as [title](permalink). const RedisLinks = "links" // RedisProcessed is a set of processed full names. const RedisProcessed = "processed" // Redis is a client of redis information type Redis struct { *redis.Client client *Client config *Config } var ctx = context.Background() // NewRedisClient creates a new Redis client. func NewRedisClient(client *Client, config *Config) (*Redis, error) { redisConfig := config.Redis rdb := redis.NewClient(&redis.Options{ Addr: redisConfig.Addr, Password: <PASSWORD>, DB: redisConfig.DB, }) if err := rdb.Ping(ctx).Err(); err != nil { return nil, err } return &Redis{rdb, client, config}, nil } func (r *Redis) addSubmissions(pushshiftSubmissions []PushshiftSubmission) error { var submissions []interface{} var links []interface{} var upvotes []*redis.Z flairs := make(map[string][]*redis.Z) searches := make(map[string][]*redis.Z) for _, submission := range pushshiftSubmissions { fullID := "t3_" + submission.ID submissions = append(submissions, fullID, submission) link := fmt.Sprintf("[%s](%s)", submission.Title, submission.Permalink) links = append(links, fullID, link) upvotes = append(upvotes, &redis.Z{Member: fullID, Score: float64(submission.Ups)}) flairs[submission.LinkFlairText] = append(flairs[submission.LinkFlairText], &redis.Z{Member: fullID, Score: submission.DateCreated}) matches := r.client.Search.getTitleMatches(submission.Title) for _, match := range matches { searches[match] = append(searches[match], &redis.Z{Score: submission.DateCreated, Member: fullID}) } } if err := r.HSet(ctx, RedisAllSubmissions, submissions...).Err(); err != nil { return fmt.Errorf("could not set submissions: %w", err) } if err := r.HSet(ctx, RedisLinks, links...).Err(); err != nil { return fmt.Errorf("could not add submission title: %w", err) } if err := r.ZAdd(ctx, RedisUpvotes, upvotes...).Err(); err != nil { return fmt.Errorf("could not add submission upvotes: %w", err) } var flairNames []interface{} flairsSet := make(map[string]struct{}) for flairName, members := range flairs { if err := r.ZAdd(ctx, RedisFlairsPrefix+flairName, members...).Err(); err != nil { return fmt.Errorf("could not add flairs for %s: %w", flairName, err) } if _, ok := flairsSet[flairName]; !ok { flairsSet[flairName] = struct{}{} flairNames = append(flairNames, flairName) } } if err := r.SAdd(ctx, RedisFlairNames, flairNames...).Err(); err != nil { return fmt.Errorf("could not add Redis flair names: %w", err) } for searchName, search := range searches { if err := r.ZAdd(ctx, RedisSearchPrefix+searchName, search...).Err(); err != nil { return fmt.Errorf("could not add search term %s: %w", searchName, err) } } return nil } func (r *Redis) getHashMap(key string) (map[string]string, *ContextError) { submissions, err := r.HGetAll(ctx, key).Result() if err != nil { return nil, NewWrappedError(fmt.Sprintf("error in reading %s", key), err, nil) } return submissions, nil } func (r *Redis) getSetMap(prefix string) (map[string][]redis.Z, *ContextError) { items := make(map[string][]redis.Z) iter := r.Scan(ctx, 0, prefix+"*", 0).Iterator() for iter.Next(ctx) { val := iter.Val() scores, ce := r.getZSet(val) if ce != nil { return nil, NewWrappedError(fmt.Sprintf("error in reading %s", val), ce, nil) } items[val] = scores } if err := iter.Err(); err != nil { return nil, NewWrappedError(fmt.Sprintf(`error in sets of prefix "%s"`, prefix), err, nil) } return items, nil } func (r *Redis) getZSet(name string) ([]redis.Z, *ContextError) { return r.getZSetRange(name, &redis.ZRangeBy{ Min: "-inf", Max: "+inf", Offset: 0, }) } func (r *Redis) getZSetRange(name string, rangeBy *redis.ZRangeBy) ([]redis.Z, *ContextError) { result, err := r.ZRangeByScoreWithScores(ctx, name, rangeBy).Result() if err != nil { return nil, NewContextError(err, []ContextParam{ {"Set Key", name}, }) } return result, nil } func (r *Redis) updateVotes(submissions []PushshiftSubmission) *ContextError { i := 0 updates := make([]*redis.Z, len(submissions)) for _, submission := range submissions { updates[i] = &redis.Z{Score: float64(submission.Ups), Member: submission.ID} i++ } if err := r.ZAdd(ctx, RedisUpvotes, updates...).Err(); err != nil { return NewWrappedError("could not update submission upvotes", err, []ContextParam{ {"updates", fmt.Sprint(updates)}, }) } return nil } func (r *Redis) setRemoved(submissions []PushshiftSubmission, removedMap map[string]bool) *ContextError { removed := make([]interface{}, 0, len(submissions)*2) unremoved := make([]interface{}, 0, len(submissions)*2) for _, submission := range submissions { isRemoved := removedMap[submission.ID] if isRemoved { removed = append(removed, submission.ID, submission) } else { unremoved = append(unremoved, submission.ID, submission) } } if err := r.HSet(ctx, RedisSubmissions, unremoved).Err(); err != nil { return NewWrappedError("could not update " + RedisSubmissions, err, []ContextParam{ {"updates", fmt.Sprint(unremoved)}, }) } if err := r.HSet(ctx, RedisRemovedSubmissions, removed).Err(); err != nil { return NewWrappedError("could not update " + RedisRemovedSubmissions, err, []ContextParam{ {"updates", fmt.Sprint(removed)}, }) } return nil } func (r *Redis) setAnchor(anchorKey string, fullID string, timestamp reddit.Timestamp) *ContextError { anchorString := fmt.Sprintf("%s:%d", fullID, timestamp.Unix()) c := r.client c.Logger.Infof("Setting %s to %s.", anchorKey, anchorString) if err := r.Set(ctx, anchorKey, anchorString, 0).Err(); err != nil { c.dfatal(NewContextError(fmt.Errorf("could not set %s: %w", anchorKey, err), []ContextParam{ {"Anchor String", anchorString}, })) } return nil } func (r *Redis) setCurrentAnchor(anchorKey string, fullID string, timestamp reddit.Timestamp, isForwards bool) *ContextError { err := r.setAnchor(anchorKey, fullID, timestamp) if err != nil { return err } if err := r.Set(ctx, RedisSearchIsForwards, isForwards, 0).Err(); err != nil { r.client.dfatal(NewContextlessError(fmt.Errorf("could not set %s: %w", RedisSearchIsForwards, err))) } return nil } <file_sep>/go.mod module github.com/DavidArchibald/ArchiveBot go 1.13 require ( github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect github.com/go-redis/redis/v8 v8.0.0-beta.8 github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect github.com/jonboulle/clockwork v0.2.0 // indirect github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible github.com/lestrrat-go/strftime v1.0.3 // indirect github.com/pelletier/go-toml v1.8.0 github.com/pkg/errors v0.9.1 // indirect github.com/tebeka/strftime v0.1.5 // indirect github.com/vartanbeno/go-reddit v1.0.0 go.opentelemetry.io/otel v0.11.0 // indirect go.uber.org/zap v1.16.0 golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 // indirect ) <file_sep>/config-schema.toml [Application] production = <bool> # In development any unexpected error will halt the application, logging is formatted, and everything is logged. loop_delay = "<duration>" # The delay between iterations of each loop, in addition to rate limit waits. Must be a positive, parseable duration, see https://golang.org/pkg/time/#ParseDuration. tick_speed = "<duration>" # The speed at which the client updates its state. Should be small enough to react quickly and less than loop_delay. [Pushshift] url = "<string>" # e.g. https://api.pushshift.io/reddit/submission/search/ delay = <integer> # Delay between requests in seconds [Reddit] username = "<string>" # Account username password = "<<PASSWORD>>" # Account password client_id = "<string>" # Script Client ID client_secret = "<string>" # Script Client Secret redirect_url = "<string>" # The redirect url. Currently not implemented. user_agent = "<string>" # User-Agent; format <platform>:Archive-Bot:v0.2.0 by /u/LukeAbby) url = "<string>" # Reddit API URL, e.g. http://api.reddit.com/ search_limit = <integer> # The limit on the number of comments [Subreddit] name = "<string>" # Subreddit Name search_limit = <integer> # Limit on searching [Redis] addr = "<string>" # Database Address password = "<<PASSWORD>>" # Database Password db = <integer> # Database Index [Constants] could_not_parse = "<string>" # Error message for when the message isn't parsed. help_start = "<string>" # The start of an help message. help_body = "<string>" # The shared portion of a help message. no_results = "<string>" # Message for when no results are found. Takes the command as an argument. found_results = "<string>" # Message for when results are found. Takes the command as an argument, footer = "<string>" # The footer of the bot. searches = [ # A list of searches to use. ["<name>", "<alias>", ...], # The first name must be the official name and the rest will be used as aliases. .. ]
969526cdac69ea52d57cc4b07b64ac7f7a727614
[ "TOML", "Go Module", "Go" ]
13
Go
DavidArchibald/ArchiveBot
c9726b976134a852f85ebf8cd7a9271770ac20f9
928c16819b097ffd3d522463a4a8e98f65a8590c
refs/heads/master
<file_sep># 橘猫 orange-mall springCloud + consul <file_sep>package com.linyi.mall.orange.web.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.linyi.mall.orange.common.entity.User; /** * <p> * Mapper 接口 * </p> * * @author linyi * @since 2019-04-17 */ public interface UserMapper extends BaseMapper<User> { } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent> <groupId>com.linyi.mall</groupId> <artifactId>orange</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>orange-common</module> <module>orange-web</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> <lombok.version>1.18.6</lombok.version> <mybatis-plus.version>3.1.0</mybatis-plus.version> <consul.version>2.1.1.RELEASE</consul.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-dependencies</artifactId> <version>${spring-cloud.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-commons</artifactId> <version>${spring-cloud.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> <version>${consul.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> <version>${consul.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-commons</artifactId> <version>${consul.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> </dependencies> </dependencyManagement> <profiles> <profile> <id>rdc-private-repo</id> <repositories> <repository> <id>rdc-releases</id> <url>https://repo.rdc.aliyun.com/repository/72806-release-CyayRp/</url> </repository> <repository> <id>rdc-snapshots</id> <url>https://repo.rdc.aliyun.com/repository/72806-snapshot-uFyiyH/</url> </repository> </repositories> </profile> </profiles> </project>
d9ea9b4018f176bc17e82ddd772cd4206aa668b1
[ "Markdown", "Java", "Maven POM" ]
3
Markdown
linyi4843/orange
04356a9b081e5a0d83a50ca2ff13757a4cca69b6
1cb349f41494045fa71912cad24318d374437bd2
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.verticle.k8s</groupId> <artifactId>oculus</artifactId> <version>0.8</version> <packaging>jar</packaging> <name>oculus</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!-- docker --> <docker.build.skip>true</docker.build.skip> <docker.host.url>unix:///var/run/docker.sock</docker.host.url> <docker.image.prefix>verticleio</docker.image.prefix> <docker.plugin.version>0.4.13</docker.plugin.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-client</artifactId> <version>4.0.3</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-kubernetes-config</artifactId> <version>0.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-kubernetes-core</artifactId> <version>0.3.0.RELEASE</version> </dependency> <dependency> <groupId>com.github.verticleio</groupId> <artifactId>fireboard-client-java</artifactId> <version>LATEST</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>docker</id> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>${docker.plugin.version}</version> <executions> <execution> <id>build-image</id> <phase>package</phase> <goals> <goal>build</goal> </goals> </execution> <execution> <id>tag-image</id> <phase>package</phase> <goals> <goal>tag</goal> </goals> </execution> <!-- <execution> <id>push-image</id> <phase>package</phase> <goals> <goal>push</goal> </goals> </execution> --> </executions> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <image>${docker.image.prefix}/${project.artifactId}</image> <newName>${docker.image.prefix}/${project.artifactId} </newName> <imageTags> <imageTag>${project.version}</imageTag> <imageTag>latest</imageTag> </imageTags> <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory> <dockerHost>${docker.host.url}</dockerHost> <resources> <resource> <targetPath>/</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> <noCache>true</noCache> <buildArgs> <JAR_FILE>${project.build.finalName}.jar</JAR_FILE> </buildArgs> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep>[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/verticle-io/fireboard) oculus ====== **Kubernetes event monitoring for [Fireboard](https://fireboard.verticle.io)** **Oculus** is a small Spring Boot application that connects to the k8s api service and forwards the events in all namespaces to the Fireboard API. **Fireboard** is a service for meta monitoring of digital assets. > Fireboard reduces and abstracts events happening in a digital environment in order to monitor them as weighted success/failure states in a domain agnostic manner. > Events are evaluated right on the spot where they occur, e.g. within an integrated application or script, a 3rd party service webhook or a human interaction. <img src="https://raw.githubusercontent.com/verticle-io/oculus/master/images/fireboard-oculus-5.png" alt="Screenshot" style="max-width:100%;"> <img src="https://raw.githubusercontent.com/verticle-io/oculus/master/images/fireboard-oculus-6.png" alt="Screenshot" style="max-width:100%;"> <img src="https://raw.githubusercontent.com/verticle-io/oculus/master/images/fireboard-oculus-7.png" alt="Screenshot" style="max-width:100%;"> <img src="https://raw.githubusercontent.com/verticle-io/oculus/master/images/fireboard-oculus-8.png" alt="Screenshot" style="max-width:100%;"> <img src="https://raw.githubusercontent.com/verticle-io/oculus/master/images/fireboard-oculus-9.png" alt="Screenshot" style="max-width:100%;"> Installation ------------ Clone this repository. ### Prerequisites Create a ServiceAccount to allow oculus to access the k8s api server: ``` $ kubectl apply -f serviceaccount-rbac.yaml ``` ### Configure & Deploy Open a free Fireboard beta account at [fireboard.verticle.io](https://fireboard.verticle.io) . You can use your github account to sign in. When done, access Fireboard, head to "set" in the nav bar and retrieve * your API key * your tenant ID * the default data bucket ID Adjust `oculus-configmap.yaml` accordingly ... ``` apiVersion: v1 kind: ConfigMap metadata: name: oculus namespace: default data: application.properties: |- tenantId=1101 bucketId=59bab939749c252e09f3770c authToken=<KEY>... ``` ... and deploy the configuration: ``` $ kubectl apply -f oculus-configmap.yaml ``` Finally deploy the oculus service: ``` $ kubectl apply -f oculus-deployment.yaml ``` Now head to https://fireboard.verticle.io and open the Fireboard web application and trigger some events on your cluster. <file_sep>package io.verticle.k8s.oculus; import io.verticle.oss.fireboard.client.FireboardAccessConfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author <NAME> */ @Configuration public class FireboardAccessConfigMap { @ConfigurationProperties @Bean public FireboardAccessConfig configure() { FireboardAccessConfig config = new FireboardAccessConfig(); return config; } }
ad0a7df447663113ae6f5a1dc51174bab35942e1
[ "Markdown", "Java", "Maven POM" ]
3
Maven POM
verticle-io/oculus
ed0131bade7340d96f3377770500fbafaefbaea1
38b9b9e78ddc98f5b86ddceb9dcb126514e6c466
refs/heads/master
<repo_name>RodrigoCerdaR/sort-algorithms<file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/auxiliares.h #ifndef AUXILIARES_H_INCLUDED #define AUXILIARES_H_INCLUDED #endif // AUXILIARES_H_INCLUDED /**< Estructura inferior. En ella se almacenan los datos de rendimiento de cada algoritmo */ typedef struct{ double contadorTiempo; int contadorComparaciones; int contadorIntercambios; }Datos; /**< Estructura superior. En ella se almacena el arreglo y los datos de rendimiento */ typedef struct{ int *arreglo; Datos datos; int size; }Resultados; /**< Enum para manejar errores */ typedef enum code {OK, ERR_FILE_NOT_FOUND, ERR_BAD_FILE} code; /** \brief Intercambia elementos de un arreglo * * \param "a", "b", punteros a int */ void intercambio(int * a, int * b){ int temp; temp=*a; *a=*b; *b=temp; } <file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/algoritmos.h #ifndef ALGORITMOS_H_INCLUDED #define ALGORITMOS_H_INCLUDED #endif // ALGORITMOS_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> /** \brief Algoritmo de ordenamiento de tipo Insercion. ordena el arreglo contenido dentro de la estructura "resultados" * junto con los datos del rendimiento del algoritmo en dicha tarea * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento */ void Insercion(Resultados *r){ r->datos.contadorComparaciones=0; r->datos.contadorIntercambios=0; r->datos.contadorTiempo=0; clock_t tiempoini, tiempofin; tiempoini = clock(); int a; int i,j; for(i=1;i<r->size;i++){ j=i; r->datos.contadorComparaciones++; while( (r->arreglo[j]<r->arreglo[j-1]) & j>0){ r->datos.contadorComparaciones++; intercambio(&r->arreglo[j],&r->arreglo[j-1]); r->datos.contadorIntercambios++; j--; } } tiempofin=clock(); r->datos.contadorTiempo=(double)tiempofin-tiempoini; } /** \brief * Algoritmo de ordenamiento "burbuja" (iterativo)ordena el arreglo contenido dentro de la estructura "resultados" * junto con los datos del rendimiento del algoritmo en dicha tarea * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento */ void Burbuja(Resultados *r){ r->datos.contadorComparaciones=0; r->datos.contadorIntercambios=0; r->datos.contadorTiempo=0; clock_t tiempoini, tiempofin; tiempoini= clock(); int i,j; for (i=0;i<r->size;i++){ for(j=r->size-1;j>=i+1;j--){ r->datos.contadorComparaciones++; if(r->arreglo[j]<r->arreglo[j-1]){ r->datos.contadorIntercambios++; intercambio(&r->arreglo[j],&r->arreglo[j-1]); } } } tiempofin=clock(); r->datos.contadorTiempo=(double)tiempofin-tiempoini; } /** \brief llama a la funcion quicksortaux, encargada de ordenar el arreglo contenido en la estructura "resultado", * ademas de inicializar las variables de datos de rendimiento del algoritmo. * \param "*r" puntero a estructura "resultados" */ void Quicksort(Resultados *r){ r->datos.contadorComparaciones=0; r->datos.contadorIntercambios=0; r->datos.contadorTiempo=0; clock_t tiempoini, tiempofin; tiempoini= clock(); QuicksortAux(0, r->size-1, r); tiempofin=clock(); r->datos.contadorTiempo=(double)tiempofin-tiempoini; } /** \brief * Algoritmo quicksort que particiona el arreglo para ordenarlo, tomando el primer elemento de la partición como * pivote para comparar. * \param "prim", "ult" indice del primer y ultimo elemento del arreglo * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento * \return "corte", int que devuelve la posición en la que quedó el elemento pivote */ int particion(int prim, int ult, Resultados *r){ int pivote, corte, k; pivote = r->arreglo[prim]; corte=prim; for (k=prim +1;k<=ult;k++){ r->datos.contadorComparaciones++; if (r->arreglo[k]< pivote){ corte=corte+1; intercambio(&r->arreglo[corte],&r->arreglo[k]); r->datos.contadorIntercambios++; } } r->datos.contadorIntercambios++; intercambio(&r->arreglo[prim],&r->arreglo[corte]); return corte; } /** \brief * (recursiva) Funcion que calcula los indices de las particiones, llegando a una particion de 1 elemento * gracias a la recursividad. Luego llama a la función "particion", que a traves del algoritmo quicksort, * ordena el array contenido dentro de la estructura "resultados" * \param "prim","ult", int, indices del primer y ultimo elemento que analiza la función * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento */ void QuicksortAux(int prim, int ult, Resultados *r){ int corte; if (ult - prim>=1){ corte= particion(prim,ult,r); QuicksortAux(prim,corte - 1,r); QuicksortAux(corte +1, ult,r); } } /** \brief llama a la funcion Mergesortaux, encargada de ordenar el arreglo contenido en la estructura "resultado", * ademas de inicializar las variables de datos de rendimiento del algoritmo. * \param "*r" puntero a estructura "resultados" */ void Mergesort(Resultados *r){ r->datos.contadorComparaciones=0; r->datos.contadorIntercambios=0; r->datos.contadorTiempo=0; clock_t tiempoini, tiempofin; tiempoini= clock(); MergesortAux(r, 0, r->size-1); tiempofin=clock(); r->datos.contadorTiempo=(double)tiempofin-tiempoini; } /** \brief * Función que, por medio del algoritmo mergesort, ordena el arreglo, separandolo recursivamente en mitades de * arreglos mas pequeños, con el fin de ordenarlos por separado y luego entrelazarlos. * \param "inicio","medio", "fin", int de indices del elemento inicial, medio, y final del arreglo a ordenar. * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento */ void Merge(Resultados *r,int inicio, int medio, int fin){ int h,i,j,k,l; int arrayAux[fin-inicio+1]; h = 0; i = inicio; j = medio + 1; while ( (i<=medio)&&(j <= fin) ) { r->datos.contadorComparaciones++; if (r->arreglo[i]<r->arreglo[j]){ arrayAux[h]=r->arreglo[i]; i++; }else{ r->datos.contadorIntercambios++; arrayAux[h]=r->arreglo[j]; j++; } h++; } if (i> medio){ for (k=j;k<=fin;k++){ arrayAux[h]=r->arreglo[k]; h++; } }else{ for(k=i;k<=medio;k++){ arrayAux[h]=r->arreglo[k]; h++; } } l=0; for (k=inicio;k<=fin;k++){ r->arreglo[k]=arrayAux[l]; l++; } } /** \brief * (recursiva)Función que divide el array de la estructura "resultados" en arrays mas pequeños, con el fin de comenzar a ordenarlos una vez * se llegue a la división mas pequeña. * \param "*r" puntero a estructura "resultados" donde se almacena el arreglo y los datos de rendimiento * \param "ini", "fi", int. indices del primer y ultimo elemento del array a ordenar. */ void MergesortAux(Resultados *r,int ini, int fi){ int med; if(ini < fi){ med=(ini+fi) / 2; MergesortAux(r,ini,med); MergesortAux(r,(med+1),fi); Merge(r,ini,med,fi); } } <file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/generar.h #ifndef GENERAR_H_INCLUDED #define GENERAR_H_INCLUDED #endif // GENERAR_H_INCLUDED #include <time.h> #include <math.h> #include <dirent.h> /** \brief genera "c" elementos en orden ascendente y los almacena en la direccion donde apunta el puntero a int ingresado como parametro * \param "*array", puntero a int * \param "c" tamaño del arreglo al que se le añadiran elementos */ void arrayAscendente(int *array, int c){ int i; array[0]=rand(); for(i=1;i<c;i++){ array[i]=array[i-1]+rand() %40 +1; } } /** \brief genera "c" elementos en orden descendente y los almacena en la direccion donde apunta el puntero a int ingresado como parametro * \param "*array", puntero a int * \param "c" tamaño del arreglo al que se le añadiran elementos */ void arrayDescendente(int *array,int c){ int i; array[0]=rand(); for(i=1;i<c;i++){ array[i]=array[i-1]-rand() % 30 - 1; } } /** \brief genera "c" elementos ordenados de manera intercalada (los pares ascendentes y los impares descendentes) * y los almacena en la direccion donde apunta el puntero a int ingresado como parametro * \param "*array", puntero a int * \param "c" tamaño del arreglo al que se le añadiran elementos */ void arrayIntercalado(int *array,int c){ int i; array[0]=100; array[1]=array[0]-rand(); for(i=2;i<c;i++){ if (i%2==0){ array[i]=array[i-2]+2; }else{ array[i]=array[i-2]-2; } } } /** \brief Genera "c elementos" eligiendo un numero inicial y dividiendo el arreglo en dos mitades, la primera * que el y la segunda que el. Luego se almacenan en la direccion donde apunta el puntero ingresado como * parametro * \param "*array", puntero a int * \param "c" tamaño del arreglo al que se le añadiran elementos */ void arrayMitades(int *array,int c){ int i,o, numeroInicial, acum,cont; numeroInicial= rand(); for (i=0;i<c;i++){ cont=0; if(i<c/2){ acum=numeroInicial-rand(); for (o=0;o<=i;o++){ if (array[o]==acum) //para revisar que el numero no este repetido cont=1; } if (cont!=1){ array[i]= acum; }else{ i--; } }else{ acum=numeroInicial+rand(); for (o=(c/2);o<=i;o++){ if (array[o]==acum)//para revisar que el numero no este repetido cont=1; } if (cont!=1){ array[i]= acum; }else{ i--; } } } } /** \brief Genera "c" elementos de manera aleatoria para asignarlos en la direccion donde apunta el puntero a int * ingresado como parametro * * \param "*array", puntero a int * \param "c" tamaño del arreglo al que se le añadiran elementos */ void arraySimple(int *array,int c){ int i,o, numeroInicial, acum,cont,signo; for (i=0; i < c; i++){ cont=0; numeroInicial= rand(); signo= rand()%2; if (signo==1){ numeroInicial=numeroInicial*(-1); } for (o=0;o<=i;o++){ if(array[o]==numeroInicial) cont=1; } if (cont!=1){ array[i]=numeroInicial; }else{ i--; } } } /** \brief almacena el arreglo de tamaño "c" al que apunta el primer parametro, * en un archivo de extencion.dat, cuyo nombre es ingresado como parametro * * \param "*arreglo" puntero a un arreglo de int, "c" tamaño del arreglo apuntado por el primer parametro * \param "filename" cadena de caracteres con el nombre del archivo a guardar * */ void guardarArreglo (int *arreglo,char filename[100],int c){ FILE *f; DIR *dir; int i; dir = opendir("arrays"); if (dir==NULL){ mkdir("arrays"); } char folder[100] = "arrays/"; char extension[30] = ".dat"; strcat(folder,filename); strcat(folder,extension); f= fopen(folder,"w"); fprintf(f,"%d\n",c); for (i=0;i<c;i++){ fprintf(f,"%d\n",arreglo[i]); } fclose(f); closedir(dir); } /** \brief Nivel superior de las funciones para generar los archivos de arreglos. * Esta función es en la cual el usuario actúa directamente. * * \param "c" int con el tamaño de los arreglos que se desean generar * \param * */ void GenerarArchivos(int c){ int i, array1[c],array2[c],array3[c],array4[c],array5[c]; char filename[100]; srand(time(NULL)); arrayAscendente(&array1,c); guardarArreglo(&array1,"arrayAscendente",c); arrayDescendente(&array2,c); guardarArreglo(&array2,"arrayDescendente",c); arrayIntercalado(&array3,c); guardarArreglo(&array3,"arrayIntercalado",c); arrayMitades(&array4,c); guardarArreglo(&array4,"arrayMitades",c); for (i=1;i<=16;i++){ arraySimple(&array5,c); sprintf(filename,"arraySimple%d",i); guardarArreglo(&array5,filename,c); } printf("Archivos generados en la carpeta \"arrays\" \n"); } <file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/main.c #include <stdio.h> #include <stdlib.h> #include "leer.h" #include "algoritmos.h" #include "ordenar.h" #include "generar.h" /** \brief Funcion que imprime por pantalla el dialogo con el usuario, y recibe la información que este proporciona para * realizar la tarea solicitada */ void MenuPrincipal(){ int eleccion=0; char *p, s[100]; while (eleccion !=3){ printf("Laboratorio 1 Algoritmos y Estructuras de Datos \n\n"); printf("Para generar los archivos con los arreglos a ordenar, ingrese 1\n"); printf("Para ordenar algun arreglo contenido en un archivo, ingrese 2\n"); printf("Para salir, ingrese 3\n"); while (fgets(s, sizeof(s), stdin) ){ eleccion=strtol(s,&p,10); if (p == s || *p != '\n' || eleccion < 1 || eleccion > 3) { printf("Favor ingresar un entero entre 1 y 3: "); } else break; } if (eleccion==1){ int size; printf("Cantidad de elementos dentro de los arreglos a generar (max: 20000): "); while (fgets(s, sizeof(s), stdin) ){ size=strtol(s,&p,10); if (p == s || *p != '\n' || size > 20000) { printf("Favor ingresar un entero (max 20000): "); } else break; } GenerarArchivos(size); } if (eleccion==2){ Resultados rInscercion, rBurbuja, rQuicksort, rMergesort; char filename[100]; code statusCode; printf("arrayAscendente, arrayDescendente, arrayIntercalado, \narrayMitades, arraySimple1, ..., arraySimple16\n"); printf("Ingrese el nombre del archivo a evaluar (sin extencion): "); scanf("%s",filename); printf("\n"); Ordenar(&rInscercion, &rBurbuja, &rQuicksort, &rMergesort, filename, &statusCode); } if (eleccion==3){ return 0; } } } int main(){ MenuPrincipal(); return 0; } <file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/ordenar.h #ifndef ORDENAR_H_INCLUDED #define ORDENAR_H_INCLUDED #endif // ORDENAR_H_INCLUDED #include <dirent.h> /** \brief asigna a cada una de las estructuras "resultado" ingresadas el array que se desea analizar, para luego enviar * dichas estructuras a cada algoritmo de ordenamiento. almacena el resultado y los imprime en pantalla * \param "*a","*b","*c","*d" punteros a estructuras "resultado". * \param "filename" char con nombre del arreglo que se desea ordenar * \param "*statusCode" enum para manejo de errores * */ void Ordenar(Resultados *a,Resultados *b,Resultados *c,Resultados *d,char filename[100],code *statusCode){ int id; leerArray(filename, a, statusCode); leerArray(filename, b, statusCode); leerArray(filename, c, statusCode); leerArray(filename, d, statusCode); if (*statusCode == OK){ Insercion(a); Burbuja(b); Quicksort(c); Mergesort(d); GuardarResultado(a,b,c,d,&id); printf("\nGuardado en registros/registro%d.txt \n\n", id); } if (*statusCode == ERR_FILE_NOT_FOUND){ printf("No se ha encontrado el archivo\n"); } } /** \brief * Lee el archivo contador.dat, donde se almacena la cantidad de registros grabados por el programa, para asi generar * una cuenta de estos, dando un numero a cada registro guardado. * \return "contador", int que entrega la cantidad de regitros almacenados, incluyendo el generado en la llamada a esta función * */ int IncrementoContador(){ FILE *f1; int contador=0; char scan[30]; char nombreArchivo[] = "contador.dat"; char cantidad[]= "<cantidad>%d</cantidad>"; f1=fopen(nombreArchivo,"r"); if (f1==NULL){ f1=fopen(nombreArchivo,"a+"); contador = 1; fprintf(f1,cantidad,contador); fclose(f1); }else{ rewind(f1); fscanf(f1,cantidad,&contador); contador++; fclose(f1); f1=fopen(nombreArchivo,"w"); fprintf(f1,cantidad,contador); fclose(f1); } return contador; } /** \brief * Guarda en un archivo.txt unico, los resultados de la ejecución de los algoritmos de ordenamiento * \param "*a","*b","*c","*d", puntero a estructuras tipo "Resultados" Los resultados para cada algoritmo. * \param "*id" puntero a int, en la memoria apuntada se almacena el identificador del archivo guardado. * */ void GuardarResultado(Resultados *a,Resultados *b,Resultados *c,Resultados *d,int *id){ FILE *f; DIR *dir; dir = opendir("registros"); if (dir ==NULL){ mkdir("registros"); } int i, newId; newId = IncrementoContador(); *id = newId; char nombreArchivo[]= "registros/registro"; char num[3]; char ext[]=".txt"; sprintf(num,"%d",newId); strcat(nombreArchivo,num); strcat(nombreArchivo,ext); f= fopen(nombreArchivo,"w"); for (i=0;i<a->size;i++){ fprintf(f,"%d ", a->arreglo[i]); } fprintf(f,"%s","\nInsercion:\n"); fprintf(f,"Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",a->datos.contadorTiempo,a->datos.contadorComparaciones,a->datos.contadorIntercambios); fprintf(f,"Burbuja:\n"); fprintf(f,"Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",b->datos.contadorTiempo,b->datos.contadorComparaciones,b->datos.contadorIntercambios); fprintf(f,"Quicksort:\n"); fprintf(f,"Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",c->datos.contadorTiempo,c->datos.contadorComparaciones,c->datos.contadorIntercambios); fprintf(f,"Mergesort:\n"); fprintf(f,"Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",d->datos.contadorTiempo,d->datos.contadorComparaciones,d->datos.contadorIntercambios); fclose(f); closedir(dir); PrintResultados(a,b,c,d); } /** \brief Imprime por pantalla los resultados almacenados en las direcciones que apuntan * los 4 punteros a estructuras "resultados" * "*a","*b","*c","*d", puntero a estructuras tipo "Resultados" Los resultados para cada algoritmo. */ void PrintResultados(Resultados *a, Resultados *b, Resultados *c, Resultados *d){ int i; for (i=0;i<a->size;i++){ printf("%d ", a->arreglo[i]); } printf("\n\nInsercion:\n"); printf("Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",a->datos.contadorTiempo,a->datos.contadorComparaciones,a->datos.contadorIntercambios); printf("\nBurbuja:\n"); printf("Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",b->datos.contadorTiempo,b->datos.contadorComparaciones,b->datos.contadorIntercambios); printf("\nQuicksort:\n"); printf("Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",c->datos.contadorTiempo,c->datos.contadorComparaciones,c->datos.contadorIntercambios); printf("\nMergesort:\n"); printf("Tiempo: %f (mseg) \nComparaciones: %d \nIntercambios: %d \n",d->datos.contadorTiempo,d->datos.contadorComparaciones,d->datos.contadorIntercambios); } <file_sep>/README.md # Algoritmos This code was writted to measure the response of sort algorithms (insertion, quicksort, bubblesort and mergesort). it's capable to make text files until 20000 numbers sorted intencionally in crease, decrease, half lower and half higher, pair lower higher and random sort. sort from lower to higher and gives you the time elapsed, and quantity of changes mades. thanks! <file_sep>/Lab 1 algoritmos Rodrigo Cerda/Lab 1 Rodrigo Cerda R/leer.h #ifndef LEER_H_INCLUDED #define LEER_H_INCLUDED #endif // LEER_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #include "auxiliares.h" /** \brief lee el arreglo dentro del archivo solicitdo, y lo asigna dentro de la estructura apuntada por el puntero * a "Resultado" ingresado como parametro, siempre que el archivo exista * \param "arrayfile" nombre del archivo a leer * \param "*r" puntero a una estructura resultado, donde se almacenará el array leido. * \param "*statusCode" enum para manejo de errores */ void leerArray(char arrayfile[100], Resultados * r, code *statusCode){ int asize, c ; FILE *f; char filename[100]="arrays/"; char extension[30]=".dat"; strcat(filename,arrayfile); strcat(filename,extension); f= fopen(filename,"r"); if (f==NULL){ *statusCode= ERR_FILE_NOT_FOUND; }else{ *statusCode=OK; fscanf(f,"%d\n",&asize); r->size=asize; r->arreglo=(int*)malloc(asize * (sizeof(int)) ); for (c=0;c<asize;c++){ fscanf(f,"%d\n",&r->arreglo[c]); } } fclose(f); }
3ad001ad048ea327cd4a8ffb16c787032e2d10e3
[ "Markdown", "C" ]
7
C
RodrigoCerdaR/sort-algorithms
5d1ac66d0e8dd68f20b2d82afe832bb19fc62b45
d457ba2d90a2c5b7af12b791d1753e4aa3f2cfbf
refs/heads/master
<repo_name>NP-chaonay/LinuxTroubleshooter<file_sep>/GraphicalLogin.py #!/usr/bin/python3 import sys,posix,time Name='<NAME>' Author='NP-chaonay' Issues='- Cannot login to user screen but always loop back to the login screen.\n\ - User appeared as already logged in without your action.' code=None def getUserID(user_name): user_entry=open('/etc/passwd').read().splitlines() for no in range(0,len(user_entry)): if user_entry[no].split(':')[0] == user_name: return int(user_entry[no].split(':')[3]) return None def finish(status) : if status == 'Continue': return if status == 'Complete': print('Troubleshooter has solved the problem completely.') input('Press enter to exit.') exit(0) if status == 'NoSolution': print('Troubleshooter hasn\'t found the solution to the problem.') input('Press enter to exit.') exit(1) if status == 'Cancelled': print('Troubleshooter has been cancelled by user.') input('Press enter to exit.') exit(0) if status == 'RequiredRoot': print('Troubleshooter requires root permission in order to continue solving the problem.') input('Press enter to exit.') exit(0) else: print('Troubleshooter hasn\'t solved the problem completely.') input('Press enter to exit.') exit(2) def runMethod(text,function): print('\n### '+text+' ###') function() placeholder=('########') for count in range(0,len(text)): placeholder+='#' print(placeholder+'\n') finish(code) def Method1(): global code user_id=getUserID(input('# Type your user login ID : ')) for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/'+entry).st_uid == user_id: code='Continue' break if code == 'Continue': print('# Any process belonged to typed user is found.') while True: option=input('# Do you want to send signal to these processes for closing? (Y/N) : ') if option in ['Y','N'] : break if option == 'N': code='Cancelled' return else: print('# Retriving processes list...') pids=[] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/'+entry).st_uid == user_id: pids.append(int(entry)) print('# Quitting processes...') if posix.getuid() != user_id and posix.getuid() != 0: print('# Error : Don\'t have enough permission. Make sure to run this troubleshooter as root.') code='RequiredRoot' return for pid in pids: posix.kill(pid, 15) input('Waiting for processes to be closed properly (Recommended at 20 seconds). When ready then press enter.') print('# Retriving processes list...') pids=[] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/'+entry).st_uid == user_id: pids.append(int(entry)) if pids: while True: option=input('# There are processes not quitted by the signal. Do you want to force killing it? (Y/N) : ') if option in ['Y','N'] : break if option == 'N': code='Cancelled' return print('# Killing processes...') for pid in pids: posix.kill(pid, 9) code='Complete' return else: print('# No any process belonged to typed user is found.') code='NoSolution' return print('Linux Troubleshooter : '+Name) print('Created by : '+Author+'\n') if sys.platform == 'linux' : pass else: print('Error : The current system isn\'t regular Linux system.') print('(Current system type is "'+sys.platform+'". Should be "linux".)') exit(3) print('This troubleshooter is able to fix these issues :') print(Issues+'\n') while True: option=input('Do you want to proceed? (Y/N) : ') if option in ['Y','N'] : break if option == 'N': exit(0) print() runMethod('Detect running processes of the user.', Method1) <file_sep>/README.md ## Contents ### Python scripts - GraphicalLogin.py : Troubleshoot graphical login issues
59f47fa20afdfc203686242bfd3762ddb5e79afa
[ "Markdown", "Python" ]
2
Python
NP-chaonay/LinuxTroubleshooter
bb27cebb40ab807af340134ba21b25da859df3b3
664acaac7b808517d60368cef6cf3076e4d599d7
refs/heads/master
<repo_name>wfpc/SuperSTUN<file_sep>/SuperSTUNServer.py import socket import threading import time import sys from multiprocessing import Process, Pipe, Queue def sendError(error, addr, sock): print 'ERROR ', error, ' on user ', addr sock.sendto(error, addr) def createSocket(port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, port)) return sock def subSocketKiller(proc, kTime): time.sleep(kTime) print 'Kill proccess: ', proc #sock.close() proc.terminate() def subSocketListener(port, addr, lastSock): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.bind((UDP_IP, port)) print 'Bind subsocket port: ', port print 'Start listening' lastSock.sendto('PORTOK', addr) #clallback.put(sock) while True: data, addr = sock.recvfrom(1024) print 'subsubsocket new packet', data, ' from ', addr sock.sendto(data+" "+str(addr), addr) sock.close() except Exception, e: print 'exep ', e sendError('ERRORPORT', addr, lastSock) sock.close() def testPort(port): if port.isdigit(): iport = int(port) if iport>50000 and iport<65000: return True return False def createSubsocket(port, sock, addr): p = Process(target=subSocketListener, args=(port, addr, sock, )) p.start() #s = q.get() kp = Process(target=subSocketKiller, args=(p, 5 )) kp.start() def listenProcess(sock): while True: data, addr = sock.recvfrom(1024) print 'main socket new packet', data, ' from ', addr if testPort(data): port = int(data) createSubsocket(int(data), sock, addr) else: sendError("ERRORPARSEPORT", addr, sock) sock.close() UDP_IP = "" UDP_PORT = 7777 mainSock = createSocket(UDP_PORT) print 'server started on ', UDP_PORT parent_conn, child_conn = Pipe() p = Process(target=listenProcess, args=(mainSock,)) p.start() print parent_conn.recv() # prints "[42, None, 'hello']" p.join() <file_sep>/README.md # SuperSTUN Simple server for traversal of the Symmetric NAT when server port is known before usage
aa569502d19f24b301fc7f995fe6b29b68640aec
[ "Markdown", "Python" ]
2
Python
wfpc/SuperSTUN
f01791ad4ad433adae350fe41e9cb86c373e14e1
1335625c3845c6d785c871b7a34d7e3a040f7d2b
refs/heads/master
<repo_name>standardgalactic/vim-codespell<file_sep>/dict/build.sh rm all.list cat *.list >> all.temp mv all.temp all.list aspell --lang=en create master ./cs.dict < all.list <file_sep>/plugin/codespell.py # TODO: correct header # Python 3 from collections import defaultdict import re from subprocess import Popen, PIPE, STDOUT import vim def tokenize(line): words = [m.group(0) for m in re.finditer(r"[a-zA-Z]+", line)] # TODO: maybe merge the two regex or make this more efficient final_words = [] for word in words: # Ref: https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python final_words += [m.group(0) for m in re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", word)] return final_words def filter_multi_occurance(words): counts = defaultdict(lambda: 0) for word in words: counts[word] += 1 filtered = [] for word, count in counts.items(): # TODO: make this configurable if count < 5: filtered.append(word) return filtered def find_spell_errors_cs(words): # Must be executed from the top level script_dir = vim.eval("s:dir") return find_spell_errors(words, ["-d", "cs.dict", "--dict-dir={dir}/../dict".format(dir=script_dir)]) def find_spell_errors(words, extra_args=[]): base_aspell_cmd = ["aspell", "--list"] extra_aspell_args = ["-l", "en-US"] cmd = base_aspell_cmd + extra_aspell_args + extra_args p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT) stdout = p.communicate(input=str.encode(" ".join(words)))[0] output = stdout.decode() return output.rstrip().split("\n") # Main lines = " ".join(vim.current.buffer) words = tokenize(lines) words = filter_multi_occurance(words) unique_words = list(set(words)) for word in find_spell_errors(find_spell_errors_cs(unique_words)): # silently skip empty string, which is usually due to the dictionary not # working correctly if len(word) == 0: continue # We ignore words that has more lowercase char after it, because we # might be matching a prefix. if word[0].isupper(): # If the word starts with a upper case, it might be part of a CamelCase # word, so we need to allow characters before it. # TODO: extract this matchadd command as a function vim.command( "call matchadd(\'Error\', \'\\v{word}\ze[^a-z]\')".format( word=re.escape(word) ) ) else: # If the word starts with a lower case, we don't allow any lowercase # charater before it, becuase the match may be a suffix vim.command( "call matchadd(\'Error\', \'\\v[^a-z]\zs{word}\ze[^a-z]\')".format( word=re.escape(word) ) ) <file_sep>/README.md vim-codespell --------------------- A vim plugin for checking the spelling for source code. The main difference from the built-in spell checker is that it handles CamelCase, snake_case better, and you can add custom words to it. # Installation * Enable vim python3 support * Install [aspell][http://aspell.net/] * Mac: `brew install aspell` * Ubuntu: `sudo apt-get install aspell` * Add it to vim with the vim plugin manager of your choice. * Vundle: Add `Plugin 'shinglyu/vim-codespell'` to your `~/.vimrc` and run `:PluginInstall` * To use the custom dictionary, you need to build it. * Go to the installed location of the plugin. (For Vundle on Mac it's `cd ~/.vim/bundle/vim-codespell`) * `cd dict` * `./build.sh` # Commands * `:Codespell`: Run the spell checker once * To run it everytime you save a `*.py` file, add the following to your vimrc: ``` :autocmd BufWritePre *.py :Codespell ``` # Testing * `sudo pip3 install pytest pytest-benchmark` (Or use `virtualenv`) * `py.test` # Generating Dictionaries You can add custom words to the dictionary. * Create a text file in `dict/` (e.g. `dict/cs.list`) of words, one word per line * Generate the dictionary ``` aspell --lang=en create master ./cs.dict < cs.list ``` A dictionary file `cs.dict` will be generated in the current dir. The plugin will pick it up using the default filename. * Test the dictionary locally: ``` cat file_to_be_checked.txt | aspell -l en -d cs.dict --dict-dir=./ --list ``` The `--dict-dir` must be specified otherwise `aspell` will check the default location. # Tips * Check if `python3` is supported in your vim build: `vim --version`, look for the string "+python3". * To load it temporarily for test, `cd` to `plugin/`, run `vim -S codespell.vim`. * `:match Error /\%2l\%>1c\%<4c./`: highlight line 2 (`\%2l`) and column 2 (`\%>1c`) to column 3 (`\%<4c`), the `.` is required because the match is 0 width. # References * Python's `vim` interface [doc](http://vimdoc.sourceforge.net/htmldoc/if_pyth.html) * [Learn vimscript the hard way](http://learnvimscriptthehardway.stevelosh.com)
40314eeae9a8199bd09003be25096f60d0bdca72
[ "Markdown", "Python", "Shell" ]
3
Shell
standardgalactic/vim-codespell
bd9efe8331a9f15929562d7a5fbecbcf7bef6c9b
bdd1c7563111647b2188975cd01ec02cffc2b4b1
refs/heads/master
<file_sep>""" Applications enviroment configuration settings """ from os import getenv class Config: """ Common configurations """ SECRET_KEY = getenv('SECRET KEY', 'my_precious_secret_key') DEBUG = False class DevelopmentConfig(Config): """ Development configurations """ DEBUG = True SQLALCHEMY_DATABSE_URI = getenv('DATABASE_URL') SQLALCHEMY_TRACK_MODIFICATION = False class TestingConfig(Config): """ Testing configurations """ DEBUG = True TESTING = True SQLALCHEMY_DATABSE_URI = getenv('TEST_DATABASE_URL') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): """ Production configurations """ DEBUG = False app_config = { 'dev': DevelopmentConfig, 'test': TestingConfig, 'prod': ProductionConfig } <file_sep># app/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import app_config db = SQLAlchemy() def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config['config_name']) db.init(app) return app <file_sep># Book Share Book share is `Peer to Peer` lending application that help book lovers to add and borrow books from other peers <file_sep>"""app entry point.""" from os import getenv from flask import jsonify from flask_script import Manager from main import create_app from config import app_config config_name = getenv('FLASK_ENV', default='production') app = create_app(app_config[config_name]) manager = Manager(app) @app.route('/') def root(): """ Dummy Endpoint for testing""" return jsonify({'hello': 'world'}) if __name__ == '__main__': manager.run() <file_sep>""" Initialize the flask app instance """ # Third Party Imports from flask import Flask def create_app(config): """ Initialize the app instance depending on the enviroment passed to it """ app = Flask(__name__) app.config.from_object(config) return app
0dc45607f7c9723fe8bcd50efca893b48bb642fd
[ "Markdown", "Python" ]
5
Python
frankip/book-share
6e453f9c096ac71e8693b1d60cd3503aa698ef9e
feb9dc69444fa71331da7fae269ad83413cc17b4
refs/heads/master
<repo_name>onkcharkupalli1051/c-programming<file_sep>/DS/LINKED LIST/dll_1_23_11_20.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next,*prev; }; struct node *head = 0, *temp, *tail; void create(); void display(); void insert(); void insertatbeg(); void insertatend(); void insertatloc(); int lenofdll(); void deletedata(); void deletefrombeg(); void deleteatloc(); void deleteatend(); void reverse(); void main() { int choice; while(1) { printf("\nOperations :\n1. Create\n2. Exit\n3. Display\n4. Insert\n5. Calculate Length\n6. Delete data\n7. Reverse DLL\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: exit(0); case 3: display(); break; case 4: insert(); break; case 5: lenofdll(); break; case 6: deletedata(); break; case 7: reverse(); break; default: printf("\nInvalid Selection"); } } getch(); } void create() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; newnode->prev = 0; if(head == 0) { head = newnode; tail = newnode; } else { tail->next = newnode; newnode->prev = tail; newnode->next = 0; tail = newnode; /* temp->next = newnode; newnode->prev = temp; temp = newnode; /* temp = head; while(temp->next != 0) { temp = temp->next; } newnode->prev = temp; temp->next = newnode; newnode->next = 0; */ } printf("\nCreated Succesfully"); } void display() { printf("\nDoubly Linked List : "); temp = head; while(temp != 0) { printf("%d\t",temp->data); temp = temp->next; } } void insert() { int choice; printf("\n1. Insert At Beginning\n2. Insert At Location\n3. Insert At End\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: insertatbeg(); break; case 2: insertatloc(); break; case 3: insertatend(); default: printf("\nInvalid insert operation"); } } void insertatbeg() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; temp = newnode; newnode->prev = 0; newnode->next = 0; tail = newnode; /* tail newnode head 0 10 0 */ } else { head->prev = newnode; newnode->next = head; head = newnode; /* head->prev = newnode; temp = head; head = newnode; newnode->prev = 0; newnode->next = temp; head newnode tail 10-> <-20 30 40 50 12 20 28 36 44 */ } } void insertatend() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; temp = newnode; tail = newnode; newnode->prev = 0; newnode->next = 0; } else { newnode->prev = tail; tail->next = newnode; newnode->next = 0; tail = newnode; /* head tail newnode original : 10 20 30 40 address : 44 52 60 70 */ } } void insertatloc() { int pos; printf("\nEnter position (1,%d) : ",lenofdll()); scanf("%d",&pos); if(pos == 1) { insertatbeg(); } if(pos == lenofdll()) { insertatend(); } else { int i=1; struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); temp = head; while(i < pos-1) { temp = temp->next; i++; } newnode->prev = temp; newnode->next = temp->next; temp->next = newnode; newnode->next->prev = newnode; } } int lenofdll() { int count=1; temp = head; while(temp != 0) { temp = temp->next; count++; } return count; } void deletedata() { int choice; printf("\n1. Delete At Beginning\n2. Delete At Location\n3. Delete At End\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: deletefrombeg(); break; case 2: deleteatloc(); break; case 3: deleteatend(); default: printf("\nInvalid"); } } void deletefrombeg() { if(head == 0) printf("\nCannot Delete, Empty Dll"); else temp = head->next; temp->prev = 0; free(head); head = temp; /* temp = head; head = head->next; head->prev = 0; free(temp); */ printf("\nDeleted Succesfully!"); } void deleteatend() { if(head == 0) printf("\nCannot Delete, Empty Dll"); else temp = tail->prev; temp->next = 0; tail = temp; free(tail); /* temp = tail; tail->prev->next = 0; tail = tail->prev; free(temp); */ printf("\nDeleted Succesfully!"); } void deleteatloc() { if(head == 0) printf("\nCannot Delete, Empty Dll"); else { int i = 1,pos; temp = head; printf("Enter position from 1 to %d which you want to delete : ",lenofdll()); scanf("%d",&pos); while(i < pos) { temp = temp->next; i++; } temp->prev->next = temp->next; temp->next->prev = temp->prev; free(temp); printf("\nDeleted Succesfully!"); } } void reverse() { struct node *nextnode,*current; if(head == 0) printf("\nCannot Reverse, Empty Dll"); else { current = head; while(current != 0) nextnode = current->next; current->next = current->prev; current->prev = nextnode; current = nextnode; current = head; head = tail; tail = current; } } <file_sep>/DS/QUEUE/queue_implementation_using_stack.c #include<stdio.h> #include<conio.h> #define N 5 int s1[N],s2[N]; int top1 = -1, top2 = -1; int count = 0; void enqueue() { int x; printf("\nEnter data : "); scanf("%d",&x); push1(x); count++; } void push1(int x) { if(top1 == N-1) { printf("\nOverflow."); } else { top1++; s1[top1] = x; } printf("\nEntered Succesfully"); } void dequeue() { if(top1 == -1 && top2 == -1) { printf("\nUnderflow"); } else { for(int i =0; i<count; i++) { int a = pop1(); push2(a); } int b = pop2(); printf("%d",b); count--; for(int i = 0; i < count; i++) { int a = pop2(); push1(a); } } } void push2(int data) { if(top2 == N-1) { printf("\nOverflow."); } else { top2++; s2[top2] = data; } printf("\nEntered Succesfully"); } int pop1() { return s1[top1--]; } int pop2() { return s2[top2--]; } void display() { if(top1 == -1) { printf("\nEmpty Queue"); } else { int i; printf("\nDisplay : "); for(i = 0;i<top1+1;i++) { printf("%d ",s1[i]); } } } void peek() { if(top1 == -1) { printf("\nEmpty Queue"); } else { int i = 0; printf("\nFront : %d",s1[i]); } } void main() { int choice; while(1) { printf("\nOperations :\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display\n5. Exit"); printf("\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid"); } } } <file_sep>/DS/insertion_sort.c #include<stdio.h> #include<stdlib.h> void insert_sort(int arr[],int n) { int i,j,temp; for(i=1;i<n;i++) { temp = arr[i]; j = i-1; while(j >= 0 && arr[j] > temp) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } } void selection_sort(int arr[], int n) { int i,j,temp,low; for(i=0; i<n; i++) { low = arr[i]; for(j=i+1; j<n; j++) { if(low > arr[j]) { low = low + arr[j]; arr[j] = low - arr[j]; low = low - arr[j]; } } arr[i] = arr[i] + low; low = arr[i] - low; arr[i] = arr[i] - low; } } void merge_sort(int arr[],int l, int r) { if (l < r) { int m = l + (r - l) / 2; merge_sort(arr, l, m); merge_sort(arr, m + 1, r); merge(arr, l, m, r); } } void merge(int arr[],int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; int L[n1], R[n2]; for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } /* void merge(int a[],int min,int mid,int max) { int temp[max],i,l1,r1; l1=min; r1=mid+1; i=min; while(l1<=mid && r1<=max)//#1 { if(a[l1]<a[r1]) { temp[i]=a[l1]; l1++; i++; } else { temp[i]=a[r1]; r1++; i++; } } while(l1<=mid) { temp[i]=a[l1]; l1++; i++; } while(r1<=max) { temp[i]=a[r1]; r1++; i++; } for(i=min;i<=max;i++) a[i]=temp[i]; } */ void printarr(int arr[], int n) { int i; printf("\nSORTED ARRAY : "); for(i=0; i<n; i++) { printf("%d ",arr[i]); } } void main() { int n,i,choice; printf("Enter size of array : "); scanf("%d",&n); int arr[n]; printf("\nARRAY : "); for(i=0;i<n;i++) { printf("\nEnter array element : "); scanf("%d",&arr[i]); } printf("\nUnsorted ARRAY : "); for(i=0;i<n;i++) { printf("%d ",arr[i]); } printf("\nSorting :\n1. Insertion Sort\n2. Selection Sort\n3. Merge Sort\n4. Exit\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: insert_sort(arr,n); break; case 2: selection_sort(arr,n); break; case 3: merge_sort(arr,0,n-1); break; case 4: exit(0); } printarr(arr,n); } <file_sep>/DS/LINKED LIST/circular_doubly_ll.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; struct node *prev; }; struct node *head = 0,*temp; void create() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { newnode->next = newnode; newnode->prev = newnode; head = newnode; } else { temp = head->prev; temp->next = newnode; newnode->prev = temp; newnode->next = head; head->prev = newnode; } } void insert() { int choice; printf("\n1. Insert at beginning\n2. Insert at end\n3. Insert at location\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: insertatbeg(); break; case 2: insertatend(); break; case 3: insertatloc(); break; default: printf("\nInvalid"); } } void insertatbeg() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { newnode->prev = newnode; newnode->next = newnode; head = newnode; } else { newnode->next = head; newnode->prev = head->prev; head->prev->next = newnode; head->prev = newnode; head = newnode; } printf("\n%d Entered Succesfully!"); } void insertatend() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { newnode->next = 0; newnode->prev = 0; head = newnode; } else { newnode->prev = head->prev; newnode->next = head; head->prev->next = newnode; head->prev = newnode; } } void insertatloc() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); int loc,count= 1; printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { newnode->next = newnode; newnode->prev = newnode; head = newnode; } else { int count = 1; printf("\nEnter Location to insert at : "); scanf("%d",&loc); temp = head; while(temp->next != head && count < loc-1) { count++; temp = temp->next; } newnode->prev = temp; newnode->next = temp->next; temp->next->prev = newnode; temp->next = newnode; } printf("%d Inserted At End",newnode->data); } void display() { if(head == 0) { printf("\nLinked List is EMpty"); } else { temp = head; printf("Doubly Circular Linked list : "); printf("%d ",temp->data); temp = temp->next; while(temp != head) { printf("%d ",temp->data); temp = temp->next; } } } void main() { int choice; while(1) { printf("\n\nOPERATIONS : "); printf("\n1. Create\n2. Display\n3. Exit\n4. Insert"); printf("\nEnter Choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: display(); break; case 3: exit(0); case 4: insert(); break; default: printf("\nInvalid, Try again"); } } return 0; } <file_sep>/Practise/Swap1.c #include<stdio.h> #include<stdlib.h> void swap(float a, float b) { int temp = a; a = b; b = temp; printf("%f %f",a,b); } void swap2(float a,float b) // 5 10 { a = a + b; //15 10 b = a - b; //15 5 a = a - b; //10 5 printf("%f %f",a,b); } void swap3(float *a, float *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; printf("%f %f",*a,*b); } // void swap4(float &a,float &b) // { // a = a+b; // b = a-b; // a = a-b; // } int main() { float n1, n2; printf("Enter 1st number : "); scanf("%f",&n1); printf("\nEnter 2nd number : "); scanf("%f",&n2); printf("\nSwap Approach 1 : "); swap(n1,n2); printf("\nSwap Approach 2 : "); swap2(n1,n2); printf("\nSwap Approach 3 : "); swap3(&n1,&n2); // printf("\nSwap Approach 4 : "); // swap4(n1,n2); // printf("%f %f",n1,n2); return 0; } <file_sep>/DS/LINKED LIST/sll_insertatbegin_end_pos.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head = 0; void addatbegin(); void addatend(); void addatloc(); void display(); int main() { int choice; while(1) { printf("\nOperations :\n\n1. ADD AT BEGINNING\n2. ADD AT END\n3. ADD AT LOCATION\n4. DISPLAY\n5. EXIT"); printf("\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: addatbegin(); break; case 2: addatend(); break; case 3: addatloc(); break; case 4: display(); break; case 5: exit(1); default: printf("\nInvalid NO."); } } getch(); } void addatbegin() { int choice = 1; struct node *newnode,*temp; while(choice == 1) { newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data to insert at beginning : "); scanf("%d",&newnode->data); newnode->next = head; head = newnode; printf("\nDo you want to contine adding at beginning? (1/0) : "); scanf("%d",&choice); } } //some error in here void addatend() { int choice = 1; struct node *newnode,*temp; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data to insert at end :"); scanf("%d",&newnode->data); newnode->next = 0; if(head == 0) { head = newnode; temp = newnode; } else { temp = head; while(temp->next != 0) temp = temp->next; temp->next = 0; /* temp->next = newnode; temp = newnode; */ } } void display() { struct node *temp; if(head == 0) printf("\nLinked List is empty."); else { temp = head; printf("\nLinked list :\n"); while(temp != 0) { printf("%d\t",temp->data); temp = temp->next; } } } <file_sep>/HACKERRANK/hackerrank_arrayreversal.c #include<stdio.h> #include<conio.h> int main() { int n,*arr,*narr,i; scanf("%d",&n); arr = (int*)malloc(n * sizeof(int)); narr = (int*)malloc(n * sizeof(int)); for(i=0; i<n; i++) scanf("%d",arr+i); for( i=1; i<=n; i++) narr[i-1] = arr[n-i]; for(i=0;i<n;i++) printf("%d ",*(narr + i)); return 0; } <file_sep>/LB DS/1.Reverse_array.cpp #include<iostream> using namespace std; void reverseArray(int arr[],int start, int end) { while(start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } void printArray(int arr[],int size) { for(int i=0;i<size;i++) { cout<<arr[i]<<" "; } cout<<endl; } int main() { int size,i; cout<<"Enter array size : "; cin>>size; int *arr = new int[size]; cout<<"\nEnter array elements : "; for(i=0;i<size;i++) { cin>>arr[i]; } cout<<"\n1st Array Elements are : "; printArray(arr,size); reverseArray(arr,0,size-1); printArray(arr,size); return 0; } <file_sep>/LB DS/17. Best Time To Buy And Sell Stock.cpp // class Solution { // public: // int maxProfit(vector<int>& prices) { // int n = prices.size(); // int buy=prices[0], bi = 0; // for(int i=1;i<n;i++) // { // if(buy > prices[i]) // { // buy = prices[i]; // bi = i; // } // } // int sell = prices[bi]; // for(int j=bi+1;j<n;j++) // { // if(prices[j] > buy) // { // sell = prices[j]; // } // } // if(sell > buy) return (sell-buy); // if(sell == prices[bi]) // return 0; // } // }; class Solution{ public int maxProfit(int[] prices) { int minprice = INT_MAX; int maxprofit = 0; for(int i=0;i<prices.length;i++) { if(prices[i] < minprice) minprice = prices[i]; else if(prices[i]-minprice > maxprofit) maxprofit = prices[i] - minprice; } return maxprofit; } }<file_sep>/DS/STACK/stack_implementation_using_arrays.c #include<stdio.h> #include<stdlib.h> #define N 5 int stack[N]; int top = -1; void push(); void pop(); void peek(); void display(); void main() { int choice; while(1) { printf("\n\nOPerations :\n1. Push\n2. Pop\n3. Top/Peek\n4. Display\n5. Exit\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: push(); break; case 2: pop(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid"); } } getch(); } void push() { if(top == N-1) printf("Cannot push! Overflow"); else top++; printf("\nPUSH OPERATION :\nEnter data : "); scanf("%d",&stack[top]); printf("\nInserted Succesfully."); } void pop() { if(top == -1) printf("\nInvalid Operation! Underflow"); else printf("\nPOP Operation\nPopped Element : %d",stack[top]); top--; printf("\nPopped Succesfully."); } void peek() { if(top == -1) printf("\nEmpty Stack"); else printf("\nTOP Operation\nTop Element : %d",stack[top]); printf("\nTopped Succesfully."); } void display() { if(top == -1) printf("Empty Stack"); else { int i; printf("\nDisplay Of Stack : "); for(i = top;i >= 0; i--) printf("%d\t",stack[i]); } } <file_sep>/delete.c #include<stdio.h> #include<stdlib.h> int dll() { int count = 5; return count; } void main() { printf("\nCount : %d",dll()); getch(); } <file_sep>/DS/fibonacci_recursion.c #include<stdio.h> int fib(int); void main() { int num, c, i=0 ; printf("Enter num : "); scanf("%d",&num); printf("\nFibonacci series : "); for(c=1; c<=num; c++) { printf("%d\t",fib(i)); i++; } getch(); } int fib(int num) { if(num <= 1) return num; return (fib(num-1) + fib(num-2)); } <file_sep>/DS/LINKED LIST/doubly_linked_list.c #include"stdio.h" #include"stdlib.h" struct Node { int data; struct Node *prev; struct Node *next; }; struct Node *head=NULL; void addatend(int); void addatbeg(int); void display(); void addafterval(int,int); void delatbeg(); void delatend(); void delspec(int); int main() { display(); addatend(10); addatend(20); addatend(30); addatend(40); addatend(50); addatend(999); display(); addatbeg(888); display(); addafterval(777,20);//add 666 after 20 display(); delatbeg(); display(); delatend(); display(); delspec(777); display(); } void delspec(int x) { struct Node *temp; if(head==NULL) { printf("\nError: linked list is empty so can't delete item"); } else { if(head->data == x) { if(head->next==NULL) { temp=head; head=NULL; free(temp); } else { temp=head; head=temp->next; head->prev=NULL; free(temp); } } else { temp=head; while(temp->data!=x) { temp=temp->next; if(temp==NULL) { printf("\nError: no element with value %d, so can't delete",x); return; } } if(temp->next==NULL) { temp->prev->next=NULL; free(temp); } else { temp->prev->next=temp->next; temp->next->prev=temp->prev; free(temp); } } } } void delatend() { struct Node *temp; if(head==NULL) { printf("\nError: linked list is empty so can't delete item"); } else { if(head->next==NULL) { temp=head; head=NULL; free(temp); } else { temp=head; while(temp->next!=NULL) { temp=temp->next; } //temp->prev->next=NULL; //free(temp); //OR temp=temp->prev; free(temp->next); temp->next=NULL; } } } void delatbeg() { struct Node *temp; if(head==NULL) { printf("\nError: linked list is empty so can't delete item"); } else { if(head->next == NULL) { temp=head; head=NULL; free(temp); } else { temp=head; head=head->next; head->prev=NULL; free(temp); } } } void addafterval(int x,int val) { struct Node *newNode,*temp; newNode=(struct Node *) malloc(sizeof(struct Node)); newNode->data=x; if(head==NULL) { printf("\nError: linked list is empty(No node with value %d), so can't add %d",val,x); } else { temp=head; while(temp!=NULL) { if(temp->data==val) { newNode->next=temp->next; if(temp->next!=NULL) temp->next->prev=newNode; temp->next=newNode; newNode->prev=temp; break; } temp=temp->next; } if(temp==NULL) { printf("\nError: No node with value %d, so can't add %d",val,x); } } } void addatbeg(int x) { struct Node *newNode,*temp; newNode=(struct Node*) malloc(sizeof(struct Node)); newNode->data=x; if(head==NULL) { newNode->prev=NULL; newNode->next=NULL; head=newNode; } else { temp=head; temp->prev=newNode; newNode->next=temp; newNode->prev=NULL; head=newNode; } } void addatend(int x) { struct Node *newNode,*temp; newNode=(struct Node*) malloc(sizeof(struct Node)); newNode->data=x; if(head==NULL) { newNode->prev=NULL; newNode->next=NULL; head=newNode; } else { temp=head; while(temp->next!=NULL) temp=temp->next; newNode->prev=temp; newNode->next=NULL; temp->next=newNode; } } void display() { struct Node *temp,*temp1,*temp2; if(head==NULL) { printf("\nDoubly linked list is empty."); } else { temp=head; temp1=head; printf("\nDoubly linked list is: "); while(temp!=NULL) { temp2=temp; printf("%d ",temp->data); temp=temp->next; } } } <file_sep>/struct.c #include<stdio.h> #include<conio.h> struct book { char name[10]; int pages; }; void main() { struct book b1 = {"Ass",10}; struct book *p; p = &b1; printf("\n %s %d ",b1.name,b1.pages); printf("\n\n %s %d ",(*p).name,(*p).pages); printf("\n %s %d ",p->name,p->pages); return 0; } <file_sep>/DS/ARRAY/duplicate_elements.c #include<stdio.h> #include<stdlib.h> void main() { int size,i,j,count=0,ele,mm=1; printf("Enter Size : "); scanf("%d",&size); int a[size]; printf("\nEnter array elements : "); for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("\nDisplay of array elements : "); for(i=0;i<size;i++) { printf("%d ",a[i]); } int b[size],c[size]; for(i=0;i<size;i++) { b[i] = a[i]; c[i] = 0; } for(i=0;i<size;i++) { for(j=0;j<size;j++) { if(a[i] == b[j]) { c[j] = mm; mm++; } } mm = 1; } for(i=0;i<size;i++) { if(c[i] == 2) { count++; } } printf("\nCOunt : %d",count); } <file_sep>/DS/QUEUE/CIRCULAR_QUEUE_USING_LINKED_LIST.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *front = 0, *rear = 0,*temp; void enqueue() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; if(front == 0 && rear == 0) { front = newnode; rear->next = front; } else { rear->next = newnode; rear = newnode; rear->next = front; } } void dequeue() { if(front ==0 && rear == 0) { printf("\nEmpty Queue, Underflow"); } else if(front == rear) { temp = front; printf("\n%d Dequeued succesfully",front->data); front = rear = 0; free(temp); } else { printf("\n%d Dequeued",front->data); temp = front; rear = front->next; front = front->next; free(temp); } } void peek() { if(front ==0 && rear == 0) { printf("\nEmpty Queue"); } else { printf("Front Data : ",front->data); } } void display() { if(front ==0 && rear == 0) { printf("\nEmpty Queue"); } else { temp = front; printf("\nCircular Queue"); while(temp->next != front) { printf("%d ",temp->data); temp = temp->next; } printf("%d ",temp->data); } } void main() { int choice; while(1) { printf("\nOperations :\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display\n5. Exit"); printf("\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid"); } } } <file_sep>/DS/LINKED LIST/copy_linked_list_2.c //Copying the Linked List 222 //The easy one #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; }; struct node *start1=NULL, *start2=NULL; void create(int num, int ll); void Copy(); void Display(int i); void create(int num, int ll) { struct node *newp,*a; newp=(struct node*)malloc(sizeof(struct node)); newp->data=num; if(ll==1) { if(start1==NULL) { newp->next=NULL; start1=newp; } else { a=start1; while(a->next!=NULL) { a=a->next; } a->next=newp; newp->next=NULL; } } else { if(start2==NULL) { newp->next=NULL; start2=newp; } else { a=start2; while(a->next!=NULL) { a=a->next; } a->next=newp; newp->next=NULL; } } } void Display(int i) { struct node *start; if(i==1) { start=start1; printf("\n Elements in Linked List no. %d : ",i); } else if(i==2) { start=start2; printf("\n Elements in Linked List no. %d : ",i); } else { printf(" "); } while(start!=NULL){ printf("%d ", start->data); start=start->next; } printf("\n"); } void Copy() { struct node *a=start1; while(a!=NULL){ create(a->data,2); a=a->next; } } int main() { int x; printf("\n Creation of a linked list\n"); while(1) { printf("\n Enter Data :"); scanf("%d",&x); create(x,1); printf("\n Do you want to continue ? 1.Yes 2.No ---"); scanf("%d",&x); if(x==2){ break; } } Display(1); printf("\n"); printf("\n Copying the Linked List..."); for(x=0;x<3;x++){ printf("\n ..."); } Copy(); printf("\n The Linked List is copied successfully !\n\n"); Display(1); Display(2); return 0; } <file_sep>/DS/LINKED LIST/linked_list_implementation.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; int main() { int choice = 1; struct node *newnode,*head,*temp; head = 0; newnode = (struct node*)malloc(sizeof(struct node)); while(choice == 1) { newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data :"); scanf("%d",&newnode->data); newnode->next = 0; if(head == 0) { head = newnode; temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to cont. (1/0) : "); scanf("%d",&choice); if(choice == 1) continue; else break; } //printing the linked list temp = head; printf("\nLinked list :\n"); while(temp != 0) { printf("%d\t",temp->data); temp = temp->next; } getch(); } <file_sep>/DS/merge_sort.cpp // C++ program for Merge Sort #include <iostream> using namespace std; void merge(int arr[], int l, int m, int r) { int n1 = m-l+1, n2 = r-m; int L[n1],R[n2]; for(int i=0;i<n1;i++) { L[i] = arr[l+i]; } for(int j=0;j<n2;j++) { R[j] = arr[m+1+j]; } int i=0,j=0,k=l; while(i<n1 && j<n2) { if(L[i] < R[j]){arr[k]=L[i];i++;} else{arr[k]=R[j];j++;} k++; } while(i<n1){arr[k]=L[i];i++;k++;} while(j<n2){arr[k]=R[j];j++;k++;} } void mergeSort(int arr[],int l, int r) { if(l <= r) return; int m = l + (r-1)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r); } // UTILITY FUNCTIONS // Function to print an array void printArray(int A[], int size) { for (int i = 0; i < size; i++) cout << A[i] << " "; } // Driver code int main() { int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); cout << "\nSorted array is \n"; printArray(arr, arr_size); return 0; } <file_sep>/CodeChef/DigitMatrix.c /* You are given a matrix A of non-negative integers with N rows (numbered 1 through N) and N columns (numbered 1 through N). For each valid i and j, let's denote the element in the i-th row and j-th column by Ai,j. You need to find a matrix B with N+1 rows and N+1 columns (numbered similarly) such that: each element of this matrix is a digit between 0 and 9 (inclusive) Ai,j=Bi,j+Bi+1,j+Bi,j+1+Bi+1,j+1 for each valid i,j The matrix A is chosen in such a way that at least one solution exists. If there are multiple solutions, you may find any one of them. Input The first line of the input contains a single integer N. N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai,1,Ai,2,…,Ai,N. Output Print N+1 lines. For each valid i, the i-th of these lines should contain N+1 characters Bi,1,Bi,2,…,Bi,N+1. Constraints 1≤N≤100 for the matrix A, at least one valid matrix B exists Subtasks Subtask #1 (10 points): N≤5 Subtask #2 (90 points): original constraints Example Input 2 12 16 24 28 Example Output 123 456 789 All submissions for this problem are available. Author: ildar_adm Editorial: https://discuss.codechef.com/problems/DGMATRIX Tags: ad-hoc, dec20, ildar_adm, medium-hard, shortest-path Date Added: 29-11-2020 Time Limit: 1 secs Source Limit: 50000 Bytes Languages: CPP14, C, JAVA, PYTH 3.6, PYTH, CS2, ADA, PYPY, PYP3, TEXT, CPP17, PAS fpc, RUBY, PHP, NODEJS, GO, TCL, HASK, PERL, SCALA, kotlin, BASH, JS, PAS gpc, BF, LISP sbcl, CLOJ, LUA, D, R, CAML, rust, ASM, FORT, FS, LISP clisp, SQL, swift, SCM guile, PERL6, CLPS, WSPC, ERL, ICK, NICE, PRLG, ICON, PIKE, COB, SCM chicken, SCM qobi, ST, NEM Submit My SubmissionsAll Submissions Successful Submissions */ #include<stdio.h> #include<stdlib.h> int main() { int N; scanf("%d",&N); int A[N][N]; int i,j; int B[N+1][N+1]; for(i=0;i<N;i++) { for(j=0;j<N;j++) { scanf("%d",&A[i][j]); } } for(int k=0;k<N+1;k++) { } } <file_sep>/LB DS/16. Count Inversions.cpp #include<iostream> using namespace std; //My Solution // long long int inversionCount(long long arr[], long long N) // { // int count=0,i=0; // for(i;i<N;i++) // { // for(int j=0;j<N;j++) // { // if(i<j && arr[i]>arr[j]) // { // cout<<"\n"<<arr[i]<<" "<<arr[j]; // int tmp = arr[i]; // arr[i] = arr[j]; // arr[j] = tmp; // count++; // } // } // } // return count; // } 2 4 1 3 5 1 4 2 3 5 //GFG Solution // long long int inversionCount(long long arr[], long long N) // { // int count=0,i=0; // for(i;i<N;i++) // { // for(int j=i+1;j<N;j++) // { // if(arr[i]>arr[j]) // { // cout<<"\n"<<arr[i]<<" "<<arr[j]; // int tmp = arr[i]; // arr[i] = arr[j]; // arr[j] = tmp; // count++; // } // } // } // return count; // } int main() { // long long int A[] = {2,4,1,3,5}; // long long int n = inversionCount(A,5); // cout<<endl<<"n : "<<n; int arr[] = { 1, 20, 6, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = mergeSort(arr, n); cout << " Number of inversions are " << ans; return 0; } <file_sep>/DS/sort_from_standard_library.c #include<stdio.h> #include<stdlib.h> int compare(const void *a, const void *b) { return (*(int*)a < *(int*)b); } int main() { int data[] = {99,55,44,77,22,33,11,66,55,77}; qsort(data, 10, sizeof(int), compare); for(int i=0; i<10; i++) printf("%d ",data[i]); return 0; } <file_sep>/Practise/CompundInterest.c #include<stdio.h> #include<stdlib.h> #include<math.h> int main() { double pA, rOI, n, t; double cI; printf("Enter Principal Amount : "); scanf("%lf",&pA); printf("\nEnter Number Of Times interest compounded : "); scanf("%lf",&n); printf("\nEnter Rate Of Interest : "); scanf("%lf",&rOI); printf("\nEnter time period : "); scanf("%lf",&t); cI = pA * pow((1 + (rOI/n)), (n*t)); printf("\nCompound Interest : %lf",cI); return 0; }<file_sep>/DS/LINKED LIST/SLL2.c #include"stdio.h" #include"conio.h" #include"stdlib.h" struct Node { int data; struct Node *next; }; struct Node *head=NULL; void addatend(int); void display(); void addatbeg(int); int main() { display(); addatbeg(10); display(); addatend(20); display(); addatend(30); display(); addatend(40); display(); addatend(50); display(); addatbeg(60); display(); addatbeg(70); display(); } void addatend(int x) { struct Node *temp, *newNode; newNode=(struct Node*) malloc(sizeof(struct Node)); newNode->data=x; newNode->next=NULL; if(head==NULL) { head=newNode; } else { temp=head; while(temp->next!=NULL) temp=temp->next; temp->next=newNode; } } void addatbeg(int x) { struct Node *newNode; newNode=(struct Node*) malloc(sizeof(struct Node)); newNode->data=x; newNode->next=NULL; if(head==NULL) { head=newNode; } else { newNode->next=head; head=newNode; } } void display() { struct Node *temp; if(head==NULL) printf("\nLinked list is empty"); else { temp=head; printf("\nLinked list is: "); while(temp!=NULL) { printf("%d\t",temp->data); temp=temp->next; } } } <file_sep>/DS/LINKED LIST/length of ll.c #include<stdio.h> #include<conio.h> struct node { int data; struct node *next; }; struct node *head = 0; struct node *temp; void create(); void insertatend(); void lenofll(); void display(); void reverse(); void main() { int choice; while(1) { printf("\nOperations :\n1. Create\n2. Insert at end\n3. Find length\n4. Exit\n5. Display\n6. Reverse\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: insertatend(); break; case 3: lenofll(); break; case 4: exit(0); case 5: display(); break; case 6: reverse(); break; default: printf("\nInvalid Choice"); break; } } getch(); } void create() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; if(head == 0) { head = newnode; temp = newnode; } else { temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; } printf("\nInserted Successfully."); } void insertatend() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; printf("Inserted Succesfully at the end."); } void lenofll() { int count = 0; temp = head; while(temp->next != 0) { count++; temp = temp->next; } printf("\nLength of linked list : %d",count+1); } void display() { temp = head; printf("\n\nLinked list is : "); while(temp->next != 0) { printf("%d\t",temp->data); temp = temp->next; } } void delete() { /* int k; struct node *r; r = (struct node*)malloc(sizeof(struct node)); printf("\nEnter the element you want to delete : "); scanf("%d",&k); temp = head; while(temp->next != 0 && temp->data != k) { r = temp; temp = temp->next; } if(temp == head) { head = temp->next; free(temp); } else { r->next = p->next; free(p); } printf("\nDeleted Successfully"); */ return 0; } void reverse() { struct node *prevnode,*currentnode,*nextnode; if(head == 0) printf("\nCannot reverse"); else { prevnode = 0; currentnode = nextnode = head; while(nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; } } <file_sep>/DS/TREE/binary_tree_implementation.c /* Creation of binary tree, Inorder, postorder doesn't work preorder works. */ #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node *temp; int create() { int x; struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data (-1 for no node) : "); scanf("%d",&x); if(x == -1) { return 0; } newnode->data = x; printf("\nEnter left child of %d : ",x); newnode->left = create(); printf("\nEnter right child of %d : ",x); newnode->right = create(); return newnode; } //inorder traversal : left root right void inorder(struct node *root) { if(root = 0 || root == -1) { return; } inorder(root->left); printf("%d ",root->data); inorder(root->right); } //pre-order traversal : root left right void preorder(struct node *root) { if(root == 0) { return; } printf("%d ",root->data); preorder(root->left); preorder(root->right); } //post-order traversal : left right root void postorder(struct node *root) { if(root == 0) { return; } postorder(root->left); postorder(root->right); printf("%d ",root->data); } void main() { struct node *root = 0; root = create(); printf("\nPre-order is : "); preorder(root); printf("\nIn-order is : "); inorder(root); printf("\nPostorder is : "); postorder(root); } <file_sep>/LB DS/2.maximum_minimum_element_in_array.cpp #include<iostream> using namespace std; int main() { int size,i; cout<<"Enter array size : "; cin>>size; int *arr = new int[size]; cout<<"\nEnter array elements : "; for(i=0;i<size;i++) { cin>>arr[i]; } cout<<"\n1st Array Elements are : "; for(i=0;i<size;i++) { cout<<arr[i]<<" "; } int max=arr[0] , min = arr[0]; for(i=1;i<size;i++) { if(max < arr[i]) { max = arr[i]; } if(min > arr[i]) { min = arr[i]; } } cout<<endl<<"Max Element : "<<max; cout<<endl<<"Min Element : "<<min; return 0; } <file_sep>/DS/QUEUE/queue_implementation_using_arrays.c #include<stdio.h> #include<stdlib.h> #define N 10 int queue[N]; int front = -1, rear = -1; void enqueue() { if(rear == N-1) { printf("\nOverflow Condition."); } else if(front== -1 && rear == -1) { front=rear=0; printf("\nEnter data : "); scanf("%d",&queue[rear]); printf("\nEntered Succesfully!"); } else { rear++; printf("\nEnter data : "); scanf("%d",&queue[rear]); printf("\nEntered Succesfully!"); } } void dequeue() { if(front == -1 && rear == -1) { printf("\nUnderflow Condition"); } else if(front == rear) { front = rear = -1; } else { printf("\n%d Dequeued Succesfully",queue[front]); front++; } } void peek() { if(front == -1 && rear == -1) { printf("\nEMpty Queue"); } else { printf("\nFRONT DATA : %d",queue[front]); } } void display() { if(front == -1 && rear == -1) { printf("\nEmpty Queue"); } else { printf("\nQueue :"); for(int i=front;i<rear+1;i++) { printf(" %d",queue[i]); } } } void main() { int choice; while(1) { printf("\n\nOperations :\n1. Enqueue\n2. Dequeue\n3. Peek/Front\n4. Display\n5. Exit\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid Choice"); } } getch(); } <file_sep>/DS/ARRAY/Untitled1.c #include<stdio.h> #include<ctype.h> #include<string.h> #define SIZE 50 char stack[SIZE]; int top = -1; int isfull() { if (top == SIZE-1) return 1; else return 0; } int isempty() { if (top == -1) return 1; else return 0; } void push(char op) { if(isfull()) printf("\nStack is Full"); else { top++; stack[top] = op; } } char pop() { char op; if(isempty()) printf("\nStack Is Empty"); else op = stack[top]; top--; return op; } int isoperator(char ele) { if(ele == '^' || ele == '/' || ele == '*' || ele == '+' || ele == '-') return 1; else return 0; } int precedence(char op) { if(op == '^') return 3; else if(op == '/' || op == '*') return 2; else if(op == '+' || op == '-') return 1; else return 0; } void infixtopostfix(char infix[], char postfix[]) { int i = 0, j=0; char item,x; push('('); strcat(infix,')'); item = infix[i]; while(item != '\0') { if(item == '(') push(item); else if(isdigit(item) || isalpha(item)) { postfix[j] = item; j++; } else if(isoperator(item) == 1) { x = pop(); while(isoperator(x) == 1 && precedence(x) >= precedence(item)) { postfix[j] = x; j++; x = pop(); } push(x); push(item); } else if(item == ')') { x = pop(); while(x != '(') { postfix[j] = x; j++; x = pop(); } } else { printf("\nInvalid Expression."); break; } i++; item = infix[i]; } postfix[j] = '\0'; } void main() { char infix[SIZE], postfix[SIZE]; printf("\nEnter Infix Expression : "); gets(infix); infixtopostfix(infix,postfix); printf("\Postfix Expression : "); puts(postfix); getch(); } <file_sep>/Practise/Array_copy.cpp #include<iostream> #include<array> using namespace std; int *a2; int main() { int n,i=0; cout<<"Enter size : "; cin>>n; int *arr = new int[n]; for(i=0;i<n;i++) { cout<<"\nEnter element : "; cin>>arr[i]; } cout<<"First Array Elements : "; for(i=0;i<n;i++) { cout<<arr[i]<<" "; } if(sizeof(arr)%2 == 0) int *a2 = new int[sizeof(arr)]; else int *a2 = new int[sizeof(arr)+1]; for(i=0;i < sizeof(a2);i++) { a2[i] = arr[i]; } cout<<"\nSecond Array Elements : "; for(i=0;i < sizeof(a2);i++) { cout<<a2[i]<<" "; } return 0; }<file_sep>/LB DS/15. Next Permutation.cpp #include<iostream> using namespace std; class Solution{ public void nextPermutation(int[] A) { if(A==null || A.length<=1) return; int i = A.length-2; while(i>=0 && A[i]>=A[i+1]) i--; if(i>=0) { int j = A.length-1; while(A[j] < A[i]) j--; swap(A,i,j); } reverse(A,i+1,A.length-1); } public void swap(int[] A, int i, int j) { int tmp = A[i];A[i]=A[j];A[j]=tmp; } public void reverse(int[] A,int i,int j) { while(i<j) swap(A,i++,j--); } } // 1 2 3 // i j /* void nextPermutation(vector<int>& nums) { if(nums.size() == 0) { return; } int n = nums.size(); int pt = 0; for(int i=n-1;i>=0;i--) { if(nums[i+1] < nums[i]) { pt = i+1; } } for(int i=n-1;i>=0;i--) { if(nums[i] > nums[pt]) { swap(nums[i],nums[pt]); } } reverse(nums,pt+1,n); } public: void swap(int &n1, int &n2) { n1 = n1 + n2; n2 = n1 - n2; n1 = n1 - n2; } public: void reverse(vector<int>nums,int i, int j) { while(i < j) { swap(nums[i++],nums[j--]); } } */ int main() { return 0; } <file_sep>/DS/tower_of_hanoi_recursion.c /* TOwer OF Hanoi No disk can be placed on top of smaller disk */ void toh(int, char, char, char); void main() { int num; printf("Enter number of disks : "); scanf("%d",&num); toh(num, 'A', 'C', 'B'); getch(); } void toh(int n, char f_r, char t_r, char a_r) { if(n == 1) { printf("\nMove disk 1 from rod %c to rod %c",f_r,t_r); return; } toh(n-1,f_r,t_r,a_r); printf("\nMove disk %d from rod %c to rod %c",n,f_r,t_r); toh(n-1,a_r,t_r,f_r); } <file_sep>/Practise/tempCodeRunnerFile.c // printf("\nSwap Approach 4 : "); // swap4(n1,n2); // printf("%f %f",n1,n2); <file_sep>/LB DS/DEL.cpp #include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<int> A; if(A.size() <= 1) { cout<<"empty"; } // sort(A,A+7); // for(int i=0;i<7;i++) // { // cout<<A[i]<<" "; // } int B[] = {1,2,3}; n = B.length(); cout<<n; return 0; }<file_sep>/DS/TREE/construction_of_binary_search_tree.c #include<stdio.h> #include<conio.h> struct node { int data; struct node *left,*right; }; struct node *root = NULL; struct node *insert(struct node* x,int val) { if(x == NULL) { x = (struct node*)malloc(sizeof(struct node)); x->data = val; x->left = NULL; x->right = NULL; return x; } else if(val < x->data) { x->left = insert(x->right,val); return x; } else { x->right = insert(x->right,val); return x; } }; void inorder(struct node *root) { if(root == NULL) { return; } else { inorder(root->left); printf("%d ",root->data); inorder(root->right); } } void preorder(struct node *root) { if(root == NULL) { return; } else { printf("%d ",root->data); preorder(root->left); preorder(root->right); } } void postorder(struct node *root) { if(root == NULL) { return; } else { preorder(root->left); preorder(root->right); printf("%d ",root->data); } } int search(struct node *x,int val) { if(x == NULL) { return 0; } else if(val == x->data) { return 1; } else if(val < x->data) { search(x->left,val); } else { search(x->right,val); } return 0; } int main() { int choice,val; while(1) { printf("\nOperations :\n1. Insert\n2. Inorder Traversal\n3. Preorder Traversal\n4. Postorder Traversal\n5. Search\n6. Exit\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter data to insert : "); scanf("%d",&val); root = insert(root,val); break; case 2: inorder(root); break; case 3: preorder(root); break; case 4: postorder(root); break; case 5: printf("\nEnter data to search : "); scanf("%d",&val); int item = search(root,val); if(item == 1) { printf("\nElement %d found in BS Tree",val); } else { print("Element %d not found.",val); } break; case 6: exit(0); default: printf("\nInvalid! Try again"); } } } <file_sep>/Practise/Simpleinterest.c #include<stdio.h> #include<conio.h> int main() { double pA, nOY, rOI; double sI; printf("Enter Principal Amount : "); scanf("%lf",&pA); printf("\nEnter Number OF Years : "); scanf("%lf",&nOY); printf("\nEnter Rate Of Interest : "); scanf("%lf",&rOI); sI = pA*nOY*rOI; printf("Simple Interest is : %lf Rs ",sI); return 0; }<file_sep>/DS/gcd_recursion.c #include<stdio.h> int gcd(int a, int b) { if(a == 0) return b; else if(b == 0) return a; else if(a == b) return a; if(a>b) return gcd(a-b,b); return gcd(a,b-a); } void main() { int num1,num2,ans; printf("Enter no. to check gcd : "); scanf("%d%d",&num1,&num2); ans = gcd(num1,num2); printf("\n GCD of %d and %d : %d",num1,num2,ans); getch(); } <file_sep>/DS/ARRAY/reverse_print_array.c #include<stdio.h> #include<stdlib.h> void main() { int size,i; printf("Enter Size : "); scanf("%d",&size); int a[size]; printf("ENter array elements : "); for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("Display of array elements : "); for(i=size-1;i>=0;i--) { printf("%d ",a[i]); } } <file_sep>/DS/bubble_sort.c #include<stdio.h> #include<stdlib.h> int main() { int data[] = {99,77,55,88,44,66,88,22,33}; int n = 9; for(int i=0;i<n;i++) { for(int j=0; j<n;j++) { if(data[j] > data[j+1]) { int temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; } } } printf("\nSorted Array : "); for(int i=0;i<n;i++) { printf("%d ",data[i]); } } <file_sep>/DS/GRAPH/dfs_24_1.c #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define MAX 5 struct vertex { char label; bool visited; }; //stack variables int stack[MAX]; int top = -1; //graph variables //array of vertices struct vertex* vertices1[MAX]; //adjacency matrix int adjMatrix[MAX][MAX]; int vertexcount = 0; //stack functions void push(int item) { stack[++top] = item; } int pop() { return stack[top--]; } int peek() { return stack[top]; } bool isempty() { return top == -1; } //********** graph functions ****************** //add vertex to the vertex list void addvertex(char label) { struct vertex* vertex = (struct vertex*)malloc(sizeof(struct vertex)); vertex->label = label; vertex->visited = false; vertices1[vertexcount++] = vertex; } //add edge to edge array void addedge(int start,int end) { adjMatrix[start][end] = 1; adjMatrix[end][start] = 1; } //display the vertex void displayvertex(int vertexindex) { printf("%c ",vertices1[vertexindex]->label); } //get the adjacent unvisited vertex int getAdjUnvisitedVertex(int vertexindex) { int i; for(i=0; i<vertexcount; i++) { if(adjMatrix[vertexindex][i] == 1 && vertices1[i]->visited == false) { return i; } } return -1; } void depthfirstsearch() { int i; //mark first node as visited vertices1[0]->visited = true; displayvertex(0); push(0); while(!isempty()) { //get the unvisited vertex of vertex which is at top of the stack int unvisitedvertex = getAdjUnvisitedVertex(peek()); //no adjacent vertex found if(unvisitedvertex == -1) { pop(); } else { vertices1[unvisitedvertex]->visited = true; displayvertex(unvisitedvertex); push(unvisitedvertex); } } for(i=0; i<vertexcount; i++) { vertices1[i]->visited = false; } } int main() { int i,j; for(i=0; i<MAX; i++) { for(j=0; j<MAX; j++) { adjMatrix[i][j] = 0; } } addvertex('S'); addvertex('A'); addvertex('B'); addvertex('C'); addvertex('D'); addedge(0,1); addedge(0,2); addedge(0,3); addedge(1,4); addedge(2,4); addedge(3,4); printf("\nDepth First Search : "); depthfirstsearch(); return 0; } <file_sep>/LB DS/7 Cyclically Rotate An Array By One.cpp #include<iostream> using namespace std; int main() { int n,i; cin>>n; int arr[n]; cout<<"\nEnter array elements : "; for(i=0;i<n;i++) { cin>>arr[i]; } cout<<"\n1st Array Elements are : "; for(i=0;i<n;i++) { cout<<arr[i]; } int first = arr[n-1]; int count = n-2; while(count > -1) { arr[count+1] = arr[count]; count--; } arr[0] = first; cout<<"\n2nd Array Elements are : "; for(i=0;i<n;i++) { cout<<arr[i]; } return 0; }<file_sep>/LB DS/8. Largest Sum Of Sub Contiguos Array Kadane's algo.cpp //Kadane's Algorithm #include<iostream> using namespace std; int maxSubArray(int arr[], int size) { int max_so_far = 0, max_ending_here = 0; for(int i=0;i<size;i++) { max_ending_here = max_ending_here + arr[i]; if(max_so_far < max_ending_here) max_so_far = max_ending_here; if(max_ending_here < 0) max_ending_here = 0; } return max_so_far; } int main() { int n,i; cout<<"Enter n : "; cin>>n; int arr[n]; cout<<"\nEnter array elements : "; for(i=0;i<n;i++) { cin>>arr[i]; } cout<<"\n1st Array Elements are : "; for(i=0;i<n;i++) { cout<<arr[i]; } int max_sum = maxSubArray(arr,n); cout<<"\nMax Contigous Sum : "<<max_sum; return 0; } <file_sep>/LB DS/1.Test Reverse.cpp #include <iostream> using namespace std; int main() { //code int T,N,A; cin>>T; while(T--) { cin>>N; int *A = new int[N]; for(int i=0;i<N;i++) { cin>>A[i]; } int start = 0; int end = N-1; while(start < end) { int temp = A[start]; A[start] = A[end]; A[end] = temp; start++; end--; } for(int i=0;i<N;i++) { cout<<A[i]<<" "; } } return 0; } <file_sep>/DS/LINKED LIST/sll.c #include<stdio.h> #include<conio.h> struct node { int data; struct node *next; }; struct node *head = 0; void create(); void insertatbeg(); void insertatmid(); void insertatend(); void display(); void deleteatbeg(); void deleteatend(); void deleteatloc(); void main() { int choice; while(1) { printf("\nOperations :\n1. Create\n2. Insert at beginning\n3. Insert at mid\n4. Insert at end\n5. Display\n6. Exit\n7. DeleteAtBeg\n8. Deleteatend\n9. Delete at loc\n"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: insertatbeg(); break; case 3: insertatmid(); break; case 4: insertatend(); break; case 5: display(); break; case 6: exit(0); case 7: deleteatbeg(); break; case 8: deleteatend(); break; case 9: deleteatloc(); break; default: printf("\nInvalid"); } } } void create() { struct node *newnode,*temp; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; if(head == 0) { head = newnode; temp = newnode; } else { temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; } printf("\nCreated Successfully"); } void insertatbeg() { struct node *newnode,*temp; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = head; head = newnode; printf("Successfully Inserted at Beginning."); } void insertatmid() { int x; struct node *newnode,*temp; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; printf("\nEnter the value after which you want to insert : "); scanf("%d",&x); temp = head; while(temp->next != 0 && temp->data == x) { temp = temp->next; } if(temp == 0) { printf("\nNo such element"); } else { newnode->next = temp->next; temp->next = newnode; } printf("\nInserted Succesfully"); } void insertatend() { struct node *newnode,*temp; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; temp = newnode; } else { temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; newnode->next = 0; } printf("\nInserted Successfully"); } void display() { if(head == 0) printf("\nCAnnot display!"); else printf("\nLinked liSt :\n "); struct node *temp; temp = head; while(temp != 0) printf("%d\t",temp->data); temp = temp->next; } void deleteatbeg() { struct node *temp; if(head == 0) printf("\nEmpty LL"); else temp = head; head = head->next; free(temp); } void deleteatend() { struct node *temp,*prevnode; if(head == 0) printf("\nEMPTY LL."); else temp = head; while(temp->next != 0) prevnode = temp; temp = temp->next; free(temp); prevnode->next = 0; } void deleteatloc() { struct node *temp,*prevnode; int pos,count,i; printf("\nEnter position : "); scanf("%d",&pos); temp = head; while(i < pos-1) { temp = temp->next; i++; } } <file_sep>/DS/binary_search.c #include<stdio.h> #include<stdlib.h> int compare(const void * a,const void * b) { if(*(int*)a < *(int*)b) return -1; if(*(int*)a == *(int*)b) return 0; if(*(int*)a > *(int*)b) return 1; } int main() { int data[] = {11,77,88,99,44,55,66,33,22}; int key = 11; if(bsearch(&key,data,9,sizeof(int),compare)) printf("Found"); else printf("Not Found!"); return 0; } <file_sep>/LB DS/5_Move_neg_nos_to_end.cpp void rearrange(int arr[], int n) { int j=0; for(int i=0; i<n; i++) { if(arr[i] < 0) { if(i != j) { swap(arr[i],arr[j]); } j++; } } }<file_sep>/DS/natural_number_recursion.c #include<stdio.h> int mult(n) { if (n == 1) return 1; else return (n*mult(n-1)); } void main() { int num; printf("Enter no. : "); scanf("%d",&num); printf("\nMultiplication of Natural No. : %d",mult(num)); getch(); } <file_sep>/Practise/Array_print_reverse.cpp #include<iostream> #include<array> using namespace std; int main() { int n,i=0,sum=0; cout<<"Enter size : "; cin>>n; int *arr = new int[n]; for(i=0;i<n;i++) { cout<<"\nEnter element : "; cin>>arr[i]; } cout<<"Array Elements : "; for(i=n-1;i>=0;i--) { cout<<arr[i]<<" "; sum += arr[i]; } cout<<"\nSum : "<<sum; return 0; }<file_sep>/Practise/Array_unique_elements.cpp #include<iostream> using namespace std; int main() { int n,i=0,count=0; cout<<"Enter array size : "; cin>>n; int *arr = new int[n]; for(i=0;i<n;i++) { cout<<"\nEnter element : "; cin>>arr[i]; } cout<<"First Array Elements : "; for(i=0;i<n;i++) { cout<<arr[i]<<" "; } int *a2 = new int[n]; for(i=0;i<n;i++) { a2[i] = arr[i]; } for(i=0;i<n;i++) { int ele = arr[i]; int flag = 0; for(int j=i+1; j<n;j++) { if(ele == a2[j]) { flag = 1; a2[j] = 0; } } if(flag == 1) { count++; } else { cout<<"\nU : "<<ele; } } cout<<"\nDuplicate elements : "<<count; cout<<"\nUnique Elements : "; for(i=0;i<n;i++) { if(a2[i] != 0) cout<<a2[i]<<" "; } return 0; }<file_sep>/LB DS/Rotate_Array.cpp #include <iostream> using namespace std; int main() { //code int T,N,D; cin>>T; while(T--) { cin>>N>>D; int *A = new int[N]; int *C = new int[N]; for(int i=0;i<N;i++) { cin>>A[i]; } int cc = 0; for(int j=D; j<N;j++) { C[cc] = A[j]; cout<<C[cc]; cc++; } for(int j=0;j<D;j++) { C[cc] = A[j]; cout<<C[cc]; cc++; } cout<<endl; } return 0; } <file_sep>/LB DS/6. Union OF Array.cpp #include<iostream> using namespace std; void doUnion(int arr1[], int n, int arr2[], int m) { int uc = 0; int i=0, j=0; while(i<m && j<n) { if(arr1[i] < arr2[j]) { cout<<arr1[i++]<<" "; uc++; } else if(arr1[i] > arr2[j]) { cout<<arr2[j++]<<" "; uc++; } else { cout<<arr2[j++]<<" "; uc++; } } //Printing remaining elements of large array while(i< m) { cout<<arr1[i++]<<" "; uc++; } while(j<n) { cout<<arr2[j++]<<" "; } cout<<"|||||| "<<uc; } int main() { int arr1[] = {1,2,4,5,6}; int arr2[] = {2,3,5,7}; int m = sizeof(arr1)/sizeof(arr1[0]); int n = sizeof(arr2)/sizeof(arr2[0]); cout<<"Union Elements : "; doUnion(arr1,n,arr2,m); cout<<"<-No. Of Union Elements : "; return 0; } <file_sep>/DS/QUEUE/circular_queue_using_array.c #include<stdio.h> #include<stdlib.h> #define N 10 int queue[N]; int front = -1; int rear = -1; void enqueue() { if(front == -1 && rear == -1) { front = rear = 0; printf("\nEnter data : "); scanf("%d",&queue[rear]); } else if((rear+1)%N == front) { printf("\nQueue Is Full"); } else { rear = (rear+1)%N; rear++; printf("\nEnter data : "); scanf("%d",&queue[rear]); } printf("\nEnqueued Succesfully"); } void dequeue() { if(front == -1 && rear == -1) { printf("\nEmpty Queue"); } else if(front == rear) { printf("\n%d Dequeued Succesfully",queue[front]); front = rear = -1; } else { printf("\n%d Dequeued Succesfully",queue[front]); front = (front+1)%N; } } void display() { int i = front; if(front == -1 && rear == -1) { printf("\nEmpty Queue"); } else { printf("\nDisplay of Queue : "); while(i != rear) { printf("%d ",queue[i]); i = (i+1)%N; } } } void peek() { if(front == -1 && rear == -1) { printf("EMpty QUeue"); } else { printf("\nFront Data : ",queue[front]); } } void main() { int choice; while(1) { printf("\nOperations :\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display\n5. Exit"); printf("\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid"); } } } <file_sep>/DS/TREE/binary_search_tree.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *left; struct mode *right; }; struct node *tree = NULL,*temp; void create() { struct node *newnode; int key,x; do { newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter Data : "); scanf("%d",&newnode->data); key = newnode->data; newnode->left = NULL; newnode->right = NULL; if(tree == NULL) { tree = newnode; } else { temp = tree; while(key != temp->data) { if(key < temp->data) { if(temp->left == NULL) { temp->left = newnode; } else { temp = temp->left; } } else if(key > temp->data) { if(temp->right == NULL) { temp->right = newnode; } else { temp = temp->right; } } } } printf("\nDo you want to continue entering data (1. Yes/ 2.NO): "); scanf("%d",&x); } while(x != 2); } void search() { int key; temp = tree; printf("\nEnter data to search : "); scanf("%d",&key); if(searchcode(tree,key)) { printf("%d Found.",key); } else { printf("%d not found.",key); } /* while(temp != NULL && temp->data != key) { if(key < temp->data) { temp = temp->left; } else { temp = temp->right; } if(temp == NULL) { printf("\n%d Not Found.",key); } else { printf("\n%d Found.",key); } }*/ return; } void searchcode(struct node *tree,int key) { if(tree == NULL || tree->data == key) { return tree; } if(tree->data < key) { return searchcode(tree->right,key); } return searchcode(tree->left,key); } void inorder(struct node *temp) { if(temp == NULL) { return; } else { inorder(temp->left); printf("%d ",temp->data); inorder(temp->right); } } void preorder(struct node *temp) { if(temp == NULL) { return; } else { printf("%d ",temp->data); preorder(temp->left); preorder(temp->right); } } void postorder(struct node *temp) { if(temp == NULL) { return; } else { postorder(temp->left); postorder(temp->right); printf("%d ",temp->data); } } void main() { int choice; while(1) { printf("\n\n1. Create\n2. Search\n3. Inorder\n4. Preorder\n5. Postorder\n6. Exit\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("\nCreation : "); create(); break; case 2: printf("\nSearch Operation : "); search(); break; case 3: printf("\nInorder : "); inorder(tree); break; case 4: printf("\nPreorder : "); preorder(tree); break; case 5: printf("\nPostorder : "); postorder(tree); break; case 6: exit(0); default: printf("Invalid\n"); } } } <file_sep>/Practise/AreaOfShapes.c #include<stdio.h> #include<math.h> #include<stdlib.h> int main() { double r,l,b,h; int choice; printf("Shapes : \n1. Circle \n2. Rectangle\n3. Square\nEnter your choice(1/2/3) : "); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter Radius : "); scanf("%lf",&r); printf("\nArea of circle : %lf",3.14*r*r); break; case 2: printf("\nEnter Length : "); scanf("%lf",&l); printf("\nEnter Breadth : "); scanf("%lf",&b); printf("\nEnter Height : "); scanf("%lf",&h); printf("\nArea Of Rectangle : %lf",l*b*h); break; case 3: printf("\nEnter Side of Sqaure : "); scanf("%lf",&l); printf("\nArea Of Square : %lf",l*l); break; } return 0; } <file_sep>/HACKERRANK/hackerrank_singlearray.c // int *arr = (int *)malloc(n * sizeof(int)) #include<stdio.h> #include<conio.h> int main() { int n,i,*arr,sum = 0; scanf("%d",&n); arr = (int*)malloc(n * sizeof(int)); for(i = 0; i < n;i++) scanf("%d",arr + i); for(i=0;i<n;i++) sum += *(arr + i); printf("\nSum : %d",sum); free(arr); return 0; } <file_sep>/HACKERRANK/hackerrank_sum_of_digits.c #include<stdio.h> #include<conio.h> int main() { int n,sum = 0,d; scanf("%d",&n); while(n>0) { d = n%10; n /= 10; sum += d; } printf("\n%d",sum); return 0; } <file_sep>/DS/LINKED LIST/printingtokens.c #include<stdio.h> int main() { char *s; s = malloc(1024 * sizeof(char)); scanf("%[^\n]",s); s = realloc(s,strlen(s)+1); } <file_sep>/HACKERRANK/hackerrank_conditional_statements_in_c.c #include<stdio.h> #include<conio.h> void main() { int n; scanf("%d",&n); if (n >= 1 && n <= 9) { if(n == 1) { printf("\none"); } else if(n == 2) { printf("\ntwo"); } else if(n == 3) { printf("\nthree"); } else if(n == 4) { printf("\nfour"); } else if(n == 5) { printf("\nfive"); } else if(n == 6) { printf("\nsix"); } else if(n == 7) { printf("\nseven"); } else if(n == 8) { printf("\neight"); } else if(n == 9) { printf("\nnine"); } } else if(n > 9) { printf("\nGreater than 9"); } } <file_sep>/DS/ARRAY/insertion_1.c #include<stdio.h> #include<stdlib.h> void main() { int size,pos,data,i; printf("Enter Size : "); scanf("%d",&size); int a[size]; printf("ENter array elements : "); for(int t=0;t<size;t++) { scanf("%d",&a[t]); } printf("Display of array elements : "); for(int t=0;t<size;t++) { printf("%d ",a[t]); } printf("\nEnter position of element : "); scanf("%d",&pos); printf("\nEnter data to enter : "); scanf("%d",&data); for(int t=size-1;t>=pos-1;t--) { a[t+1] = a[t]; } a[pos-1] = data; size++; /* pos 0 1 2 */ printf("Display of array elements : "); for(int t=0;t<size;t++) { printf("%d ",a[t]); } printf("\nInsert at beginning : "); printf("Enter data to enter : "); scanf("%d",&data); for(i=size-1;i>=0;i--) { a[i+1] = a[i]; } a[0] = data; size++; printf("Display of array elements : "); for(int t=0;t<size;t++) { printf("%d ",a[t]); } printf("\nInsert at End : "); printf("Enter data to enter : "); scanf("%d",&data); a[size] = data; size++; printf("Display of array elements : "); for(int t=0;t<size;t++) { printf("%d ",a[t]); } } <file_sep>/HACKERRANK/hackerrank_printing_pattern.c /* Print a pattern of numbers from to as shown below. Each of the numbers is separated by a single space. 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Input Format The input will contain a single integer . Constraints Sample Input 0 2 Sample Output 0 2 2 2 2 1 2 2 2 2 Sample Input 1 5 Sample Output 1 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 5 5 4 3 3 3 3 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 2 1 2 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 3 3 3 3 4 5 5 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 Sample Input 2 7 Sample Output 2 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 6 7 7 6 5 5 5 5 5 5 5 5 5 6 7 7 6 5 4 4 4 4 4 4 4 5 6 7 7 6 5 4 3 3 3 3 3 4 5 6 7 7 6 5 4 3 2 2 2 3 4 5 6 7 7 6 5 4 3 2 1 2 3 4 5 6 7 7 6 5 4 3 2 2 2 3 4 5 6 7 7 6 5 4 3 3 3 3 3 4 5 6 7 7 6 5 4 4 4 4 4 4 4 5 6 7 7 6 5 5 5 5 5 5 5 5 5 6 7 7 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n; scanf("%d", &n); // Complete the code to print the pattern. int len = n*2 - 1; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ int min = i < j ? i : j; min = min < len-i ? min : len-i-1; min = min < len-j-1 ? min : len-j-1; printf("%d ", n-min); } printf("\n"); } return 0; } <file_sep>/DS/ARRAY/unique_elements.c #include<stdio.h> #include<stdlib.h> void main() { int size,i,j,count=0,k=0; printf("Enter Size : "); scanf("%d",&size); int a[size]; printf("\nEnter array elements : "); for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("\nDisplay of array elements : "); for(i=0;i<size;i++) { printf("%d ",a[i]); } int b[size]; printf("\nDisplay of Unique array elements : "); for(i=0;i<size;i++) { count = 0; for(j=0,k=size;j<k+1;j++) { if(i != j) { if(a[i] == a[j]) { count++; } } } if(count == 0) { printf("%d ",a[i]); } } } <file_sep>/DS/LINKED LIST/copy_linked_list.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; void create(); void insertatend(); void copy(); void display(); struct node *head = 0,*head2 = 0, *temp, *temp2; void main() { int choice; while(1) { printf("\nOPERATIONS :\n1. CREATE LL\n2. INSERT AT END\n3. COPY INTO ANOTHER\n4. DISPLAY\n5. EXIT\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: insertatend(); break; case 3: copy(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid INput"); } } getch(); } void create() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data"); scanf("%d",&newnode->data); if(head == 0) { newnode->next = 0; head = newnode; temp = newnode; } else { temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; newnode->next = 0; } printf("Created Succesfully."); } void insertatend() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; temp->next = newnode; temp = newnode; /* temp = head; while(temp->next != 0) { temp = temp->next; } temp->next = newnode; */ printf("Inserted Succesfully."); } void display() { int c; printf("\nEnter 1 to print original linked list, 2 to print copied linked list : "); scanf("%d",&c); if(c == 1) { printf("\nOriginal Linked List :"); temp = head; while(temp != 0) { printf("%d\t",temp->data); temp = temp->next; } } else if(c == 2) { printf("\nCopied Linked List :\n"); temp2 = head2; while(temp2 != 0) { printf("%d\t",temp2->data); temp2 = temp2->next; } } } void copy() { struct node *newnode; if(head == 0) printf("\nCannot copy, EMPTY LINKED LIST"); else { temp = head; while(temp != 0) { newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = temp->data; if(head2 == 0) { head2 = newnode; temp2 = newnode; newnode->next = 0; } else { temp2 = head2; while(temp2->next != 0) { temp2 = temp2->next; } temp2->next = newnode; newnode->next = 0; } temp = temp->next; } } } <file_sep>/DS/LINKED LIST/circular_linked_list.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head = 0, *temp; void create() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; head->next = newnode; } else { temp = head; while(temp->next != head) { temp = temp->next; } temp->next = newnode; } newnode->next = head; printf("\nCreated Succesfully!"); } void display() { if(head == 0) { printf("\nLinked List is EMPTY"); } else { printf("\nLinked List : "); temp = head; printf("%d ",temp->data); temp = temp->next; while(temp != head) { printf("%d ",temp->data); temp = temp->next; } } } void insert() { int choice; printf("\n1. Insert at beginning\n2. INsert at end\nInsert at location\nEnter choice : "); scanf("%d",&choice); switch(choice) { case 1: insertatbeg(); break; case 2: insertatend(); break; case 3: insertatloc(); break; default: printf("\nInvalid"); } } void insertatbeg() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("Enter data : "); scanf("%d",&newnode->data); newnode->next = 0; if(head == 0) { head = newnode; temp = newnode; newnode->next = head; } else { temp = head; while(temp->next != head) { temp = temp->next; } newnode->next = head; head = newnode; temp->next = head; } printf("\nInserted Succesfully at the beginning."); } void insertatend() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter Data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; newnode->next = head; } else { temp = head; while(temp->next != head) { temp = temp->next; } temp->next = newnode; newnode->next = head; } printf("\nInserted Succesfully at end."); } void insertatloc() { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter Data : "); scanf("%d",&newnode->data); if(head == 0) { head = newnode; newnode->next = head; } else { int loc; printf("Enter location : ); scanf("%d",&loc); temp = head; int count = 1; while(temp->next != head && count<loc-1) { temp = temp->next; count++; } struct node *new; new = temp->next; temp->next = newnode; newnode->next = new; } printf("\nInserted Succesfully at location"); } void main() { int choice; while(1) { printf("\n\nOPERATIONS : "); printf("\n1. Create\n2. Display\n3. Exit\n4. Insert"); printf("\nEnter Choice : "); scanf("%d",&choice); switch(choice) { case 1: create(); break; case 2: display(); break; case 3: exit(0); case 4: insert(); break; default: printf("\nInvalid, Try again"); continue; } } } <file_sep>/DS/QUEUE/queue_implementation_using_linked_list.c #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *front = 0,*rear=0; void enqueue() { if(front == 0 && rear == 0) { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; front = rear = newnode; } else { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter data : "); scanf("%d",&newnode->data); newnode->next = 0; rear->next = newnode; rear = newnode; } printf("\nEnqueued Succesfully"); } void dequeue() { if(front == 0 && rear == 0) { printf("\nEmpty QUeue"); } else { struct node *temp; temp = front; printf("\n%d Dequeued Succesfully",front->data); front = front->next; free(temp); } } void display() { if(front == 0 && rear == 0) { printf("\nEmpty Queue"); } else { struct node *temp; printf("\nQueue : "); temp = front; while(temp != 0) { printf("%d ",temp->data); temp = temp->next; } } } void peek() { if(front == 0 && rear == 0) { printf("\nEMpty Queue"); } else { printf("Front Data : %d",front->data); } } void main() { int choice; while(1) { printf("\n\nOperations :\n1. Enqueue\n2. Dequeue\n3. Peek/Front\n4. Display\n5. Exit\nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); default: printf("\nInvalid Choice"); } } getch(); } <file_sep>/LB DS/4.Sort_0,1,,2.cpp #include <iostream> using namespace std; void sort012(int a[], int arr_size) { int lo = 0, mid = 0, hi = arr_size-1; while(mid <= hi) { switch(a[mid]) { case 0: swap(a[lo++],a[mid++]); break; case 1: mid++; break; case 2: swap(a[mid],a[hi--]); break; } } } void printArray(int arr[], int arr_size) { for(int i=0;i<arr_size;i++) { cout<<arr[i]<<" "; } cout<<endl; } int main() { //code int T,N,D; cin>>T; while(T--) { cin>>N>>D; int *A = new int[N]; for(int i=0;i<N;i++) { cin>>A[i]; } sort012(A,N); printArray(A,N); } return 0; } <file_sep>/DS/LINKED LIST/B5_dll.c #include<stdio.h> #include<stdlib.h> struct node { struct node *prev; struct node *next; int data; }; struct node *head; void insert(); void insertion_beginning(); void insertion_last(); void insertion_specified(); void delete(); void deletion_beginning(); void deletion_last(); void deletion_specified(); void display(); void search(); void main () { int choice =0; while(choice != 9) { printf("\nOPERATIONS : \n"); printf("\n 1.Insert \n"); printf("\n 2.Delete \n"); printf("\n 3.Search \n"); printf("\n 4.Display \n"); printf("\n 5.Exit \n"); printf("\n--------------------------------------\n"); printf("Enter your choice-> "); scanf("%d",&choice); switch(choice) { case 1: insert(); break; case 2: delete(); break; case 3: search(); break; case 4: display(); break; case 5: exit(0); break; default: printf("Please enter valid choice\n"); } } } void insert() { int choice; do { printf("\n--------------------------------------\n"); printf("\n 1.Insert at the beginning: "); printf("\n 2.Insert at specified position: "); printf("\n 3.Insert at the end: "); printf("\n 4.Exit from insert: "); printf("\n--------------------------------------\n"); printf("\nEnter Your Choice-> "); scanf("%d", &choice); printf("\n--------------------------------------\n"); switch(choice) { case 1: insertion_beginning(); break; case 2: insertion_specified(); break; case 3: insertion_last(); break; case 4: break; default: printf("Wrong Choice"); } } while(choice!=4); } void delete() { int choice; do { printf("\n--------------------------------------\n"); printf("\n 1.Delete at the beginning: "); printf("\n 2.Delete at specified position: "); printf("\n 3.Delete at the end: "); printf("\n 4.Exit from insert: "); printf("\n--------------------------------------\n"); printf("\nEnter Your Choice-> "); scanf("%d", &choice); printf("\n--------------------------------------\n"); switch(choice) { case 1: deletion_beginning(); break; case 2: deletion_specified(); break; case 3: deletion_last(); break; case 4: break; default: printf("Wrong Choice"); } } while(choice!=4); } void insertion_beginning() { struct node *ptr; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter Item value->"); scanf("%d",&item); if(head==NULL) { ptr->next = NULL; ptr->prev=NULL; ptr->data=item; head=ptr; } else { ptr->data=item; ptr->prev=NULL; ptr->next = head; head->prev=ptr; head=ptr; } printf("\nNode inserted successfully\n"); } } void insertion_last() { struct node *ptr,*temp; int item; ptr = (struct node *) malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter Item value->"); scanf("%d",&item); ptr->data=item; if(head == NULL) { ptr->next = NULL; ptr->prev = NULL; head = ptr; } else { temp = head; while(temp->next!=NULL) { temp = temp->next; } temp->next = ptr; ptr ->prev=temp; ptr->next = NULL; } } printf("\nNode inserted successfully\n"); } void insertion_specified() { struct node *ptr,*temp; int item,loc,i; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\n OVERFLOW"); } else { temp=head; printf("Enter the location"); scanf("%d",&loc); for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("\n There are less than %d elements", loc); return; } } printf("Enter value"); scanf("%d",&item); ptr->data = item; ptr->next = temp->next; ptr -> prev = temp; temp->next = ptr; temp->next->prev=ptr; printf("\nNode inserted successfully\n"); } } void deletion_beginning() { struct node *ptr; if(head == NULL) { printf("\n UNDERFLOW"); } else if(head->next == NULL) { head = NULL; free(head); printf("\nNode deleted\n"); } else { ptr = head; head = head -> next; head -> prev = NULL; free(ptr); printf("\nNode deleted\n"); } } void deletion_last() { struct node *ptr; if(head == NULL) { printf("\n UNDERFLOW"); } else if(head->next == NULL) { head = NULL; free(head); printf("\nNode deleted\n"); } else { ptr = head; if(ptr->next != NULL) { ptr = ptr -> next; } ptr -> prev -> next = NULL; free(ptr); printf("\nNode deleted\n"); } } void deletion_specified() { struct node *ptr, *temp; int val; printf("\n Enter the data after which the node is to be deleted : "); scanf("%d", &val); ptr = head; while(ptr -> data != val) ptr = ptr -> next; if(ptr -> next == NULL) { printf("\nCan't delete\n"); } else if(ptr -> next -> next == NULL) { ptr ->next = NULL; } else { temp = ptr -> next; ptr -> next = temp -> next; temp -> next -> prev = ptr; free(temp); printf("\nNode deleted\n"); } } void display() { struct node *ptr; printf("\n Elements present in the list are...\n"); ptr = head; while(ptr != NULL) { printf("%d\n",ptr->data); ptr=ptr->next; } } void search() { struct node *ptr; int item,i=0,flag; ptr = head; if(ptr == NULL) { printf("\nEmpty List\n"); } else { printf("\nEnter item which you want to search?\n"); scanf("%d",&item); while (ptr!=NULL) { if(ptr->data == item) { printf("\nItem found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; ptr = ptr -> next; } if(flag==1) { printf("\nItem not found\n"); } } }
34f404b882001eb8f5e5660eb6162b702454e17e
[ "C", "C++" ]
66
C
onkcharkupalli1051/c-programming
29aedc781f268b22cd2f30df72e8873063ff98cb
b811dcf6e3ccd9748410ea0d5fb7f3759137fd4a
refs/heads/master
<file_sep>import React, { Component } from 'react'; import axios from 'axios'; import AuthFunctions from '../../../AuthFunctions'; import { Redirect } from 'react-router-dom'; import './RegisterForm.css'; class RegisterForm extends Component { constructor() { super(); this.state = { name: '', email: '', password: '', password2: '', errorList: '', user: '', }; this.Auth = new AuthFunctions(); this.onChange = this.onChange.bind(this); this.register = this.register.bind(this); } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } register(e) { e.preventDefault(); const newUser = { name: this.state.name, email: this.state.email, password: <PASSWORD>, password2: <PASSWORD> }; console.log(newUser) axios.post('http://localhost:5000/api/users/register', newUser) .then((res)=>{ axios.post('http://localhost:5000/api/users/login', { email: res.data.email, password: <PASSWORD> }).then((res)=>{ this.Auth.clearToken(); let token = res.data.token.replace(/Bearer/g, '').trim(); this.Auth.setToken(token, ()=>{ this.setState({ token: token }) }); this.Auth.setUser(res.data.user, ()=> { this.setState({ user: res.data.user }) }); }) }) .catch(errors => this.showErrors(errors) ); } showErrors = (errors) => { var tmpErrList = []; var errArr = errors.response.data; for (var key in errArr) { if (errArr.hasOwnProperty(key)) { tmpErrList.push(errArr[key]); } } this.setState({ errorList: tmpErrList }); } render() { const { name, email, password, <PASSWORD> } = this.state; if(this.Auth.loggedIn()){ if (this.state.user) return <Redirect to='/Hub' user={this.Auth.getUser()}/> } return ( <div className="container"> <h1>Sign Up</h1> {/* <form onSubmit={this.register}> */} <div className="formItem"> <input type="text" className="formControl" placeholder="username" name="name" value={name} onChange={this.onChange} required /> </div> <div className="formItem"> <input type="email" className="formControl" placeholder="email" name="email" value={email} onChange={this.onChange} required /> </div> <div className="formItem"> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="password" value={<PASSWORD>} onChange={this.onChange} required /> </div> <div className="formItem"> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>2" value={<PASSWORD>} onChange={this.onChange} required /> </div> <div className="errorsList"> { this.state.errorList ? <ul> {this.state.errorList.map((item, i) => { return (<li key={i} className="errorItem">{item}</li>); })} </ul> : "" } </div> <input onClick={this.register} type="submit" className="loginBtn" /> {/* </form> */} </div> ); } } export default RegisterForm; <file_sep>import React, { Component } from "react" import './Contact.scss' import axios from 'axios' import AOS from 'aos' import 'aos/dist/aos.css' import LinearProgress from '@material-ui/core/LinearProgress'; class Contact extends Component { constructor() { super() this.state = { firstname: '', email: '', message: '', buttonState: false, sending: false } } componentDidMount(){ AOS.init({ duration : 500 }) } async handleSubmit(e) { this.setState({ sending: true }) document.getElementById("theForm").reset(); e.preventDefault() const { firstname, email, message} = this.state axios.post('http://localhost:5000/api/mailto', { name:firstname, email:email, message:message }).then(res => { console.log(res, this.state.buttonState) this.setState({ buttonState: true, sending: false }) }); } handleChange = e => { this.setState({ [e.target.name]: e.target.value }) } render() { const buttonSpot = this.state.buttonState ? (<div id='formSubmitText'> Thank you for filling out the form.< br /> Your information has been successfully sent!</div>) : (<button className='contactBtnHome'>Submit</button>) return ( <div className="lp2_contactContainer"> <div className="contactContent"> <div className="contactHeader"> <p data-aos="fade-down">Got a question?</p> <p>I'd love to hear from you. Contact me about projects or just to chat<br/>and I'll get back to you as soon as&nbsp;possible</p> </div> <form id="theForm" className="contactForm" onSubmit={this.handleSubmit.bind(this)}> <div className="input-container"> <i className="icon icon1"></i> <input id="firstname" type="text" name="firstname" placeholder="<NAME>" required onChange={this.handleChange.bind(this)} /> </div> <div className="input-container"> <i className="icon icon2"></i> <input id="email" type="email" name="email" placeholder="Your email" required onChange={this.handleChange.bind(this)} /> </div> <div className="input-container"> <i className="icon icon3"></i> <textarea id="message" type="textarea" name="message" placeholder="Your Message" required onChange={this.handleChange.bind(this)} /> </div> <div className="submitContainer"> {this.state.sending ? <LinearProgress /> : buttonSpot } </div> </form> </div> </div> ); } } export default Contact;<file_sep>import React, { Component } from "react"; import './Login.css'; import RegisterForm from './RegisterForm/RegisterForm'; import LoginForm from './LoginForm/LoginForm'; class Login extends Component { constructor() { super(); this.state = { tabState: '1', }; } changeTab = (tab) => { this.setState({ tabState: tab }); } render() { return ( <div className="loginContainer"> <div className="loginMiddle"> <div className="loginContent"> {/* <h2><img src={bannerAlpha} alt="logo" /></h2> */} { this.state.tabState === "1" ? <div><LoginForm /></div> : <div><RegisterForm/></div> } </div> <div id="tabContainer" className="tabContainer"> <div className={this.state.tabState==="1" ? "tab-item active" : "tab-item"} onClick={() => this.changeTab("1")}>Sign In</div> <div className={this.state.tabState==="2" ? "tab-item active" : "tab-item"} onClick={() => this.changeTab("2")}>Sign Up</div> </div> </div> </div> ); } } export default Login; <file_sep>import React from 'react'; import './Hub.scss'; import AuthFunctions from '../../AuthFunctions'; import { Redirect } from 'react-router-dom'; //import axios from 'axios'; import NavBar from '../NavBar/NavBar'; class Hub extends React.Component{ constructor(){ super(); this.state={ logout: false, searchTerm: '', } this.Auth = new AuthFunctions(); } componentDidMount = () => { } isSearched = searchTerm => item => item.make.toLowerCase().includes(searchTerm.toLowerCase()); onSearchChange = (event) => { console.log(event.target.value) this.setState({ searchTerm: event.target.value }); } render(){ //console.log("HUBS PROPS: ", this.props) if(this.state.logout){ return <Redirect to='/login'/> } var listItem = "empty"; return ( <React.Fragment> <NavBar /> <div className='mainContainer'> <div className="userInfo"> <div className="userInfo_name">Name: {this.props.user.name}</div> <div className="userInfo_email">Email:{this.props.user.email}</div> </div> <form className='searcher'> <input placeholder="Search . . ." type='text' value={this.state.searchTerm} onChange={this.onSearchChange} /> </form> {listItem === "notEmpty" ? "" : <div className="loadingContainer"><div className="loadContainer"><div className="load-shadow"></div><div className="load-box"></div></div></div>} </div> </React.Fragment> ); } }; export default Hub; <file_sep> /* ******************************************** MAIL TO */ const express = require('express'); const router = express.Router(); const nodemailer = require('nodemailer'); router.get('/', function(req, res, next) { res.json({status:"success", message:"Parcel Pending API", data:{"version_number":"v1.0.0"}}) }); router.post("/", (req, res) => { //console.log(req.body); nodemailer.createTestAccount((err, account) => { const htmlEmail = ` <h3>CONTACT INFO</h3> <ul> <li>First name: ${req.body.firstname}</li> <li>Last name: ${req.body.lastname}</li> <li>Email: ${req.body.email}</li> <li>Phone number: ${req.body.pnumber}</li> </ul> <br> <p>${req.body.message}</p> ` let transporter = nodemailer.createTransport({ //service: 'gmail', host: 'smtp.gmail.com', port: 587, secure: false, requireTLS: true, auth: { user: '<EMAIL>', pass: '<PASSWORD>!' } }); let mailOptions = { from: '"<EMAIL>', // sender address to: '<EMAIL>', // list of receivers replyTo: '<EMAIL>', subject: 'Hello ✔', // Subject line text: req.body.message, // plain text body html: htmlEmail // html body }; transporter.sendMail(mailOptions, (err, info) => { if (err) { return console.log(err); } console.log('Message sent: %s', info.messageId); res.json({success : "Updated Successfully", status : 200}); }); }) }) module.exports = router; /* ******************************************** MAIL TO */<file_sep>import React, { Component } from "react"; import './About.scss'; class About extends Component { render() { return ( <div className="lp2_aboutContainer"> <div className="aboutContent"> <p>about</p> </div> </div> ); } } export default About;<file_sep>import React, { Component } from "react"; import './App.scss'; import { Route, BrowserRouter } from "react-router-dom"; import Landing from './layout/pages/Landing/Landing'; import Login from './Admin/Login/Login'; import Hub from './Admin/Hub/Hub'; import PrivateRoute from './PrivateRoute'; import AuthFunctions from './AuthFunctions'; import LandingRouter from './layout/LandingRouter' class App extends Component { constructor() { super(); this.state = { user: '', token: '', }; this.Auth = new AuthFunctions(); } componentDidMount = () => { this.setState({ user: this.Auth.getUser() || "", token: this.Auth.getToken() || "" }); } render() { return ( <BrowserRouter> <React.Fragment> <PrivateRoute exact path="/hub" component={Hub} user={this.state.user} token={this.state.token}/> {/* <PrivateRoute exact path="/newPage" component={newPage} user={this.state.user} token={this.state.token}/> */} <Route exact path="/" component={Landing} /> <Route exact path='/login' render={ () => (<Login />) } /> <Route exact path="/landing/games" component={LandingRouter} /> <Route exact path="/landing/projects" component={LandingRouter} /> <Route exact path="/landing/about" component={LandingRouter} /> <Route exact path="/landing/contact" component={LandingRouter} /> </React.Fragment> </BrowserRouter> ); } } export default App; <file_sep>export default class AuthService { // Initializing important variables loggedIn() { // Checks if there is a saved token and it's still valid const token = this.getToken() // Getting token from localstorage return !!token;// handwaiving here } setToken(token, callback) { localStorage.setItem('token', token); callback && callback(); } getToken() { return localStorage.getItem('token') } setUser(user, callback) { localStorage.setItem('user', JSON.stringify(user)); callback && callback(); } getUser() { return JSON.parse(localStorage.getItem('user')); } clearToken() { localStorage.clear(); } logout() { // Clear user token and profile data from localStorage localStorage.removeItem('token'); localStorage.removeItem('user'); } } <file_sep>import React, { Component } from 'react' import { NavLink, withRouter } from 'react-router-dom' import './NavBar.scss' class NavBar extends Component { render() { return ( <div className="lp2_navBar"> <div className="navBar"> <div className="topNavContainer"> <NavLink to="/" className="navItem"><img src={ require('../../files/images/logoLW.png') } /></NavLink> <NavLink to="/landing/games" className="navItem">Games</NavLink> <NavLink to="/landing/projects" className="navItem">Projects</NavLink> <NavLink to="/landing/about" className="navItem">About</NavLink> <NavLink to="/landing/contact" className="navItem">Contact</NavLink> </div> </div> </div> ) } } export default withRouter((NavBar));<file_sep>import React, { Component } from 'react'; import axios from 'axios'; import AuthFunctions from '../../../AuthFunctions'; import { Redirect } from 'react-router-dom'; import './LoginForm.css'; class LoginForm extends Component { constructor() { super(); this.state = { user: '', email: '', password: '', }; this.Auth = new AuthFunctions(); } handleChange = (event) => { const target = event.target; const value = target.type==='checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } login = () => { axios.post('http://localhost:5000/api/users/login', { email: this.state.email, password: <PASSWORD> }) .then((res)=>{ let token = res.data.token.replace(/Bearer/g, '').trim(); this.Auth.setToken(token, ()=>{ this.setState({ token: token }) }); this.Auth.setUser(res.data.user, () => { this.setState({ user: res.data.user }) }) }) }; render() { const { email, password } = this.state; if (this.state.user) { if(this.Auth.loggedIn()) return <Redirect to='/Hub' user={this.Auth.getUser()}/> } return ( <React.Fragment> {/* <form onSubmit={this.login}> */} <h1 className="">Sign In</h1> <div className="formItem"> <input className="formControl" placeholder="email" name='email' type='text' onChange={this.handleChange} value={email} required /> </div> <div className="formItem"> <input className="formControl" placeholder="<PASSWORD>" name='password' type='password' onChange={this.handleChange} value={password} required /> </div> <input onClick={this.login} type="submit" value="Login" className="loginBtn" /> {/* </form> */} </React.Fragment> ); } } export default LoginForm; <file_sep>import React, { Component } from "react" import './Landing.css' import { Link } from "react-router-dom" class Landing extends Component { render() { return ( <div className="lp2_HomePage"> <div className="HomePage"> <div className="heroAnimation"> <div id="heroLayer0" className="heroLayer"></div> <div id="heroLayer1" className="heroLayer"></div> <div id="heroLayer2" className="heroLayer"></div> <div id="heroLayer3" className="heroLayer"></div> </div> <div className="heroContent"> <div className="flex"> <div className="hiText">Hi, i'm <NAME>.</div> </div> <div className="flex"> <p className="heroP paddingTop">An app connecting employers to me.</p> </div> <div className="flex"> <p className="heroP paddingBottom">Lets get to know each&nbsp;other...</p> </div> <div className="flex"> <Link to="/login"><div className="selectBtnContainer">Login</div></Link> <Link to="/landing/about"><div className="selectBtnContainer">Skip...</div></Link> </div> </div> </div> </div> ); } } export default Landing;
f09bd1981a5ca85062095e137f3840cc55fb0336
[ "JavaScript" ]
11
JavaScript
mikeint/profile_template_full_stack
9073ed6d5402b4a0cc1c70972dfc1add27f255da
5f2659fa7513f3a5462fb5213545867c3f66027a
refs/heads/master
<file_sep>#immport-galaxy tools <file_sep>#!/usr/bin/env python from __future__ import print_function import sys import os import pandas as pd from argparse import ArgumentParser def compare_file(file_un, file_dx): df1 = pd.read_table(file_un) df2 = pd.read_table(file_dx) if df1.equals(df2): print("yay") else: print("ohno") return def compare_text(file1, file2): with open(file1, "r") as un, open(file2, "r") as dx: i = 0 for line in un: ln = dx.readline() if not line == ln: print ("ohno") i += 1 with open("compare_report.txt", "a") as rt: rt.write(file1 + "\n" + line + "\n" + file2 + "\n" + ln + "\n\n") if i==10: sys.exit(2) if i == 0: print ("yay") return if __name__ == "__main__": parser = ArgumentParser( prog="CompareFile", description="compares 2 files") parser.add_argument( '-u', dest="input1", required=True, help="File location for the first file.") parser.add_argument( '-d', dest="input2", required=True, help="File location for the second file.") parser.add_argument( '-t', dest="as_text", help="compare files as text files") args = parser.parse_args() if args.as_text: compare_text(args.input1, args.input2) else: compare_file(args.input1, args.input2) sys.exit(0)
47b2d418fdf835d7d0d94dc012f76cdeba5f3949
[ "Markdown", "Python" ]
2
Markdown
cristhomas/immport-galaxy-tools
2434fd65e60f7f7967f289cbce7107ebbb49c4fc
5e8992c70b28a833daf68d3a9864700329f68a56
refs/heads/master
<file_sep>"use strict"; /////creating universal variables///// const variableGroup = { ////Variables used by LoginScene//// characterButton: null, characterSelect: null, headArrow: null, headSelect: null, headSelectIcon: null, ////Variables used by the UI Scene//// menu: null, lookTab: null, itemsTab: null, spellsTab: null, mapTab: null, optionsTab: null, tabDisplay: null, numberButton: null, ////Variables used by the Game Scene//// playerObject: null, player: null, playerHead: null, playerBody: null, moveLeft: null, leftBody: null, leftHead: null, moveRight: null, rightBody: null, rightHead: null, standStill: null, player_id: null, cursors: null, cam1: null, cam2: null, go: null, controls: {}, playerCount: 1, playerCountText: null, ////Are these being used?//// //let blocked; collider: null, //Endpoints for communication - These look like different connections but sockets.io will share one ioSystem: null, ioGame: null, ioChat: null }; //Object with all UI related variables / functions let ui = { dragging: { element: null, //Element being dragged offsetX: 0, offsetY: 0, //Difference between mouse location and topleft of element startDragging: function (e) { let possibleElement = $(this).closest(".draggable"), offset; if (e.which !== 1 || typeof possibleElement === 'undefined' || ui.dragging.element !== null) return; e.preventDefault(); ui.dragging.element = possibleElement[0]; offset = possibleElement.offset(); //Offset of the element's topLeft corner ui.dragging.offsetX = e.clientX - offset.left; ui.dragging.offsetY = e.clientY - offset.top; $(document).mouseup(ui.dragging.stopDragging); $(document).mousemove(ui.dragging.movement); }, stopDragging: function (e) { $(document).off('mousemove', ui.dragging.movement); ui.dragging.element = null; }, movement: function (e) { ui.dragging.element.style.left = e.clientX - ui.dragging.offsetX + 'px'; ui.dragging.element.style.top = e.clientY - ui.dragging.offsetY + 'px'; } } }; ////having trouble putting these in the above variableGroup Constant//// let send_data = null; let debug = false; /////configuring game state///// const config = { type: Phaser.AUTO, width: 1921, height: 1041, physics: { default: 'arcade', arcade: { debug: true } }, scene: ////this lists all the scenes there are in the game to be referenced later//// ////only launches scenes that have "active" set to "true"//// [BootScene, LoginScene, GameScene, UiScene] }; const Game = new Phaser.Game(config); //Stuff in the jQuery $() function runs after everything else has loaded $(function(){ $('#ui .dragFrom').mousedown(ui.dragging.startDragging); $('#uiLogin_loginButton').click(function() { let username = $('#uiLogin_username').val(); if (typeof username !== 'string' || username === '') username = 'anon'; variableGroup.ioSystem.emit('login', {user:username}); Game.scene.start('LoginScene'); //TODO: Login - Error handling if server rejects such $('#uiLogin').hide(); }); });<file_sep>let remote_players = {}; let remote_playersBody = {}; let remote_playersHead = {}; let movement = {left: false, right: false, up: false, down: false}; //This is more intendedMovement, it may differ from actual velocities due to physics ////most of this does nothing at the moment, with the exception of the final "else" command//// ////setting player velocity to 0 here is important because it keeps non-local player's sprites ////from sliding all over the screen//// function update_movement(player, movement) { if (player) { animation = ''; //X Axis if (movement.left) { //player.setVelocityX(-160); animation = 'otherleft'; } else if (movement.right) { // player.setVelocityX(160); animation = 'otherright'; } else player.setVelocityX(0); //Y Axis if (movement.up) { //player.setVelocityY(-160); if (!animation) animation = 'otherright'; } else if (movement.down) { //player.setVelocityY(160); //if (!animation) animation = 'otherright'; } //else player.setVelocityY(0); player.anims.play(animation || 'standstill', true); } } ////called from index.js, tells server when players connect and disconnect//// function start_multiplayer() { variableGroup.ioGame = io(location.host + '/game'); ////I have no idea what this data_storage stuff is//// const data_storage = {connected: false}; variableGroup.ioGame.on("connected", (data) => { if (data_storage.connected) { location.reload(true); } else { console.log("connected", data); variableGroup.player_id = data.id; data_storage.connected = true; console.log("data.id variable = ", data.id); } console.log('data_storage variable = ', data_storage); }); ////when server says player has joined, log player id in console//// variableGroup.ioGame.on("joined", (data) => { console.log("joined", data); remote_players[data.id] = data; console.log(remote_players); }); ////if server say player left remove player id and destroy player info//// variableGroup.ioGame.on("left", (data) => { console.log("left", data); if (remote_players[data.id]) { remote_players[data.id].player.destroy(); delete remote_players[data.id]; } console.log('logged out: ', remote_players); update_hud(); }); variableGroup.ioGame.on("players", (data) => { remote_players = data; }); ////when server says player has moved, update position on other players screen?//// ////Honestly most of this is a mystery to me...//// variableGroup.ioGame.on("update_other", (data) => { if (variableGroup.go) { //console.log('variableGroup.go was called'); if (data.id !== variableGroup.player_id) { //console.log('data.id !== variableGroup.player_id'); if (!remote_players[data.id]) remote_players[data.id] = data; //console.log('!remote_players[data.id]) remote_players[data.id] = data'); if (remote_players[data.id].player) { //console.log('remote_players[data.id].player'); remote_players[data.id].movement = data.movement; if (data.movement) { //console.log('data.movement'); update_movement(remote_players[data.id].player, data.movement); } remote_players[data.id].player.setPosition(data.position.x, data.position.y); //console.log('data = ', data); ///////////////////////////////////////////////////////////////////////////////////////// ////THIS! This code right here! This causes the delay for remote players! This is what causes ////remote players to continue moving even after they've let go of the arrow key! //remote_players[data.id].player.setVelocity(data.velocity.x, data.velocity.y); //////////////////////////////////////////////////////////////////////////////////////// /*remote_players[data.id].playerHead.setPosition(data.position.x, data.position.y); remote_players[data.id].playerHead.setVelocity(data.velocity.x, data.velocity.y); remote_players[data.id].playerBody.setPosition(data.position.x, data.position.y); remote_players[data.id].playerBody.setVelocity(data.velocity.x, data.velocity.y);*/ } else { ////This part I know! Defines spawn point of non-local players along with their sprite//// ////also defines hitbox of non-local player sprites and gives them physics to they can collide with things//// const new_player = variableGroup.go.physics.add.sprite(4320, 4320, 'emptyplayer'); /*const new_playerHead = variableGroup.go.physics.add.sprite(4320, 4320, 'dudeheadpurple'); const new_playerBody = variableGroup.go.physics.add.sprite(4320, 4320, 'dudebody');*/ new_player.setSize(8, 8); new_player.setOffset(11, 40); new_player.setBounce(0.0); new_player.setCollideWorldBounds(false); new_player.setMaxVelocity(160, 400); new_player.setDragX(350); new_player.update(); variableGroup.go.physics.add.collider(new_player, blocked); remote_players[data.id].player = new_player; console.log('player = ', variableGroup.player); /* new_playerHead.setSize(8, 8); new_playerHead.setOffset(11, 40); new_playerHead.setBounce(0.0); new_playerHead.setCollideWorldBounds(false); new_playerHead.setMaxVelocity(160, 400); new_playerHead.setDragX(350); new_playerHead.update(); variableGroup.go.physics.add.collider(new_playerHead, blocked); remote_players[data.id].playerHead = new_playerHead; new_playerBody.setSize(8, 8); new_playerBody.setOffset(11, 40); new_playerBody.setBounce(0.0); new_playerBody.setCollideWorldBounds(false); new_playerBody.setMaxVelocity(160, 400); new_playerBody.setDragX(350); new_playerBody.update(); variableGroup.go.physics.add.collider(new_playerBody, blocked); remote_players[data.id].playerBody = new_playerBody; console.log('remote_players variable = ', remote_players); */ } if (!remote_players[data.id].player) delete remote_players[data.id]; } } }); ////outputs whether or not players are moving to change variables above//// ////Honestly mostly useless right now I think?//// variableGroup.player.setPosition(variableGroup.player.body.position.x, variableGroup.player.body.position.y); const keybinds = { ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down" }; /* These are now combined as part of the update tick since the keydown/keyup events weren't triggering promptly ///////////////////ARE THESE BEING CALLED PROPERLY?///////////////// ////adds a value to the array above if one of the arrows are pressed//// ////Are they even important at all?//// document.addEventListener('keydown', function (e) { if (e.code in keybinds) { if (movement[keybinds[e.code]] !== 1) { movement[keybinds[e.code]] = 1; emit_movement(); } } }); ////removes value to the array above when the arrow key is released//// document.addEventListener("keyup", function (e) { if (e.code in keybinds) { if (movement[keybinds[e.code]] !== 0) { movement[keybinds[e.code]] = 0; emit_movement(); } } }); */ //Utility function to send data function send_data(message, data) { return variableGroup.ioGame.emit(message, data) } return send_data; console.log('send_data =', send_data); } ////sends player position and velocity to server? Maybe also?//// ////This is called whenever a local player presses an arrow key...//// ////So it must be important for movement...but I don't know what actually uses this data//// function emit_movement() { console.log('emit_movement called successfully'); if (send_data && variableGroup.player && variableGroup.player_id) { const player_data = {}; player_data.id = variableGroup.player_id; console.log('emit_movement player_data = ', variableGroup.player_id); player_data.velocity = variableGroup.player.body.velocity; player_data.position = {x: variableGroup.player.x, y: variableGroup.player.y}; player_data.movement = movement; send_data('update', player_data); } else { console.error('Attempting to send player movement data before multiplayer initialized') } } <file_sep>////create BootScene//// var BootScene = new Phaser.Class({ Extends: Phaser.Scene, initialize: function BootScene() { ////because active is set to true, scene launches instantly//// Phaser.Scene.call(this, {key: 'BootScene', active: true}); }, ////Load up all assets game uses before game starts //// preload: function () { console.log('Preloader started..'); boot = this; //boot.load.image('preloader-bar', 'client/assets/images/preloader-bar.png'); let progressBar = this.add.graphics(); let progressBarHolder = this.add.graphics(); progressBarHolder.fillStyle(0x222222, 0.8); progressBarHolder.fillRect(735, 270, 320, 50); /* //This seems to tick through individual files, which isn't so useful. boot.load.on('fileprogress', function (file, value) { console.log("File progress event: ", file, ", ", value); }); */ //This seems to capture a total ratio (between 0.0 and 1.0) boot.load.on('progress', function (ratio) { progressBar.clear(); progressBar.fillStyle(0xffffff, 1); progressBar.fillRect(745, 280, 300 * ratio, 30); }); boot.load.on('complete', function () { progressBar.destroy(); progressBarHolder.destroy(); }); //This loads the tilesheet that the map uses to generate pictures//// boot.load.image('spritesheet', 'client/assets/images/spritesheet.png'); //This loads the map json file that says what coordinates have what pictures//// boot.load.tilemapTiledJSON('level_2', 'client/assets/tilemaps/level2.json'); //loads song file//// boot.load.audio('bgm_calm', 'client/assets/music/Electrodoodle.mp3'); //loads sprite files to be used for players//// boot.load.spritesheet('emptyplayer', 'client/assets/spritesheets/emptyplayer.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dude', 'client/assets/spritesheets/dude.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dude2', 'client/assets/spritesheets/dude2.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dudebody', 'client/assets/spritesheets/dudebody.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dudeheadpurple', 'client/assets/spritesheets/dudeheadpurple.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dudeheadgreen', 'client/assets/spritesheets/dudeheadgreen.png', {frameWidth: 32, frameHeight: 48}); boot.load.spritesheet('dudeheadblue', 'client/assets/spritesheets/dudeheadblue.png', {frameWidth: 32, frameHeight: 48}); ////preloads clickable login button //// boot.load.image('loginbutton', 'client/assets/images/loginbutton.png'); boot.load.image('characterselect', 'client/assets/images/characterselect.png'); boot.load.image('leftarrow', 'client/assets/images/leftarrow.png'); boot.load.image('rightarrow', 'client/assets/images/rightarrow.png'); boot.load.image('headselectpurple', 'client/assets/images/headselectpurple.png'); boot.load.image('headselectgreen', 'client/assets/images/headselectgreen.png'); boot.load.image('headselectblue', 'client/assets/images/headselectblue.png'); //preloading menu assets//// boot.load.image('menuframe', 'client/assets/images/menuframe.png', {frameWidth: 1921, frameHeight: 1041}); boot.load.image('numberbutton', 'client/assets/images/numberbutton.png'); boot.load.image('looktab', 'client/assets/images/looktab.png'); boot.load.image('lookdisplay', 'client/assets/images/lookdisplay.png'); boot.load.image('itemstab', 'client/assets/images/itemstab.png'); boot.load.image('itemsdisplay', 'client/assets/images/itemsdisplay.png'); boot.load.image('spellstab', 'client/assets/images/spellstab.png'); boot.load.image('spellsdisplay', 'client/assets/images/spellsdisplay.png'); boot.load.image('maptab', 'client/assets/images/maptab.png'); boot.load.image('mapdisplay', 'client/assets/images/mapdisplay.png'); boot.load.image('optionstab', 'client/assets/images/optionstab.png'); boot.load.image('optionsdisplay', 'client/assets/images/optionsdisplay.png'); boot.load.image('clothesavatar', 'client/assets/images/clothesavatar.png'); }, create: function() { variableGroup.ioSystem = io(location.host); //Connect here, since we may eventually do MOTD type things before login $('#uiLogin').show(); //boot.scene.start('LoginScene'); } }); <file_sep>let remote_players = {}; let movement = {Left: 0, Right: 0, Up: 0, Down: 0}; ////most of this does nothing at the moment, with the exception of the final "else" command//// ////setting player velocity to 0 here is important because it keeps non-local player's sprites ////from sliding all over the screen//// function update_movement(player, movement) { if (player) { if (movement["Left"]) { //player.setVelocityX(-160); player.anims.play('otherleft', true); } else if (movement["Right"]) { // player.setVelocityX(160); player.anims.play('otherright', true); } else if (movement['Up']) { //player.setVelocityY(-160); player.anims.play('right', true); } else if (movement['Down']) { //player.setVelocityY(160); player.anims.play('left', true); } else{ player.setVelocityX(0); player.setVelocityY(0); player.anims.play('turn'); } }} ////called from index.js, tells server when players connect and disconnect//// function start_multiplayer() { ////tells non-local players where to look to find the game files//// let socket = io('172.16.17.32:8081'); ////I have no idea what this data_storage stuff is//// const data_storage = {connected: false}; socket.on("connected", (data) => { if (data_storage.connected) { location.reload(true); } else { console.log("connected", data); player_id = data.id; data_storage.connected = true; console.log("data.id variable = ", data.id); } console.log('data_storage variable = ', data_storage); }); ////when server says player has joined, log player id in console//// socket.on("joined", (data) => { console.log("joined", data); remote_players[data.id] = data; console.log(remote_players); }); ////if server say player left remove player id and destroy player info//// socket.on("left", (data) => { console.log("left", data); if (remote_players[data.id]) { remote_players[data.id].player.destroy(); delete remote_players[data.id]; } console.log('logged out: ', remote_players); update_hud(); }); socket.on("players", (data) => { remote_players = data; }); ////when server says player has moved, update position on other players screen?//// ////Honestly most of this is a mystery to me...//// socket.on("update_other", (data) => { if (go) { if (data.id !== player_id) { if (!remote_players[data.id]) remote_players[data.id] = data; if (remote_players[data.id].player) { remote_players[data.id].movement = data.movement; if (data.movement) { update_movement(remote_players[data.id].player, data.movement); } remote_players[data.id].player.setPosition(data.position.x, data.position.y); remote_players[data.id].player.setVelocity(data.velocity.x, data.velocity.y); } else { ////This part I know! Defines spawn point of non-local players along with their sprite//// ////also defines hitbox of non-local player sprites and gives them physics to they can collide with things//// const new_player = go.physics.add.sprite(4320, 4320, 'dude2'); player.setSize(8, 8); player.setOffset(11, 40); player.setBounce(0.0); new_player.setCollideWorldBounds(false); new_player.setMaxVelocity(160, 400); new_player.setDragX(350); new_player.update(); go.physics.add.collider(new_player, blocked); remote_players[data.id].player = new_player; console.log('remote_players variable = ', remote_players); } if (!remote_players[data.id].player) delete remote_players[data.id]; } } }); ////send movement data//// ////I'm guessing this is sending player coordinates to the server? I dunno/// function send_data(message, data) { return socket.emit(message, data) } return send_data ////outputs whether or not players are moving to change variables above//// ////Honestly mostly useless right now I think?//// player.setPosition(player.body.position.x, player.body.position.y); const keybinds = { ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down" }; ///////////////////ARE THESE BEING CALLED PROPERLY?///////////////// ////adds a value to the array above if one of the arrows are pressed//// ////Are they even important at all?//// document.addEventListener('keydown', function (e) { if (e.code in keybinds) { if (movement[keybinds[e.code]] !== 1) { movement[keybinds[e.code]] = 1; emit_movement(); } } }); ////removes value to the array above when the arrow key is released//// document.addEventListener("keyup", function (e) { if (e.code in keybinds) { if (movement[keybinds[e.code]] !== 0) { movement[keybinds[e.code]] = 0; emit_movement(); } } }); } ////sends player position and velocity to server? Maybe also?//// ////This is called whenever a local player presses an arrow key...//// ////So it must be important for movement...but I don't know what actually uses this data//// function emit_movement() { if (send_data && player && player_id) { const player_data = {}; player_data.id = player_id; player_data.velocity = player.body.velocity; player_data.position = {x: player.x, y: player.y}; player_data.movement = movement; send_data('update', player_data); } else { console.error('Attempting to send player movement data before multiplayer initialized') } } <file_sep>////supposed to update HUD...not sure this is working right...//// function update_hud() { variableGroup.playerCount = (Object.keys(remote_players).length); if (variableGroup.playerCount <= 0) { variableGroup.playerCountText.setText('Multiplayer server offline'); } else { variableGroup.playerCountText.setText('Players: ' + (Object.keys(remote_players).length)); } }<file_sep>////create GameScene//// //var oldVelocityX = 0, oldVelocityY = 0; var GameScene = new Phaser.Class({ Extends: Phaser.Scene, initialize: function GameScene() { ////active is set to false here, so it waits for a command to launch//// Phaser.Scene.call(this, {key: 'GameScene', active: false}); this.pic; }, ////This function actually generates in the game what has been preloaded//// create: function () { const game = this; console.log('GameScene Started'); ////scene.launch will launch new scene in parallel with current scene//// this.scene.launch('UiScene') /////plays music///// let background_music = this.sound.add('bgm_calm'); background_music.volume = 0.05; background_music.loop = true; background_music.play(); ////Loads the json file and also the map tileset//// const map = this.make.tilemap({key: 'level_2'}); const tileset = map.addTilesetImage('spritesheet'); ////Creates "layers" of different map tiles to be placed on top of one another//// const roof2_layer = map.createStaticLayer('roof2', tileset, 0, 0); const roof_layer = map.createStaticLayer('roof', tileset, 0, 0); const grass_layer = map.createStaticLayer('grass', tileset, 0, 0); const background_layer = map.createStaticLayer('background', tileset, 0, 0); const background2_layer = map.createStaticLayer('background2', tileset, 0, 0); const background3_layer = map.createStaticLayer('background3', tileset, 0, 0); const ground_layer = map.createStaticLayer('blocked', tileset, 0, 0); const ground2_layer = map.createStaticLayer('blocked2', tileset, 0, 0); ////defines the height that each map layer is displayed at and what tile IDs player can collide with//// roof2_layer.depth = 4; roof2_layer.setCollision(-1); roof_layer.depth = 3; roof_layer.setCollision(-1); grass_layer.depth = 2; grass_layer.setCollision(-1); ground_layer.setCollision([73, 74, 75, 292, 329, 450, 451, 452, 454, 455, 456, 482, 513, 514, 515, 516, 517, 518, 518, 583, 584, 589, 609, 610, 611, 645, 646, 647, 648, 651, 705, 706, 707, 712, 771, 772, 773, 774, 775, 776, 833, 834, 835, 836, 837, 838, 839, 840, 1300, 1301, 1302, 1363, 1364, 1366, 1367, 1427, 1431, 1491, 1492, 1494, 1495, 1556, 1557, 1558, 2369, 2370, 2371, 2433, 2434, 2435, 2497, 2498, 2499,]); ground_layer.depth = 0; ground2_layer.setCollision(-1); background_layer.setCollision(-1); background2_layer.setCollision(-1); background3_layer.setCollision(-1); ground_layer.setCollisionFromCollisionGroup(); ////makes all the objects you can't walk through///// blocked = this.physics.add.staticGroup(); ////////////////////////experimental playerObject grouping code///////////////////////////////// //The idea is to create a set of "player info" that will be sent from the client to the server //The server will receive this packet of info and send back to other clients a message saying //"player_ID is at this location and using spritesheet1 for head, spritesheet 4 for body" so on and so forth //Clients will receive this message from server and know that playerID is at this location and has these accessories //the location of accessories will be determined client side by setting the location of the accessories to match the player location //client will apply spritesheets for those accessories based on the info pack received from the server. variableGroup.playerObject = { playerIDNumber: variableGroup.ioSystem.id, //define where player is //playerLocation, //the "base sprite" that all other accessory sprites are layered on top of playerBody: null, //"accessory" sprites that will be grouped together with the base sprite playerHead: null //playerEars, //playerTail, //playerPatterns, }; variableGroup.playerObject.playerHead = this.physics.add.sprite(4320, 4320, 'emptyplayer') variableGroup.playerObject.playerBody = this.physics.add.sprite(4320, 4320, 'emptyplayer') console.log('variableGroup.playerObject = ', variableGroup.playerObject); ////////////////////////END experimental playerObject grouping code///////////////////////////////// ////Defines local player spawn position and what sprite local player will use//// variableGroup.player = this.physics.add.sprite(4320, 4320, 'dudebody') /////makes it so local player can leave the edges of the map///// ////also defines "hitbox" of local player and commands camera to follow//// variableGroup.player.setSize(8, 8); variableGroup.player.setOffset(11, 40); variableGroup.player.setBounce(0.0); variableGroup.player.setCollideWorldBounds(false); variableGroup.playerObject.playerHead.setSize(8, 8); variableGroup.playerObject.playerHead.setOffset(11, 40); variableGroup.playerObject.playerHead.setBounce(0.0); variableGroup.playerObject.playerHead.setCollideWorldBounds(false); variableGroup.playerObject.playerBody.setSize(8, 8); variableGroup.playerObject.playerBody.setOffset(11, 40); variableGroup.playerObject.playerBody.setBounce(0.0); variableGroup.playerObject.playerBody.setCollideWorldBounds(false); ////gives physics to local player so that they will obey blocked objects///// game.physics.add.collider(variableGroup.player, ground_layer); game.physics.add.collider(variableGroup.playerObject.playerHead, ground_layer); game.physics.add.collider(variableGroup.playerObject.playerBody, ground_layer); variableGroup.cam1 = this.cameras.main.setSize(920, 920).startFollow(variableGroup.player).setName('Camera 1'); /////tells game to look at arrow keys for game input///// variableGroup.cursors = this.input.keyboard.createCursorKeys(); /////creates the available animations to call on when moving sprites///// this.anims.create({ key: 'otherleft', frames: this.anims.generateFrameNumbers('dude2', {start: 0, end: 3}), frameRate: 10, repeat: -1 }); this.anims.create({ key: 'otherturn', frames: [{key: 'dude2', frame: 4}], frameRate: 20 }); this.anims.create({ key: 'otherright', frames: this.anims.generateFrameNumbers('dude2', {start: 5, end: 8}), frameRate: 10, repeat: -1 }); ////animation grouping//// ////Left Facing Animations//// variableGroup.leftBody = { key: 'leftbody', frames: this.anims.generateFrameNumbers('dudebody', {start: 0, end: 3}), frameRate: 10, repeat: -1 }; ////if purple head was selected, play this//// this.anims.create(variableGroup.leftBody); if (variableGroup.headSelect == 1) { variableGroup.leftHead = { key: 'lefthead', frames: this.anims.generateFrameNumbers('dudeheadpurple', {start: 0, end: 3}), frameRate: 10, repeat: -1 }; } ////if blue head was selected, play this//// if (variableGroup.headSelect == 2) { variableGroup.leftHead = { key: 'lefthead', frames: this.anims.generateFrameNumbers('dudeheadblue', {start: 0, end: 3}), frameRate: 10, repeat: -1 }; } ////if green head was selected, play this//// if (variableGroup.headSelect == 3) { variableGroup.leftHead = { key: 'lefthead', frames: this.anims.generateFrameNumbers('dudeheadgreen', {start: 0, end: 3}), frameRate: 10, repeat: -1 }; } ////assign whatever animation is chosen above to variableGroup.leftHead//// this.anims.create(variableGroup.leftHead); ////Right Facing Animations//// variableGroup.rightBody = { key: 'rightbody', frames: this.anims.generateFrameNumbers('dudebody', {start: 5, end: 8}), frameRate: 10, repeat: -1 }; this.anims.create(variableGroup.rightBody); ////if purple head was selected, play this//// if (variableGroup.headSelect == 1) { variableGroup.rightHead = { key: 'righthead', frames: this.anims.generateFrameNumbers('dudeheadpurple', {start: 5, end: 8}), frameRate: 10, repeat: -1 }; } ////if blue head was selected, play this//// if (variableGroup.headSelect == 2) { variableGroup.rightHead = { key: 'righthead', frames: this.anims.generateFrameNumbers('dudeheadblue', {start: 5, end: 8}), frameRate: 10, repeat: -1 }; } ////if green head was selected, play this//// if (variableGroup.headSelect == 3) { variableGroup.rightHead = { key: 'righthead', frames: this.anims.generateFrameNumbers('dudeheadgreen', {start: 5, end: 8}), frameRate: 10, repeat: -1 }; } ////assign whatever animation is chosen above to variableGroup.rightHead//// this.anims.create(variableGroup.rightHead); ////Animation played when player is not moving//// ////if purple head was selected, play this//// if (variableGroup.headSelect == 1) { variableGroup.standStill = { key: 'standstill', frames: [{key: 'dudeheadpurple', frame: 4}], frameRate: 20 }; } ////if blue head was selected, play this//// if (variableGroup.headSelect == 2) { variableGroup.standStill = { key: 'standstill', frames: [{key: 'dudeheadblue', frame: 4}], frameRate: 20 }; } ////if green head was selected, play this//// if (variableGroup.headSelect == 3) { variableGroup.standStill = { key: 'standstill', frames: [{key: 'dudeheadgreen', frame: 4}], frameRate: 20 }; } ////assign whatever animation is chosen above to variableGroup.standStill//// this.anims.create(variableGroup.standStill); ////go - this; is some how important to representing non-local player movement//// ////line 78 of multiplayer.js updates player position only "if go"//// variableGroup.go = this; variableGroup.collider = this.physics.add.collider(variableGroup.player, blocked); variableGroup.controls.velocity = variableGroup.player.body.velocity; ////will soon display how many people are connected? Hopefully? Maybe?///// variableGroup.playerCountText = this.add.text(16, 70, 'Players: Connecting...', {fontSize: '30px', fill: '#000'}); /////call start_multiplayer function in multiplayer.js file///// send_data = start_multiplayer(); }, ////Game continually loops this function to check for input//// update: function () { ////if an arrow key is pressed, move local player in appropriate direction//// ////also assigns animations to local player sprite//// ////emit_movement calls this function in the multiplayer.js file//// let animation = ''; let velocityX = 0, velocityY = 0; //X Axis if (variableGroup.cursors.left.isDown) { velocityX = -160; //oldVelocityX = velocityX //animation = 'leftbody'; variableGroup.playerObject.playerBody.anims.play('leftbody', true); variableGroup.playerObject.playerHead.anims.play('lefthead', true); } else if (variableGroup.cursors.right.isDown) { velocityX = 160; //oldVelocityX = velocityX //animation = 'rightbody'; variableGroup.playerObject.playerBody.anims.play('rightbody', true); variableGroup.playerObject.playerHead.anims.play('righthead', true); } //Y Axis else if (variableGroup.cursors.up.isDown) { velocityY = -160; //oldVelocityY = velocityY //animation = 'rightbody'; variableGroup.playerObject.playerBody.anims.play('rightbody', true); variableGroup.playerObject.playerHead.anims.play('righthead', true); } else if (variableGroup.cursors.down.isDown) { velocityY = 160; //oldVelocityY = velocityY //animation = 'leftbody'; variableGroup.playerObject.playerBody.anims.play('leftbody', true); variableGroup.playerObject.playerHead.anims.play('lefthead', true); } else { velocityX = 0; velocityY = 0; variableGroup.playerObject.playerBody.anims.play('standstill', true); variableGroup.playerObject.playerHead.anims.play('standstill', true); //emit_movement(); } variableGroup.player.setVelocityX(velocityX); variableGroup.player.setVelocityY(velocityY); variableGroup.playerObject.playerHead.setVelocityX(velocityX); variableGroup.playerObject.playerHead.setVelocityY(velocityY); variableGroup.playerObject.playerBody.setVelocityX(velocityX); variableGroup.playerObject.playerBody.setVelocityY(velocityY); //Notify server if we have either velocity OR the previous frame had some movement (so that it receives stops) if (velocityX || velocityY || movement.left || movement.right || movement.up || movement.down) { //Update actual movement before sending movement.left = (velocityX < 0); movement.right = (velocityX > 0); movement.up = (velocityY < 0); movement.down = (velocityY > 0); console.log('Sending ', movement); console.log('VX = ', velocityX); console.log('VY = ', velocityY); emit_movement(); } /*else { console.error('emit_movement failed to be called'); } console.log('Sending ', movement); console.log('VX = ', velocityX); console.log('VY = ', velocityY); */ //variableGroup.player.anims.play(animation || 'turn', true); //variableGroup.playerObject.playerBody.anims.play('leftbody' || 'rightbody' || 'standstill', true); //variableGroup.playerObject.playerHead.anims.play('lefthead' || 'righthead' || 'standstill', true); //variableGroup.playerObject.playerBody.anims.play('rightbody' || 'standstill', true); //variableGroup.playerObject.playerHead.anims.play('righthead' || 'standstill', true); ////haven't figured out what this is for yet...but seems important//// ////Has something to do with updating player movements for other clients?/// for (let id in remote_players) { if (remote_players.hasOwnProperty(id)) { if (remote_players[id].player && remote_players[id].movement) { //update_movement(remote_players[id].player, remote_players[id].movement); } } } }, });<file_sep># Top Down Game **Installing and running the game** You will need `Node.js` to download and install the `socket.io` and `express` packages the game needs using an npm command. **To Download Node.js go here:** [https://nodejs.org/en/](https://nodejs.org/en/) Once Node.js is installed open your command prompt and navigate to the directory you cloned this repository to. **Basic CMD Navigation Tips** You can use `cd/foldername\foldername\` to find the folder you saved this repository in. If you need to go up a directory you can use `cd..` to go backwards in your file structure. **Installing `socket.io` and `express`** Make sure that you are inside of the `top_down_test_game` folder that is defined in this repository. With CMD looking at this directory run the command: `npm install` This will automatically install both the `socket.io` and the `express` packages using the .json files that are inside the `top_down_test_game` folder. **How to run the game server** Now that we have the packages installed, we need to run the `server.js` file located inside the same `top_down_test_game` folder. To do this, use the command: `node server.js` If all goes well, you should get a message `server starting with ID: xxxxx` `Server is now running...Listening on 8081` This means it is up and running properly! Congratulations! You are now ready to test the game. The server will be listening to connections on port 8081; should you need to, you can change this by editing line 28 of the `server.js` file. Assuming no changes are made, you can now run the game by navigating to http://localhost:8081/ in your internet browser. ## Things to do in order to reach Alpha Version 0.00 1. **Solve "rubber banding" issue.** Non-local player sprites are currently not updating properly. When a player stops moving, the game will show them continuing to move forwards for a time before snapping them back to the correct position. 2. **Integrate chat program.** Make chat program display on top of the game in the bottom right quadrant of the screen. 3. **Implement usernames.** Make it so that users can type in a username and have their player represented by and referenced to as that username in the code. 4. **Create a character selector.** A scene that runs at the start of the game where the player can scroll through a selection of available sprites and choose one to represent them. We will work on allowing players to customize their sprites in later Alpha versions. And that's it! With these 4 issues in place we will be able to make the game go live on our website as Alpha Version 0.00!
5c24f3218aa4cc3683f161b2855a6ed8fc0e900e
[ "JavaScript", "Markdown" ]
7
JavaScript
twintailsstudios/Top-Down-Test-Game
59ad0d031dc9f9ba055c7b0f603f936a667485b8
6f42cba12e704f19476882c4c02ae45506ff5bfb