branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>class HostReviewsController < ApplicationController def create @reservation = Reseration.where( id: host_review_params[:reservation_id] room_id: host_review_params[:room_id] user_id: host_review_params[:guest_id] ).first if [email protected]? @has_reviewed = HostReview.where( reservation_id: @reservation.id guest_id: host_review_params[:guest_id] ).first if @has_reviewed.nil? @host_review = current_user.host_reviews.create(host_review_params) flash[:success] = 'Review created' else flash[:alert] = "You have already reviwing this reservation " end else flash[:alert] = "Not ound this registration" end redirect_back(fallback_location: request.referrer) end def destroy @host_review = Review.find(params[:id]) @host_review.destroy redirect_back(fallback_location: request.referrer, notice: "Removed!") end private def host_review_params params.require(:host_review).permit(:comment, :star, :room_id, :reservation_id, :guest_id) end end <file_sep>class ReservationsController < ApplicationController before_action :authenticate_user! def create room = Room.find(params[:room_id]) if current_user == room.user flash[:alert] = "You can not book your own property" else start_date = Date.parse(reservation_params[:start_date]) end_date = Date.parse(reservation_params[:end_date]) days = (end_date - start_date).to_i + 1 @reservation = current_user.reservations.build(reservation_params) @reservation.room = room @reservation.price = room.price @reservation.total = @reservation.price * days @reservation.save flash[:notice] = "Boocked Successfully" end redirect_to room end def your_trips @trips = current_user.reservations.order(start_date: :asc) end def your_reservations @rooms = current_user.rooms end private def reservation_params params.require(:reservation).permit(:start_date, :end_date) end end
24eb395164caeff73a1a0cb429f52152a39c6d5d
[ "Ruby" ]
2
Ruby
ShevchukTania/Airbnb_clone
9c7220e2ffb45d251f9f2cd7c1645c5fe2a996df
226b351e23752d11aaedb036ddbd8767cd48d3f9
refs/heads/master
<repo_name>robotronik/tests<file_sep>/Fork/Makefile SRC = test_fork.c OBJ = $(SRC:.c=.o) %.o: %.c @echo " CC $(notdir $@)" @$(CC) $(CFLAGS) $< -o $@ -c test-fork: $(OBJ) @$(CC) $(CFLAGS) $^ -o $@ run: test-fork ./$< <file_sep>/libopencm3_tests/Makefile PROJECT=TestsLibopencm3 default: all # Default Options export ARCH = libopencm3 export ROBOT ?= gros export SDL ?= no export DEBUG ?= 0 PARENT_DIR = ../../ # Constantes de compilation EXEC = tests include $(PARENT_DIR)/hardware/common.mk ################################################################################ # Fichiers du projet FICHIERS_C = \ test.c CFLAGS += -Ihardware/$(ARCH)/ \ -Ihardware/ \ -IInc FICHIERS_O += $(addprefix $(BUILD_DIR)/, $(FICHIERS_C:.c=.o) ) ################################################################################ .PHONY: all view all: $(BUILD_DIR)/$(EXEC) $(BUILD_DIR)/$(EXEC): $(FICHIERS_O) libHardware @echo " CC $(PROJECT)|$(notdir $@)" @$(CC) -o $@ $(FICHIERS_O) $(CFLAGS) -lHardware $(LDFLAGS) $(BUILD_DIR): @mkdir -p $(BUILD_DIR) <file_sep>/libopencm3_tests/test.c /* * * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <libopencm3/stm32/rcc.h> #include "libopencm3/stm32/gpio.h" #include <libopencm3/stm32/flash.h> #include <libopencm3/stm32/timer.h> #include <libopencm3/cm3/nvic.h> #include <libopencm3/stm32/exti.h> #include <libopencmsis/core_cm3.h> #include "pwm.h" #define RADD_GPIO GPIOA #define RADD_PINA GPIO0 #define RADD_PINB GPIO1 #define RADD_PINC GPIO2 static void radd_init(void) { /// init gpios rcc_periph_clock_enable(RCC_GPIOA); gpio_set(RADD_GPIO, RADD_PINA | RADD_PINB | RADD_PINC); gpio_mode_setup(RADD_GPIO, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, RADD_PINA | RADD_PINB | RADD_PINC); gpio_set_output_options(RADD_GPIO, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, RADD_PINA | RADD_PINB | RADD_PINC); /// init timer for waveform generation rcc_periph_clock_enable(RCC_TIM2); timer_reset(TIM2); timer_set_mode(TIM2, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); timer_set_prescaler(TIM2, 120000 / 2 / (10)); timer_set_period(TIM2, 1000); timer_enable_counter(TIM2); nvic_enable_irq(NVIC_TIM2_IRQ); timer_enable_irq(TIM2, TIM_DIER_UIE); /// init timer for speed control rcc_periph_clock_enable(RCC_TIM3); timer_reset(TIM3); timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); timer_set_prescaler(TIM3, 120000 / 2 / (50)); timer_set_period(TIM3, 1000); timer_enable_counter(TIM3); nvic_enable_irq(NVIC_TIM3_IRQ); timer_enable_irq(TIM3, TIM_DIER_UIE); /// red led rcc_periph_clock_enable(RCC_GPIOD); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO14); } void radd_set_freq(int freq) { timer_set_prescaler(TIM2, 120000 / 2 / freq); timer_set_period(TIM2, 1000); } void tim2_isr(void) { if (timer_get_flag(TIM2, TIM_DIER_UIE)) timer_clear_flag(TIM2, TIM_DIER_UIE); static int cnt = 0; switch(cnt++) { case 0: gpio_set(RADD_GPIO, RADD_PINA); gpio_clear(RADD_GPIO, RADD_PINB | RADD_PINC); break; case 1: gpio_set(RADD_GPIO, RADD_PINB); gpio_clear(RADD_GPIO, RADD_PINA | RADD_PINC); break; case 2: gpio_set(RADD_GPIO, RADD_PINC); gpio_clear(RADD_GPIO, RADD_PINA | RADD_PINB); cnt = 0; break; default: break; } } void tim3_isr(void) { if (timer_get_flag(TIM3, TIM_DIER_UIE)) timer_clear_flag(TIM3, TIM_DIER_UIE); gpio_toggle(GPIOD, GPIO14); static uint32_t freq = 0 *(1<<16); uint32_t freq_target = 600 *(1<<16); freq += (freq - freq_target) >> 16; //if ( freq > freq_max ) freq = freq_max; radd_set_freq(freq >> 16); } const struct rcc_clock_scale rcc_hse_8mhz_3v3_perf = { /* 165MHz : sysclk = 8/pllm*plln/pllp*/ .pllm = 8, .plln = 330, .pllp = 2, .pllq = 5, .hpre = RCC_CFGR_HPRE_DIV_NONE, .ppre1 = RCC_CFGR_PPRE_DIV_4, .ppre2 = RCC_CFGR_PPRE_DIV_2, //.power_save = 1, .flash_config = FLASH_ACR_ICE | FLASH_ACR_DCE | FLASH_ACR_LATENCY_7WS, .apb1_frequency = 41250000, /* sysclk / ppre1 */ .apb2_frequency = 82500000, /* sysclk / ppre2 */ }; static void gpio_setup(void) { /* Enable GPIOC clock. */ rcc_periph_clock_enable(RCC_GPIOD); /* Set GPIO12 (in GPIO port C) to 'output push-pull'. */ gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO14 | GPIO15 | GPIO12 ); gpio_set(GPIOD, GPIO14); gpio_clear(GPIOD, GPIO15 | GPIO14 ); } typedef struct { int numTurns; int numIncrements; }EncoderPosition; static EncoderPosition encoderPos; void counter_enc_update(void); void counter_enc_update(void) { encoderPos.numIncrements = timer_get_counter(TIM2); } #define LED_GREEN_PIN GPIO12 #define LED_ORANGE_PIN GPIO13 #define LED_RED_PIN GPIO14 #define LED_BLUE_PIN GPIO15 void board_leds_init() { rcc_periph_clock_enable(RCC_GPIOD); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT,GPIO_PUPD_NONE, LED_BLUE_PIN | LED_GREEN_PIN | LED_ORANGE_PIN | LED_RED_PIN ); } int main(void) { rcc_clock_setup_hse_3v3(&rcc_hse_8mhz_3v3_perf); /* init leds */ //board_leds_init(); /* init complementary pwm */ /* gpios */ /* rcc_periph_clock_enable(RCC_GPIOE); /\* init gpio clk *\/ */ /* gpio_mode_setup(GPIOE, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO9); /\* alternate func mode *\/ */ /* gpio_set_output_options(GPIOE, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO9); /\* open drain *\/ */ /* gpio_set_af(GPIOE, GPIO_AF1, GPIO9); /\* alternate func 1 -> TIM1 output *\/ */ /* /\* timer *\/ */ /* rcc_periph_clock_enable(RCC_TIM1); */ /* timer_reset(RCC_TIM1); */ /* timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); */ /* timer_set_prescaler(TIM1, rcc_apb1_frequency / 2 / ( 2*15000*1024 )); */ /* timer_set_oc_mode(TIM1, TIM_OC1, TIM_OCM_PWM1); */ /* timer_enable_oc_output(TIM1, TIM_OC1); */ /* /\* timer_enable_oc_output(TIM1, TIM_OC1N); *\/ */ /* timer_set_oc_value(TIM1, TIM_OC1, 512); */ /* timer_set_period(TIM1, 1024); */ /* timer_enable_counter(TIM1); */ /* gpios */ rcc_periph_clock_enable(RCC_GPIOD); gpio_mode_setup(GPIOD, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO12 | GPIO13 | GPIO14 | GPIO15); gpio_set_af(GPIOD, GPIO_AF2, GPIO12 | GPIO13 | GPIO14 | GPIO15); /* gpio_set_output_options(GPIOD, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, */ /* GPIO12); */ /* timer */ rcc_periph_clock_enable(RCC_TIM4); timer_reset(TIM4); timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_CENTER_2, TIM_CR1_DIR_UP); timer_set_prescaler(TIM4, rcc_apb2_frequency / 2 / (2* 15000 * 1024)); timer_set_oc_mode(TIM4, TIM_OC1, TIM_OCM_PWM1); timer_set_oc_mode(TIM4, TIM_OC2, TIM_OCM_PWM1); timer_set_oc_mode(TIM4, TIM_OC3, TIM_OCM_PWM1); timer_set_oc_mode(TIM4, TIM_OC4, TIM_OCM_PWM1); timer_enable_oc_output(TIM4, TIM_OC1); timer_enable_oc_output(TIM4, TIM_OC1N); timer_enable_oc_output(TIM4, TIM_OC2); timer_enable_oc_output(TIM4, TIM_OC3); timer_enable_oc_output(TIM4, TIM_OC4); //timer_enable_break_main_output(TIM4); timer_set_oc_value(TIM4, TIM_OC1, 128); timer_set_oc_value(TIM4, TIM_OC2, 256); timer_set_oc_value(TIM4, TIM_OC3, 512); timer_set_oc_value(TIM4, TIM_OC4, 1024); timer_set_period(TIM4, 1023); timer_enable_counter(TIM4); radd_init(); while(1) { } //gpio_clear(RADD_GPIO, RADD_PINA); /* // Button pin rcc_periph_clock_enable(RCC_GPIOA); gpio_mode_setup(GPIOA, GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO0); gpio_setup(); // 4 pwms rcc_periph_clock_enable(RCC_TIM4); gpio_mode_setup(GPIOD, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO12 | GPIO13 | GPIO14 | GPIO15); gpio_set_af(GPIOD, GPIO_AF2, GPIO12 | GPIO13 | GPIO14 | GPIO15); rcc_periph_clock_enable(RCC_TIM4); timer_reset(TIM4); timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_CENTER_2, TIM_CR1_DIR_UP); timer_set_prescaler(TIM4, 120000000 / 2 / (2* 15000 * 1024)); timer_set_oc_mode(TIM4, TIM_OC1, TIM_OCM_PWM2); timer_set_oc_mode(TIM4, TIM_OC2, TIM_OCM_PWM2); timer_set_oc_mode(TIM4, TIM_OC3, TIM_OCM_PWM2); timer_set_oc_mode(TIM4, TIM_OC4, TIM_OCM_PWM2); timer_enable_oc_output(TIM4, TIM_OC1); timer_enable_oc_output(TIM4, TIM_OC2); timer_enable_oc_output(TIM4, TIM_OC3); timer_enable_oc_output(TIM4, TIM_OC4); //timer_enable_break_main_output(TIM4); timer_set_oc_value(TIM4, TIM_OC1, 512); timer_set_oc_value(TIM4, TIM_OC2, 1); timer_set_oc_value(TIM4, TIM_OC3, 1); timer_set_oc_value(TIM4, TIM_OC4, 1023); timer_set_period(TIM4, 1023); timer_enable_counter(TIM4); // encoder rcc_periph_clock_enable(RCC_GPIOA); gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO1 | GPIO15); gpio_set_af(GPIOA, GPIO_AF1, GPIO1 | GPIO15); rcc_periph_clock_enable(RCC_TIM2); timer_reset(TIM2); timer_set_period(TIM2, 512 -1); // number of increments // set encoder mode // * 0x1 : only one input generate an event timer_slave_set_mode(TIM2, 0x1); // divide by 2, so the counter reflects the encoder position in increment timer_set_prescaler(TIM2, 1); timer_ic_set_input(TIM2, TIM_IC1, TIM_IC_IN_TI1); timer_ic_set_input(TIM2, TIM_IC2, TIM_IC_IN_TI2); timer_enable_counter(TIM2); nvic_enable_irq(NVIC_TIM2_IRQ); timer_enable_irq(TIM2, TIM_DIER_UIE); // red led gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO14); gpio_set(GPIOD, GPIO14); timer_set_oc_value(TIM4, TIM_OC1, 300); while (1) { counter_enc_update(); if ( encoderPos.numIncrements <= low ) { timer_set_oc_mode(TIM4, TIM_OC1, TIM_OCM_PWM1); gpio_clear(GPIOD, GPIO14); } if ( encoderPos.numIncrements >= high ) { timer_set_oc_mode(TIM4, TIM_OC1, TIM_OCM_PWM2); gpio_set(GPIOD, GPIO14); } } */ while(1) {} } /* void tim2_isr(void) { if (timer_get_flag(TIM2, TIM_DIER_UIE)) timer_clear_flag(TIM2, TIM_DIER_UIE); if ( timer_get_counter(TIM2) ) encoderPos.numTurns++; else encoderPos.numTurns--; } */ <file_sep>/communication_bi_directionnelle/b.c #include <unistd.h> #include <stdio.h> int main(void) { while(1) { char receive; fprintf(stderr, "b.c est en attente d'un char\n"); scanf("%c", &receive); fprintf(stderr, "b.c a reçu %c\n", receive); int send = 300; printf("%d\n", send); fflush(stdout); fprintf(stderr, "b.c a envoyé %d\n", send); sleep(1); } return 0; } <file_sep>/README.md # tests Ce répertoire sert à faire tout les tests que l'on veux. <file_sep>/communication_bi_directionnelle/a.c #include <unistd.h> #include <stdio.h> int main(void) { while(1) { sleep(1); char send = '+'; printf("%c", send); fflush(stdout); fprintf(stderr, "a.c a envoyé %c\n", send); sleep(1); int receive; fprintf(stderr, "a.c est en attente d'un entier\n"); scanf("%d", &receive); fprintf(stderr, "a.c a reçu %d\n", receive); } return 0; } <file_sep>/communication_bi_directionnelle/Makefile all: a b mkfifo pipe_nomme 0<pipe_nomme ./a | ./b 1>pipe_nomme a: a.c gcc -o a a.c b: b.c gcc -o b b.c clean: rm a b pipe_nomme <file_sep>/Fork/test_fork.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #define EXEC "../../asservissement/build/PC/_DEBUG_/asser_robot" #define READ 0 #define WRITE 1 int main(int argc, char const *argv[]) { int to_child_stdin[2]; pid_t childpid; pipe(to_child_stdin); if((childpid = fork()) == -1) { perror("fork"); exit(1); } if(childpid == 0) { /* Child process closes up input side of pipe */ close(to_child_stdin[WRITE]); dup2(to_child_stdin[READ], STDIN_FILENO); execl("/bin/sh", "/bin/sh", "-c", EXEC, NULL); exit(0); } else { printf("pid : %d\n", childpid); /* Parent process closes up output side of pipe */ close(to_child_stdin[READ]); write(to_child_stdin[WRITE], "x=1000\ny=1000\nxy_absolu()\n", 26); int stat; waitpid(childpid, &stat, 0); kill(childpid, SIGKILL); } return 0; }
3f266acb90ce5bb6daa0cf3a2a97dd825185e719
[ "Markdown", "C", "Makefile" ]
8
Makefile
robotronik/tests
9c9e741d0d6454034e4e2903f147037d8b6acfea
6b29e18d6c42000d3e11848c42111346261b6676
refs/heads/main
<file_sep>using System; using System.IO; using System.Collections; using System.Xaml; namespace XAMLParser { public class Program { static void Main(string[] args) { string[] fileNames = Directory.GetFiles("/Users/abhibhandari/Desktop/JOLT/xaml_outputs"); string[] fileContents = new string[fileNames.Length]; object[] xamlGraphs = new object[fileNames.Length]; for (int i = 0; i < fileNames.Length; i++) { Console.WriteLine(i); fileContents[i] = File.ReadAllText(fileNames[i]); } for (int i = 0; i < fileNames.Length; i++) { xamlGraphs[i] = XamlServices.Parse(fileContents[i]); } } } }
afe23987c8e4ba2ce615e3b67a8071faeed28095
[ "C#" ]
1
C#
abhibhan212/XAMLParser
33dab8bb49dca9081cd359a3165ee17ffb70961e
943349c9237428632761ed21de5ce22d100f0ce6
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace PruebaDeEscritorio { public partial class frmMenu : Form { public frmMenu() { InitializeComponent(); } private void btnRegistrar_Click(object sender, EventArgs e) { SqlConnection cn = new SqlConnection("Data Source=LAPTOP-C4043JNM;Initial Catalog=PruebaEscritorio;Integrated Security=True"); cn.Open(); SqlCommand adaptador = new SqlCommand(); adaptador.Connection = cn; adaptador.CommandText = "insert into Usuarios values (" + txbCodigoRegistar.Text + ",'" + txbNombreRegistrar.Text + "','" + txbApellidoRegistrar.Text + "','" + txbDNIRegistrar.Text + "','" + txbTelefonoRegistrar.Text + "')"; adaptador.ExecuteNonQuery(); MessageBox.Show("Se registro correctamente"); cn.Close(); } private void btnBuscarActializar_Click(object sender, EventArgs e) { SqlConnection cn = new SqlConnection("Data Source=LAPTOP-C4043JNM;Initial Catalog=PruebaEscritorio;Integrated Security=True"); cn.Open(); SqlDataAdapter adaptador = new SqlDataAdapter("select * from Usuarios where codigo=" + txbCodigoActualizar.Text + "",cn); DataSet t = new DataSet(); adaptador.Fill(t); } } }
f8d3b73588c1d56b029f84bbd71cabcadd8bf279
[ "C#" ]
1
C#
santilucini/PruebaEscritorio
d4af063a8a802d86943cf267d08073f6a2139d2f
827b1b5d0f3281122f8cc5d53ef3c5cfe3879c68
refs/heads/master
<repo_name>sudhanshu599/phpassign<file_sep>/handler45.php <?php header("Content-Type: application/json; charset=UTF-8"); require 'database45.php'; require 'customer45.php'; $req=$_GET['req'] ?? null; $db=new database(); $customer= new customer($db->connect()); switch($req){ case 'insert': $obj=$_GET['object']; $temp=json_decode($obj); echo $customer->insertcustomerdetail($temp); break; case 'list': echo $customer->getcutomerdetails(); break; default: echo json_encode(["In-valid request"]); break; } ?> <file_sep>/js/main.js let base_url = "handler45.php"; var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } var eventList = document.getElementById("event"); var myEventList = document.getElementById("myregistration"); var data = document.getElementById("data"); var nodata = document.getElementById("ini"); myEventList.style.display = "none"; eventList.style.display = "block"; function events() { if(eventList.style.display === "none"){ eventList.style.display = "block"; myEventList.style.display = "none"; } } function myreg() { if(myEventList.style.display === "none"){ myEventList.style.display = "block"; eventList.style.display = "none"; showdata(); } } let successbut = document.querySelector(".checkk"); successbut.addEventListener("click", validation); function validation(ev) { ev.preventDefault(); var fname = document.getElementById("fname").value; var lname = document.getElementById("lname").value; var phno = document.getElementById("phno").value; var email = document.getElementById("email").value; var e = document.getElementById("eventname"); var strUser = e.options[e.selectedIndex].value; var strUser1 = e.options[e.selectedIndex].text; // console.log(strUser1); if (strUser === 0) { document.getElementById("eventname1").innerHTML = "Please Select a Event"; // alert("Please select a Contest"); return false; } setTimeout(() => { document.getElementById("eventname1").innerHTML = " "; }, 2000); if (fname === "") { document.getElementById("fname1").innerHTML = "Please fill the Frist Name"; setTimeout(() => { document.getElementById("fname1").innerHTML = " "; }, 2000); return false; } if (fname.length <= 2 || fname.length > 20) { document.getElementById("fname1").innerHTML = "Please enter a valid name"; setTimeout(() => { document.getElementById("fname1").innerHTML = " "; }, 2000); return false; } if (!isNaN(fname)) { document.getElementById("fname1").innerHTML = "only characters are allowed"; setTimeout(() => { document.getElementById("fname1").innerHTML = " "; }, 2000); return false; } if (lname === "") { document.getElementById("lname1").innerHTML = "Please fill the Last Name"; setTimeout(() => { document.getElementById("lname1").innerHTML = " "; }, 2000); return false; } if (fname.length <= 2 || fname.length > 20) { document.getElementById("lname1").innerHTML = "Please enter a valid name"; setTimeout(() => { document.getElementById("lname1").innerHTML = " "; }, 2000); return false; } if (!isNaN(fname)) { document.getElementById("lname1").innerHTML = "only characters are allowed"; setTimeout(() => { document.getElementById("lname1").innerHTML = " "; }, 2000); return false; } if (phno === "") { document.getElementById("phno1").innerHTML = "Please fill the mobile Number field"; setTimeout(() => { document.getElementById("phno1").innerHTML = " "; }, 2000); return false; } if (isNaN(phno)) { document.getElementById("phno1").innerHTML = "User must write digits only not characters"; setTimeout(() => { document.getElementById("phno1").innerHTML = " "; }, 2000); return false; } if (phno.length != 10) { document.getElementById("phno1").innerHTML = "Mobile Number must be 10 digits only"; setTimeout(() => { document.getElementById("phno1").innerHTML = " "; }, 2000); return false; } if (email === "") { document.getElementById("email1").innerHTML = "Please fill the email field"; setTimeout(() => { document.getElementById("email1").innerHTML = " "; }, 2000); return false; } if (email.indexOf("@") <= 0) { document.getElementById("email1").innerHTML = "@ Invalid Position"; setTimeout(() => { document.getElementById("email1").innerHTML = " "; }, 2000); return false; } if ( email.charAt(email.length - 4) != "." && email.charAt(email.length - 3) != "." ) { document.getElementById("email1").innerHTML = " . Invalid Email"; setTimeout(() => { document.getElementById("email1").innerHTML = ""; }, 2000); return false; } let today = new Date(); let timestamp = today.getHours() + " " + "Hr" + ":" + today.getMinutes() + " " + "Min"; var k={fname: fname, lname: lname,pno : phno, email: email, event1 : strUser1 ,timestamp: timestamp}; getthedata(k); document.getElementById("form_register").reset(); } function getthedata(k){ var k = JSON.stringify(k); let url = base_url + "?req=insert&object="+k; $.get(url,function(data,success){ if(data=="Form successfully submitted"){ alert(data); } else{ alert(data); } }); } function showdata(){ let url = base_url + "?req=list"; $.get(url,function(data,success){ if(data.length == 0){ document.getElementById("data").innerHTML="<h3><div class='container text-center'>None registered till now. Be the first one to register.</div></h3>"; } else{ var text; text= "<table class='table table-striped mt-5 co'><thead class='thread-dark'>"; text=text + "<tr><th scope='col'>Name</th><th scope='col'>Phone Number</th><th scope='col'>Email</th><th scope='col'>Event Name</th><th scope='col'>TimeStamp</th></tr></thead>"; for(i=0;i<data.length;i++) { text= text + "<tr><td>" + data[i].fname+" "+data[i].lname + "</td><td>" + data[i].pno + "</td><td>" + data[i].email + "</td><td>" + data[i].event1 + "</td><td>" + data[i].timestamp + "</td></tr>"; } text += "<tbody class='values'></tbody></table>"; document.getElementById("data").innerHTML=text; } }); } <file_sep>/customer45.php <?php class customer{ public $fname; public $lname; public $pno; public $email; public $event1; private $conn; public function __construct($conn) { $this->conn=$conn; } public function insertcustomerdetail($obj){ $sql="INSERT INTO eventer (fname,lname,pno,email,event1) VALUES('$obj->fname','$obj->lname','$obj->pno','$obj->email','$obj->event1');"; $result=mysqli_query($this->conn,$sql); if($result==TRUE){ $msg=["Form successfully submitted"]; } else { $msg=["Error occurred while submitting information. Please try again later."]; } return json_encode($msg); } public function getcutomerdetails(){ $sql="SELECT * FROM eventer;"; $result=mysqli_query($this->conn,$sql); $arr=array(); if(mysqli_num_rows($result)>0) { while($row=mysqli_fetch_assoc($result)) { $arr[]=$row; } } return json_encode($arr); } } ?>
bdf786372ec008fe2b47b1238243d07f09a88f1e
[ "JavaScript", "PHP" ]
3
PHP
sudhanshu599/phpassign
0c5b471ca3d2b9e35fbf11c1536b821c6db12f14
f53feaf9b40e283ddd514309d040c5ca9c642896
refs/heads/master
<file_sep>/** * Copyright (c) 2017 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <map> #include <queue> #include <string> #include <tuple> #include <fstream> #include <algorithm> #include <atomic> #include <mutex> #include <utility> #include <boost/utility/in_place_factory.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "dbglog/dbglog.hpp" #include "utility/path.hpp" #include "utility/streams.hpp" #include "utility/path.hpp" #include "utility/uri.hpp" #include "utility/binaryio.hpp" #include "utility/format.hpp" #include "utility/stl-helpers.hpp" #include "imgproc/readimage.hpp" #include "jsoncpp/json.hpp" #include "jsoncpp/as.hpp" #include "jsoncpp/io.hpp" #include "writer.hpp" #include "restapi.hpp" #include "detail/files.hpp" namespace fs = boost::filesystem; namespace bio = boost::iostreams; namespace bin = utility::binaryio; namespace slpk { TextureSaver::~TextureSaver() {} MeshSaver::~MeshSaver() {} namespace { template <typename T> std::string asString(const T &value) { return boost::lexical_cast<std::string>(value); } // fwd template <typename T> void build(Json::Value &value, const std::vector<T> &array); // builders void build(Json::Value &value, const Capabilities &capabilities) { value = Json::arrayValue; for (auto capability : capabilities) { value.append(asString(capability)); } } void build(Json::Value &value, const ResourcePatterns &resourcepatterns) { value = Json::arrayValue; for (auto resourcepattern : resourcepatterns) { value.append(asString(resourcepattern)); } } void build(Json::Value &value, const SpatialReference &srs) { value = Json::objectValue; if (srs.wkid) { value["wkid"] = srs.wkid; if (!srs.latestWkid) { value["latestWkid"] = srs.wkid; } } if (srs.latestWkid) { value["latestWkid"] = srs.latestWkid; } if (srs.vcsWkid) { value["vcsWkid"] = srs.vcsWkid; if (!srs.latestVcsWkid) { value["latestVcsWkid"] = srs.vcsWkid; } } if (srs.latestVcsWkid) { value["latestVcsWkid"] = srs.latestVcsWkid; } if (!srs.wkt.empty()) { value["wkt"] = srs.wkt; } else if (srs.wkid) { value["wkt"] = srs.srs().as(geo::SrsDefinition::Type::wkt).srs; } } void build(Json::Value &value, const HeightModelInfo &hmi) { value = Json::objectValue; value["heightModel"] = asString(hmi.heightModel); value["ellipsoid"] = hmi.ellipsoid; value["heightUnit"] = hmi.heightUnit; } void build(Json::Value &value, const FeatureRange &range) { value = Json::arrayValue; value.append(range.min); value.append(range.max); } void build(Json::Value &value, const math::Point3 &p) { value = Json::arrayValue; value.append(p(0)); value.append(p(1)); value.append(p(2)); } void build(Json::Value &value, const math::Extents2 &extents) { value = Json::arrayValue; value.append(extents.ll(0)); value.append(extents.ll(1)); value.append(extents.ur(0)); value.append(extents.ur(1)); } void build(Json::Value &value, const math::Extents3 &extents) { value = Json::arrayValue; value.append(extents.ll(0)); value.append(extents.ll(1)); value.append(extents.ll(2)); value.append(extents.ur(0)); value.append(extents.ur(1)); value.append(extents.ur(2)); } void build(Json::Value &value, const math::Matrix4 &m) { value = Json::arrayValue; for (int j(0); j < 4; ++j) { for (int i(0); i < 4; ++i) { value.append(m(j, i)); } } } void build(Json::Value &value, const Encoding &encoding) { value = encoding.mime; } void build(Json::Value &value, const Encoding::list &encodings) { value = Json::arrayValue; for (const auto encoding : encodings) { value.append(encoding.mime); } } void build(Json::Value &value, const Cardinality &cardinality) { value = Json::arrayValue; value.append(cardinality.min); value.append(cardinality.max); } void build(Json::Value &value, const IndexScheme &indexingScheme) { value = Json::objectValue; value["name"] = asString(indexingScheme.name); value["inclusive"] = indexingScheme.inclusive; value["dimensionality"] = indexingScheme.dimensionality; build(value["childrenCardinality"], indexingScheme.childrenCardinality); build(value["neighborCardinality"], indexingScheme.neighborCardinality); } void build(Json::Value &value, const HeaderAttribute &header) { value = Json::objectValue; value["property"] = header.property; value["type"] = asString(header.type); } void build(Json::Value &value, const GeometryAttribute &attr) { value = Json::objectValue; if (attr.byteOffset) { value["byteOffset"] = Json::Int(attr.byteOffset); } if (attr.count) { value["count"] = Json::Int(attr.count); } value["valueType"] = asString(attr.valueType); value["valuesPerElement"] = Json::Int(attr.valuesPerElement); // TODO: values? if (!attr.componentIndices.empty()) { auto jcomponentIndices(value["componentIndices"] = Json::arrayValue); for (auto ci : attr.componentIndices) { jcomponentIndices.append(ci); } } } void build(Json::Value &jattrs, Json::Value &jordering , const GeometryAttribute::list &attrs) { jattrs = Json::objectValue; jordering = Json::arrayValue; for (const auto &attr : attrs) { build(jattrs[attr.key], attr); jordering.append(attr.key); } } void build(Json::Value &value, const GeometryAttribute::list &attrs) { value = Json::objectValue; for (const auto &attr : attrs) { build(value[attr.key], attr); } } void build(Json::Value &value, const GeometrySchema &geometrySchema) { value = Json::objectValue; value["geometryType"] = asString(geometrySchema.geometryType); value["topology"] = asString(geometrySchema.topology); build(value["header"], geometrySchema.header); if (!geometrySchema.vertexAttributes.empty()) { build(value["vertexAttributes"], value["ordering"] , geometrySchema.vertexAttributes); } if (!geometrySchema.faces.empty()) { build(value["faces"], geometrySchema.faces); } if (!geometrySchema.featureAttributes.empty()) { build(value["featureAttributes"], value["featureAttributeOrder"] , geometrySchema.featureAttributes); } } void build(Json::Value &value, const Store &store, const Metadata &metadata) { value = Json::objectValue; value["id"] = store.id; value["profile"] = asString(store.profile); build(value["resourcePattern"], store.resourcePattern); value["rootNode"] = store.rootNode; value["version"] = store.version; build(value["extent"], store.extents); value["normalReferenceFrame"] = asString(store.normalReferenceFrame); { const auto gzipped (metadata.resourceCompressionType == ResourceCompressionType::gzip); std::string jsonEncoding (str(boost::format ("application/vnd.esri.I3S.json%s; version=%d.%d") % (gzipped ? "+gzip" : "") % metadata.version.major % metadata.version.minor)); value["nidEncoding"] = jsonEncoding; value["featureEncoding"] = jsonEncoding; value["geometryEncoding"] = jsonEncoding; } build(value["textureEncoding"], store.textureEncoding); value["lodType"] = asString(store.lodType); value["lodModel"] = asString(store.lodModel); build(value["indexingScheme"], store.indexingScheme); if (store.defaultGeometrySchema) { build(value["defaultGeometrySchema"], *store.defaultGeometrySchema); } } void build(Json::Value &value, const Version &version) { value = utility::format("%d.%d", version.major, version.minor); } void build(Json::Value &value, const SceneLayerInfo &sli , const Metadata &metadata) { value = Json::objectValue; value["id"] = sli.id; value["layerType"] = asString(sli.layerType); value["href"] = sli.href; value["name"] = sli.name; if (sli.alias) { value["alias"] = *sli.alias; } if (sli.description) { value["description"] = *sli.description; } if (sli.copyrightText) { value["copyrightText"] = *sli.copyrightText; } build(value["capabilities"], sli.capabilities); build(value["spatialReference"], sli.spatialReference); build(value["heightModelInfo"], sli.heightModelInfo); if (sli.store) { auto &store(value["store"]); build(store, *sli.store, metadata); auto crs(str(boost::format("http://www.opengis.net/def/crs/EPSG/0/%d") % sli.spatialReference.wkid)); store["indexCRS"] = crs; store["vertexCRS"] = crs; build(store["version"], metadata.version); } } void build(Json::Value &value, const Metadata &metadata) { value = Json::objectValue; value["folderPattern"] = asString(metadata.folderPattern); value["ArchiveCompressionType"] = asString(metadata.archiveCompressionType); value["ResourceCompressionType"] = asString(metadata.resourceCompressionType); build(value["I3SVersion"], metadata.version); value["nodeCount"] = Json::UInt64(metadata.nodeCount); } void build(Json::Value &value, const MinimumBoundingSphere &mbs) { value = Json::arrayValue; value.append(mbs.center(0)); value.append(mbs.center(1)); value.append(mbs.center(2)); value.append(mbs.r); } void build(Json::Value &value, const NodeReference &nodeReference) { value = Json::objectValue; value["id"] = nodeReference.id; build(value["mbs"], nodeReference.mbs); value["href"] = nodeReference.href; if (!nodeReference.version.empty()) { value["version"] = nodeReference.version; } if (nodeReference.featureCount) { value["featureCount"] = nodeReference.featureCount; } } void build(Json::Value &value, const Resource &resource) { value = Json::objectValue; value["href"] = resource.href; // TODO: rest } void build(Json::Value &value, const LodSelection &lodSelection) { value = Json::objectValue; value["metricType"] = asString(lodSelection.metricType); if (lodSelection.maxValue) { value["maxValue"] = lodSelection.maxValue; } if (lodSelection.avgValue) { value["avgValue"] = lodSelection.avgValue; } if (lodSelection.minValue) { value["minValue"] = lodSelection.minValue; } if (lodSelection.maxError) { value["maxError"] = lodSelection.maxError; } } void build(Json::Value &value, const Node &node , bool standardSharedResource = false) { value = Json::objectValue; value["id"] = node.id; value["level"] = node.level; if (!node.version.empty()) { value["version"] = node.version; } build(value["mbs"], node.mbs); if (node.parentNode) { build(value["parentNode"], *node.parentNode); } if (!node.children.empty()) { build(value["children"], node.children); } if (!node.neighbors.empty()) { build(value["neighbors"], node.neighbors); } if (node.sharedResource) { build(value["sharedResource"], *node.sharedResource); } else if (standardSharedResource) { build(value["sharedResource"], Resource("./shared")); } if (!node.featureData.empty()) { build(value["featureData"], node.featureData); } if (!node.geometryData.empty()) { build(value["geometryData"], node.geometryData); } if (!node.textureData.empty()) { build(value["textureData"], node.textureData); } if (!node.lodSelection.empty()) { build(value["lodSelection"], node.lodSelection); } } void build(Json::Value &value, const Color &color) { value = Json::arrayValue; value.append(color[0]); value.append(color[1]); value.append(color[2]); } void build(Json::Value &value, const Material &material) { value = Json::objectValue; value["name"] = material.name; value["type"] = asString(material.type); if (!material.ref.empty()) { value["$ref"] = material.ref; } auto &params(value["params"] = Json::objectValue); params["vertexRegions"] = material.params.vertexRegions; params["vertexColors"] = material.params.vertexColors; params["useVertexColorAlpha"] = material.params.useVertexColorAlpha; params["transparency"] = material.params.transparency; params["reflectivity"] = material.params.reflectivity; params["shininess"] = material.params.shininess; build(params["ambient"], material.params.ambient); build(params["difuse"], material.params.difuse); build(params["specular"], material.params.specular); params["renderMode"] = asString(material.params.renderMode); params["castShadows"] = material.params.castShadows; params["receiveShadows"] = material.params.receiveShadows; params["cullFace"] = asString(material.params.cullFace); } void build(Json::Value &value, const Image &image) { value = Json::objectValue; value["id"] = image.id; value["size"] = Json::UInt64(image.size); value["pixelInWorldUnits"] = image.pixelInWorldUnits; auto &href(value["href"] = Json::arrayValue); auto &byteOffset(value["byteOffset"] = Json::arrayValue); auto &length(value["length"] = Json::arrayValue); for (const auto &version : image.versions) { href.append(version.href); byteOffset.append(Json::UInt64(version.byteOffset)); length.append(Json::UInt64(version.length)); } } void build(Json::Value &value, const Texture &texture) { value = Json::objectValue; auto &encoding(value["encoding"] = Json::arrayValue); for (const auto &e : texture.encoding) { encoding.append(e.mime); } auto &wrap(value["wrap"] = Json::arrayValue); wrap.append(asString(texture.wrap[0])); wrap.append(asString(texture.wrap[1])); value["atlas"] = texture.atlas; value["uvSet"] = texture.uvSet; value["channels"] = texture.channels; auto &images(value["images"] = Json::arrayValue); for (const auto &image : texture.images) { build(images.append({}), image); } } void build(Json::Value &value, const SharedResource &sr) { if (!sr.materialDefinitions.empty()) { auto &md(value["materialDefinitions"] = Json::objectValue); for (const auto &materialDefinition : sr.materialDefinitions) { build(md[materialDefinition.key], materialDefinition); } } if (!sr.textureDefinitions.empty()) { auto &md(value["textureDefinitions"] = Json::objectValue); for (const auto &textureDefinition : sr.textureDefinitions) { build(md[textureDefinition.key], textureDefinition); } } } void build(Json::Value &value, const GeometryReference &geometry) { value = Json::objectValue; value["type"] = asString(GeometryClass::GeometryReference); value["$ref"] = geometry.ref; build(value["faceRange"], geometry.faceRange); value["lodGeometry"] = geometry.lodGeometry; } void build(Json::Value &value, GeometryReference::list &geometries) { value = Json::arrayValue; for (const auto geometry : geometries) { build(value.append({}), geometry); } } void build(Json::Value &value, const FeatureData::Feature &feature) { value = Json::objectValue; value["id"] = feature.id; build(value["position"], feature.position); build(value["pivotOffset"], feature.pivotOffset); build(value["mbb"], feature.mbb); value["layer"] = feature.layer; build(value["geometries"], feature.geometries); } void build(Json::Value &value, const ArrayBufferView &geometry) { value = Json::objectValue; value["type"] = asString(GeometryClass::ArrayBufferView); value["id"] = geometry.id; build(value["transformation"], geometry.transformation); auto &params(value["params"]); params["type"] = asString(geometry.type); params["topology"] = asString(geometry.topology); params["material"] = geometry.material; params["texture"] = geometry.texture; if (!geometry.vertexAttributes.empty()) { build(params["vertexAttributes"], geometry.vertexAttributes); } if (!geometry.faces.empty()) { build(params["faces"], geometry.faces); } } void build(Json::Value &value, const FeatureData::Feature::list &features) { value = Json::arrayValue; for (const auto feature : features) { build(value.append({}), feature); } } void build(Json::Value &value, const ArrayBufferView::list &geometries) { value = Json::arrayValue; for (const auto geometry : geometries) { build(value.append({}), geometry); } } void build(Json::Value &value, const FeatureData &fd) { value = Json::objectValue; build(value["featureData"], fd.featureData); build(value["geometryData"], fd.geometryData); } // implementation must be here to see other build functions template <typename T> void build(Json::Value &value, const std::vector<T> &array) { value = Json::arrayValue; for (const auto &item : array) { build(value.append({}), item); } } template <typename T1, typename T2> void build(Json::Value &value, const std::tuple<T1, T2> &tupple) { build(value, std::get<0>(tupple), std::get<1>(tupple)); } template <typename T> void write(std::ostream &out, DataType type, const T &value) { #define WRITE_DATATYPE(ENUM, TYPE) \ case DataType::ENUM: bin::write(out, TYPE(value)); return switch (type) { WRITE_DATATYPE(uint8, std::uint8_t); WRITE_DATATYPE(uint16, std::uint16_t); WRITE_DATATYPE(uint32, std::uint32_t); WRITE_DATATYPE(uint64, std::uint64_t); WRITE_DATATYPE(int8, std::int8_t); WRITE_DATATYPE(int16, std::int16_t); WRITE_DATATYPE(int32, std::int32_t); WRITE_DATATYPE(int64, std::int64_t); WRITE_DATATYPE(float32, float); WRITE_DATATYPE(float64, double); } #undef WRITE_DATATYPE LOGTHROW(err1, std::logic_error) << "Invalid datatype (int code=" << static_cast<int>(type) << ")."; throw; } void write(std::ostream &out, const GeometryAttribute &ga , const math::Point3 &p) { write(out, ga.valueType, p(0)); write(out, ga.valueType, p(1)); write(out, ga.valueType, p(2)); } void write(std::ostream &out, const GeometryAttribute &ga , const math::Point2 &p) { write(out, ga.valueType, p(0)); write(out, ga.valueType, p(1)); } class SavePerAttributeArray { public: SavePerAttributeArray(std::ostream &os, const Node &node , const MeshSaver &meshSaver , const GeometrySchema &gs , FeatureData::Feature &feature , ArrayBufferView &arrayBufferView) : os_(os), node_(node), meshSaver_(meshSaver), gs_(gs) , feature_(feature), arrayBufferView_(arrayBufferView) , properties_(meshSaver_.properties()) , vertexCount_(3 * properties_.faceCount) { // store array buffer view info arrayBufferView_.type = gs.geometryType; arrayBufferView_.topology = gs.topology; // save header for (const auto &header : gs_.header) { if (header.property == "vertexCount") { // vertex count write(os, header.type, vertexCount_); } else if (header.property == "featureCount") { // feature count: whole mesh is a single feature write(os, header.type, 1); } else { LOGTHROW(err2, std::runtime_error) << "Header element <" << header.property << "> not supported."; } } // save mesh data for (const auto &ga : gs_.vertexAttributes) { if (ga.key == "position") { auto &oga(utility::append (arrayBufferView_.vertexAttributes, ga)); oga.byteOffset = os.tellp(); oga.count = vertexCount_; saveFaces(ga); } else if (ga.key == "uv0") { auto &oga(utility::append (arrayBufferView_.vertexAttributes, ga)); oga.byteOffset = os.tellp(); oga.count = vertexCount_; saveFacesTc(ga); } else { LOGTHROW(err2, std::runtime_error) << "Geometry attribute <" << ga.key << "> not supported."; } } // save features for (const auto &fa : gs_.featureAttributes) { if (fa.key == "id") { if (fa.valuesPerElement != 1) { LOGTHROW(err1, std::runtime_error) << "Number of feaure.id elements must be 1 not " << fa.valuesPerElement << "."; } // ID = 0 write(os, fa.valueType, 0); } else if (fa.key == "faceRange") { if (fa.valuesPerElement != 2) { LOGTHROW(err1, std::runtime_error) << "Number of feaure.faceRanage elements must be " "2 not " << fa.valuesPerElement << "."; } // whole mesh; doc says inclusive range -> faceCount - 1 write(os, fa.valueType, 0); write(os, fa.valueType, (properties_.faceCount - 1)); } else { LOGTHROW(err2, std::runtime_error) << "Feature attribute <" << fa.key << "> not supported."; } } auto &geometry(utility::append(feature_.geometries)); geometry.ref = "/geometryData/1"; geometry.faceRange.min = 0; geometry.faceRange.max = (properties_.faceCount - 1); geometry.lodGeometry = true; } private: void saveFaces(const GeometryAttribute &ga) { if (ga.valuesPerElement != 3) { LOGTHROW(err1, std::runtime_error) << "Number of vertex elements must be 3 not " << ga.valuesPerElement << "."; } feature_.mbb = math::Extents3(math::InvalidExtents{}); for (std::size_t i(0), e(properties_.faceCount); i != e; ++i) { const auto &face(meshSaver_.face(i)); for (const auto &point : face) { // update mesh extents math::update(feature_.mbb, point); // write localized point write(os_, ga, math::Point3(point - node_.mbs.center)); } } } void saveFacesTc(const GeometryAttribute &ga) { if (ga.valuesPerElement != 2) { LOGTHROW(err1, std::runtime_error) << "Number of UV elements must be 2 not " << ga.valuesPerElement << "."; } for (std::size_t i(0), e(properties_.faceCount); i != e; ++i) { const auto &face(meshSaver_.faceTc(i)); for (const auto &point : face) { write(os_, ga, point); } } } std::ostream &os_; const Node &node_; const MeshSaver &meshSaver_; const GeometrySchema &gs_; FeatureData::Feature &feature_; ArrayBufferView &arrayBufferView_; const MeshSaver::Properties properties_; std::size_t vertexCount_; }; void saveMesh(std::ostream &os, const Node &node , const MeshSaver &meshSaver , const GeometrySchema &gs , FeatureData::Feature &feature , ArrayBufferView &arrayBufferView) { switch (gs.topology) { case Topology::perAttributeArray: SavePerAttributeArray(os, node, meshSaver, gs , feature, arrayBufferView); return; default: LOGTHROW(err2, std::runtime_error) << "Unsupported geomety topology " << gs.topology << "."; } throw; } const GeometrySchema& getGeometrySchema(const SceneLayerInfo &sli) { if (!sli.store || !sli.store->defaultGeometrySchema) { LOGTHROW(err2, std::runtime_error) << "No default geometry schema present."; } const auto &gs(*sli.store->defaultGeometrySchema); if (gs.geometryType != GeometryType::triangles) { LOGTHROW(err2, std::runtime_error) << "Cannot store nothing else then trianges geometries."; } if (gs.topology != Topology::perAttributeArray) { LOGTHROW(err2, std::runtime_error) << "Cannot store nothing else then PerAttributeArray geometries."; } return gs; } } // namespace struct Writer::Detail { Detail(const boost::filesystem::path &path , const Metadata &metadata, const SceneLayerInfo &sli , bool overwrite) : sli(sli), gs(getGeometrySchema(this->sli)), zip(path, overwrite) , metadata(metadata), nodeCount(), textureCount() {} void flush(const SceneLayerInfoCallback &callback); utility::zip::Writer::OStream::pointer ostream(const fs::path &path, bool raw = false); void write(Node &node, SharedResource &sharedResource , const MeshSaver &meshSaver , const TextureSaver &textureSaver); template <typename T> void store(const T &value, const fs::path &path, bool raw = false); SceneLayerInfo sli; const GeometrySchema &gs; utility::zip::Writer zip; std::mutex mutex; Metadata metadata; std::atomic<std::size_t> nodeCount; std::atomic<std::size_t> textureCount; }; template <typename T> void Writer::Detail::store(const T &value, const fs::path &path, bool raw) { Json::Value jValue; build(jValue, value); std::unique_lock<std::mutex> lock(mutex); auto os(ostream( path, raw)); Json::write(os->get(), jValue, false); os->close(); } void Writer::Detail::flush(const SceneLayerInfoCallback &callback) { // update and store scene layer if (callback) { callback(sli); } store(std::make_tuple(std::cref(sli), std::cref(metadata)) , detail::constants::SceneLayer); // update and save metadata metadata.nodeCount = nodeCount; store(metadata, detail::constants::MetadataName, true); // done zip.close(); } utility::zip::Writer::OStream::pointer Writer::Detail::ostream(const fs::path &path, bool raw) { const utility::zip::Compression compression ((!raw && (metadata.archiveCompressionType != ArchiveCompressionType::store)) ? utility::zip::Compression::deflate : utility::zip::Compression::store); if (!raw && (metadata.resourceCompressionType == ResourceCompressionType::gzip)) { // add .gz extension and push gzip compressor at the top of this // filter stack return zip.ostream(utility::addExtension (path, detail::constants::ext::gz) , compression , [](bio::filtering_ostream &fos) { bio::zlib_params p; p.window_bits |= 16; fos.push(bio::zlib_compressor(p)); }); } return zip.ostream(path, compression); } std::uint64_t buildId(std::uint64_t id, const math::Size2 &size , unsigned int l, unsigned int al) { std::uint64_t l_al(std::uint64_t(al) << 60); std::uint64_t l_l(std::uint64_t(l) << 56); std::uint64_t l_w (std::uint64_t(size.width - 1) << 44); std::uint64_t l_h(std::uint64_t(size.height - 1) << 32); return l_al + l_l + l_w + l_h + std::uint64_t(id); } void Writer::Detail::write(Node &node, SharedResource &sharedResource , const MeshSaver &meshSaver , const TextureSaver &textureSaver) { if (sharedResource.materialDefinitions.empty()) { LOGTHROW(err2, std::runtime_error) << "No material defined in shared resource."; } auto &textures(sharedResource.textureDefinitions); if (!textures.empty()) { LOGTHROW(err2, std::runtime_error) << "Multi texture bundle not supported."; } const auto txId(textureCount++); // add texture textures.emplace_back(utility::format("tex%d", txId)); auto &texture(textures.back()); // setup texture texture.atlas = true; texture.uvSet = "uv0"; texture.channels = "rgb"; auto &image(utility::append(texture.images)); const auto imageSize(textureSaver.imageSize()); image.size = imageSize.width; // TODO: what are these levels? image.id = asString(buildId(txId, imageSize, 0, 0)); const auto index(node.geometryData.size()); // write textures int txi(0); for (const auto &encoding : sli.store->textureEncoding) { // node const auto href (utility::format("textures/0_%d", txi++)); auto &td(utility::append(node.textureData, "./" + href)); td.multiTextureBundle = false; // texture texture.encoding.push_back(encoding); auto &imageVersion(utility::append(image.versions, "../" + href)); const fs::path texturePath (detail::constants::Nodes / node.id / (href + ".bin")); std::unique_lock<std::mutex> lock(mutex); // TODO: do not report DDS as raw (if ever used) auto os(ostream(texturePath, true)); textureSaver.save(os->get(), encoding.mime); const auto stat(os->close()); imageVersion.length = stat.uncompressedSize; } // write meshes and features const auto mhref(utility::format("geometries/%d", index)); node.geometryData.emplace_back("./" + mhref); const fs::path geometryPath (detail::constants::Nodes / node.id / (mhref + ".bin")); const auto fhref(utility::format("features/%d", index)); node.featureData.emplace_back("./" + fhref); const fs::path featurePath (detail::constants::Nodes / node.id / (fhref + ".json")); // save mesh to temporary stream std::stringstream tmp; // feature stuff FeatureData featureData; { auto &fd(utility::append(featureData.featureData, 0)); fd.position = node.mbs.center; fd.layer = "3D model"; auto &gd(utility::append(featureData.geometryData, 0)); // only per-attribute array geometry type saveMesh(tmp, node, meshSaver, gs, fd, gd); // store references to material and textures gd.material = ("/materialDefinitions/" + sharedResource.materialDefinitions.back().key); gd.texture = "/textureDefinitions/" + texture.key; } { std::unique_lock<std::mutex> lock(mutex); auto os(ostream(geometryPath)); os->get() << tmp.rdbuf(); os->close(); } // store feature data store(featureData, featurePath); } Writer::Writer(const boost::filesystem::path &path , const Metadata &metadata, const SceneLayerInfo &sli , bool overwrite) : detail_(std::make_shared<Detail>(path, metadata, sli, overwrite)) {} void Writer::write(const Node &node, const SharedResource *sharedResource) { const auto dir(detail::constants::Nodes / node.id); detail_->store(std::make_tuple(std::cref(node), bool(sharedResource)) , dir / detail::constants::NodeIndex); if (sharedResource) { detail_->store(*sharedResource , (dir / detail::constants::Shared / detail::constants::SharedResource)); } ++detail_->nodeCount; } void Writer::write(Node &node, SharedResource &sharedResource , const MeshSaver &meshSaver , const TextureSaver &textureSaver) { return detail_->write(node, sharedResource, meshSaver, textureSaver); } void Writer::flush(const SceneLayerInfoCallback &callback) { detail_->flush(callback); } } // namespace slpk <file_sep>/** * Copyright (c) 2017 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <set> #include <boost/optional.hpp> #include <boost/utility/in_place_factory.hpp> #include <opencv2/highgui/highgui.hpp> #include "utility/buildsys.hpp" #include "utility/gccversion.hpp" #include "utility/limits.hpp" #include "utility/path.hpp" #include "utility/openmp.hpp" #include "service/cmdline.hpp" #include "geometry/meshop.hpp" #include "imgproc/readimage.cpp" #include "imgproc/texturing.cpp" #include "geo/csconvertor.hpp" #include "slpk/reader.hpp" namespace po = boost::program_options; namespace bio = boost::iostreams; namespace fs = boost::filesystem; namespace ublas = boost::numeric::ublas; namespace { typedef std::vector<std::string> NodeIdList; typedef std::set<std::string> NodeIdSet; bool notPicked(const std::string &nodeId , const boost::optional<NodeIdSet> &picked) { if (!picked) { return false; } return (picked->find(nodeId) == picked->end()); } class Slpk2Obj : public service::Cmdline { public: Slpk2Obj() : service::Cmdline("slpk2obj", BUILD_TARGET_VERSION) , overwrite_(false), srs_(3857) {} private: virtual void configuration(po::options_description &cmdline , po::options_description &config , po::positional_options_description &pd) UTILITY_OVERRIDE; virtual void configure(const po::variables_map &vars) UTILITY_OVERRIDE; virtual bool help(std::ostream &out, const std::string &what) const UTILITY_OVERRIDE; virtual int run() UTILITY_OVERRIDE; fs::path output_; fs::path input_; bool overwrite_; geo::SrsDefinition srs_; boost::optional<NodeIdSet> nodes_; }; void Slpk2Obj::configuration(po::options_description &cmdline , po::options_description &config , po::positional_options_description &pd) { cmdline.add_options() ("output", po::value(&output_)->required() , "Path to output converted input.") ("input", po::value(&input_)->required() , "Path to input SLPK archive.") ("overwrite", "Generate output even if output directory exists.") ("srs", po::value(&srs_)->default_value(srs_)->required() , "Destination SRS of converted meshes.") ("nodes", po::value<NodeIdList>() , "Limit output to listed nodes.") ; pd .add("input", 1) .add("output", 1) .add("nodes", -1); (void) config; } void Slpk2Obj::configure(const po::variables_map &vars) { overwrite_ = vars.count("overwrite"); if (vars.count("nodes")) { const auto &raw(vars["nodes"].as<NodeIdList>()); nodes_ = boost::in_place(raw.begin(), raw.end()); } } bool Slpk2Obj::help(std::ostream &out, const std::string &what) const { if (what.empty()) { out << R"RAW(slpk2obj Converts SLPK archive into textured meshes in OBJ format. usage slpk2obj INPUT OUTPUT [OPTIONS] )RAW"; } return false; } void writeMtl(const fs::path &path, const std::string &name) { LOG(info1) << "Writing " << path; std::ofstream f(path.string()); f << "newmtl 0\n" << "map_Kd " << name << "\n"; } class DeepCopyCsCovertor { public: DeepCopyCsCovertor(geo::SrsDefinition src, geo::SrsDefinition dst) : src_(src), dst_(dst), conv_(src_, dst_) {} DeepCopyCsCovertor(const DeepCopyCsCovertor &c) : src_(c.src_), dst_(c.dst_), conv_(src_, dst_) {} DeepCopyCsCovertor& operator=(const DeepCopyCsCovertor &c) { src_ = c.src_; dst_ = c.dst_; conv_ = geo::CsConvertor(src_, dst_); return *this; } operator const geo::CsConvertor&() const { return conv_; } template <typename T> T operator()(const T &p) const { return conv_(p); } private: geo::SrsDefinition src_; geo::SrsDefinition dst_; geo::CsConvertor conv_; }; /** Loads SLPK geometry as a list of submeshes. */ class MeasureMesh : public slpk::GeometryLoader , public slpk::MeshLoader { public: MeasureMesh(const geo::CsConvertor &conv, math::Extents2 &extents) : conv_(conv), extents_(extents) {} virtual slpk::MeshLoader& next() { return *this; } virtual void addVertex(const math::Point3d &v) { math::update(extents_, conv_(v)); } private: virtual void addTexture(const math::Point2d&) {} virtual void addFace(const Face&, const FaceTc&, const Face&) {} virtual void addNormal(const math::Point3d&) {} virtual void addTxRegion(const Region&) {} const geo::CsConvertor &conv_; math::Extents2 &extents_; }; math::Extents2 measureMesh(const slpk::Tree &tree , const slpk::Archive &input , DeepCopyCsCovertor conv , const boost::optional<NodeIdSet> &pickedNodes) { // find topLevel auto topLevel(std::numeric_limits<int>::max()); for (const auto item : tree.nodes) { if (notPicked(item.first, pickedNodes)) { continue; } const auto &node(item.second.node); if (node.hasGeometry()) { topLevel = std::min(topLevel, node.level); } } // collect nodes for OpenMP std::vector<const slpk::TreeNode*> treeNodes; for (const auto &item : tree.nodes) { if (notPicked(item.first, pickedNodes)) { continue; } const auto &node(item.second.node); if ((node.level == topLevel) && (node.hasGeometry())) { treeNodes.push_back(&item.second); } } math::Extents2 extents(math::InvalidExtents{}); UTILITY_OMP(parallel for firstprivate(conv), shared(extents, treeNodes)) for (std::size_t i = 0; i < treeNodes.size(); ++i) { const auto &treeNode(*treeNodes[i]); const auto &node(treeNode.node); // load geometry math::Extents2 e(math::InvalidExtents{}); MeasureMesh loader(conv, e); input.loadGeometry(loader, node, treeNode.sharedResource); UTILITY_OMP(critical(slpk2obj_measureMesh)) { math::update(extents, e.ll); math::update(extents, e.ur); } } return extents; } cv::Mat stream2mat(const roarchive::IStream::pointer &txStream) { const auto buf(txStream->read()); const auto image(cv::imdecode(buf, CV_LOAD_IMAGE_COLOR)); if (!image.data) { LOGTHROW(err1, std::runtime_error) << "Cannot decode image from " << txStream->path() << "."; } return image; } inline math::Extents2 remap(const math::Size2 &size , const slpk::Region &region) { return { size.width * region.ll(0), size.height * region.ll(1) , size.width * region.ur(0), size.height * region.ur(1) }; } inline math::Point2d& denormalize(const math::Size2f &rsize, math::Point2d &tc) { tc(0) *= rsize.width; tc(1) = (1.0 - tc(1)) * rsize.height; return tc; } void rebuild(slpk::SubMesh &submesh , const roarchive::IStream::pointer &txStream , const fs::path &texPath) { const auto tx(stream2mat(txStream)); const math::Size2 txSize(tx.cols, tx.rows); auto &mesh(submesh.mesh); std::vector<math::Extents2> regions; imgproc::tx::Patch::Rect::list uvRects; for (auto &region : submesh.regions) { regions.push_back(remap(txSize, region)); uvRects.emplace_back(imgproc::tx::UvPatch(regions.back())); } // UV patch per region imgproc::tx::UvPatch::list uvPatches(submesh.regions.size()); // create expanded patches std::vector<std::uint8_t> seen(mesh.tCoords.size(), false); const auto expand([&](imgproc::tx::UvPatch &uvPatch , const math::Size2f &rsize, int index) { // skip mapped tc auto &iseen(seen[index]); if (iseen) { return; } uvPatch.update(denormalize(rsize, mesh.tCoords[index])); iseen = true; }); for (const auto &face : mesh.faces) { const auto &region(regions[face.imageId]); const auto &rsize(math::size(region)); auto &uvPatch(uvPatches[face.imageId]); expand(uvPatch, rsize, face.ta); expand(uvPatch, rsize, face.tb); expand(uvPatch, rsize, face.tc); } std::vector<imgproc::tx::Patch> patches(uvPatches.begin(), uvPatches.end()); const auto size(imgproc::tx::pack(patches.begin(), patches.end())); // map texture coordinates to new texture seen.assign(mesh.tCoords.size(), false); const auto map([&](const imgproc::tx::Patch &patch, int index) -> void { // skip mapped tc auto &iseen(seen[index]); if (iseen) { return; } auto &tc(mesh.tCoords[index]); // map patch.map({}, tc); // and normalize back again tc(0) /= size.width; tc(1) /= size.height; tc(1) = 1.0 - tc(1); iseen = true; }); for (auto &face : mesh.faces) { auto &patch(patches[face.imageId]); map(patch, face.ta); map(patch, face.tb); map(patch, face.tc); // reset image ID face.imageId = 0; } // generate new texture cv::Mat_<cv::Vec3b> otx(size.height, size.width, cv::Vec3b()); const auto wrap([&](int pos, int origin, int size) -> int { auto mod(pos % size); if (mod < 0) { mod += size; } return origin + mod; }); auto iuvRects(uvRects.begin()); for (const auto &patch : patches) { const auto &uvRect(*iuvRects++); const auto &dstRect(patch.dst()); const auto &srcRect(patch.src()); const math::Point2i diff(uvRect.point - srcRect.point); // copy data for (int j(0), je(dstRect.size.height); j != je; ++j) { const auto jsrc(wrap(j - diff(1), uvRect.point(1) , uvRect.size.height)); if ((jsrc < 0) || (jsrc >= txSize.height)) { continue; } for (int i(0), ie(dstRect.size.width); i != ie; ++i) { const auto isrc(wrap(i - diff(0), uvRect.point(0) , uvRect.size.width)); if ((isrc < 0) || (isrc >= txSize.width)) { continue; } otx(dstRect.point(1) + j, dstRect.point(0) + i) = tx.at<cv::Vec3b>(jsrc, isrc); } } } cv::imwrite(texPath.string(), otx , { cv::IMWRITE_JPEG_QUALITY, 85 , cv::IMWRITE_PNG_COMPRESSION, 9 }); } void write(const slpk::Archive &input, fs::path &output , const geo::SrsDefinition &srs , const boost::optional<NodeIdSet> &pickedNodes) { DeepCopyCsCovertor conv (input.sceneLayerInfo().spatialReference.srs(), srs); const auto tree(input.loadTree()); // find extents in destination SRS to localize mesh const auto extents(measureMesh(tree, input, conv, pickedNodes)); const auto center(math::center(extents)); // collect nodes for OpenMP std::vector<const slpk::TreeNode*> treeNodes; for (const auto &item : tree.nodes) { if (notPicked(item.first, pickedNodes)) { continue; } treeNodes.push_back(&item.second); } UTILITY_OMP(parallel for firstprivate(conv), shared(treeNodes, center)) for (std::size_t i = 0; i < treeNodes.size(); ++i) { const auto &treeNode(*treeNodes[i]); const auto &node(treeNode.node); LOG(info3) << "Converting <" << node.id << ">."; auto geometry(input.loadGeometry(node, treeNode.sharedResource)); auto igd(node.geometryData.begin()); int meshIndex(0); for (auto &submesh : geometry.submeshes) { auto &mesh(submesh.mesh); for (auto &v : mesh.vertices) { v = conv(v); v(0) -= center(0); v(1) -= center(1); } const fs::path path(output / (*igd++).href); const auto meshPath(utility::addExtension(path, ".obj")); create_directories(meshPath.parent_path()); auto texture(input.texture(node, meshIndex)); // detect extension const auto mtlPath(utility::addExtension(path, ".mtl")); fs::path texPath; if (submesh.regions.empty()) { // copy texture as-is texPath = utility::addExtension (path, imgproc::imageType (*texture, texture->path())); copy(texture, texPath); } else { // texture atlas, need to repack/unpack texture texPath = utility::addExtension(path, ".jpg"); rebuild(submesh, texture, texPath); } { // save mesh utility::ofstreambuf os(meshPath.string()); os.precision(12); saveAsObj(mesh, os, mtlPath.filename().string()); os.flush(); } writeMtl(mtlPath, texPath.filename().string()); ++meshIndex; } } } int Slpk2Obj::run() { LOG(info4) << "Opening SLPK archive at " << input_ << "."; slpk::Archive archive(input_); LOG(info4) << "Generating textured meshes at " << output_ << "."; write(archive, output_, srs_, nodes_); return EXIT_SUCCESS; } } // namespace int main(int argc, char *argv[]) { utility::unlimitedCoredump(); return Slpk2Obj()(argc, argv); }
2e59cd1178735d6d09042e330cc096a3d204d3a1
[ "C++" ]
2
C++
Chirag19/libslpk
0958fc51ea5d99235cefe45fe082e409adb47501
ffe4d5795595029fd5c098c14dcbcfa07216b852
refs/heads/master
<file_sep>package Vehicle; public class Car extends Vehicle{ public Car (int id, String type) { this.name = "Car"; this.id = id; this.type = type; this.moveMethod = "drive"; this.noofDoors = 4; } } <file_sep>package Vehicle; import java.util.ArrayList; public class Garage { public ArrayList<Vehicle> vehicleList = new ArrayList<>(); public double bill; public void addList (Vehicle c) { vehicleList.add(c); } public void removeList(int id, String type) { if(vehicleList.size()>0) { for(int count = 0; count< vehicleList.size(); count++) { if(vehicleList.get(count).id == id && vehicleList.get(count).type.equals(type)) { vehicleList.remove(count); } } } } public double billCal(Vehicle c) { if(c.type.equals("Car")) { bill = 200000; } else if(c.type.equals("Motorcycle") ) { bill = 100000; } else if(c.type.equals("Airplane")) { bill = 20000000; } return bill; } public void empty() { vehicleList.removeAll(vehicleList); } }
e1859d3cc491444e5ad61dc93123898fa2199993
[ "Java" ]
2
Java
Tolu12343/GarageTestProject
b2069326832078cbbf11f8398ad0fbbebcb7b9e5
ca769f8304d96ba63407b7021e88118075b576b5
refs/heads/master
<file_sep>__author__ = 'gazelle' print '<NAME>' print 'supriya' print '300 \t terrace avenue\n jersey city nj' a = 1 b = 2 print a + b print a * b truebool = True c = False print truebool print c
1e15dd3487458d92f4a4b0ce41ae3b7fad8b3ddd
[ "Python" ]
1
Python
supriyanarlawar/PythonProject
fccf068501b1f4f3f97c1aad8881b3083012377b
a7e21a8764763139a964955ebe1dd47da58ef374
refs/heads/master
<repo_name>ColorfulCodes/Coding-Challenges-Python<file_sep>/thegame.py #The game:feed each challenges into a variable then initiate Random #include skip option. Place every 5 in batches. Have option to select batch. import random, os from time import sleep reverse = "Write a method that will take a string as input, and return a new string with the same letters in reverse order.\n" reverse2 = "Reverse string input with recursion\n" factorial = "Write a method that takes an integer `n` in; it should return n*(n-1)*(n-2)*...*2*1. Assume n >= 0.\n" longest_word = ''' Write a method that takes in a string. Return the longest word in the string. You may assume that the string contains only letters and spaces. You may use the String `split` method to aid you in your quest.\n''' sum_nums = """Write a method that takes in an integer `num` and returns the sum of all integers between zero and num, up to and including `num`. Two ways! Thanks Stack Overflow\n""" time = """Write a method that will take in a number of minutes, and returns a string that formats the number into `hours:minutes`.\n""" vowels = """Write a method that takes a string and returns the number of vowels in the string. You may assume that all the letters are lower cased.""" nearby_az = """Write a method that takes a string and returns true if it is a palindrome. A palindrome is a string that is the same whether written backward or forward. Assume that there are no spaces; only lowercase letters will be given.""" palindrome = """Write a method that takes a string in and returns true if the letter "z" appears within three letters **after** an "a". You may assume that the string contains only lowercase letters.""" sum_list = """Define a procedure, sum_list, that takes as its input a list of numbers, and returns the sum of all the elements in the input list.""" position = """Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return None.""" divisible = """Write a method that takes in a number and returns true if it is a power of 2. Otherwise, return false. You may want to use the `%` modulo operation. `5 % 2` returns the remainder when dividing 5 by 2; therefore, `5 % 2 == 1`. In the case of `6 % 2`, since 2 evenly divides 6 with no remainder, `6 % 2 == 0`.""" evenorodd = """Create a function that takes an array and separates numbers that are odd and #those that are even.""" third_greatest = """Write a method that takes an array of numbers in. Your method should # return the third greatest number in the array. You may assume that # the array has at least three numbers in it.""" duplicate = """Write a method that takes in a string. Your method should return the most common letter in the string, and a count of how many times it appears. Then iterate a list after.""" dashes = """Write a method that takes in a number and returns a string, placing a single dash before and after each odd digit. There is one exception: don't start or end the string with a dash.""" capitalize = """Write a method that takes in a string of lowercase letters and spaces, producing a new string that capitalizes the first letter of each word. You'll want to use the `split` and `join` methods. Also, the String method `upcase`, which converts a string to all upper case will be helpful.""" uhh = """ Write a method that takes in a string and an array of indices in the # string. Produce a new string, which contains letters from the input # string in the order specified by the indices of the array of indices. """ prime = """ Write a method that takes in an integer (greater than one) and returns true if it is prime; otherwise return false.""" nth_prime = """ Write a method that returns the `n`th prime number. Recall that only # numbers greater than 1 can be prime. No positive dividers other than #one and itself""" bprime = """List all prime numbers between this and this.""" # most common sites people visit, average person's day batch1 = [reverse, reverse2, factorial, longest_word, sum_nums, time, vowels] batch2 = [palindrome, nearby_az, sum_list, position, divisible, evenorodd, third_greatest] batch3 = [duplicate, dashes, capitalize, uhh, prime, nth_prime, bprime] def answer(): print "\n" answer = raw_input("Great Choice! When finished type 'n' to move to next question or 'e' to exit: ") if answer == "n": print random.choice(batch1) os.system('clear') elif answer == "e": return def test(): emp = [] os.system('clear') print "Welcome to interview prep. You will be working through your chosen batch. \n" choice = raw_input( "Which batch would you like? Batch 1, 2, or 3? ") if choice == '1': os.system('clear') print random.choice(batch1) answer() elif choice == '2': os.system('clear') print random.choice(batch2) answer() elif choice == '3': os.system('clear') print random.choice(batch3) answer() else: os.system('clear') print "Sorry, not an option. Please try again." sleep(3) test() #next question option, store in array when next is continued. Then state #current batch is complete #emp.append(i) test() <file_sep>/ctci.py def unique(x): if len(x) == 1: return True else: emp = [] for i in x: if i not in emp: emp.append(i) else: return False return True print unique("string") print unique("pizza") print unique("I") print unique("Delivery") print unique("style") <file_sep>/roman.py #Convert Roman Numerals to Integers def to_roman(t): ro_val= {"I":1, "V":5,"X":10,"L": 50,"C ":100,"D": 500,"M": 1000} number = raw_input('Insert a number you would like to convert to a Roman Numeral: ') if number <= 0: print "Numbers above 0 please." for k, v in number: <file_sep>/stack.py class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) s=Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size()) print (s.items) def rev_string(string): rev_str = Stack() # push all characters into stack. for c in string: rev_str.push(c) # Build a new reverse string and return it rev_str1 = "" while rev_str.size(): rev_str1 += rev_str.pop() return rev_str1 print (rev_string("peace")) <file_sep>/README.md # Coding-Challenges-Python In progress This program was created first as a way to document the most common Python challenges for a job interview. Later I decided instead to turn this repo into a game while teaching english abroad. I feared my Python knowledge may get rusty so it'd be best to build a program that had me solving coding challenges. This program randomly selects 7 of the most common challenges for the user to solve. It then times them based on selected difficulty level. Also when I miss too many days of practice the challenges weaken. <file_sep>/test1.py # Write a method that takes in a string and returns the number of # letters that appear more than once in the string. You may assume # the string contains only lowercase letters. Count the number of # letters that repeat, not the number of times they repeat in the # string. """ def sduplicate(s): emp =[] count = 0 for i in s: if i not in emp: emp.append(i) elif i in s: count += 1 return emp print sduplicate("assume") print sduplicate("team") print sduplicate("mississippi") """ <file_sep>/challenges.py # Prep Work # Write a method that will take a string as input, and return a new # string with the same letters in reverse order. def reverse(string): string = string[::-1] return string # OR def reverse2(string): string = string.split() string2 = string[::-1] string3 = ' '.join(string2) return string3 print reverse("I like eggs") print reverse2("I like eggs") #reverse with recursion def reverse(s): print s if s == "": return s else: return reverse(s[1:]) + s[0] print reverse("hola") print reverse("timeline") # Write a method that takes an integer `n` in; it should return # n*(n-1)*(n-2)*...*2*1. Assume n >= 0. def factorial(n): if n == 0: return 1 if n < 0: print "Not Valid. Number must be larger than 0." else: return n * factorial(n-1) print factorial(4) # Write a method that takes in a string. Return the longest word in # the string. You may assume that the string contains only letters and # spaces. # You may use the String `split` method to aid you in your quest. def longest_word(sentence): sentence = max(sentence.split(), key = len) return sentence print longest_word("Ay yo ma, where you at?") # Write a method that takes in an integer `num` and returns the sum of # all integers between zero and num, up to and including `num`. # Two ways! Thanks Stack Overflow def sum_nums(num): total = 0 for i in range(num + 1): total += i print total #OR def sum_numbers(num): return sum(range(num +1)) #Explained Example: num = 5 # range(num) = [0,1,2,3,4] # range(num + 1) = [0,1,2,3,4,5] #sum([0,1,2,3,4,5]) adds them all together # Thanks Stack Overflow print sum_nums(5) print sum_nums(2) print sum_numbers(5) print sum_numbers(2) # Write a method that will take in a number of minutes, and returns a # string that formats the number into `hours:minutes`. def time_conversion(min): minutes = min hour = minutes / 60 left = minutes % 60 print "%d:%d" % (hour, left) time_conversion(70) time_conversion(170) # Write a method that takes a string and returns the number of vowels # in the string. You may assume that all the letters are lower cased. def count_vowels(s): vowel_count = 0 for i in s: if i in "aeiouAEIOU": vowel_count += 1 return vowel_count print count_vowels("pizza please") print count_vowels("Do you love me?") # Write a method that takes a string and returns true if it is a # palindrome. A palindrome is a string that is the same whether written # backward or forward. Assume that there are no spaces; only lowercase # letters will be given. def palindrome(s): if s == s[::-1]: return True else: return False print palindrome("racecar") print palindrome("pizza") # Write a method that takes a string in and returns true if the letter # "z" appears within three letters **after** an "a". You may assume # that the string contains only lowercase letters. def nearby_az(s): for i in range(len(s)): if s[i] == 'a': if ((i+1 < len(s) and s[i +1] == 'z') or (i+2 < len(s) and s[i+2] == 'z') or (i+3 < len(s) and s[i+3] == 'z')): return True return False print nearby_az('jennisapizza') print nearby_az('jhileneissosmart') # Define a procedure, sum_list, # that takes as its input a # list of numbers, and returns # the sum of all the elements in # the input list. def sum_list(y): x = 0 for i in y: x = x + i return x print sum_list([2,7,9]) # Write a method that takes an array of numbers. If a pair of numbers # in the array sums to zero, return the positions of those two numbers. # If no pair of numbers sums to zero, return None. import itertools def position(q): result =[] w = itertools.combinations(q,2) for k in w: if k[0] + k[1] == 0: result.append((q.index(k[0]), q.index(k[1]))) #without appending to empty list and returning #only the first tuple that equals 1 will be returned #return q.index(k[0]), q.index(k[1]) if result == []: return None return result print position([1, 2,3,-1,4,0, -4]) print position([1, 2,3,0, -4]) # Write a method that takes in a number and returns true if it is a # power of 2. Otherwise, return false. # You may want to use the `%` modulo operation. `5 % 2` returns the # remainder when dividing 5 by 2; therefore, `5 % 2 == 1`. In the case # of `6 % 2`, since 2 evenly divides 6 with no remainder, `6 % 2 == 0`. def divisible(t): if t % 2 == 0: return True else: return False print divisible(890) print divisible(10) print divisible(33) #Create a function that takes an array and separates numbers that are odd and #those that are even. def evenorodd(thing): even = [] odd = [] for i in thing: if i % 2 == 0: even.append(i) else: odd.append(i) print odd print even evenorodd([1,2,3,4,5,6,7,8,9,99,23,43,44,17]) # Write a method that takes an array of numbers in. Your method should # return the third greatest number in the array. You may assume that # the array has at least three numbers in it. def third_greatest(r): #range(3), max #sort, [-3] biggest = r[0] time = r[:] big = [] for _ in range(2): biggest = time[0] #thank's Jen! & Ryan for i in time: if i > biggest: biggest = i time.remove(biggest) biggest = time[0] for i in time: if i > biggest: biggest = i return biggest print third_greatest([100, 156, 23, 45, 94]) print third_greatest([17,22,84,56,78]) print third_greatest([17,22,84,56,23,78,100, 156]) # Write a method that takes in a string. Your method should return the # most common letter in the string, and a count of how many times it # appears. Then iterate a list after. def duplicate(w): dict = {} for i in w: if i not in dict: dict[i] = 0 dict[i] = dict[i] + 1 if dict[i] == 1: return None maxi= max(dict, key= dict.get) return maxi, dict[maxi] #v=list(d.values()) #k=list(d.keys()) #return k[v.index(max(v))] print duplicate('abcdcbbb') print duplicate('hkls') print duplicate('there once was a young boy who owned a nice toy but') #strip all white spaces # Write a method that takes in a number and returns a string, placing # a single dash before and after each odd digit. There is one # exception: don't start or end the string with a dash. def dashes(s): res = '' for i, x in enumerate(s): if int(x) % 2 != 0: if i == 0: res += x + '-' elif i == len(s) - 1: res += '-' + x else: res += '-' + x + '-' else: res += x return res print dashes('0802341') print dashes('123456789011') print dashes('84375495947336485') # Write a method that takes in a string of lowercase letters and # spaces, producing a new string that capitalizes the first letter of # each word. # You'll want to use the `split` and `join` methods. Also, the String # method `upcase`, which converts a string to all upper case will be # helpful. def capitalize(s): #split every word #s.split(' ') #capitalize first letter of each word s = s.split() answer = [] for i in s: i = i[0].upper() + i[1:] answer.append(i) t = " ".join(answer) return t #lst = [word[0].upper() + word[1:] for word in s.split()] #s = " ".join(lst) print capitalize('there was once a time of love') print capitalize('pina colada') # Write a method that takes in a string and an array of indices in the # string. Produce a new string, which contains letters from the input # string in the order specified by the indices of the array of indices. def uhh(y,x): #count indices in string pizza = '' for i in range(len(y)): pizza += y[x[i]] return pizza print uhh('word', [3,2,3,2]) #output --> drdr print uhh('umbrella', [3,2,5,6,7,4,3,2]) print uhh('jamba', [4,1,3,3,1,2]) # Write a method that takes in an integer (greater than one) and # returns true if it is prime; otherwise return false. def prime(x): if x >= 2 : for i in range(2,x): #print(x % i) #print(x, i) if x % i == 0: return False #if not (x % i): #return False return True else: return False #return True print prime(6) print prime(1) print prime(13) print prime(1000) # Write a method that returns the `n`th prime number. Recall that only # numbers greater than 1 can be prime. No positive dividers other than #one and itself def nth_prime(n): #print 'Choose any number between 2 and 1000.' emp = [] i = 2 l = 0 while i < 1000: for l in range(2, i+1): #search range 2 to 3 and up if i % l == 0: #divisors less than i break if l == i and i != 2: emp.append(i) i = i + 1 if emp: return emp[n-1] else: return None print nth_prime(3) print nth_prime(18) print nth_prime(1) print nth_prime(4) print nth_prime(6) #list all prime numbers between this and this. def bprime(x,y): for i in range(x,y): prime = True for j in range(2, i): #range needs to start at 2 to check every number up to there if i < 2: print "Only numbers greater than one are accepted" return if i % j == 0: prime = False if prime: print i bprime(10,14) #check if word is a palindrome. Many ways. #check if whether given string is a palindrome. Not returning true or false in terminal. def is_palindrome(x): if x == x[::-1]: print x return True else: return False is_palindrome("mom") is_palindrome("teacher") is_palindrome("madam") #using with while loop def is_palindrome(word): letters = list(word) is_palindrome = True i = 0 while len(letters) > 0 and is_palindrome: if letters[0] != letters[(len(letters) - 1)]: is_palindrome = False else: letters.pop(0) if len(letters) > 0: letters.pop((len(letters) - 1)) print is_palindrome is_palindrome("mom") is_palindrome("team") # with a for-loop def is_palindrome(word): letters = list(word) is_palindrome = True for letter in letters: if letter == letters[-1]: letters.pop(-1) else: is_palindrome = False break print is_palindrome is_palindrome("mom") is_palindrome("team") is_palindrome("madam") #Check whether a string is an integer or float >>> x = 12 >>> isinstance(x, int) True >>> y = 12.0 >>> isinstance(y, float) True # OR inNumber = somenumber try: inNumberint = int(inNumber) print "this number is an int" except ValueError: pass try: inNumberfloat = float(inNumber) print "this number is a float" except ValueError: pass #Implement an algorithm to determine if a string has all unique characters def unique(s): #s = list(s) #create list add unique characters for x in list. unique(x) if len(set(s)) == len(s): print True else: print False # turn into set. Check if size of set is smaller than size of string. # no sets: do hash table. #with a hashmap def unique(string): hashMap = {} for c in string: if c not in hashMap: #This is just a place holder to add c to dict. "None" can be anything # You could put a second if for last letter of word and not in hashMap #then add. But it is cleaner without another if. hashMap[c] = None elif c in hashMap: return False return True print unique("food") # should print False print unique("numbers") #should print True print unique("greest") #False #recursion is this """def fun(x): x+= 1 if x <= 10: f(x) else: return x """ # Find wheter a substring is in another def substring(x,y): if x in y: print True else: print False substring("what","Hey girl whatcha up to") substring("ayo","Hey girl whatcha up to") substring("rl","Hey girl whatcha up to") #OR #This function returns -1 when there is no substring. def sub(x,y): if x.find(y): print True else: print False sub("I like eggs", "gg") ## Write a method that takes in a string of lowercase letters (no # uppercase letters, no repeats). Consider the *substrings* of the # string: consecutive sequences of letters contained inside the string. # Find the longest such string of letters that is a palindrome. # Note that the entire string may itself be a palindrome. def lpalindrome(x): if x == x[::-1]: print "this is a palindrome" return True x = x.split() for i in x: if i == i[::-1]: #emp.append(i) #for i in emp: #if i <= range(i+1): print i lpalindrome("sore was I ere I saw eros") lpalindrome("I like eggs") lpalindrome("radar") lpalindrome("anna") #check if a string has duplicates def duplication(string): count = {} #string = string.split() for s in string: if count.has_key(s): count[s] += 1 else: count[s] = 1 #for key in count: #if count[key] > 1: #print key, count[key] print duplication("I like eggs and popcorn iceiiiiiiii") print duplication("recurse center is lit") #check if a string has duplicates def duplicates(string): count = [] for c in string: if c not in count: count.append(c) else: return True return False print duplicates("I like eggs") print duplicates("recurse center is awesome") print duplicates("ice") #get RC explanation. Counts occurence. import collections def thestring(s): d = collections.defaultdict(int) for c in s: d[c] += 1 for c in sorted(d, key=d.get, reverse=True): print '%s %6d' % (c, d[c]) thestring("pizza") thestring('icecream') # Write a method that takes in two numbers. Return the greatest # integer that evenly divides both numbers. You may wish to use the # `%` modulo operation. def twonum(a,b): #ask why this does not work # for loop for numbers upto given #this is recursion #for i in range(1,j): #if i > 1: #if i % j == 0 and i % q == 0: #print i if b == 0: return a else: return twonum(b, a % b) print twonum(10,20) print twonum(3,12) print twonum(10,55) #also built in from fractions import gcd gcd(20,8) #should produce >>> 4 #interesting algo from interactive python def moveTower(height,fromPole, toPole, withPole): if height >= 1: moveTower(height-1,fromPole,withPole,toPole) moveDisk(fromPole,toPole) moveTower(height-1,withPole,toPole,fromPole) def moveDisk(fp,tp): print("moving disk from",fp,"to",tp) moveTower(3,"A","B","C") #replace all spaces with percents def replace(t): for i in t: if " " in t: t = t.replace(" ", "%") return t print replace("pink chai is good") #Determine if two strings are anagrams def anagram(j,w): # creates list of characters in alphabetical order if sorted(j) == sorted(w): return True else: return False print anagram('car', 'rac') print anagram("sealion", "rainbow") print anagram("star", "tars") #Find the first non-repeated character in a string def fduplicate(word): count = {} for c in word: if c not in count: count[c] = 0 count[c] += 1 for c in word: if count[c] == 1: return c print fduplicate("steameys") print fduplicate("mississippi") #check if a string contains only digits def ifint(x): if x.isdigit(): return True else: return False print ifint('slime') print ifint('s35t') print ifint('53342') #reverse words in sentence without library method def sinlib(x): if len(x) <= 1: return x else: x = x.split() x = x[::-1] return " ".join(x) print sinlib("Time to eat pie") print sinlib("Summer is awesome") #convert numeric string to int "3456" to 3456 def toint(b): b = int(b) return b print toint("434354") <file_sep>/algorithms.py # Implement bubblesort on list def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = [54,26,93,17,77,31,44,55,20] bubbleSort(alist) print(alist) # O(n) ^2 time as well but better than bubblesort def selectionSort(alist): for fillslot in range(len(alist)-1,0,-1): positionOfMax=0 for location in range(1,fillslot+1): if alist[location]>alist[positionOfMax]: positionOfMax = location temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp alist = [54,26,93,17,77,31,44,55,20] selectionSort(alist) print(alist) # O(n)^2 but faster than bubbleSort and selectionSort def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue alist = [54,26,93,17,77,31,44,55,20] insertionSort(alist) print(alist) # Shell sort better than insertionSort. Between O(n) and O (n)^2 def shellSort(alist): sublistcount = len(alist)//2 while sublistcount > 0: for startposition in range(sublistcount): gapInsertionSort(alist,startposition,sublistcount) print("After increments of size",sublistcount, "The list is",alist) sublistcount = sublistcount // 2 def gapInsertionSort(alist,start,gap): for i in range(start+gap,len(alist),gap): currentvalue = alist[i] position = i while position>=gap and alist[position-gap]>currentvalue: alist[position]=alist[position-gap] position = position-gap alist[position]=currentvalue alist = [54,26,93,17,77,31,44,55,20] shellSort(alist) print(alist) # A merge sort is an O(nlogn) algorithm. def quickSort(alist): quickSortHelper(alist,0,len(alist)-1) def quickSortHelper(alist,first,last): if first<last: splitpoint = partition(alist,first,last) quickSortHelper(alist,first,splitpoint-1) quickSortHelper(alist,splitpoint+1,last) def partition(alist,first,last): pivotvalue = alist[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and alist[leftmark] <= pivotvalue: leftmark = leftmark + 1 while alist[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = alist[leftmark] alist[leftmark] = alist[rightmark] alist[rightmark] = temp temp = alist[first] alist[first] = alist[rightmark] alist[rightmark] = temp return rightmark alist = [54,26,93,17,77,31,44,55,20] quickSort(alist) print(alist) #unordered list class class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext class UnorderedList: def __init__(self): self.head = None def isEmpty(self): return self.head == None def add(self,item): temp = Node(item) temp.setNext(self.head) self.head = temp def size(self): current = self.head count = 0 while current != None: count = count + 1 current = current.getNext() return count def search(self,item): current = self.head found = False while current != None and not found: if current.getData() == item: found = True else: current = current.getNext() return found def remove(self,item): current = self.head previous = None found = False while not found: if current.getData() == item: found = True else: previous = current current = current.getNext() if previous == None: self.head = current.getNext() else: previous.setNext(current.getNext()) mylist = UnorderedList() mylist.add(31) mylist.add(77) mylist.add(17) mylist.add(93) mylist.add(26) mylist.add(54) print(mylist.size()) print(mylist.search(93)) print(mylist.search(100)) mylist.add(100) print(mylist.search(100)) print(mylist.size()) mylist.remove(54) print(mylist.size()) mylist.remove(93) print(mylist.size()) mylist.remove(31) print(mylist.size()) print(mylist.search(93)) # ordered linked list. Search, remove and add all require traverasal process o(n) class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext class OrderedList: def __init__(self): self.head = None def search(self,item): current = self.head found = False stop = False while current != None and not found and not stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext() return found def add(self,item): current = self.head previous = None stop = False while current != None and not stop: if current.getData() > item: stop = True else: previous = current current = current.getNext() temp = Node(item) if previous == None: temp.setNext(self.head) self.head = temp else: temp.setNext(current) previous.setNext(temp) def isEmpty(self): return self.head == None def size(self): current = self.head count = 0 while current != None: count = count + 1 current = current.getNext() return count mylist = OrderedList() mylist.add(31) mylist.add(77) mylist.add(17) mylist.add(93) mylist.add(26) mylist.add(54) print(mylist.size()) print(mylist.search(93)) print(mylist.search(100)) #DP algorithm for giving change with least amount of coins def dpMakeChange(coinValueList,change,minCoins,coinsUsed): for cents in range(change+1): coinCount = cents newCoin = 1 for j in [c for c in coinValueList if c <= cents]: if minCoins[cents-j] + 1 < coinCount: coinCount = minCoins[cents-j]+1 newCoin = j minCoins[cents] = coinCount coinsUsed[cents] = newCoin return minCoins[change] def printCoins(coinsUsed,change): coin = change while coin > 0: thisCoin = coinsUsed[coin] print(thisCoin) coin = coin - thisCoin def main(): amnt = 63 clist = [1,5,10,21,25] coinsUsed = [0]*(amnt+1) coinCount = [0]*(amnt+1) print("Making change for",amnt,"requires") print(dpMakeChange(clist,amnt,coinCount,coinsUsed),"coins") print("They are:") printCoins(coinsUsed,amnt) print("The used list is as follows:") print(coinsUsed) main() <file_sep>/pina.py # get help understanding fibonacci (make dentist appointment now!) #find all permutations of a string with and without recursion #remove duplicate characters from a string #given a 2d array print out the numbers in a swirl # lucky number: remove every second number, then every third number # Todo: 4 above coding challenges, batch 2&3 of 'the game', finish dynamic programming chapter # 3.15- 3.18, 2 esperanto circles, spanish obsessed, blog post, 1 chapter book - bed up at 7 a.m. # Tmm 7 am, meditate, bible push ups and 20 minute hit by 8:30, 3 esperanto bubbles, #finish book, finish 'the game' batches, 3.14 simulation, 6.7 - 6.10, blog post week 2. #spanish obsessed, renew library book #given to lists, find out how many combinations you can make with them in one list #______________________________________________________________________________ #Ceasar Cipher #----------------------------------------------------------------------------- #Roman Numerals Converter #practice python questions(3 from here and 3 from most common list at a time) #list of 20 most common #image carasel javascript and battle ship game python # Build Random Question shooter for algorithms to study (Do 5-7 per batch) # if done already, choose one not done. Store each question in variable (first), # then let each question link to the answers, allow person to choose how many # questions to answer # explain out loud how each question works #drop box gets back next day. #"Tell me about a project you created" #return stops function. Print keeps it going. # discovered python tutor to visualize #learning algortithms with recursion and stack makes me understand much more
b514ecf53c62910715e5f799fb37b682ef2dcdae
[ "Markdown", "Python" ]
9
Python
ColorfulCodes/Coding-Challenges-Python
c93621a75b5dc4be8203944398c9c1f9f5515cab
fe929feb2394a9b078c0cf8af728a1006ebc3ceb
refs/heads/master
<file_sep> # App Inventor Docker This repo contains a ready-to-use Dockerfile to help you build an App Inventor server docker image. ### Build and run by Dockerfile To build the image, simply run: ``` docker build . ``` (Do not miss the dot at the end!) You may give the image an easy-to-remember tag by the ``-t`` option. ``` docker build -t appinventorserver . ``` (Do not miss the dot at the end!) After the image is built, you can log on to the container by: ``` docker run -it -p 8888:8888 -v "YOUR_APP_INVENTOR_PARENT_FOLDER_FULL_PATH:/root/appinventor-sources/" appinventorserver ``` The ``-p 8888:8888`` option forwards your 8888 port to the container 8888 port, so that you can access it at http://localhost:8888 on your host computer. (Host computer is the machine you are using, e.g., your Windows or Mac computer) The ``-v "YOUR_APP_INVENTOR_PARENT_FOLDER_FULL_PATH:/root/appinventor-sources/"`` option mounts the source code at your host computer to the container. The reason is that normally we shall use our favorite IDE to change the source code on our host computer. By mounting the source code as a volume, any changes to the source code will be synced to the container. ### Build and run by docker-compose Alternatively, you can use docker-compose to build and run the container. The benefit is that you don't need to memorize the run command and the options. You can save it to the *docker-compose.yml* file. You may refer to *docker-compose.yml.example*. Change *YOUR\_APP\_INVENTOR\_PARENT\_FOLDER\_FULL\_PATH* to the path of your source code. For example, ``` volumes: - /Users/macuser/Development/appinventor-sources:/root/appinventor-sources ``` To build and run: ``` docker-compose up -d ``` It should say: ``` Starting appinventor-docker_appinventorserver_1 ... done ``` Note the container name. In this case, the name is *appinventor-docker\_appinventorserver\_1*. You can also run ``docker container ls`` to check the name of all your containers. To log on to the container, use ``docker exec -it <CONTAINER_NAME> /bin/bash``. For example: ``` docker exec -it appinventor-docker_appinventorserver_1 /bin/bash ``` Follow the setup instructions at https://github.com/mit-cml/appinventor-sources. ### Starting the server After logged on to the container, to start the server, you normally run ``` YOUR_APPENGINE_SDK_FOLDER/bin/dev_appserver.sh --port=8888 --address=0.0.0.0 appengine/build/war/ ``` Alternatively, a *startserver.sh* script is prepared for you and added to the PATH, so that you do not need to memorize the path of your appengine SDK folder. You can simply run this command in your container (i.e., after you execute ``docker exec -it appinventor-docker_appinventorserver_1 /bin/bash``) ``` startserver.sh ``` The server should start within a few minutes, and say: ``` INFO: Dev App Server is now running ``` Now you can open it at http://localhost:8888/ on your browser. # App Inventor Development This section contains detailed instructions on how to set up an App Inventor server using Docker and how to develop App Inventor blocks. The objective of this tutorial is to help you set up a local App Inventor server and to add new blocks to App Inventor. Before you start, you should be familiar with the following: 1. The basic operation of command line tools, either Linux or Windows 2. Git - Git command - Github - Using Git for development (e.g., Git flow, Github flow) - How to do version control using Git - You can use some of the Git GUI tools instead of the Git command line to manage the source code 3. The concept of software development, e.g., local environment, compiling, running a local server, testing, automated testing 4. Java programming 5. Java IDE ## 1. Get started 1. Install Git on your computer at https://git-scm.com/download 1. Read the instructions carefully at https://github.com/mit-cml/appinventor-sources. 2. You need to set up a local App Inventor server on your computer and run the source code on your computer. 3. For setup, you can follow the above instructions on MIT Github. Alternatively, we have prepared a Docker version for you. ### 1.1 Using Docker to set up an App Inventor server on your local computer **If you do not want to use Docker, you can always set up a server on your Window, Mac or Linux computer. Follow the setup instructions at https://github.com/mit-cml/appinventor-sources and https://docs.google.com/document/pub?id=1Xc9yt02x3BRoq5m1PJHBr81OOv69rEBy8LVG_84j9jc.** 1. Install Docker on your computer: https://www.docker.com 2. After installation, start the Docker demon by clicking Docker.exe on Windows or Docker app on Mac. ![](https://i.imgur.com/3TCv04h.png) ![](https://i.imgur.com/nwLnhfD.png) Make sure the Docker demon is running. Check your status bar. ![](https://i.imgur.com/Mk5r6Rg.png) ![](https://i.imgur.com/fYHiq3M.png) 3. Then open your command line tool. You should be able to run ``` docker ``` 4. Download the Dockerfile prepared for you at https://github.com/himgodfreyho/appinventor-docker. 5. Unzip the file. 6. Open command line tool, change the current directory where the Dockerfile is located. 7. Run ``` docker build -t appinventorserver . ``` (Do not miss the dot at the end!) This will build an App Inventor image with all the dependencies based on Ubuntu 14.04. It can take from 3 to 10 minutes (depending on the configuration of your computer and the speed of the network). While you are waiting, you can start downloading the source code of App Inventor first by following the instructions at Section 1.2. 5. If it is built successfully, you should see something like this: ``` ... Removing intermediate container 563dcb472750 ---> b09dfafffa70 Successfully built 0bbb2254e236 Successfully tagged appinventorserver:latest ``` Note the container ID from the message: `Successfully built 0bbb2254e236 `. In the above example, the container ID is _0bbb2254e236_. And we have given it a name _appinventorserver_. ### 1.2 Download the source code of App Inventor 1. Download the source code to your preferred directory by opening the command line tool and typing: (Note that you should do it on your host computer.) ``` git clone https://github.com/mit-cml/appinventor-sources.git ``` 2. The *appinventor parent folder* is the directory containing the following folder and files: ![](https://i.imgur.com/pnLeTc9.png) 3. The *appinventor-sources folder* is the directory containing the following folders and files: ![](https://i.imgur.com/zQOI3Lr.png) 4. After cloning, go to *appinventor-sources* (``cd appinventor-sources``) and type the following commands: ``` git submodule update --init ``` ### 1.3 To start the docker container You can change the CPU and memory resources for your Docker container, depending on the specifications of your computer. Generally, we recommend assigning half of your CPU cores and memories for Docker so that it will not affect the performance of your host computer. ![](https://i.imgur.com/kJCqQQS.png) When you start the container, you need to copy the source code (the *appinventor parent folder*) as a mounted volume from your host computer into the container. The command for start and mount is: ``` docker run -it -v "YOUR_APP_INVENTOR_PARENT_FOLDER_FULL_PATH:/root/appinventor-sources/" -p 8888:8888 appinventorserver ``` (Don't miss the double quote on the path.) For example, on Mac if the App Inventor parent folder is at */Users/macuser/Development/appinventor-source/*, the command will be: ``` docker run -it -v "/Users/macuser/Development/appinventor-source/:/root/appinventor-sources/" -p 127.0.0.1:8888:8888 appinventorserver ``` On Windows, if the App Inventor parent folder is at *C:\Users\Win User\Downloads\appinventor-sources-master/*, the command will be: ``` docker run -it -v "C:\Users\Win User\Downloads\appinventor-sources-master/:/root/appinventor-sources/" -p 127.0.0.1:8888:8888 appinventorserver ``` You may be asked to enter the User's password on the Windows computer for granting share folder right. After running the command, the container should start, and you have logged into the container environment. Type ``ls`` and you should see that the appinventor-sources folder is mounted. ## 2. Build your source code For details, read the instruction carefully at https://github.com/mit-cml/appinventor-sources. **For the first-time setup** you need to run the following commands: (Note that if you are using Docker, make sure you are working in the container environment instead of your host computer.) 1. ``cd appinventor`` 2. ``ant MakeAuthKey`` To build the source code, at the *appinventor-sources/appinventor* directory run ``` ant ``` If you are using my Docker image, a script has been prepared for you to start the server, you just need to type ``` startserver.sh ``` After a few minutes, you should see: ``` ... INFO: The admin console is running at http://localhost:8888/_ah/admin Oct 12, 2018 5:11:54 AM com.google.appengine.tools.development.DevAppServerImpl doStart INFO: Dev App Server is now running ``` The App Inventor server is now started. Open the browser and go to http://localhost:8888, you should see your local version of App Inventor. ![](https://i.imgur.com/cIYlcOg.png) Click <u>Click Here to use your Google Account to login</u>, then click Login. **Leave the email "<EMAIL>" unchanged!** ![](https://i.imgur.com/HbcIFK3.png) ## 3. Modifying the source code You can use any IDE you are familiar with to edit the source code. If you are using Docker, you should edit the source code on your host computer, and then build and run the source code in the Docker container. Every time you have changed the code, you may need to re-build it. To speed up the development process, see <a href="https://docs.google.com/document/d/1sAw0QObTxTWqRX7GQRCa2z9TIV2r5AKT9UKMFF1acZI/pub#h.e5ttjsa1wtlw">https://docs.google.com/document/d/1sAw0QObTxTWqRX7GQRCa2z9TIV2r5AKT9UKMFF1acZI/pub#h.e5ttjsa1wtlw</a> ## 4. Exercise: Creating a block Referring to the following application, when a user shakes his/her phone, the phone will say a message using the Text-to-Speech function. ![](https://i.imgur.com/PwQ069F.png) In this exercise, we are going to combine the blocks into one block. The source code of the component are located at *appinventor-sources/appinventor/components/src/com/google/appinventor/components/runtime*. Open *AccelerometerSensor.java*, you can see the source code of the block. ![](https://i.imgur.com/hDrIvbQ.png) If we need to use the Text-to-Speech function, we should import the TextToSpeech class. At line 21, add: ```java import com.google.appinventor.components.runtime.TextToSpeech; ``` ![](https://i.imgur.com/h1Oxkct.png) At line 130, add ``private ComponentContainer container;`` to define a private variable for the container instance. ![](https://i.imgur.com/lmZnOz1.png) At line 140, add ```java this.container = container; ``` ![](https://i.imgur.com/UpMsdt4.png) At line 275: add: ```java /** * Indicates the device started being shaken, and say Hello to the user. */ @SimpleEvent public void ShakeToSayHello() { TextToSpeech textToSpeech = new TextToSpeech(this.container); textToSpeech.Speak("Hello"); EventDispatcher.dispatchEvent(this, "Shaking"); } ``` ![](https://i.imgur.com/rXKI14C.png) Finally, after adding a new block, we need to add the definition to the Block editor. Open *OdeMessages.java* at *appinventor-sources/appinventor/appengine/src/com/google/appinventor/client*. Add these lines at the end of the file. ```java @DefaultMessage("ShakeToSayHello") @Description("") String ShakeToSayHelloEvents(); ``` ![](https://i.imgur.com/2mC3q9Q.png). Go to the command line tool and type: ``` ant ``` to build the code. After building it successfully, type: ``` startserver.sh ``` to start the server. Go to http://localhost:8888, you should see the block you have added. ![](https://i.imgur.com/KqOjIPp.png) (Although it might seem combining shaking and text-to-speech into one block is not very useful to users, the primary purpose of this exercise is letting you know how to build your own block, and know what is the concept behind when building App Inventor block.) For details, you can refer to https://docs.google.com/document/d/1CNNT5MSzRR7vrHPOGNVxtV3GqWqx29wtLv1QfHosvqk/ **Remember to update the apk every time you have changed the code by copying the apk to your phone manually using a USB cable and installing it.** ## 5. Points to note 1. If you see errors during compiling, it is highly possible that there are bugs or errors in your newly modified codes! If this is not the case, try ``ant clean`` before compiling. 2. If you cannot see App Inventor on your browser, try clearing the cache of your browser. Also, you might try using the private mode. ![](https://i.imgur.com/k4nCkic.png) ![](https://i.imgur.com/7rgQSHO.png) 3. If you cannot see the changes on your browser after the codes are compiled successfully, try clearing the cache of your browser. 4. Make good use of Git version control to keep track of what you have changed. 5. Write meaningful commit messages. <!--stackedit_data: eyJoaXN0b3J5IjpbMTY5ODA4NzExOF19 --><file_sep>FROM ubuntu:14.04 RUN apt-get update && apt-get install -y software-properties-common && add-apt-repository ppa:openjdk-r/ppa && apt-get update && apt-get install -y \ wget \ unzip \ openjdk-8-jdk \ ant \ lib32z1 \ lib32ncurses5 \ lib32bz2-1.0 \ lib32stdc++6 \ git RUN wget -O /tmp/appengine.zip https://storage.googleapis.com/appengine-sdks/featured/appengine-java-sdk-1.9.66.zip RUN unzip /tmp/appengine.zip -d /root && rm /tmp/appengine.zip COPY startserver.sh /root/scripts/ RUN chmod +x /root/scripts/startserver.sh ENV PATH="$PATH:/root/appengine-java-sdk-1.9.66/bin/" ENV PATH="$PATH:/root/scripts/" ENV JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64" ENV PATH="$PATH:$JAVA_HOME/bin" WORKDIR /root/ EXPOSE 8888 <file_sep>#!/bin/bash set -e cd /root/appinventor-sources/appinventor && dev_appserver.sh --port=8888 --address=0.0.0.0 appengine/build/war/
8444c6222b13ff9916e637bead53c1de421f039b
[ "Markdown", "Dockerfile", "Shell" ]
3
Markdown
VedangSolaskar/appinventor-docker
42a8bffd7adea12945228b0d1f61d4fd380e6ada
241e5268a6d507f8474f1eefcc465a3ae83954a8
refs/heads/master
<file_sep>export function classNames(...classes: (string | { [className: string]: boolean | undefined | null } | undefined | null)[]) { return classes.reduce<string[]>((acc, item) => { if (typeof item === 'string') { acc.push(item); } else if (item instanceof Object) { Object.getOwnPropertyNames(item).forEach(p => { if (item[p]) { acc.push(p); } }); } return acc; }, []).filter(x => x).join(' '); }
9fff17247710f7788d1424a4bcb84f0c01faf87b
[ "TypeScript" ]
1
TypeScript
billhannah/chromatic-spike
129a25568f4dff530c188363cc23eee71addf25d
ab2cbbd00ce8493fa89ce42e30a21e766723bb67
refs/heads/master
<file_sep>import React, { Component } from 'react'; class ListContainer extends Component { listItems = () => { // Get the listItems from the properties passed in to the component const items = this.props.listItems; if(items.length) { // If confused with this mess, look up JS array map and using react with that // Basically just run a function for each item in the list/array, // then return the output for all of them combined return items.map((item, i) => { // CSS text-decoration: line-through is shown for li.checked // The onChange event handler is passed in as a property to the component return ( <li key={i} className={item.checked ? "checked" : ""}> <input type="checkbox" value={i} onChange={this.props.handleCheckBox} checked={item.checked} /> {item.title} </li> ); }); } else { // When no items in list return ( <li>No Items</li> ); } } render() { return ( <div className="ListContainer"> <ul> {this.listItems()} </ul> </div> ); } } export default ListContainer; <file_sep>import React, { Component } from 'react'; class ItemForm extends Component { constructor(props){ super(props); this.state = { title : '' } } handleSubmit = (e) => { e.preventDefault(); this.props.addItem(this.state.title); this.setState({title: ''}); } handleInputChange = (e) => { this.setState({[e.target.name]: e.target.value}); } render() { return ( <div className="ItemForm"> <form onSubmit={this.handleSubmit}> <input type="text" name="title" value={this.state.title} onChange={this.handleInputChange} /> <input type="submit" value="Add" /> </form> </div> ); } } export default ItemForm; <file_sep># React To-Do List This is an example of using react to create a simple to-do list. An example of the use of component state and properties to store non-persistent data for a simple to-do list. ## Install dependencies Make sure you have node.js installed In the project directory before you can run the app you need to install the dependencies: ```bash npm install ``` Now you can run the app ```bash npm start ``` This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
6300461c097f4f76469da009624cd2a4c2035f46
[ "JavaScript", "Markdown" ]
3
JavaScript
benlongmire/react-todo-list
8d0fed2184b25306eb0108ebaf9e1b6cdbe26d78
b21d5f394622f5bc482b224f77ce02dcce15cc3a
refs/heads/master
<repo_name>sn94/IntentsAndroid<file_sep>/app/src/main/java/com/example/sonia/intentsandroid/MainActivity.java package com.example.sonia.intentsandroid; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<Contacto> contactos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactos= new ArrayList<Contacto>(); contactos.add( new Contacto("Sonia","0983 129 494", "email1") ); contactos.add( new Contacto("Sofia","0982 509 114", "email2") ); contactos.add( new Contacto("Sandra","0973 129 004", "email3") ); contactos.add( new Contacto("Samanta","0985 177 474", "email4") ); contactos.add( new Contacto("Soledad","0983 129 321", "email5") ); contactos.add( new Contacto("Susana","0993 130 822", "email6") ); ArrayList<String> lstNombres= new ArrayList<String>(); for(Contacto ite:contactos){ lstNombres.add( ite.getNombre() ); } final ListView lstContac= (ListView) findViewById(R.id.lst); lstContac.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lstNombres)); lstContac.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intento= new Intent( MainActivity.this, DetalleContacto.class ); intento.putExtra("nombre", contactos.get(position).getNombre()); intento.putExtra("telefono", contactos.get(position).getTelefono()); intento.putExtra("email", contactos.get(position).getEmail()); startActivity( intento ); //finish();//cerrar actividad } }); } } <file_sep>/app/src/main/java/com/example/sonia/intentsandroid/DetalleContacto.java package com.example.sonia.intentsandroid; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.TextView; public class DetalleContacto extends AppCompatActivity { private TextView tnombre; private TextView ttelefono; private TextView temail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalle_contacto); Bundle dts = getIntent().getExtras(); String nom = dts.getString("nombre"); String tel = dts.getString("telefono"); String email = dts.getString("email"); tnombre = (TextView) findViewById(R.id.tvNombre); ttelefono = (TextView) findViewById(R.id.tvTelefono); temail = (TextView) findViewById(R.id.tvemail); tnombre.setText(nom); ttelefono.setText(tel); temail.setText(email); } public void do_call(View v) { String TXT = "tel:" + ttelefono.getText().toString(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(TXT))); } public void sent_email( View v){ String email= "mailto:"+temail.getText().toString(); Intent intentEmail= new Intent( Intent.ACTION_SEND); intentEmail.setData(Uri.parse(email)); // el email como uri intentEmail.putExtra(Intent.EXTRA_EMAIL, email);//la direccion intentEmail.setType("message/rfc822");// tipo de envio startActivity( Intent.createChooser(intentEmail , "Email ")); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { /* if( keyCode == KeyEvent.KEYCODE_BACK){ Intent MENS= new Intent( this, MainActivity.class); startActivity( MENS); }*/ return super.onKeyDown(keyCode, event); } }
d951a7413c87e1ceb93810d48963279787bbda9a
[ "Java" ]
2
Java
sn94/IntentsAndroid
8f1b70ad218fb5fd7436a1c8064bfa7d4620e6f0
ca648b842ad6f884bf33ede60ae3817b889637d8
refs/heads/master
<repo_name>matvaibhav/SwaggerGen<file_sep>/README.md # SwaggerGen Swagger Generator is capable of generating a swagger specification from a JSON sample data. More details on Swagger specification: https://swagger.io/specification/ <file_sep>/src/sg.properties Mode=RELEASE DumpAPIInfo=FAILED SpecDeployPath=../webapps/swaggerdeploy/ APIDumpPath=../savedStates/ TMPUploadPath=../temp<file_sep>/src/com/infa/rest/swagger/impl/EVerb.java package com.infa.rest.swagger.impl; import java.util.ArrayList; import java.util.List; public enum EVerb { GET("get"), POST("post"), PUT("put"), DELETE("delete"); private String verb; private EVerb(String verb) { this.verb = verb; } public static EVerb getVerb(String verb) { EVerb verbType = GET; for (EVerb eVerb : EVerb.values()) { if (eVerb.toString().equalsIgnoreCase(verb)) { verbType = eVerb; break; } } return verbType; } public String toString() { return verb; } public List<EParameterType> getPayloadParamTypes() { List<EParameterType> types = new ArrayList<EParameterType>(); types.add(EParameterType.Header); if (GET != this) types.add(EParameterType.Body); return types; } } <file_sep>/src/com/infa/rest/swagger/serv/Util.java package com.infa.rest.swagger.serv; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import javax.servlet.http.HttpServletRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.informatica.sdk.helper.common.ApiException; public class Util { public static boolean isValidJson(String jsonContent) throws ApiException{ try { new JSONObject(jsonContent); } catch (JSONException ex) { try { new JSONArray(jsonContent); } catch (JSONException e) { throw new ApiException(600, "Invalid Raw body JSON." + e.getMessage()); } } return true; } public static String writeSwaggerToFile(SavedState state, String fileName) throws IOException { File path = new File(GlobalConfig.getInstance() .getSwaggerDeployLocation() + "/" + state.getSessionId()+state.getPad()); if (!path.exists()) { path.mkdirs(); } String fullFileName = path.getAbsolutePath() + "/" + fileName; try (PrintWriter out = new PrintWriter(fullFileName)) { out.println(state.getApiResponse().getSwagger()); } return fullFileName.substring(fullFileName.indexOf("webapps") + 7); } public static String deployExistingSwagger(File source, String destFolder, String fileName) throws IOException { File path = new File(GlobalConfig.getInstance() .getSwaggerDeployLocation() + "/" + destFolder); if (!path.exists()) { path.mkdirs(); } File fullPath = new File(path.getAbsolutePath()+ "/" + fileName); Files.copy(source.toPath(), fullPath.toPath(), StandardCopyOption.REPLACE_EXISTING); String fullFileName = fullPath.getAbsolutePath(); return fullFileName.substring(fullFileName.indexOf("webapps") + 7); } public static String getHostURL(HttpServletRequest request) { String hostURLParts[] = request.getRequestURL().toString() .split("/", 4); String hostURL = hostURLParts[0] + "//" + hostURLParts[2]; return hostURL; } } <file_sep>/src/com/infa/rest/swagger/serv/SavedState.java package com.infa.rest.swagger.serv; import java.io.Serializable; import com.infa.rest.swagger.reqres.model.API; import com.infa.rest.swagger.reqres.model.Response; import com.informatica.sdk.helper.common.ApiException; import com.informatica.sdk.helper.common.JsonUtil; public class SavedState implements Serializable{ private static final long serialVersionUID = 1L; String pad = ""; String sessionId = ""; API apiRequest = new API(); Response apiResponse = null; String userResponseFileName=null; public SavedState(String sessionId) { this.sessionId = sessionId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getPad() { return pad; } public void setPad(String pad) { this.pad = pad; } public void setApiResponse(String apiResponse) throws ApiException { this.apiResponse = (Response) JsonUtil.deserialize(apiResponse, null, Response.class); } public Response getApiResponse() { return apiResponse; } public API getApiRequest() { return apiRequest; } public void setApiRequest(API apiRequest) { this.apiRequest = apiRequest; } public void setApiRequest(String apiRequest) throws ApiException { this.apiRequest = (API) JsonUtil.deserialize(apiRequest, null, API.class); } public boolean hasUserResponse() { return (userResponseFileName!=null)?true:false; } public String getUserResponseFileName() { return userResponseFileName; } public void setUserResponseFileName(String userResponseFileName) { this.userResponseFileName = userResponseFileName; } } <file_sep>/src/com/infa/rest/swagger/impl/RestSamplingConsts.java package com.infa.rest.swagger.impl; public class RestSamplingConsts { public static final String TYPE = "type";//$NON-NLS-1$ public static final String FORMAT = "format";//$NON-NLS-1$ public static final String PROPERTIES = "properties";//$NON-NLS-1$ public static final String PARAMETERS = "parameters";//$NON-NLS-1$ public static final String ITEMS = "items";//$NON-NLS-1$ public static final String DEFINITIONS = "definitions";//$NON-NLS-1$ public static final String DEFINITIONS_HASH = "#/definitions/";//$NON-NLS-1$ public static final String SCHEMA = "schema";//$NON-NLS-1$ public static final String PROTOCOLS = "schemes";//$NON-NLS-1$ public static final String REF = "$ref";//$NON-NLS-1$ public static final String DESCRIPTION = "description";//$NON-NLS-1$ public static final String REQUIRED = "required";//$NON-NLS-1$ public static final String NAME = "name";//$NON-NLS-1$ public static final String IN = "in";//$NON-NLS-1$ public static final String PATHS = "paths";//$NON-NLS-1$ public static final String RESPONSES = "responses";//$NON-NLS-1$ public static final String REQUEST = "_Request";//$NON-NLS-1$ } <file_sep>/src/com/infa/rest/swagger/impl/EContentType.java package com.infa.rest.swagger.impl; public enum EContentType { APPLICATION_JSON("application/json"), APPLICATION_XML("application/xml"), FORM_URL_ENCODED("application/x-www-form-urlencoded"), //only for Request/content_Type NONE(""); private String displayName; EContentType(String displayName){ this.displayName=displayName; } @Override public String toString(){ return displayName; } } <file_sep>/src/com/infa/rest/swagger/reqres/model/Response.java package com.infa.rest.swagger.reqres.model; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.infa.rest.swagger.reqres.model.Status; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "status", "req", "res", "swag" }) public class Response implements Serializable{ private static final long serialVersionUID = 1760864816360482911L; @JsonProperty("status") private Status status; @JsonProperty("req") private String request; @JsonProperty("res") private String response; @JsonProperty("swag") private String swagger; @JsonProperty("code") private String code; @JsonProperty("message") private String message; public Status getStatus() { if(message!=null && code!=null){ response=message; return new Status(code,"",message); } else return status; } public void setStatus(Status status) { this.status = status; } public String getRequest() { return request; } public void setRequest(String request) { this.request = request; } public String getResponse() { if(response!=null) return response; else if(message!=null) return message; else return status.getMessage(); } public void setResponse(String response) { this.response = response; } public String getSwagger() { if(swagger != null) return swagger; else if( message != null) return message; else return status.getMessage(); } public void setSwagger(String swagger) { this.swagger = swagger; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
ab7818d6dfa2031cd5e1abcc40c9bc1e9206a06c
[ "Markdown", "Java", "INI" ]
8
Markdown
matvaibhav/SwaggerGen
d7c7cbe390101f192e041fe7b0e6b7e2bd611208
fa94a6201b1163af2f95dfa6413c906ff3afb149
refs/heads/main
<repo_name>oiagorodrigues/ds-bootcamp-java-task-1<file_sep>/README.md # DS Client API Simple Client REST API made as the first task of the DevSuperior Spring React Bootcamp, using Spring Boot and persiting in a memory database using Spring Data JPA. ## How to install Clone this repo ```bash git clone https://github.com/oiagorodrigues/dsbootcamp-java-first-task.git or git clone <EMAIL>:oiagorodrigues/dsbootcamp-java-first-task.git ``` Open it in your favorite IDE. Recommended using [Intellij](https://www.jetbrains.com/pt-br/idea/), [STS](https://spring.io/tools) or [VSCode](https://code.visualstudio.com/). ## Learning topics - Creating a Data Layer with Entity|Model, Repository and Service - Creating a API layer with Controller and DTO - Creating custom Exceptions, and StandarError and an ExceptionHandler - Seeing the database ## Conceptual model <img src="https://raw.githubusercontent.com/oiagorodrigues/dsbootcamp-java-first-task/main/conceptual_model.jpg" width="300"> ## Technologies - Java 11 - Spring Boot 2.4.6 - Spring Data JPA - H2 Database ## Endpoints ### Client [[Postman docs]](https://documenter.getpostman.com/view/6767905/TzXzEcpC#cf7c6d12-e9b6-4ec5-8a8a-80e51297d65b) #### Add a client > POST - /clients Example Request ```json { "name": "<NAME>", "cpf": "12345678901", "income": 6500.0, "birthDate": "1994-07-20T10:30:00Z", "children": 2 } ``` Example Response ```json // 201 CREATED // Location: /clients/11 { "id": 11, "name": "<NAME>", "cpf": "12345678901", "income": 6500, "birthDate": "1994-07-20T10:30:00Z", "children": 2 } ``` #### Fetch Clients (Pageable) > GET - /clients Params - **page** - Gets a list specified by the page number. Default = 0 - **linesPerPage** - Gets the size of the list specified. Default = 12 - **direction** - Gets the list sorted by a direction. [ASC, DESC] Default = DESC - **orderBy** - Gets the list ordered by the fields of the Client. Default = id. ``` Example Response ```json // 200 OK { "content": [ { "id": 10, "name": "<NAME>", "cpf": "58298663900", "income": 20000, "birthDate": "1968-08-02T20:50:07Z", "children": 2 }, { "id": 8, "name": "<NAME>", "cpf": "38294706221", "income": 3000, "birthDate": "1953-11-09T20:50:07Z", "children": 1 }, { "id": 5, "name": "<NAME>", "cpf": "58093464565", "income": 11000, "birthDate": "1982-06-14T20:50:07Z", "children": 5 }, { "id": 6, "name": "<NAME>", "cpf": "54636645529", "income": 1000, "birthDate": "1949-09-07T20:50:07Z", "children": 1 }, { "id": 2, "name": "<NAME>", "cpf": "74665963398", "income": 1070, "birthDate": "1963-07-13T20:50:07Z", "children": 1 }, { "id": 9, "name": "<NAME>", "cpf": "81025624122", "income": 3200, "birthDate": "1989-03-22T20:50:07Z", "children": 4 } ], "pageable": { "sort": { "sorted": true, "unsorted": false, "empty": false }, "pageSize": 6, "pageNumber": 0, "offset": 0, "unpaged": false, "paged": true }, "last": false, "totalPages": 2, "totalElements": 10, "sort": { "sorted": true, "unsorted": false, "empty": false }, "first": true, "numberOfElements": 6, "size": 6, "number": 0, "empty": false } ``` #### Fetch Client by Id > GET - /clients/{id} Example Response ```json // 200 OK { "id": 10, "name": "<NAME>", "cpf": "58298663900", "income": 20000, "birthDate": "1968-08-02T20:50:07Z", "children": 2 } ``` #### Update Client > PUT - /clients/{id} Example Request ```json { "name": "<NAME>", "cpf": "12345678901", "income": 6500.0, "birthDate": "1994-07-20T10:30:00Z", "children": 2 } ``` Example Response ```json // 200 OK { "id": 1, "name": "<NAME>", "cpf": "12345678901", "income": 6500, "birthDate": "1994-07-20T10:30:00Z", "children": 2 } ``` #### Delete Client > DELETE - /clients/{id} Example Response ```json // 201 NO CONTENT ``` <file_sep>/src/main/java/dev/iagorodrigues/clientapi/services/ClientService.java package dev.iagorodrigues.clientapi.services; import dev.iagorodrigues.clientapi.dto.ClientDTO; import dev.iagorodrigues.clientapi.entities.Client; import dev.iagorodrigues.clientapi.exceptions.ResourceNotFoundException; import dev.iagorodrigues.clientapi.repositories.ClientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; import java.util.Optional; @Service public class ClientService { @Autowired private ClientRepository clientRepository; @Transactional(readOnly = true) public Page<ClientDTO> findAll(PageRequest pageRequest) { return clientRepository.findAll(pageRequest).map(ClientDTO::new); } @Transactional(readOnly = true) public ClientDTO findById(Long id) { return clientRepository.findById(id) .map(ClientDTO::new) .orElseThrow(() -> new ResourceNotFoundException("Client doesn't exist")); } @Transactional public ClientDTO insert(ClientDTO clientDTO) { Client client = new Client(); mapClientDtoToEntity(clientDTO, client); client = clientRepository.save(client); return new ClientDTO(client); } @Transactional public ClientDTO update(Long id, ClientDTO clientDTO) { try { Client client = clientRepository.getOne(id); mapClientDtoToEntity(clientDTO, client); client = clientRepository.save(client); return new ClientDTO(client); } catch (EntityNotFoundException ex) { throw new ResourceNotFoundException("Client doesn't exist."); } } @Transactional public void delete(Long id) { try { clientRepository.deleteById(id); } catch (Exception ex) { throw new ResourceNotFoundException("Client doesn't exist."); } } private void mapClientDtoToEntity(ClientDTO clientDTO, Client client) { client.setName(clientDTO.getName()); client.setChildren(clientDTO.getChildren()); client.setCpf(clientDTO.getCpf()); client.setIncome(clientDTO.getIncome()); client.setBirthDate(clientDTO.getBirthDate()); } } <file_sep>/src/main/java/dev/iagorodrigues/clientapi/controllers/ClientController.java package dev.iagorodrigues.clientapi.controllers; import dev.iagorodrigues.clientapi.dto.ClientDTO; import dev.iagorodrigues.clientapi.services.ClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @RestController @RequestMapping("/clients") public class ClientController { @Autowired private ClientService clientService; @GetMapping public ResponseEntity<Page<ClientDTO>> fetchClients( @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "linesPerPage", defaultValue = "12") Integer linesPerPage, @RequestParam(value = "direction", defaultValue = "DESC") String direction, @RequestParam(value = "orderBy", defaultValue = "id") String orderBy ) { PageRequest pageRequest = PageRequest.of(page, linesPerPage, Sort.Direction.valueOf(direction), orderBy); Page<ClientDTO> clients = clientService.findAll(pageRequest); return ResponseEntity.ok().body(clients); } @GetMapping("/{id}") public ResponseEntity<ClientDTO> fetchClientById(@PathVariable Long id) { ClientDTO clientDTO = clientService.findById(id); return ResponseEntity.ok(clientDTO); } @PostMapping public ResponseEntity<ClientDTO> createClient(@RequestBody ClientDTO clientDTO) { ClientDTO createdClientDto = clientService.insert(clientDTO); URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(createdClientDto.getId()).toUri(); return ResponseEntity.created(uri).body(createdClientDto); } @PutMapping("/{id}") public ResponseEntity<ClientDTO> updateClient(@PathVariable Long id, @RequestBody ClientDTO clientDTO) { ClientDTO updatedClientDto = clientService.update(id, clientDTO); return ResponseEntity.ok(updatedClientDto); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteClient(@PathVariable Long id) { clientService.delete(id); return ResponseEntity.noContent().build(); } }
85d5e0f38a044ed012bcbe5568aab4eb27dd843c
[ "Markdown", "Java" ]
3
Markdown
oiagorodrigues/ds-bootcamp-java-task-1
6e82200beed9cc08202a781b22876007d81d4e6d
278cc296ee1e581f0cea4eea35f52c11ce4880b1
refs/heads/master
<repo_name>a15y87/udslogbeat<file_sep>/config/config.go // Config is put into a different package to prevent cyclic imports in case // it is needed in several locations package config import "time" type Config struct { Period time.Duration `config:"period"` SocketPath string `config:"socketpath"` MaxMessageSize int `config:"maxmessagesize"` } var DefaultConfig = Config{ Period: 1 * time.Second, MaxMessageSize: 8192, SocketPath: "/run/udslogbeat.sock", } <file_sep>/docs/index.asciidoc = Udslogbeat Docs Welcome to the Udslogbeat documentation. <file_sep>/beater/udslogbeat.go package beater import ( "fmt" "time" "github.com/elastic/beats/libbeat/beat" "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/logp" "github.com/elastic/beats/libbeat/publisher" "github.com/a15y87/udslogbeat/config" "net" ) type Udslogbeat struct { done chan struct{} config config.Config client publisher.Client udsocket net.Listener } // Creates beater func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) { config := config.DefaultConfig if err := cfg.Unpack(&config); err != nil { return nil, fmt.Errorf("Error reading config file: %v", err) } udsocket, err := net.Listen("unix", config.SocketPath) if err != nil { return nil, fmt.Errorf("Error create unix domain socket: %v", err) } bt := &Udslogbeat{ done: make(chan struct{}), config: config, udsocket: udsocket, } return bt, nil } func (bt *Udslogbeat) Run(b *beat.Beat) error { logp.Info("udslogbeat is running! Hit CTRL-C to stop it.") bt.client = b.Publisher.Connect() buf := make([]byte, bt.config.MaxMessageSize) ticker := time.NewTicker(bt.config.Period) counter := 1 for { select { case <-bt.done: return nil default: } fd, err := bt.udsocket.Accept() if err != nil { logp.Err(err.Error()) return err } nr, err := fd.Read(buf) message := string(buf[0:nr]) fd.Close() logp.Info(message) event := common.MapStr{ "@timestamp": common.Time(time.Now()), "type": b.Name, "message": string(message[:]), "counter": counter, } bt.client.PublishEvent(event) logp.Info("Event sent") counter++ } } func (bt *Udslogbeat) Stop() { bt.client.Close() close(bt.done) }
db28afa14b09381132673ff5f48f866a076a4c9d
[ "Go", "AsciiDoc" ]
3
Go
a15y87/udslogbeat
86fef62e8883080ec45e624f907075c5e88a64ea
f90f6fdb4c9d67993ab8f95ebc52b80ebc740a6b
refs/heads/master
<repo_name>lioneldiaz/PHPUnit-test<file_sep>/tests/conversion/ConversionTest.php <?php use PHPUnit\Framework\TestCase; require __DIR__ . "/../../src/conversion/Conversion.php"; class ConversionTest extends TestCase { /** @test */ public function testConversionCmToMeter () { $conversion = new Conversion(200,5); $this->assertEquals( 2, $conversion->doConvertionCmToMeter() ); } /** @test */ public function testConversionMeterToCm () { $conversion = new Conversion(200,5); $this->assertEquals ( 500, $conversion->doConversionMeterToCm() ); } }<file_sep>/README.md # PHPUnit-test How to use PHPUnit to test code. ## Getting Started ### Prerequisites You should install any web-server ### Installing Clone the repository ``` git clone https://github.com/lioneldiaz/PHPUnit-test.git ``` * Run test ``` - cd PHPUnit-test - run this command vendor\bin\phpunit ``` ## Built With * [PHP](http://php.net/) - Hypertext Preprocessor is a server-side scripting language designed for Web development, but also used as a general-purpose programming language. * [PHPUnit](https://phpunit.de/index.html) - is a programmer-oriented testing framework for PHP. ## Contributing Please read [contributors](https://github.com/lioneldiaz/PHPUnit-test/graphs/contributors) ## Authors **<NAME>** ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. <file_sep>/src/conversion/Conversion.php <?php class Conversion { /** * @decription Attribute */ private $cm; private $meter; /** * @description Constructor of the Conversion class * @param {Number} cm * @param {Number} meter */ public function __construct ($cm, $meter) { $this->cm = $cm; $this->meter = $meter; } /** * @description Do a conversion from cm to meter * @return {Number} */ public function doConvertionCmToMeter () { return $this->cm / 100; } /** * @description Do a conversion from meter to cm * @return {Number} */ public function doConversionMeterToCm () { return $this->meter * 100; } }
bff267eee471dec24aca1ad431b124b6503ac27a
[ "Markdown", "PHP" ]
3
PHP
lioneldiaz/PHPUnit-test
b7988c4582973f65256ba45805703b2ca89fbbae
868d41382b03f1715f2ae512717b297a99e230eb
refs/heads/master
<repo_name>brharrelldev/weatherapi<file_sep>/main.go package main import ( "compress/gzip" "database/sql" "encoding/json" "fmt" "github.com/gorilla/mux" _ "github.com/mattn/go-sqlite3" "io" "io/ioutil" "net/http" "os" "strings" ) type coord struct { Lon float64 `json:"lon"` Lat float64 `json:"lat"` } type weather struct { Id int `json:"id"` Name string `json:"name"` Country string `json:"country"` Coord coord `json:"coord"` } func downloaddata(url string) (int64, error) { resp, err := http.Get(url) fmt.Println("Downloading datasource") defer resp.Body.Close() if err != nil { fmt.Errorf("could not retrieve url %v", err) } urlSlice := strings.Split(url, "/") filename := urlSlice[len(urlSlice)-1] data, err := os.Create(filename) if err != nil { panic("Could not create file") } fmt.Println("Staging datasouce...") copyfile, err := io.Copy(data, resp.Body) if err != nil { panic("Could not generate file when copying, aborting ...") } fmt.Println("Datasource staged successfully!") return copyfile, nil } func unzip(file, result string) error { gz, err := os.Open(file) if err != nil { panic("something went wrong when trying to read file") } uz, err := gzip.NewReader(gz) if err != nil { fmt.Errorf("could not read file %v", err) } jsonf, err := os.Create(result) defer jsonf.Close() if err != nil { fmt.Errorf("could not unzip file %v", err) } fmt.Println("Unarchiving datasource...") io.Copy(jsonf, uz) fmt.Println("Datasource unarchived") return nil } func splitfile(bigfile string) ([]weather, error) { var weath []weather f, err := ioutil.ReadFile(bigfile) if err != nil { fmt.Errorf("could not read file %v", err) } e := json.Unmarshal(f, &weath) if e != nil { fmt.Println(e) } return weath, nil } func dbOps(db string, data []weather) error { if _, err := os.Stat(db); err != nil { f, err := os.Create(db) if err != nil { fmt.Errorf("could not create db file %v", err) return nil } defer f.Close() } sqldb, err := sql.Open("sqlite3", db) if err != nil { fmt.Errorf("could not open db file %v", err) return err } fmt.Println("Creating weather table...") createWeatherDb := `CREATE TABLE WEATHER (id integer not null primary key, city text)` _, err = sqldb.Exec(createWeatherDb) fmt.Println("weather table has been created") if err != nil { fmt.Errorf("could not execute statement %v", err) return err } stmt, err := sqldb.Begin() if err != nil { fmt.Errorf("error occured in transaction %v", err) } insert, err := stmt.Prepare("insert into weather(id, city) values(?,?)") if err != nil { fmt.Errorf("error with db driver %v") return err } for _, recs := range data { insert.Exec(recs.Id, recs.Name) } stmt.Commit() fmt.Println("Database load complete!") defer sqldb.Close() return nil } func GetWeather(writer http.ResponseWriter, request *http.Request) { request.Header.Set("Context-Type", "application/json") cities := mux.Vars(request) var cityId int db, err := sql.Open("sqlite3", "weather.db") if err != nil { fmt.Errorf("error connecting to database %v", err) } query, err := db.Prepare("select id from weather where city=? order by id") defer query.Close() err = query.QueryRow(cities["city"]).Scan(&cityId) if err != nil { fmt.Errorf("could not retrieve records from database %v") } fmt.Println(cityId) reqUrl := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?id=%d&appid=6fbe6282bf59f3cf7bed8c66bdd3a63c", cityId) req, err := http.Get(reqUrl) if err != nil { fmt.Errorf("could not complete request %v", err) writer.WriteHeader(http.StatusBadRequest) } defer req.Body.Close() respBody, err := ioutil.ReadAll(req.Body) var weathermap map[string]map[string]float32 json.Unmarshal([]byte(respBody), &weathermap) temperatureMap := weathermap["main"] currentTemp := fmt.Sprintf("%d", int(temperatureMap["temp"]*9/5-459.67)) if err != nil { fmt.Errorf("could not read response body %v", err) } writer.Write([]byte("Current weather is: " + currentTemp + "F")) } func main() { url := "http://bulk.openweathermap.org/sample" arc := "city.list.json.gz" result := "city.list.json" dbfile := "weather.db" if _, err := os.Stat(result); os.IsNotExist(err) { fmt.Println("Necessary files not detected, beginning setup ...") var urlArr = []string{url, arc} endpoint := strings.Join(urlArr, "/") _, err := downloaddata(endpoint) if err != nil { fmt.Errorf("could not create arc %v", err) } err = unzip(arc, result) if err != nil { fmt.Errorf("something happened in trying to decompress arc %v", err) } datalist, err := splitfile(result) if err != nil { fmt.Errorf("could not decode data %v\n", err) } err = dbOps(dbfile, datalist) fmt.Println(err) if err != nil { fmt.Errorf("could not operate on database %v", err) } } r := mux.NewRouter() r.HandleFunc("/weather/{city}", GetWeather).Methods("GET") fmt.Println("Launching server") http.ListenAndServe(":9000", r) } <file_sep>/Dockerfile FROM ubuntu:18.04 RUN apt-get update RUN apt-get install golang -y RUN apt-get install sqlite3 -y RUN apt-get install git -y RUN mkdir -p /etc/workspace/go ENV GOPATH=/etc/workspace/go RUN go get -u -v github.com/brharrelldev/weatherapi RUN cd /etc/workspace/go/src/github.com/brharrelldev/weatherapi/ ENTRYPOINT ["go run /etc/workspace/go/src/github.com/brharrelldev/weatherapi/main.go"]
f8363baad759d52d62d15fadcb7721b71b871f89
[ "Go", "Dockerfile" ]
2
Go
brharrelldev/weatherapi
5f23ef3d1cb0c24c020828f48a18a9d1e4f89787
f49bf35d7bd619d96da94b6ca57adb3604a568fc
refs/heads/master
<file_sep>$(document).ready(function(){ $('#home').click( function(){ $('.box').fadeOut(500); $('.eve').fadeOut(500); $('#w_nav').fadeIn(500); $('#w_name').fadeIn(500); }); $('#gala').click( function(){ $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); $('.box').fadeIn(500); $('.ash').load("gal.html"); }); $('#team').click( function(){ $('.box').fadeIn(500); $('.ash').load("teami.html"); }); $('#about').click( function(){ $('.box').fadeIn(500); $('.ash').load("about.html"); }); $('#mus').click( function(){ $('.eve').fadeIn(500); $('.eve').load("music.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#dan').click( function(){ $('.eve').fadeIn(500); $('.eve').load("dance.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#dra').click( function(){ $('.eve').fadeIn(500); $('.eve').load("drama.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#aur').click( function(){ $('.eve').fadeIn(500); $('.eve').load("aura.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#tro').click( function(){ $('.eve').fadeIn(500); $('.eve').load("pond.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#per').click( function(){ $('.eve').fadeIn(500); $('.eve').load("persona.html"); $('#w_nav').fadeOut(500); $('#w_name').fadeOut(500); }); $('#contact').click( function(){ $('.box').fadeIn(500); $('.ash').load("contact.html"); }); $('.clo').click( function(){ $('.box').fadeOut(500); $('#w_nav').fadeIn(500); $('#w_name').fadeIn(500); }); $('#mus').click(function(){ $("html, body").animate({ scrollX: 1540},600); return false; }); //calling jPreLoader var timer; $('body').jpreLoader( { splashID: "#jSplash", loaderVPos: '80%',//LOCATION OF LOADING BAR splashVPos: '40%',//LOCATION OF LOADING IMGS autoClose: true, closeBtnText: "", onetimeLoad: false, splashFunction: function() { //passing Splash Screen script to jPreLoader $('#jSplash').children('section').not('.selected').hide(); $('#jSplash').hide().fadeIn(800); timer = setInterval(function() { splashRotator(); },2000); } }, function() { //callback function clearInterval(timer); //loadingComplete(); }); //create splash screen animation function splashRotator() { var cur = $('#jSplash').children('.selected'); var next = $(cur).next(); if($(next).length != 0) { $(next).addClass('selected'); } else { $('#jSplash').children('section:nth-child(2)').addClass('selected'); next = $('#jSplash').children('section:nth-child(2)'); } $(cur).removeClass('selected').hide(700); $(next).show(700); } });
30f368b41f2ee58cd66ea1d1f80922b0786d4ff7
[ "JavaScript" ]
1
JavaScript
ashishkankal/zenith
de75b6e76d2cc9e86d273458d6cbb64016f1f0ad
7c743338db2522cb93dce8032ff98ee6a2f1eec5
refs/heads/master
<file_sep>// // Created by lshi on 17-9-25. // //#include "deform_conv3d_cuda.h" #include "TH/TH.h" #include "THC/THC.h" #include "deform_conv3d_cuda_kernel.h" #include "iostream" using namespace std; extern THCState *state; inline int input_to_output(int input, int pad, int kernel, int stride) { return (input + 2 * pad - kernel) / stride + 1; } void check(bool e, const char *msg) { if (!e) THError(msg); } void shape_check(THCState *state, THCudaDoubleTensor *input, THCudaDoubleTensor *weight, THCudaDoubleTensor *offset, THCudaDoubleTensor *output, THCudaDoubleTensor *columns, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group) { THCAssertSameGPU(THCudaDoubleTensor_checkGPU(state, 5, input, weight, offset, output, columns)); int kernel_dim = weight->nDimension; check(kernel_dim == 5, "kernel dim"); long kernel_output_c = weight->size[0]; long kernel_input_c = weight->size[1]; long kernel_l = weight->size[2]; long kernel_h = weight->size[3]; long kernel_w = weight->size[4]; int input_dim = input->nDimension; check(input_dim == 5, "input dim"); long input_b = input->size[0]; long input_c = input->size[1]; check(input_c == kernel_input_c, "input c != kernel c"); long input_l = input->size[2]; long input_h = input->size[3]; long input_w = input->size[4]; //out NC"L"H"W" int output_dim = output->nDimension; check(output_dim == 5, "output dim"); long output_b = output->size[0]; check(output_b == input_b, "output b != input b"); long output_c = output->size[1]; check(output_c == kernel_output_c, "ou c != ker c"); long output_l = output->size[2]; long output_h = output->size[3]; long output_w = output->size[4]; int offset_dim = offset->nDimension; check(offset_dim == 5, "off dim"); long offset_b = offset->size[0]; check(offset_b == input_b, "off batch"); long offset_c = offset->size[1]; // cout<<offset_c<<" "<<input_c / channel_per_deformable_group * 3 * kernel_l * kernel_h * kernel_w<<endl; check(offset_c == input_c / channel_per_deformable_group, "off channel"); long offset_l = offset->size[2]; check(offset_l == output_l, "off l"); long offset_h = offset->size[3]; check(offset_h == output_h, "off h"); long offset_w = offset->size[4]; check(offset_w == output_w, "off w"); int columns_dim = columns->nDimension; check(columns_dim == 2, "columns dim"); long columns_row = columns->size[0]; check(columns_row == input_c * kernel_l * kernel_h * kernel_w, "columns row"); long columns_col = columns->size[1]; check(columns_col == output_l * output_h * output_w, "columns col"); long output_ll = input_to_output(input_l, pad_l, kernel_l, stride_l); check(output_ll == output_l, "error output ll"); long output_hh = input_to_output(input_h, pad_h, kernel_h, stride_h); check(output_hh == output_h, "error outhh"); long output_ww = input_to_output(input_w, pad_w, kernel_w, stride_w); check(output_ww == output_w, "error outww"); } int deform_conv_forward_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *weight, THCudaDoubleTensor *offset, THCudaDoubleTensor *columns, THCudaDoubleTensor *output, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group) { // cout<<output->size[0]<<output->size[1]<<output->size[2]; shape_check(state, input, weight, offset, output, columns, pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group); THCudaDoubleTensor *input_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *offset_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *output_n = THCudaDoubleTensor_new(state); for(int i=0;i<input->size[0];i++){ THCudaDoubleTensor_select(state, input_n, input, 0, i); THCudaDoubleTensor_select(state, offset_n, offset, 0, i); THCudaDoubleTensor_select(state, output_n, output, 0, i); deformable_im2col(THCState_getCurrentStream(state), THCudaDoubleTensor_data(state, input_n), THCudaDoubleTensor_data(state, offset_n), input->size[1], input->size[2], input->size[3], input->size[4], output->size[2], output->size[3], output->size[4], weight->size[2], weight->size[3], weight->size[4], pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group, THCudaDoubleTensor_data(state, columns)); //GEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) //C := alpha*op( A )*op( B ) + beta*C, int m = weight->size[0]; int k = columns->size[0]; int n = columns->size[1]; THCudaBlas_Dgemm(state, 'n', 'n', n, m, k, 1.0f, THCudaDoubleTensor_data(state, columns), n, THCudaDoubleTensor_data(state, weight), k, 0.0f, THCudaDoubleTensor_data(state, output_n), n); } THCudaDoubleTensor_free(state, input_n); THCudaDoubleTensor_free(state, offset_n); THCudaDoubleTensor_free(state, output_n); return 1; } int deform_conv_backward_input_offset_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *weight, THCudaDoubleTensor *offset, THCudaDoubleTensor *grad_output, THCudaDoubleTensor *columns, THCudaDoubleTensor *grad_input, THCudaDoubleTensor *grad_offset, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group) { shape_check(state, input, weight, grad_offset, grad_output, columns, pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group); check(THCudaDoubleTensor_isSameSizeAs(state, offset, grad_offset), "offset vs grad_offset"); THCAssertSameGPU(THCudaDoubleTensor_checkGPU(state, 2, offset, grad_offset)); THCudaDoubleTensor *input_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *offset_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *grad_input_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *grad_offset_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *grad_output_n = THCudaDoubleTensor_new(state); for(int i=0;i<input->size[0];i++){ THCudaDoubleTensor_select(state, input_n, input, 0, i); THCudaDoubleTensor_select(state, offset_n, offset, 0, i); THCudaDoubleTensor_select(state, grad_input_n, grad_input, 0, i); THCudaDoubleTensor_select(state, grad_offset_n, grad_offset, 0, i); THCudaDoubleTensor_select(state, grad_output_n, grad_output, 0, i); //Wt * O = C long m = columns->size[0]; long n = columns->size[1]; long k = weight->size[0]; THCudaBlas_Dgemm(state, 'n', 't', n, m, k, 1.0f, THCudaDoubleTensor_data(state, grad_output_n), n, THCudaDoubleTensor_data(state, weight), m, 0.0f, THCudaDoubleTensor_data(state, columns), n); deformable_col2im_offset(THCState_getCurrentStream(state), THCudaDoubleTensor_data(state, columns), THCudaDoubleTensor_data(state, input_n), THCudaDoubleTensor_data(state, offset_n), input->size[1], input->size[2], input->size[3], input->size[4], grad_output->size[2], grad_output->size[3], grad_output->size[4], weight->size[2], weight->size[3], weight->size[4], pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group, THCudaDoubleTensor_data(state, grad_offset_n)); deformable_col2im_input(THCState_getCurrentStream(state), THCudaDoubleTensor_data(state, columns), THCudaDoubleTensor_data(state, offset_n), grad_input->size[1], grad_input->size[2], grad_input->size[3], grad_input->size[4], grad_output->size[2], grad_output->size[3], grad_output->size[4], weight->size[2], weight->size[3], weight->size[4], pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group, THCudaDoubleTensor_data(state, grad_input_n)); } THCudaDoubleTensor_free(state, input_n); THCudaDoubleTensor_free(state, offset_n); THCudaDoubleTensor_free(state, grad_input_n); THCudaDoubleTensor_free(state, grad_offset_n); THCudaDoubleTensor_free(state, grad_output_n); return 1; } int deform_conv_backward_weight_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *offset, THCudaDoubleTensor *grad_output, THCudaDoubleTensor *columns, THCudaDoubleTensor *grad_weight, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group) { shape_check(state, input, grad_weight, offset, grad_output, columns, pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group); THCudaDoubleTensor *input_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *offset_n = THCudaDoubleTensor_new(state); THCudaDoubleTensor *grad_output_n = THCudaDoubleTensor_new(state); for(int i=0;i<input->size[0];i++){ THCudaDoubleTensor_select(state, input_n, input, 0, i); THCudaDoubleTensor_select(state, offset_n, offset, 0, i); THCudaDoubleTensor_select(state, grad_output_n, grad_output, 0, i); deformable_im2col(THCState_getCurrentStream(state), THCudaDoubleTensor_data(state, input_n), THCudaDoubleTensor_data(state, offset_n), input->size[1], input->size[2], input->size[3], input->size[4], grad_output->size[2], grad_output->size[3], grad_output->size[4], grad_weight->size[2], grad_weight->size[3], grad_weight->size[4], pad_l, pad_h, pad_w, stride_l, stride_h, stride_w, channel_per_deformable_group, THCudaDoubleTensor_data(state, columns)); //GEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) //C := alpha*op( A )*op( B ) + beta*C, int m = grad_weight->size[0]; int k = columns->size[1]; int n = columns->size[0]; THCudaBlas_Dgemm(state, 't', 'n', n, m, k, 1.0f, THCudaDoubleTensor_data(state, columns), k, THCudaDoubleTensor_data(state, grad_output_n), k, 1.0f, THCudaDoubleTensor_data(state, grad_weight), n); } THCudaDoubleTensor_free(state, input_n); THCudaDoubleTensor_free(state, offset_n); THCudaDoubleTensor_free(state, grad_output_n); return 1; } <file_sep>import torch from deform_conv2d_functions import ConvOffset2dFunction from torch.autograd import Variable import os from gradcheck import gradcheck os.environ['CUDA_VISIBLE_DEVICES'] = '3' batchsize = 2 c_in = 2 c_out = 3 inpu = 7 kernel = 1 stri = 2 pad = 1 out = int((inpu + 2 * pad - kernel) / stri + 1) channel_per_group = 2 g_off = c_in // channel_per_group c_off = g_off * kernel * kernel * 2 # s = Variable(torch.rand(batchsize,2,3).type(torch.DoubleTensor).cuda(), requires_grad=True) # x = Variable(torch.rand(batchsize, c_in, inpu, inpu).type(torch.DoubleTensor).cuda(), requires_grad=True) # def stn(s, x): # g = F.affine_grid(s, x.size()) # x = F.grid_sample(x, g) # return x # print(gradcheck(stn, (s, x))) # conv_offset2d = ConvOffset2d(c_in, c_out, kernel, stri, pad, channel_per_group).cuda() conv_offset2d = ConvOffset2dFunction((stri, stri), (pad, pad), channel_per_group) # conv_offset2d = ConvOffset2d(c_in, c_out, kernel, stri, pad, channel_per_group).cuda() # inputs = Variable(torch.DoubleTensor([[[[1., 1., 1, 1, 1]] * 5] * c_in] * batchsize).type(torch.DoubleTensor).cuda(), # requires_grad=True) # offsets = Variable(torch.DoubleTensor([[[[0.001] * out] * out, # [[0.001] * out] * out] # * kernel * kernel * g_off] * batchsize).type(torch.DoubleTensor).cuda(), # requires_grad=False) # weight = Variable(torch.ones(c_out, c_in, kernel, kernel).type(torch.DoubleTensor).cuda(), # requires_grad=False) # inputs = Variable(torch.rand(batchsize, c_in, inpu, inpu).double().cuda(), requires_grad=True) offsets = Variable(torch.rand(batchsize, c_off, out, out).double().cuda(), requires_grad=True) weight = Variable(torch.rand(c_out, c_in, kernel, kernel).double().cuda(), requires_grad=True) print(gradcheck(conv_offset2d, (inputs, offsets, weight))) <file_sep>// // Created by lshi on 17-9-25. // //#ifndef DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_BACKWARD_CU_H //#define DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_BACKWARD_CU_H //#include "THC/THC.h" //#include "TH/TH.h" //template<typename DType> void deformable_im2col(cudaStream_t stream, const double *data_in, const double *data_offset, const int input_c, const int input_l, const int input_h, const int input_w, const int output_l, const int output_h, const int output_w, const int kernel_l, const int kernel_h, const int kernel_w, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group, double *data_col); //template<typename DType> void deformable_col2im_input(cudaStream_t stream, const double *data_col, const double *data_offset, const int input_c, const int input_l, const int input_h, const int input_w, const int output_l, const int output_h, const int output_w, const int kernel_l, const int kernel_h, const int kernel_w, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group, double *grad_im); //template<typename DType> void deformable_col2im_offset(cudaStream_t stream, const double *data_col, const double *data_im, const double *data_offset, const int input_c, const int input_l, const int input_h, const int input_w, const int output_l, const int output_h, const int output_w, const int kernel_l, const int kernel_h, const int kernel_w, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group, double *grad_offset); //#endif //DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_BACKWARD_CU_H <file_sep>// // Created by lshi on 17-9-25. // //#ifndef DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_H //#define DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_H //#include "TH/TH.h" //#include "THC/THC.h" //#include "deform_conv3d_cuda_kernel.h" int deform_conv_forward_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *weight, THCudaDoubleTensor *offset, THCudaDoubleTensor *columns, THCudaDoubleTensor *output, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group); int deform_conv_backward_input_offset_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *weight, THCudaDoubleTensor *offset, THCudaDoubleTensor *grad_output, THCudaDoubleTensor *columns, THCudaDoubleTensor *grad_input, THCudaDoubleTensor *grad_offset, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group); int deform_conv_backward_weight_cuda( THCudaDoubleTensor *input, THCudaDoubleTensor *offset, THCudaDoubleTensor *grad_output, THCudaDoubleTensor *columns, THCudaDoubleTensor *grad_weight, const int pad_l, const int pad_h, const int pad_w, const int stride_l, const int stride_h, const int stride_w, const int channel_per_deformable_group); //#endif //DEFORM3D_NEW_PYTORCH_DEFORM_CONV3D_CUDA_H <file_sep>import torch from deform_conv3dl_modules import ConvOffset3d from torch.autograd import Variable import os from gradcheck import gradcheck from deform_conv3dl_functions import ConvOffset3dFunction os.environ['CUDA_VISIBLE_DEVICES'] = '0' batchsize = 2 c_in = 2 c_out = 3 inpu = 5 kernel = 3 stri = 2 pad = 1 out = int((inpu + 2 * pad - kernel) / stri + 1) channel_per_group = 2 g_off = c_in // channel_per_group conv_offset3d = ConvOffset3dFunction((stri, stri, stri), (pad, pad, pad), channel_per_group) inputs = Variable(torch.rand(batchsize, c_in, inpu, inpu, inpu).type(torch.DoubleTensor).cuda(), requires_grad=True) offsets = Variable(torch.rand(batchsize, g_off, out, out, out).type(torch.DoubleTensor).cuda(), requires_grad=True) weight = Variable(torch.rand(c_out, c_in, kernel, kernel, kernel).type(torch.DoubleTensor).cuda(), requires_grad=True) print(gradcheck(conv_offset3d, (inputs, offsets, weight))) <file_sep>import deform_conv3dl_op as deform_conv import torch import os from deform_conv3dl_functions import ConvOffset3dFunction os.environ['CUDA_VISIBLE_DEVICES'] = '0' batchsize = 1 c_in = 1 c_out = 1 inpu = 3 kernel = 1 stri = 1 pad = 0 out = int((inpu + 2 * pad - kernel) / stri + 1) channel_per_group = 1 g_off = c_in // channel_per_group # inpu = torch.cuda.DoubleTensor([[[[[1.0, 1, 1], [1.0, 2, 3], [1.0, 3, 1]]] * inpu] * c_in] * batchsize) inpu = torch.cuda.DoubleTensor( [[[[[1.0] * inpu] * inpu, [[2.0] * inpu] * inpu, [[1.0] * inpu] * inpu]] * c_in] * batchsize) offset = torch.cuda.DoubleTensor([[[[[2.] * out] * out] * out] * g_off] * batchsize) weight = torch.cuda.DoubleTensor([[[[[1.0] * kernel] * kernel] * kernel] * c_in] * c_out) tmp = offset.cpu().numpy() padding = [pad, pad, pad] stride = [stri, stri, stri] conv_offset = ConvOffset3dFunction(stride, padding, channel_per_group) output = conv_offset.forward(inpu, offset, weight) tmp = output.cpu().numpy() grad_output = torch.cuda.DoubleTensor([[[[[1.0] * out] * out] * out] * c_out] * batchsize) columns = torch.zeros(weight.size(1) * weight.size(2) * weight.size(3) * weight.size(4), output.size(2) * output.size(3) * output.size(4)).double().cuda() # test for graph and grad # inputs = Variable(torch.randn(batchsize,c_in,in_l,in_h,in_w) # .double().cuda(),requires_grad=True) # offsets = Variable(torch.randn(batchsize,g_c,out_l,out_h,out_w) # .double().cuda(),requires_grad=True) # weights = Variable(torch.randn(c_out,c_in,kernel_l,kernel_h,kernel_w) # .double().cuda(), requires_grad=True) # o1 = conv_offset(inputs, offsets, weights) # o2 = Variable(grad_output,requires_grad=False) # loss = (o1 - o2).sum() # loss.backward() # grad_i = inputs.grad.data.cpu().numpy() # grad_o = offsets.grad.data.cpu().numpy() # grad_w = weights.grad.data.cpu().numpy() # --------------------------------------------- grad_input = inpu.new(*inpu.size()).double().zero_() grad_offset = offset.new(*offset.size()).double().zero_() deform_conv.deform_conv_backward_input_offset_cuda( inpu, weight, offset, grad_output, columns, grad_input, grad_offset, pad, pad, pad, stri, stri, stri, channel_per_group) grad_input_ = grad_input.cpu().numpy() grad_offset_ = grad_offset.cpu().numpy() grad_weight = weight.new(*weight.size()).double().zero_() deform_conv.deform_conv_backward_weight_cuda( inpu, offset, grad_output, columns, grad_weight, pad, pad, pad, stri, stri, stri, channel_per_group) grad_weight_ = grad_weight.cpu().numpy() print('forward\n', tmp) print('grad input\n', grad_input_) # print('grad weight\n', grad_weight_) print('grad offset\n', grad_offset_) <file_sep>import math import torch import torch.nn as nn from torch.nn.modules.module import Module from torch.nn.modules.utils import _triple from deform_conv3dl_functions import ConvOffset3dFunction class ConvOffset3d(Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, channel_per_group=1): super(ConvOffset3d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _triple(kernel_size) self.stride = _triple(stride) self.padding = _triple(padding) self.channel_per_group = channel_per_group self.weight = nn.Parameter(torch.cuda.DoubleTensor(out_channels, in_channels, *self.kernel_size)) nn.init.kaiming_normal(self.weight.data, mode='fan_out') def forward(self, input, offset): return ConvOffset3dFunction(self.stride, self.padding, self.channel_per_group)(input, offset, self.weight) <file_sep>import os.path as path import torch from torch.utils.ffi import create_extension sources = ['lib/deform_conv3d_cuda.cpp'] headers = ['lib/deform_conv3d_cuda.h'] defines = [('WITH_CUDA', None)] with_cuda = True this_file = path.dirname(path.realpath(__file__)) print(this_file) extra_objects = ['lib/deform_conv3d_cuda_kernel.cu.o'] extra_objects = [path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( 'deform_conv3dl_op', headers=headers, sources=sources, define_macros=defines, relative_to=__file__, with_cuda=with_cuda, extra_objects=extra_objects ) if __name__ == '__main__': assert torch.cuda.is_available(), 'Please install CUDA for GPU support.' ffi.build()
6e9ab01e955ce0fcd733e60c7a06828d275511d6
[ "C", "Python", "C++" ]
8
C++
hehuiguo/deformable-cnn-2d-3d
73d67b90b6a607361fd7820fcecd9c9462e69c30
a91a97f1d00ad9281479d57231d18f3ff3890d5b
refs/heads/master
<repo_name>goodyou10/PortalAlert<file_sep>/src/me/goodyou10/PortalAlert/CMDExecutor.java package me.goodyou10.PortalAlert; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CMDExecutor implements CommandExecutor { private PortalAlert plugin; public CMDExecutor(PortalAlert plugin) { this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } // They typed /portalalert if (cmd.getName().equalsIgnoreCase("portalalert")) { // Is there something after it? if (args.length < 1) { return false; } // If they typed /portalalert reload if (args[0].equalsIgnoreCase("reload")) { // Are they on console if (player != null) { sender.sendMessage("PortalAlert can only be reloaded through the console!"); return true; } // Reload the config this.plugin.reloadConfig(); this.plugin.loadConfig(); sender.sendMessage("[PortalAlert v" + PortalAlert.Version + "] Configuration has been reloaded!"); } // Else if they typed /portalalert version else if (args[0].equalsIgnoreCase("version")) { sender.sendMessage("This build of PortalAlert is version " + PortalAlert.Version); } else { return false; } return true; } return false; } }
cc58381c35e305841c37706c0f43b77cddd755cc
[ "Java" ]
1
Java
goodyou10/PortalAlert
3c80053d875e60caf3d3db39cfac8cd92d380b95
0b2996ac3ba745993b4ca73a24096e7135a038bc
refs/heads/master
<repo_name>rhtrai2/Flank<file_sep>/web/scripts/controllers/controllers.js // Controllers flank.controller('landingPageCtrl', function($scope, $http, $timeout, $routeParams, $window, $modal, $compile, $location, flankService) { $scope.verified = false; $scope.customerstatus; $scope.isloggedin; $scope.noneditable = false; $scope.noneditable2 = false; $scope.nonchangeable = false; $scope.nonchange = false; $scope.formshow = false; $scope.fornewuser = false; $scope.sendbtnprsd = false; $scope.resendotplink = false; $scope.showOtpform = { state1 : true, state2 : false, state3 : false, }; $scope.accessToken = null; $scope.hideContinuebtn = true; $scope.instagramButton = 'Connect us to your Instagram Account'; $scope.fbConnectButton; $scope.cpwd = null; $scope.ctmnts = 0; $scope.ctsecs = 0; $scope.startchr = 0; $scope.customer = { contact_no : '' , firstname : '' , lastname : '' , email : '' , gender : '' , pref : '' , pwd : '' , fbid : '', instagramusername : '' }; $scope.mismatch = ""; // if($scope.customer.pwd != null && $scope.cpwd != null) { // if($scope.customer.pwd != $scope.cpwd) { // $scope.mismatch = "Passwords don't match."; // } // } $scope.animationsEnabled = true; $scope.clearSearch = function () { $scope.customer.contact_no = ""; $scope.noneditable = false; $scope.showOtpform.state1 = true; $scope.showOtpform.state2 = false; $scope.showOtpform.state3 = false; $scope.sendbtnprsd = false; $scope.stopTimer(); }; $scope.formValidate = false; $scope.routeHash = $routeParams.emailId; console.log($scope.routeHash) // $scope.fbconnect = function() { // console.log('I am here!') // $scope.fbConnectButton = "Connected:"; // }; $scope.facebookConnect = function(response) { //do the login FB.login(function(response) { if (response.authResponse) { //user just authorized your app if(response.status == 'connected') { $scope.getUserData(); // $scope.fbconnect(); } } }, {scope: 'email,public_profile', return_scopes: true}); }; // Get Customer Login Id $scope.getUserData = function() { FB.api('/me', {fields: 'id,name,email,gender'}, function(response) { $scope.customer.fbid = response.id; $scope.fbemail = response.email; if(!$scope.customer.fbid) { $scope.fbConnectButton = "Connect with your facebook friends"; } else { $scope.fbConnectButton = "Connected:" + " " +$scope.fbemail; $scope.nonchangeable = true; } }); }; $scope.fbconnect = function() { // console.log($scope.customer.fbid); if(!$scope.customer.fbid) { $scope.fbConnectButton = "Connect with your facebook friends"; } else { $scope.fbConnectButton = "Connected:" + " " +$scope.fbemail; $scope.nonchangeable = true; } // console.log($scope.fbConnectButton); }; $scope.fbconnect(); $scope.setEmailCheck = function(customerdata) { // console.log(customerdata) $scope.customerdata = customerdata; $scope.customerstatus = customerdata.isAccountPresent; $scope.isloggedin = customerdata.isLoggedIn; if($scope.isloggedin == false && $scope.customerstatus == true) { var modalInstance = $modal.open({ animation: $scope.animationsEnabled, templateUrl: 'partials/modalContent.html', controller: 'ModalInstanceCtrl', backdrop : 'static', keyboard : false, size : 'md', scope: $scope, resolve: { items: function () { return $scope.customer.fbid; } } }); } if (customerdata.redirect == true) { $window.location.href = '/happilyustraa'; } if($scope.customerstatus == true) { $scope.customer.firstname = customerdata.data.firstname; $scope.customer.lastname = customerdata.data.lastname ; $scope.customer.gender = customerdata.data.gender; if(customerdata.data.contact_no){ $scope.showOtpform.state2 = false; $scope.verified = true; $scope.showOtpform.state3 = true; $scope.showOtpform.state1 = false; $scope.noneditable = true; $scope.customer.contact_no = customerdata.data.contact_no; } } $scope.sendfbid = function(id ,email) { $scope.customer.fbid = id; // console.log($scope.fbid); $scope.fbemail = email; // console.log($scope.fbemail); }; }; $scope.setEmailKey = function(response) { console.log(response) if(response.success == true) { $scope.formValidate = true; $scope.customer.email = response.email; $scope.originalemail = response.email ; flankService.getEmailCheck($scope.customer.email, $scope.setEmailCheck); } if(response.success == false) { window.location.href = '/happilyustraa'; } }; $scope.getEmailKey = function(key) { flankService.getEmailKey($scope.routeHash, $scope.setEmailKey); }; $scope.getEmailKey(); $scope.setsendOtp = function(response) { // console.log(response) if(response.success == true ) { $scope.showOtpform.state1 = false; $scope.showOtpform.state2 = true; $scope.resetTimer(); $scope.countdownTimer(); } if(response.success == false) { $scope.msgstat = "Message Sending Failed!"; } if(response.exhausted == true) { $scope.msgstat = "Number Of Tries Exceeded!"; } if(response.verified == true) { $scope.msgstat = " Number already exists. Try a different number!"; } } $scope.resetTimer = function () { $scope.ctmnts=4; $scope.ctsecs=0; $scope.startchr=0; } $scope.stopTimer = function () { $scope.ctmnts=0; $scope.ctsecs=0; $scope.startchr=2; } $scope.countdownTimer = function() { if($scope.startchr == 0) { $scope.ctmnts = 4 + 0; $scope.ctsecs = 0 * 1 + 1; $scope.startchr = 1; } if($scope.ctmnts==0 && $scope.ctsecs==0) { $scope.wrongotp = "[OTP Expired]"; return false; } else if($scope.startchr == 2){ $scope.ctmnts=0; $scope.ctsecs=0; $scope.startchr=0; return false; } else { // decrease seconds, and decrease minutes if seconds reach to 0 $scope.ctsecs--; if($scope.ctsecs < 0) { if($scope.ctmnts > 0) { $scope.ctsecs = 59; $scope.ctmnts--; } else { $scope.ctsecs = 0; $scope.ctmnts = 0; } } } $timeout( function(){$scope.countdownTimer(); }, 1000); } $scope.getsendOtp = function (number) { flankService.sendOtp(number, $scope.setsendOtp); $scope.noneditable = true; $scope.showOtpform.state3 = true; $scope.sendbtnprsd = true; }; $scope.setverifyOtp = function(response) { $scope.otp1 =""; $scope.otp2 =""; $scope.otp3 =""; $scope.otp4 =""; // console.log(response) if(response == '"correct_otp"') { // console.log(response) $scope.showOtpform.state2 = false; $scope.verified = true; $scope.showOtpform.state3 = false; } else if(response == '"[Invalid OTP, Try resending]"') { // console.log(response) $scope.wrongotp = "[Invalid OTP, Try resending]"; $scope.verified = false; $scope.resendotplink = true; } else if(response == '"OTP Expired"') { // console.log(response) $scope.wrongotp = "[OTP Expired]"; $scope.verified = false; } }; $scope.getresendOtp = function (number) { flankService.sendOtp(number, $scope.setsendOtp); $scope.wrongotp = ""; $scope.stopTimer(); }; $scope.getverifyOtp = function (otp1,otp2,otp3,otp4) { $scope.finalotp = $scope.otp1 + $scope.otp2 + $scope.otp3 + $scope.otp4; flankService.verifyOtp($scope.finalotp, $scope.setverifyOtp); }; $scope.formset = function () { if($scope.customerstatus != true ) { $scope.fornewuser = true; $scope.formshow = true; $scope.hideContinuebtn = false; $scope.noneditable2 = true; } else { $scope.formshow = true; $scope.hideContinuebtn = false; $scope.noneditable2 = true; } }; window.fbAsyncInit = function() { //SDK loaded, initialize it FB.init({ appId : '1524783554498004', xfbml : true, version : 'v2.5' }); //check user session and refresh it // FB.getLoginStatus(function(response) { // if (response.status === 'connected') { // //user is authorized // // document.getElementById('loginBtn').style.display = 'none'; // getUserData(); // } else { // //user is not authorized // } // }); }; //load the JavaScript SDK (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); $scope.sendfbid = function(id) { // console.log($scope.customer.fbid); }; $scope.setinstaConnect = function(response) { // console.log(response) // console.log(response) $scope.insturl = angular.fromJson(response); $window.open($scope.insturl, 'width=500,height=400'); $scope.name = $routeParams.codegenerated; // console.log($scope.name) }; $scope.setinstagramuserid = function(response) { $scope.customer.instagramusername = response.data.username; $scope.instagramid = response.data.username.id; if($scope.customer.instagramusername) { $scope.instagramButton = "Connected:" +" "+ $scope.customer.instagramusername; } } $scope.authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) { //the pop-up window size, change if you want var popupWidth = 700, popupHeight = 500, popupLeft = (window.screen.width - popupWidth) / 2, popupTop = (window.screen.height - popupHeight) / 2; var popup = window.open('instagramerrorhandler', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+''); popup.onload = function() { if(window.location.hash.length == 0) { popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token&scope=basic', '_self'); } //an interval runs to get the access token from the pop-up var interval = setInterval(function() { try { //check if hash exists if(popup.location.hash.length) { //hash found, that includes the access token clearInterval(interval); $scope.accessToken = popup.location.hash.slice(14); //slice #access_token= from string flankService.getinstagramuserid($scope.accessToken, $scope.setinstagramuserid ); popup.close(); if(callback != undefined && typeof callback == 'function') callback(); } } catch(evt) { //permission denied } }, 100); } }; $scope.login_callback = function() { $scope.nonchange = true; } $scope.openWindow = function() { $scope.authenticateInstagram('<PASSWORD>', 'http://localhost/', $scope.login_callback); }; $scope.setSaveData = function(response) { if(response == 'success') { $window.location.href = '/flank/web/thankyou'; } } $scope.getSaveData = function(customer,email) { if($scope.customerstatus == false) { console.log('eeee') if($scope.customer.pwd == $scope.cpwd) { console.log('rrrr') $scope.mismatch = " "; flankService.savedata($scope.customer,$scope.originalemail, $scope.setSaveData); } else { $scope.mismatch = "Password does not match!!"; } } if($scope.customerstatus == true) { flankService.savedata($scope.customer,$scope.originalemail, $scope.setSaveData); } } }); <file_sep>/web/index.php <?php require_once __DIR__ . '/../vendor/autoload.php'; require_once '../../happilyustraa/app/Mage.php'; $magento = Mage::app("default"); $app = new Silex\Application(); //debugging turned on $app['debug'] = false; // $app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../resources/views', )); // Router $app->mount('/', new Incentivization\Provider\MyClassController()); $app->run();<file_sep>/web/scripts/controllers/modalController.js // Flank Login Modal Controller flank.controller('ModalInstanceCtrl', function ($scope, $modalInstance, flankService) { // $scope.showforgetpassword = false; $scope.loginpage = true; // console.log($scope.originalemail) //Stops the modal to close $scope.clicked = function(event) { if(event){ event.stopPropagation(); event.preventDefault(); } }; //Customer Set Normal Login response $scope.setcustomerLogin = function(response) { // console.log(response) if(response == 'success') { // console.log('insidesuccess') $modalInstance.dismiss(); } if(response == 'wronglogin') { $scope.loginerrmsg = "Wrong Email or Password. Please try again!"; } if(response == 'wrongemail') { $scope.loginerrmsg = "Login from the Email You Are Registered!"; } }; //Customer get Normal Login Response $scope.customerLogin = function(email, pwd) { flankService.customerLogin($scope.originalemail, $scope.cust.email, $scope.cust.pwd, $scope.setcustomerLogin); } $scope.forgotpassword = function() { $scope.showforgetpassword = true; $scope.loginpage = false; } $scope.initialloginpage = function() { $scope.showforgetpassword = false; $scope.loginpage = true; } $scope.setcustomerResetPwd = function(response) { // console.log(response.success) if(response.success == true ) { $scope.msgshow = "A new password has been sent to your Email ID."; } if(response.success == false ) { // console.log(success) $scope.msgshow = "This email address was not found in our records."; } } $scope.resetPwd = function(email) { // console.log($scope.rec.email) flankService.resetPwd($scope.rec.email, $scope.setcustomerResetPwd); } $scope.setfacebookLoginCallback = function(response) { $scope.sessionfb = response; }; $scope.setFacebookLogin = function(response) { if(response.success == true) { // console.log('insidesuccess') $modalInstance.dismiss(); } else { $scope.loginerrmsg = "Wrong Email. Please try again!"; } }; //add event listener to login button for FaceBook $scope.facebookLoginCallback = function(response) { //do the login // $scope.session; FB.login(function(response) { if (response.authResponse) { //user just authorized your app $scope.fbaccesstoken = FB.getAuthResponse()['accessToken']; if(response.status == 'connected') { $scope.getUserData(); } } }, {scope: 'email,public_profile', return_scopes: true}); }; $scope.facebookLogin = function() { // console.log($scope.facebookdata) flankService.facebookLogin($scope.originalemail, $scope.facebookdata, $scope.setFacebookLogin); }; // Get Customer Login Id $scope.getUserData = function() { FB.api('/me', {fields: 'id,name,email,gender'}, function(response) { // console.log(response) $scope.facebookdata = response.id; $scope.facebookLogin(); $scope.fbid = response.id; $scope.fbemail = response.email; $scope.sendfbid($scope.fbid , $scope.fbemail); //console.log($scope.fbid); }); }; // $scope.setgoogleconnect = function(response) { // console.log(response) // }; // $scope.onSignIn = function(code) { // console.log('honolulu') // flankService.googleconnect(code, $scope.setgoogleconnect); // }; $scope.setGoogleLogin = function(response) { if(response.success == true) { // console.log('insidesuccess') $modalInstance.dismiss(); } else { $scope.loginerrmsg = "Wrong Email. Please try again!"; } }; $scope.$on('event:google-plus-signin-success', function (event,authResult) { $scope.googlecustomerid = authResult.wc.Ka; $scope.googlecustomeremail = authResult.wc.hg; console.log($scope.googlecustomerid); flankService.googleLogin($scope.originalemail, $scope.googlecustomerid, $scope.googlecustomeremail, $scope.setGoogleLogin); }); $scope.$on('event:google-plus-signin-failure', function (event,authResult) { // console.log('Auth failure or signout detected'); }); }); <file_sep>/web/scripts/controllers/baseController.js // Controllers flank.controller('baseCtrl', function($scope, $location) { console.log('sdfghjhgfdsdfgh') // window.location.href = "http://happilyunmarried.com"; }); <file_sep>/web/scripts/app.js window.flank = angular.module('flank', ['ngRoute', 'ngAnimate', 'ui.bootstrap']); flank.config(['$routeProvider', '$locationProvider', function( $routeProvider, $locationProvider) { $routeProvider .when('/',{ title: 'Base', templateUrl: 'partials/base-page.html', controller: 'baseCtrl', reloadOnSearch: false, }) .when('/incent/:emailId',{ title: 'Landing', templateUrl: 'partials/landing-page.html', controller: 'landingPageCtrl', reloadOnSearch: false, }) .when('/thankyou',{ title: 'Gratification', templateUrl: 'partials/gratification-page.html', // controller: 'gratificationPageCtrl', reloadOnSearch: false, }) .otherwise({ redirectTo: '/' }); $locationProvider.html5Mode({ enabled: true, requireBase: false, }); } ]); <file_sep>/src/Incentivization/Provider/MyClassController.php <?php namespace Incentivization\Provider; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class MyClassController implements ControllerProviderInterface { public function connect(Application $app) { $factory=$app['controllers_factory']; // Routes are defined here //default action $factory->get('/','Incentivization\Controller\IndexController::indexAction'); $factory->get('/incent/{hash}','Incentivization\Controller\IndexController::indexAction'); $factory->get('/thankyou','Incentivization\Controller\IndexController::indexAction'); $factory->get('/incentive/','Incentivization\Controller\IndexController::checkusersAction'); $factory->get('/checkurl/','Incentivization\Controller\IndexController::checkUrlAction'); $factory->get('/sendotp/','Incentivization\Controller\IndexController::sendotpAction'); $factory->get('/checkotp/','Incentivization\Controller\IndexController::checkotpAction'); $factory->post('/logincheck/','Incentivization\Controller\IndexController::logincheckAction'); $factory->get('/fblogin/','Incentivization\Controller\IndexController::fbloginAction'); $factory->get('/googlelogin/','Incentivization\Controller\IndexController::googleloginAction'); $factory->get('/forgotpassword/','Incentivization\Controller\IndexController::forgotpasswordAction'); $factory->get('/instagramerrorhandler/','Incentivization\Controller\IndexController::instagramServiceAction'); $factory->get('/instagramgetuser/','Incentivization\Controller\IndexController::instagramgetuserAction'); $factory->get('/savedata/','Incentivization\Controller\IndexController::saveFormDataAction'); $factory->get('/googleconnectaction/','Incentivization\Controller\IndexController::googleConnectAction'); return $factory; } }
14ea20d9918c3be91e1fe4471469619acc4e636e
[ "JavaScript", "PHP" ]
6
JavaScript
rhtrai2/Flank
6e2c98bbe7a3fb2ea0416b1587f0030241ba11d9
047e3c3de582d348a9401de97bda0bcf3422067d
refs/heads/master
<repo_name>NHJain/test_newRepo<file_sep>/index.js const express = require('express') const path = require('path') const port = process.env.PORT || 3001 const app = express() var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var dateFormat = require('dateformat'); var service = require('./service'); // serve static assets normally app.use(express.static(__dirname + '/public')) var neo4j = require('node-neo4j'); db = new neo4j('http://neo4j:[email protected]:7474'); app.get('*', function (request, response) { response.sendFile(path.resolve(__dirname, 'public', 'index.html')) }) app.post('/getAllBUnit', function (req, res) { service.getAllBUnit(req, res); }); app.post('/getAllEnvironment', function (req, res) { service.getAllEnvironment(req, res); }); app.post('/getInstanceLog', function (req, res) { service.getInstanceLog(req, res); }); app.post('/getProcessInstance', function (req, res) { service.getProcessInstance(req, res); }); //This will be called from the frontend and will be used to create process node. app.post('/defineProcess', function (req, res) { service.insertProcess(req, res); }); //This will be called from Java library to create a Process instance for the Process app.post('/creatProcessInstance', function (req, res) { service.createProcessInstance(req, res); }); app.post('/getAllProcess', function (req, res) { service.getProcess(req, res); }); //This will be called from Java library to update the status of the process instance app.post('/stopInstance', function (req, res) { service.stopInstance(req, res); }); // This is called to attach logs to the process instance app.post('/creatLog', function (req, res) { service.creatLog(req, res); }); //Port on which the pplication is listening app.listen(port) console.log("server started on port " + port)<file_sep>/service.js // 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript module.exports = { // This is the function which will be called in the main file, which is server.js // when the function is called in the main file. insertProcess: function (req, res) { db.insertNode({ ProcessName: req.body.description.name, ProcssDescription: req.body.description.tagline, Department: req.body.description.BusinessUnit, Owner: req.body.description.Env, }, 'Process', function (err, result) { console.log("Process with name " + result.ProcessName + " has been created."); }); res.json({ message: 'hooray! Process has been created' }); }, getAllBUnit: function (req, res) { db.cypherQuery('MATCH (n:BusinessUnit) return n', function (err, result) { res.json(result.data); }); }, getAllEnvironment: function (req, res) { db.cypherQuery('MATCH (n:Environment) return n', function (err, result) { res.json(result.data); }); }, getInstanceLog: function (req, res) { db.cypherQuery('MATCH (n:ProcessInstance)-[:LOGS_OF]-(pi:Log) where ID(n) = ' + req.body.processInstanceId + ' return pi', function (err, result) { res.json(result.data); }); }, getProcessInstance: function (req, res) { db.cypherQuery('MATCH (n:Process{ProcessName:"' + req.body.processName + '"})-[:INSTANCE_OF]-(pi:ProcessInstance) return pi', function (err, result) { res.json(result.data); }); }, createProcessInstance: function (req, res) { var dateTime = new Date(); db.insertNode({ ProcessName: req.body.ProcessName, StartTime: dateTime, EndTime: " ", Status: "Running" }, 'ProcessInstance', function (err, result) { getProcessId(result); console.log("Process Instance has been assigned to the Process"); res.json({ "ProcessInstanceId": result._id }); }); }, stopInstance: function (req, res) { var dateTime = new Date(); db.cypherQuery('MATCH (n) where ID(n) = ' + req.body.ProcessInstanceId + ' SET n.Status = "Completed" return n', function (err, result) { console.log(err); }); db.cypherQuery('MATCH (n) where ID(n) = ' + req.body.ProcessInstanceId + ' SET n.EndTime = "' + dateTime + '" return n', function (err, result) { console.log(err); }); res.json({ message: 'ProcessInstance has stopped and updated with the logs.' }); }, getProcess: function (req, res) { db.cypherQuery('MATCH (n:Process) return n', function (err, result) { res.json(result.data); }); }, creatLog: function (req, res) { var dateTime = new Date(); db.insertNode({ ProcessInstanceId: req.body.ProcessInstanceId, LogDescription: req.body.LogDescription, time: req.body.dateTime }, 'Log', function (err, result) { makeRelationship(result, "LOGS_OF"); console.log("Log for current Process Instance has been generated"); }); res.json({ message: 'hooray! Log has been created' }); } }; function getProcessId(result) { db.readNodesWithLabelsAndProperties('Process', { "ProcessName": result.ProcessName }, function (err, node) { if (err) throw err; makeRelationship(result, "INSTANCE_OF", node); }); } function makeRelationship(result, relation, node) { if (typeof node !== 'undefined' && node !== null) { var root_node_id = node[0]._id; } else { var root_node_id = result.ProcessInstanceId; } var other_node_id = result._id; db.insertRelationship(other_node_id, root_node_id, relation, {}, function (err, result) { console.log(err); }); }
d92a82c5d9cd42c3a0f0a6b414ffb37ce72e62e5
[ "JavaScript" ]
2
JavaScript
NHJain/test_newRepo
10a36d68e4fba28077d7d277a21570858bd95082
2b691ae7571b5a75740d666766fa0a714ac9e81b
refs/heads/master
<file_sep>#!/usr/bin/env python # try this with this randomly selected url: https://sites.google.com/site/nhcollier/home from os import remove from sys import exit, argv, stderr from optparse import OptionParser from codecs import open from urllib import urlopen from re import findall, sub ENCODING = "utf-8" DELIMITER = '\\t' def process_url(url_address, email_patterns, phone_patterns): """ Uses the given patterns to find hidden phone numbers and emails in the url provided. """ emails = [] phone_numbers = [] source = urlopen(url_address) for line in source: line = line.lower() for item in email_patterns: pattern = item[0] dots = item[1] matches = findall(pattern,line) if matches: for m in matches: user = m[0] domains = sub(dots,'.',m[1]) email = user + '@' + domains emails.append(email) for pattern in phone_patterns: matches = findall(pattern,line) if matches: for m in matches: phone_numbers.append(m) for item in emails: print item for item in phone_numbers: print item def get_patterns(input_file): """ Returns a list of the patterns as they are given in the input file. """ patterns = [] input_patterns = open(input_file, 'r', ENCODING) for line in input_patterns: patterns.append(line.strip()) input_patterns.close() return patterns def get_email_patterns(input_file, delim=DELIMITER): """ Returns a list of regex to find emails from the input file. """ patterns = [] users = [] ats = [] domains = [] dots = [] input_patterns = open(input_file, 'r', ENCODING) for line in input_patterns: if line.split(DELIMITER)[0] == 'USER': users.append(line.split(DELIMITER)[1].strip()) if line.split(DELIMITER)[0] == 'DOMAIN': domains.append(line.split(DELIMITER)[1].strip()) if line.split(DELIMITER)[0] == 'AT': ats.append(line.split(DELIMITER)[1].strip()) if line.split(DELIMITER)[0] == 'DOT': dots.append(line.split(DELIMITER)[1].strip()) for user in users: for at in ats: for domain in domains: for dot in dots: pattern = user + at + '((?:' + domain + ')(?:' + dot + '(?:' + domain + '))+)' patterns.append((pattern.lower(), dot)) input_patterns.close() return patterns def main(): usage = 'usage: %prog [options] <email_patterns> <phone_patterns> <url>\n' usage += '\nthe url must be given completely, as in: http://www.site.com' parser = OptionParser(usage = usage) parser.add_option("-e", "--encoding", dest = "encoding", default = "utf-8", help = "sets the encoding for the input and output file") options, arguments = parser.parse_args() if len(arguments) != 3: parser.error("incorrect number of arguments") if options.encoding: ENCODING = options.encoding emails_file = arguments[0] phones_file = arguments[1] url = arguments[2] process_url(url, get_email_patterns(emails_file), get_patterns(phones_file)) if __name__ == '__main__': main()
b86f6cd68e7dbe4943c323b95db61d291f67d459
[ "Python" ]
1
Python
sicotronic/email_phone_parser
4ad0c698001b8df9320337f5b0ce7ca58903ab08
83512ecb0ac66c84750777a44720b441b8120710
refs/heads/master
<repo_name>pedrorsantana/nuxeo-web-ui<file_sep>/elements/nuxeo-video/nuxeo-video-conversions.js /** @license (C) Copyright Nuxeo Corp. (http://nuxeo.com/) 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. */ import '@polymer/polymer/polymer-legacy.js'; import '@polymer/iron-icon/iron-icon.js'; import '@nuxeo/nuxeo-ui-elements/nuxeo-icons.js'; import { FormatBehavior } from '@nuxeo/nuxeo-ui-elements/nuxeo-format-behavior.js'; import '@nuxeo/nuxeo-ui-elements/widgets/nuxeo-tooltip.js'; import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js'; import { html } from '@polymer/polymer/lib/utils/html-tag.js'; import { I18nBehavior } from '@nuxeo/nuxeo-ui-elements/nuxeo-i18n-behavior.js'; /** `nuxeo-video-conversions` @group Nuxeo UI @element nuxeo-video-conversions */ Polymer({ _template: html` <style include="iron-flex"> a, a:active, a:visited, a:focus { @apply --nuxeo-link; } a:hover { @apply --nuxeo-link-hover; } </style> <h3>[[label]]</h3> <div> <template is="dom-repeat" items="[[document.properties.vid:transcodedVideos]]" as="conversion"> <template is="dom-if" if="[[conversion.content]]"> <div class="layout horizontal center"> <label class="flex">[[conversion.name]]</label> <div class="flex">[[conversion.info.width]] x [[conversion.info.height]]</div> <div class="flex">[[formatSize(conversion.content.length)]]</div> <a href="[[conversion.content.data]]"> <iron-icon icon="nuxeo:download"></iron-icon> <nuxeo-tooltip>[[i18n('videoViewLayout.download.tooltip')]]</nuxeo-tooltip> </a> </div> </template> </template> </div> `, is: 'nuxeo-video-conversions', behaviors: [I18nBehavior, FormatBehavior], properties: { document: Object, }, }); <file_sep>/packages/nuxeo-web-ui-ftest/features/step_definitions/support/fixtures/searches.js import { After } from 'cucumber'; import nuxeo from '../services/client'; After(() => nuxeo .request('/search/saved') .get() .then((res) => { const promises = []; res.entries.forEach((savedSearch) => { promises.push(nuxeo.repository().delete(savedSearch.id)); }); return Promise.all(promises); }) .catch((error) => { throw new Error(error); }), );
58289959342c4ecb5c2c1a9f5847ec2656e1501c
[ "JavaScript" ]
2
JavaScript
pedrorsantana/nuxeo-web-ui
5e13e76ca81dd25f6bda25f21f99ad6a0c7750f1
654db4e0f1743847415c48360fa65606d9fed741
refs/heads/master
<file_sep>import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint import matplotlib.lines as lines class body: def __init__(self, m, V_x, V_y, F, plott, colour): self.V_x = V_x self.V_y = V_y self.mass = m self.gravity = F self.plott = plott self.colour = colour def position(self): t = np.linspace(0, 10, 20) x = self.evolveX(t) y = self.evolveY(t) plott.plot(x,y,'C1') def evolveX(self, t): return self.V_x * t def evolveY(self, t): return self.V_y * t - self.gravity* t**2 /(2.0*self.mass) class rotator(body): def __init__(self, m, V_x, V_y, F, plott, colour, r, thi, w): self.radius = r self.angle = thi self.freq = w body.__init__(self, m, V_x, V_y, F, plott, colour) def evolve_rot_X(self, t,n): return self.V_x * t + ((-1)**n) *self.radius * np.cos(t*self.freq + self.angle) def evolve_rot_Y(self, t,n): return self.V_y * t - self.gravity* t**2 /(2.0*self.mass) + ((-1)**n)*self.radius * np.sin(t*self.freq + self.angle) def position_rot(self): t = np.linspace(0, 10, 20) x1 = self.evolve_rot_X(t,0) y1 = self.evolve_rot_Y(t,0) l = plott.plot(x1,y1,'ro') plt.setp(l, markersize=10) plt.setp(l,markerfacecolor='g') x2 = self.evolve_rot_X(t,1) y2 = self.evolve_rot_Y(t,1) l2 = plott.plot(x2,y2,'ro') plt.setp(l2, markersize=10) plt.setp(l2,markerfacecolor='r') for i in range(0,20): l3 = lines.Line2D([x1[i], x2[i]], [y1[i], y2[i]], lw=2, color='black') plott.ax.add_line(l3) class pplotter: def __init__(self): self.fig = plt.figure() self.ax = self.fig.add_subplot(111) def plot(self, x, y, colour): return self.ax.plot(x, y, colour) def show(self): plt.show() plott = pplotter() object = rotator(1.0, 1.75, 1.0, 0.5, plott, 'g', 1.0, 1.0, 0.5) object.position() object.position_rot()<file_sep>import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint import matplotlib.lines as lines class body: def __init__(self, m, V_x, V_y, F, plott, colour): self.V_x = V_x self.V_y = V_y self.mass = m self.gravity = F self.plott = plott self.colour = colour def position(self): t = np.linspace(0, 10, 20) x = self.evolveX(t) y = self.evolveY(t) plott.plot(x,y,'C1') def evolveX(self, t): return self.V_x * t def evolveY(self, t): return self.V_y * t - self.gravity* t**2 /(2.0*self.mass) def system(y,t,coeff,a): phi, omega = y dy_dt = [omega, coeff*np.sin(phi)] return dy_dt class rotator(body): def __init__(self, m, V_x, V_y, F, plott, colour, r, thi, omega, E, Q): body.__init__(self, m, V_x, V_y, F, plott, colour) self.radius = r self.angle = thi self.freq = omega self.field = E self.charge = Q def ang_on_t(self,t): in_cod = [self.angle, self.freq] coeff = self.charge * self.field / (self.radius* self.mass) return odeint(system,in_cod,t, args =(coeff,0))[:,0] def evolve_rot_X(self, t,n): return self.V_x * t + ((-1)**n)*self.radius*np.cos( self.angle) + ((-1)**n)*self.radius*np.cos(self.ang_on_t(t)) def evolve_rot_Y(self, t,n): return self.V_y * t - self.gravity* t**2 /(2.0*self.mass) + ((-1)**n)*self.radius * np.sin( self.angle) + ((-1)**n)*self.radius*np.sin(self.ang_on_t(t)) def position_rot(self): t = np.linspace(0, 10, 30) x1 = self.evolve_rot_X(t,0) y1 = self.evolve_rot_Y(t,0) l = plott.plot(x1,y1,'ro') plt.setp(l, markersize=10, markerfacecolor='g') x2 = self.evolve_rot_X(t,1) y2 = self.evolve_rot_Y(t,1) l2 = plott.plot(x2,y2,'ro') plt.setp(l2, markersize=10, markerfacecolor='r') for i in range(0,30): l3 = lines.Line2D([x1[i], x2[i]], [y1[i], y2[i]], lw=2, color='black') plott.ax.add_line(l3) class pplotter: def __init__(self): self.fig = plt.figure() self.ax = self.fig.add_subplot(111) def plot(self, x, y, colour): return self.ax.plot(x, y, colour) def show(self): plt.show() plott = pplotter() object = rotator(1., 2, 1, 0.5, plott, 'g', 1.0, np.pi/2, 0, 1., 0.05) object.position() object.position_rot() plt.show() <file_sep>import numpy as np import matplotlib.pyplot as plt import math import imageio import pylab from mpl_toolkits.mplot3d import axes3d import matplotlib import matplotlib.mlab as mlabD from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter U0 = 100 class Solving: def __init__(self,M,N,eps): self.M = M self.N = N self.eps = eps self.Unew = np.zeros((M,N)) self.Uold = np.ones((M,N)) def Jacobi(self): i=0 while i< 1/self.eps: self.Uold = self.Unew self.Unew[1:self.M-1, 1:self.N-1] = (self.Uold[0:-2, 1:-1]+self.Uold[2:, 1:-1]+self.Uold[1:-1, 2:]+self.Uold[1:-1, 0:-2])/4 self.Unew[:, 0] = 100 self.Unew[self.M - 1, :] = 0 self.Unew[0,:] = 0 self.Unew[:, self.N - 1] = 0 i+=1 return self.Unew def plotter(self, U): x = np.linspace(0, self.M, self.M) y = np.linspace(0, self.N, self.N) xgrid, ygrid = np.meshgrid(x, y) fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(xgrid, ygrid, U, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(0, 100) ax.zaxis.set_major_locator(LinearLocator(6)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() def run(self, method): if method == 'Jacobi': self.plotter(self.Jacobi()) test = Solving(100, 100, 0.002) test.run('Jacobi') <file_sep>import numpy as np import math from scipy.integrate import odeint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib import matplotlib.mlab as mlabD from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter U0=10 a=100 restr = 100 length = a + 1 X = np.linspace(0, a, length) Y = np.linspace(0, a, length) Xgrid, Ygrid = np.meshgrid(X, Y) Uset = np.zeros((length,length)) def U(x,y): potential = 0 k=0 while k <= restr: potential += 4*U0/(np.pi*(2*k+1)) * ( np.cosh(y*(2*k+1)*np.pi/a) - 1/np.tanh((2*k+1)*np.pi)*np.sinh(y*(2*k+1)*np.pi/a) )* np.sin(x*(2*k+1)*np.pi/a) k += 1 return potential for i in range(length): for j in range(length): Uset[i][j] = U(float(i),float(j)) fig = plt.figure() ax = fig.gca(projection='3d') # Plot the surface. surf = ax.plot_surface(Xgrid, Ygrid, Uset, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(0,U0) ax.zaxis.set_major_locator(LinearLocator(6)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # fig = plt.figure() # ax = fig.add_subplot(111, projection = '3d') # CS = plt.contour(Xgrid, Ygrid, Uset,cmap=cm.coolwarm, colors = ('indigo', 'purple' , 'violet', 'aqua' ) , linewidths = 1) # ax.plot_wireframe(Xgrid, Ygrid, Uset, color = 'black' ,linewidth = 0.3) fig.colorbar(surf, shrink=0.5, aspect=5) # plt.clabel(CS, fontsize=9, inline=1) # plt.title('U(x,y)') # lab1 = 'potential' # ax.set_xlabel(r'$Y$') # ax.set_ylabel(r'$X$') # ax.legend((lab1), loc='upper left') # # plt.show()
3660dc59085e90650102ce7b0c2b9f0b42219691
[ "Python" ]
4
Python
CompInfTech2017-18/Assignment1-PavelMephi
f1aee1fdbb6c0ab1d601ec7f530b98064e93bebe
d00f29db262c97c633aa8cef2d85ebb8dc78941d
refs/heads/master
<file_sep>import os, sys pdir = os.getenv('MODIM_HOME') sys.path.append(pdir + '/src/GUI') from ws_client import * import ws_client cmdsever_ip = '10.3.1.1' cmdserver_port = 9101 mc = ModimWSClient() mc.setCmdServerAddr(cmdsever_ip, cmdserver_port) # Interaction to welcome and start interaction def i1(): # im.setDemoPath("/home/ubuntu/playground/HumanRobotInteraction_ER") # im.gitpull() begin() FinishRuns = False epoch = 0 max_epoch = 5 while FinishRuns == False: im.display.remove_buttons() if epoch > 0: im.display.loadUrl('../layout1.html') im.display.loadUrl('HRIER/ERslide.html') im.executeModality('TEXT_title','Welcome to Wellness Hospital!') say('Welcome to Wellness Hospital', 'en') im.executeModality('TEXT_default','Have you been helped previously?') say('Have you been helped previously?','en') im.executeModality('BUTTONS',[['yes','Yes'],['no','No']]) im.executeModality('ASR',['yes','no']) a = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if a == 'yes': im.executeModality('TEXT_default','You are a patient in the database.') say('Welcome back', 'en') time.sleep(1) i2() # elif ('no' in aa) or a == 'no': elif a == 'no': im.executeModality('TEXT_default','You are a new patient.') say('Welcome to Wellness Hospital. I am a robot and my name is Marrtino. I will help you setup your emergency in the database', 'en') say('I will be asking some questions about your emergency and have you see a doctor as soon as possible, depending on the severity of your emergency', 'en') say('I will also be doing routine checks to let you know your remaining wait time. If at any point you have questions, come ask', 'en') say('We will take care of you. Thank you for visiting us.', 'en') time.sleep(2) i3() # elif ('' in aa): else: im.executeModality('TEXT_default','No answer received') time.sleep(3) if epoch == max_epoch: FinishRuns = True epoch += 1 end() # Interaction to check ticket info and retrieve info for the user def i2(): begin() import os, re, ast, time import numpy as np im.display.loadUrl('ERindex.html') im.executeModality('TEXT_default', 'Please enter the digits of your ticket number one by one.') say('Let me look for you in the database. Please enter your ticket number', 'en') # There are three digits in the ticket number, check one by one with buttons CorrTick = 'no' while CorrTick == 'no': # First number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num1 = im.ask(actionname=None, timeoutvalue=10000000) say('number '+Num1) im.display.remove_buttons() # Second number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num2 = im.ask(actionname=None, timeoutvalue=10000000) say('number'+Num2) im.display.remove_buttons() # Second number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num3 = im.ask(actionname=None, timeoutvalue=10000000) say('number'+Num3) im.display.remove_buttons() # Final ticket number ticketNumber = str(Num1 + Num2 + Num3) time.sleep(1) ticketStr = 'Your ticket number is: ' + ticketNumber im.executeModality('TEXT_default', ticketStr) say('Your ticket number is '+ticketNumber) # Check if ticket was entered correctly im.executeModality('BUTTONS',[['yes','Yes'],['no','No']]) im.executeModality('ASR',['yes','no']) CorrTick = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if CorrTick == 'yes': say('Great! Let me look at your information') elif CorrTick == 'no': im.executeModality('TEXT_default', 'Please enter again the digits of your ticket number one by one.') say('Sorry about that. Let us try again') # Check the tickets in the system directory = "/home/ubuntu/playground/HumanRobotInteraction_ER/patientInfo" ticketNums = [] with open(os.path.join(directory, "PatientTicketNum.txt"), "r") as patientTicketNums: for ticket in patientTicketNums.readlines(): ticket = ticket.split('\n')[0] ticketNums.append(ticket) if CorrTick == 'yes' and len(ticketNums) > 0 and ticketNumber in ticketNums: im.executeModality('TEXT_default', 'Your ticket has been found!') say('Your ticket has been found in the database', 'en') CorrTick == 'yes' # break elif CorrTick == 'yes' and ticketNumber not in ticketNums: im.executeModality('TEXT_default', 'Sorry. Your ticket was not found.') say('Your ticket was not found. Let us start again.', 'en') im.executeModality('TEXT_default', 'Please enter again the digits of your ticket number one by one.') CorrTick = 'no' # Retrieve the info of user in database RecordDict = dict() # RecordNames = ['Name', 'Age', 'PastMedicalHistory', 'EmergencySymptoms', 'Symptoms','LocationofPain', 'LevelofConsciousness', 'TimeAdmitted','UrgencyLevel', 'RemainingWaitTime', 'ChangeinWaitTime'] im.display.loadUrl('ERretrieve.html') im.executeModality('TEXT_title','Review of your Patient Record') RecordTxt = ticketNumber + ".txt" with open(os.path.join(directory, RecordTxt), "r") as record: for line in record.readlines(): line = line.replace('\n', '') item, info = line.split('=') RecordDict.update({item : info}) hello_say = 'Hello, ' + RecordDict["Name"] say(hello_say, 'en') im.executeModality('TEXT_default', 'What information are you searching for?') say('What can I help you with?', 'en') urgencyOld = float(RecordDict["UrgencyLevel"].split('-')[0]) AskAgain = True while AskAgain == True: # Ask what the user wants im.executeModality('BUTTONS',[['waittime','Get my Remaining Wait Time'],['update','Update my Records'], ['done', 'Done, exit.']]) im.executeModality('ASR',['waittime','update', 'done']) UserQues = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if UserQues == 'done': im.display.loadUrl('ERstart.html') # Calculate the urgency given the picked items of the patient agePoints = 0 if int(RecordDict["Age"]) < 10: # if it is a young patient, higher urgency agePoints += 3 elif int(RecordDict["Age"]) > 70: # if it's an old patient, higher urgency agePoints += 2 else: agePoints += 1 histPoints = 0 if 'smoke cigarettes' in RecordDict['PastMedicalHistory']: if 'chest' in RecordDict['LocationofPain'] or len([e for e in ['breathing', 'chest pain', 'coughing'] if e in RecordDict['EmergencySymptoms']]) > 0: histPoints += 1.5 else: histPoints += 1 checkHist = [e for e in ['overweight or obese', 'high cholesterol', 'hypertension', 'diabetes'] if e in RecordDict['PastMedicalHistory']] if len(checkHist) > 0: histPoints += (1.5 * len(checkHist)) if 'recurring symptoms' in RecordDict['PastMedicalHistory']: histPoints += 2 painPoints = 0 if 'some' in RecordDict['PainLevel']: painPoints = 1 elif 'moderate' in RecordDict['PainLevel']: painPoints = 2 elif 'intense' in RecordDict['PainLevel']: painPoints = 3 elif 'very intense' in RecordDict['PainLevel']: painPoints = 5 elif 'excruciating' in RecordDict['PainLevel']: painPoints = 7 emergPoints = 0 listEmerg = ['bleeding','breathing','unusual behavior','chest pain','choking','coughing','severe vomiting','fainting','serious injury','deep wound','sudden severe pain','sudden dizziness','swallowing poisonous','severe abdominal','head spine','feeling suicide murder'] checkEmerg = [e for e in listEmerg if e in RecordDict['EmergencySymptoms']] if len(checkEmerg) > 0: emergPoints += (10 * len(checkEmerg) * painPoints) symPoints = 0 listSym = ['fever or chills','nausea or vomit','limited movement','loss senses','cut','pain','inflammation','dizzy','recurring'] checkSym = [e for e in listSym if e in RecordDict['Symptoms']] if len(checkSym) > 0: symPoints += (2 * len(checkSym) * painPoints) locPoints = 0 listLoc = ['foot', 'legs', 'arms', 'hands', 'back'] listLoc2 = ['abdomen', 'chest', 'head'] checkLoc = [e for e in listLoc if e in RecordDict['LocationofPain']] checkLoc2 = [e for e in listLoc2 if e in RecordDict['LocationofPain']] if len(checkLoc) > 0: locPoints += (1.5 * len(checkLoc)) if len(checkLoc2) > 0: locPoints += (2 * len(checkLoc2)) conscPoints = 0 if 'medium' in RecordDict['LevelofConsciousness']: conscPoints += 2 elif 'barely' in RecordDict['LevelofConsciousness']: conscPoints += 7 elif 'unconscious' in RecordDict['LevelofConsciousness']: conscPoints += 15 totalPoints = agePoints + histPoints + emergPoints + symPoints + locPoints + conscPoints if totalPoints < 30: stringPoints = str(totalPoints) + '-low' if totalPoints > 30 and totalPoints < 70: stringPoints = str(totalPoints) + '-medium' if totalPoints > 70: stringPoints = str(totalPoints) + '-high' RecordDict.update({"UrgencyLevel" : stringPoints}) # Update data in record RecordDict.update({"ChangeinWaitTime" : 'has not'}) # Update data in record urgencyStr = RecordDict["UrgencyLevel"].split('-')[1] StrRecord = 'Your total urgency score is: ' + str(totalPoints) + '. Your urgency level is: ' + urgencyStr im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(2) # Calculate wait time for patient StrRecord = 'Calculating your wait time based on your urgency level and other patients waiting' im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(1) directory = "/home/ubuntu/playground/HumanRobotInteraction_ER/patientInfo" files = os.listdir(directory) drAppointTime = 15 # Time for a Dr to check each patient if urgencyOld + 10 < totalPoints and totalPoints > 70 and int(RecordDict['OrderNum']) != 1: StrRecord = 'Your urgency score has changed enough to require higher attention. Your new total urgency score is: ' + str(totalPoints) + ' from ' + str(int(urgencyOld)) + ', previously.' im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(2) # Get wait, order, and urgency level from each patient to see if any change is necessary NameList = [] levelList = [] waitList = [] orderList = [] for file in files: if file[0].isdigit(): NameList.append(file) with open(os.path.join(directory, file), "r") as record: for line in record.readlines(): if line[-1:] == '\n': line = line[:-1] if line.startswith('UrgencyLevel'): levelList.append(float(line.split('=')[1].split('-')[0])) elif line.startswith('WaitTime'): hr, minute = line.split('=')[1].split('-') waitMin = 60*int(hr) + int(minute) waitList.append(waitMin) elif line.startswith('OrderNum'): orderList.append(int(line.split('=')[1])) # Check if order of patients has to change (total points has to be 10 points greater # than another patient and at least a medium-high to change the patient's order) NoChange = False orderedLevel = sorted(levelList, reverse=True) for level in orderedLevel: if totalPoints > level + 10 and totalPoints > 50: index = levelList.index(level) newOrder = [] newWait = [] orderOld = orderList[index] for orders in orderList: if orders >= orderOld: orders += 1 newOrder.append(orders) newWait.append(orders*drAppointTime) break else: orderOld = len(orderList) + 1 NoChange = True # update info about new wait time for patient waitPat = orderOld*drAppointTime remain_min = round(waitPat) % 60 remain_hr = round(waitPat) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) waitStr = 'Your wait time since you arrived is ' + str(int(remain_hr)) + ' hours and ' + str(int(remain_min)) + ' minutes.' im.executeModality('TEXT_default', waitStr) say(waitStr, 'en') time.sleep(3) RecordDict.update({"WaitTime" : remain_str}) RecordDict.update({"OrderNum" : str(orderOld)}) stringDic = str(RecordDict) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') # Check the tickets in the system RecordTxt = ticketNumber + ".txt" recFile = open(os.path.join(directory, RecordTxt), "w+") recFile.write(stringDic) recFile.close() ticketFile = open(os.path.join(directory, "PatientTicketNum.txt"), "r") ticketStr = ticketFile.read() if ticketStr[-1:] == '\n': ticketStr = ticketStr[:-1] ticketStr = ticketStr + '\n' + ticketNumber recFile = open(os.path.join(directory, "PatientTicketNum.txt"), "w") recFile.write(ticketStr) recFile.close() ticketNums = [] with open(os.path.join(directory, "PatientTicketNum.txt"), "r") as patientTicketNums: for ticket in patientTicketNums.readlines(): ticket = ticket.split('\n')[0] ticketNums.append(ticket) im.executeModality('TEXT_default', str(ticketNums)) if len(ticketNums) > 0 and ticketNumber in ticketNums: im.executeModality('TEXT_default', 'Your record has been saved in the database') say('Thank you for adding the information.', 'en') elif ticketNumber not in ticketNums: im.executeModality('TEXT_default', 'Sorry an error occured, please re-enter your information.') say('Sorry some of the information you entered is incorrect, please enter them again carefully', 'en') # Add other patient's information to their record if NoChange == False: for file in files: for index, name in enumerate(NameList): if file == name: with open(os.path.join(directory, file), "r") as record: TempDic = dict() for line in record.readlines(): line = line.replace('\n', '') item, info = line.split('=') TempDic.update({item : info}) remain_min = round(newWait[index]) % 60 remain_hr = round(newWait[index]) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) TempDic.update({'WaitTime' : remain_str}) TempDic.update({'OrderNum' : str(newOrder[index])}) if orderList[index] != newOrder[index]: TempDic.update({'ChangeinWaitTime' : 'has'}) stringDic = str(TempDic) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') recFile = open(os.path.join(directory, file), "w") recFile.write(stringDic) recFile.close() im.display.loadUrl('ERstart.html') im.executeModality('TEXT_default', 'All records are updated, please wait for your turn.') say('Thank you, please now wait for your turn', 'en') time.sleep(3) else: StrRecord = 'Your urgency score has not changed enough to require higher attention.' im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') im.executeModality('TEXT_default', 'Thank you for checking your record.') say('Goodbye!', 'en') time.sleep(3) AskAgain = False # Get record of admit, wait and curr times. Caculate the new wait time. elif UserQues == 'waittime': urgencyStr = RecordDict["UrgencyLevel"].split('-')[1] admit_time = float(RecordDict["TimeAdmitted"]) updatedT = RecordDict["ChangeinWaitTime"] curr_sec = time.time() waittingTime = RecordDict["WaitTime"] wHour, wMin = waittingTime.split('-') waitTimeSec = int(wHour)*60*60 + int(wMin)*60 remain_time_sec = waitTimeSec - (curr_sec - admit_time) remain_min = (round(remain_time_sec) // 60) % 60 remain_hr = round(remain_time_sec) // 3600 if remain_min <= 0 or remain_hr < 0: # if no more remaining time remain_str = '0h0m' Remain_print = 'Your emergency is a ' + urgencyStr + ' level. We will be with you shortly in 0 min.' Remain_say = 'Your emergency ' + urgencyStr + ' level. It is your turn, someone will be with you shortly.' im.executeModality('TEXT_default', Remain_print) say(Remain_say, 'en') time.sleep(5) else: remain_str = str(int(remain_hr)) + 'h' + str(int(remain_min)) + 'm' if updatedT == 'has': Remain_print = 'Your emergency is a ' + urgencyStr + ' level. Your wait time ' + updatedT + ' been changed due to other higher emergency patients. We will be with you shortly in ' + str(int(remain_hr)) + ' hour(s) and ' + str(int(remain_min)) + ' minute(s)' Remain_say = 'Your emergency is ' + urgencyStr + ' level. We will be with in ' + str(int(remain_hr)) + ' hour and ' + str(int(remain_min)) + ' minutes' else: Remain_print = 'Your emergency is a ' + urgencyStr + ' level. Your wait time ' + updatedT + ' been changed. We will be with you shortly in ' + str(int(remain_hr)) + ' hour(s) and ' + str(int(remain_min)) + ' minute(s)' Remain_say = 'Your emergency is ' + urgencyStr + ' level. We will be with in ' + str(int(remain_hr)) + ' hour and ' + str(int(remain_min)) + ' minutes' im.executeModality('TEXT_default', Remain_print) say(Remain_say, 'en') time.sleep(5) # update the info in the record RecordDict.update({"RemainingWaitTime" : remain_str}) RecordDict.update({"ChangeinWaitTime" : 'has not'}) # If the user wants to update its information Record elif UserQues == 'update': updateD = True while updateD == True: im.executeModality('TEXT_default', 'Which would you like to update?') say('Pick the item you would like to change.', 'en') im.executeModality('BUTTONS',[['emergency','Emergency Symptoms'], ['symptoms', 'Symptoms'], ['location', 'Location of Pain'], ['conscious', 'Level of Consciousness'], ['painlevel', 'Pain Level'], ['done', 'Done, exit.']]) im.executeModality('ASR',['emergency', 'symptoms', 'location', 'conscious', 'painlevel', 'done']) HistQues = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if HistQues == 'done': im.executeModality('TEXT_default', 'Thank you for checking your record.') say('Goodbye!', 'en') updateD = False elif HistQues == 'emergency': im.executeModality('TEXT_default', 'Select again all that apply.') emergDone = True emer1 = 0 nextEm = False nextEm2 = False while emergDone == True: if nextEm == False and nextEm2 == False: im.executeModality('BUTTONS',[['bleeding','Bleeding that will not stop'],['breathing','Breathing problems'], ['unusual behavior', 'Unusual behavior, confusion, difficulty arousing'], ['chest pain', 'Chest pain'], ['choking', 'Choking'], ['coughing', 'Coughing up or vomiting blood'], ['severe vomiting', 'Severe or persistent vomiting'], ['fainting', 'Fainting or loss of consciousness'], \ ['next', 'See more options']]) im.executeModality('ASR',['bleeding', 'breathing', 'unusual behavior', 'chest pain', 'choking', 'coughing', 'severe vomiting', 'fainting', 'next']) elif nextEm == True and nextEm2 == False: im.executeModality('BUTTONS',[['serious injury', 'Serious injury due to: 1) vehicle accident, 2) burns/smoke inhalation, 3) near drowning'], ['deep wound', 'Deep or large wound'], ['sudden severe pain', 'Sudden, severe pain anywhere in the body'], ['next2', 'See more options']]) im.executeModality('ASR',['serious injury', 'deep wound', 'sudden severe pain', 'next2']) elif nextEm == True and nextEm2 == True: im.executeModality('BUTTONS',[ ['sudden dizziness', 'Sudden dizziness, weakness, or change in vision'], ['swallowing poisonous', 'Swallowing a poisonous substance'], ['severe abdominal', 'Severe abdominal pain or pressure'], ['head spine', 'Head or spine injury'], ['feeling suicide murder', 'Feeling of committing suicide or murder'], ['done', 'Done, exit.']]) im.executeModality('ASR',['sudden dizziness', 'swallowing poisonous', 'severe abdominal', 'head spine', 'feeling suicide murder', 'done']) emergQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not emergQ == 'done' and not emergQ == 'next' and not emergQ == 'next2': say('Item added', 'en') if emer1 == 0: emerg2add = emergQ emer1 += 1 else: emerg2add = emerg2add + '/' + emergQ RecordDict.update({"EmergencySymptoms" : emerg2add}) # Update data in record StrRecord = 'You picked: ' + RecordDict['EmergencySymptoms'] im.executeModality('TEXT_default', StrRecord) elif emergQ == 'done': emergDone = False elif emergQ == 'next': nextEm = True elif emergQ == 'next2': nextEm2 = True elif HistQues == 'symptoms': im.executeModality('TEXT_default', 'Select again all that apply.') symDone = True symp1 = 0 nextSy = False while symDone == True: if nextSy == False: im.executeModality('BUTTONS',[['fever/chills','Fever/Chills'],['nausea/vomit','Nausea/Vomit'], ['limited movement', 'Limited movement/Stiffness'], ['loss sense(s)', 'Loss of one or more: Sight, Hearing, Touch'], ['cut', 'Cut/Scrape'], ['next', 'See more options']]) im.executeModality('ASR',['fever/chills', 'nausea/vomit', 'limited movement', 'loss sense(s)', 'cut', 'next']) else: im.executeModality('BUTTONS',[ ['pain', 'Pain'], ['infection', 'Infection'], ['inflammation', 'Swelling/inflammation'], ['dizzy', 'light-headed/dizzy'], ['recurring', 'One or more of these are Recurring'], ['done', 'Done, exit.']]) im.executeModality('ASR',['pain', 'infection', 'inflammation', 'dizzy', 'recurring', 'done']) symQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not symQ == 'done' and not symQ == 'next': say('Item added', 'en') if symp1 == 0: sym2add = symQ symp1 += 1 else: sym2add = sym2add + '/' + symQ RecordDict.update({"Symptoms" : sym2add}) # Update data in record StrRecord = 'You picked: ' + RecordDict['Symptoms'] im.executeModality('TEXT_default', StrRecord) elif symQ == 'done': symDone = False elif symQ == 'next': nextSy = True elif HistQues == 'location': im.executeModality('TEXT_default', 'Select again all that apply.') locDone = True loc1 = 0 while locDone == True: im.executeModality('BUTTONS',[ ['foot', 'Foot(x2)'], ['leg(s)', 'Leg(s)'], ['arm(s)', 'Arm(s)'], ['hand(s)', 'Hand(s)'], ['abdomen', 'Abdomen'], ['chest', 'Chest'], ['back', 'Back'], ['head/face', 'Head/Face'], ['done', 'Done, exit.']]) im.executeModality('ASR',['foot', 'leg(s)', 'arm(s)', 'hand(s)', 'abdomen', 'chest', 'back', 'head/face', 'done']) locQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not locQ == 'done': say('Item added', 'en') if loc1 == 0: loc2add = locQ loc1 += 1 else: loc2add = loc2add + '/' + locQ RecordDict.update({"LocationofPain" : loc2add}) # Update data in record StrRecord = 'You picked: ' + RecordDict['LocationofPain'] im.executeModality('TEXT_default', StrRecord) elif locQ == 'done': locDone = False elif HistQues == 'conscious': im.executeModality('TEXT_default', 'Select again all that apply.') cons1 = 0 im.executeModality('BUTTONS',[ ['fully', 'Fully (awake, aware)'], ['medium', 'Medium (some confusion)'], ['barely', 'Barely (feeling of sleeping or fainting)'], ['none', 'Unconscious (fainted)']]) im.executeModality('ASR',['fully', 'medium', 'barely', 'none']) consQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() say(consQ, 'en') if cons1 == 0: cons2add = consQ cons1 += 1 else: cons2add = cons2add + '/' + consQ RecordDict.update({"LevelofConsciousness" : cons2add}) # Update data in record StrRecord = 'Your consciousness level is: ' + RecordDict['LevelofConsciousness'] im.executeModality('TEXT_default', StrRecord) time.sleep(3) elif HistQues == 'painlevel': im.executeModality('TEXT_default', 'Select again all that apply.') pain1 = 0 im.executeModality('BUTTONS',[ ['some', 'Some'], ['moderate', 'Moderate'], ['intense', 'Intense'], ['very intense', 'Very Intense'], ['excruciating', 'Excruciating']]) im.executeModality('ASR',['some', 'moderate', 'intense', 'very intense', 'abdomen', 'excruciating']) painQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() say(painQ, 'en') if pain1 == 0: pain2add = painQ pain1 += 1 else: pain2add = pain2add + '/' + painQ RecordDict.update({"PainLevel" : pain2add}) # Update data in record StrRecord = 'Your pain level is: ' + RecordDict['PainLevel'] im.executeModality('TEXT_default', StrRecord) time.sleep(3) stringDic = str(RecordDict) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') recFile = open(os.path.join(directory, RecordTxt), "w") recFile.write(stringDic) recFile.close() end() # Interaction to get info from the user to save in database def i3(): begin() im.display.loadUrl('ERnewpatient.html') im.executeModality('TEXT_default', 'Please enter the digits of your ticket number one by one.') say('Please enter the ticket number given to you', 'en') # There are three digits in the ticket number, check one by one with buttons CorrTick = 'no' while CorrTick == 'no': # First number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num1 = im.ask(actionname=None, timeoutvalue=10000000) say('number '+Num1) im.display.remove_buttons() # Second number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num2 = im.ask(actionname=None, timeoutvalue=10000000) say('number'+Num2) im.display.remove_buttons() # Second number: im.executeModality('BUTTONS',[['0','0'],['1','1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9']]) im.executeModality('ASR',['0','1','2', '3', '4', '5', '6', '7', '8', '9']) Num3 = im.ask(actionname=None, timeoutvalue=10000000) say('number'+Num3) im.display.remove_buttons() # Final ticket number ticketNumber = str(Num1 + Num2 + Num3) time.sleep(1) ticketStr = 'Your ticket number is: ' + ticketNumber im.executeModality('TEXT_default', ticketStr) say('Your ticket number is '+ticketNumber) # Check if ticket was entered correctly im.executeModality('BUTTONS',[['yes','Yes'],['no','No']]) im.executeModality('ASR',['yes','no']) CorrTick = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if CorrTick == 'yes': say('Great! Let us add your information to your record') elif CorrTick == 'no': im.executeModality('TEXT_default', 'Please enter again the digits of your ticket number one by one.') say('Sorry about that. Let us try again') im.executeModality('TEXT_title','Add information to your Patient Record') im.executeModality('TEXT_default', 'Please answer the following questions') say('Please enter the information being asked by pressing the corresponding buttons', 'en') RecordDict = dict() # Add name: im.executeModality('TEXT_default', 'Enter your FIRST and LAST name:') say('Enter your name', 'en') nameDone = True name1 = 0 while nameDone == True: im.executeModality('BUTTONS',[ ['a', 'A'], ['b', 'B'], ['c', 'C'], ['d', 'D'], ['e', 'E'], ['f', 'F'], ['g', 'G'], ['h', 'H'], ['i', 'I'], ['j', 'J'], ['k', 'K'], ['l', 'L'], ['m', 'M'], ['n', 'N'], ['o', 'O'], ['p', 'P'], ['q', 'Q'], ['r', 'R'], ['s', 'S'], ['t', 'T'], ['u', 'U'], ['v', 'V'], ['w', 'W'], ['x', 'X'], ['y', 'Y'], ['z', 'Z'], ['Space', 'space'], ['back', 'backspace'], ['done', 'Done']]) # im.executeModality('ASR',['foot', 'leg(s)', 'arm(s)', 'hand(s)', 'abdomen', 'chest', 'back', 'head/face', 'done']) nameQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not nameQ == 'done': say(nameQ, 'en') if name1 == 0: name2add = nameQ name1 += 1 elif name1 != 0 and nameQ != 'Space' and nameQ != 'back': name2add = name2add + nameQ elif nameQ == 'Space': name2add = name2add + ' ' elif nameQ == 'back': name2add = name2add[:-1] RecordDict.update({"Name" : name2add}) # Update data in record StrRecord = 'Your name is: ' + RecordDict['Name'] im.executeModality('TEXT_default', StrRecord) elif nameQ == 'done': nameDone = False # Add age: im.executeModality('TEXT_default', 'Enter your current age:') say('enter your age', 'en') ageDone = True age1 = 0 while ageDone == True: im.executeModality('BUTTONS',[ ['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8'], ['9', '9'], ['back', 'backspace'], ['done', 'Done']]) # im.executeModality('ASR',['foot', 'leg(s)', 'arm(s)', 'hand(s)', 'abdomen', 'chest', 'back', 'head/face', 'done']) ageQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not ageQ == 'done': say(ageQ, 'en') if age1 == 0: age2add = ageQ age1 += 1 elif age1 != 0 and ageQ != 'back': age2add = age2add + ageQ elif ageQ == 'back': age2add = age2add[:-1] RecordDict.update({"Age" : age2add}) # Update data in record StrRecord = 'Your age is: ' + RecordDict['Age'] im.executeModality('TEXT_default', StrRecord) elif ageQ == 'done': ageDone = False # Add medical history: im.executeModality('TEXT_default', 'Enter your past medical history:') say('enter your history', 'en') histDone = True hist1 = 0 while histDone == True: im.executeModality('BUTTONS',[['overweight or obese','Overweight or Obese'],['smoke cigarettes','Smoke Cigarettes'], ['high cholesterol', 'High Cholesterol'], ['hypertension', 'Hypertension'], ['diabetes', 'Diabetes'], ['recurring symptoms', 'Current Symptoms Recurring'], ['none', 'None'], ['remove', 'Remove last item'], ['done', 'Done']]) # im.executeModality('ASR',['overweight or obese','smoke cigarettes', 'high cholesterol', 'hypertension', 'diabetes', 'current symptoms recurring', 'done']) histQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if histQ != 'done': say(histQ, 'en') if hist1 == 0 and histQ != 'remove': hist2add = histQ hist1 += 1 elif hist1 != 0 and histQ != 'remove': hist2add = hist2add + '/' + histQ elif histQ == 'remove': if '/' in hist2add: hist2add = hist2add.rpartition('/')[0] else: hist2add = '' hist1 = 0 RecordDict.update({"PastMedicalHistory" : hist2add}) # Update data in record StrRecord = 'Your past history is: ' + RecordDict['PastMedicalHistory'] im.executeModality('TEXT_default', StrRecord) elif histQ == 'done': histDone = False # Add emergency symptoms: im.executeModality('TEXT_default', 'Enter any symptoms categorized as higher emergency:') say('enter your emergency symptoms', 'en') emergDone = True emer1 = 0 nextEm = False nextEm2 = False while emergDone == True: if nextEm == False and nextEm2 == False: im.executeModality('BUTTONS',[['bleeding','Bleeding that will not stop'],['breathing','Breathing problems'], ['unusual behavior', 'Unusual behavior, confusion, difficulty arousing'], ['chest pain', 'Chest pain'], ['choking', 'Choking'], ['coughing', 'Coughing up or vomiting blood'], ['severe vomiting', 'Severe or persistent vomiting'], ['fainting', 'Fainting or loss of consciousness'], \ ['remove', 'Remove last item'], ['next', 'See more options']]) im.executeModality('ASR',['bleeding', 'breathing', 'unusual behavior', 'chest pain', 'choking', 'coughing', 'severe vomiting', 'fainting', 'next']) elif nextEm == True and nextEm2 == False: im.executeModality('BUTTONS',[['serious injury', 'Serious injury due to: 1) vehicle accident, 2) burns/smoke inhalation, 3) near drowning'], ['deep wound', 'Deep or large wound'], ['sudden severe pain', 'Sudden, severe pain anywhere in the body'], ['remove', 'Remove last item'], ['next2', 'See more options']]) im.executeModality('ASR',['serious injury', 'deep wound', 'sudden severe pain', 'next2']) elif nextEm == True and nextEm2 == True: im.executeModality('BUTTONS',[ ['sudden dizziness', 'Sudden dizziness, weakness, or change in vision'], ['swallowing poisonous', 'Swallowing a poisonous substance'], ['severe abdominal', 'Severe abdominal pain or pressure'], ['head spine', 'Head or spine injury'], ['feeling suicide murder', 'Feeling of committing suicide or murder'], ['none', 'None'], ['remove', 'Remove last item'], ['done', 'Done']]) im.executeModality('ASR',['sudden dizziness', 'swallowing poisonous', 'severe abdominal', 'head spine', 'feeling suicide murder', 'done']) emergQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if emergQ != 'done' and emergQ != 'next' and emergQ != 'next2': say(emergQ, 'en') if emer1 == 0 and emergQ != 'remove': emerg2add = emergQ emer1 += 1 elif emer1 != 0 and emergQ != 'remove': emerg2add = emerg2add + '/' + emergQ elif emergQ == 'remove': if '/' in emerg2add: emerg2add = emerg2add.rpartition('/')[0] else: emerg2add = '' emer1 = 0 RecordDict.update({"EmergencySymptoms" : emerg2add}) # Update data in record StrRecord = 'Your emergency symptoms are: ' + RecordDict['EmergencySymptoms'] im.executeModality('TEXT_default', StrRecord) elif emergQ == 'done': emergDone = False elif emergQ == 'next': nextEm = True elif emergQ == 'next2': nextEm2 = True # Add symptoms: im.executeModality('TEXT_default', 'Enter your symptoms:') say('enter your symptoms', 'en') symDone = True symp1 = 0 nextSy = False while symDone == True: if nextSy == False: im.executeModality('BUTTONS',[['fever or chills','Fever/Chills'],['nausea or vomit','Nausea/Vomit'], ['limited movement', 'Limited movement/Stiffness'], ['loss senses', 'Loss of one or more: Sight, Hearing, Touch'], ['cut', 'Cut/Scrape'], ['remove', 'Remove last item'], ['next', 'See more options']]) im.executeModality('ASR',['fever/chills', 'nausea/vomit', 'limited movement', 'loss sense(s)', 'cut', 'next']) else: im.executeModality('BUTTONS',[ ['pain', 'Pain'], ['infection', 'Infection'], ['inflammation', 'Swelling/inflammation'], ['dizzy', 'light-headed/dizzy'], ['recurring', 'One or more of these are Recurring'], ['none', 'None'], ['remove', 'Remove last item'], ['done', 'Done']]) im.executeModality('ASR',['pain', 'infection', 'inflammation', 'dizzy', 'recurring', 'done']) symQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if symQ != 'done' and symQ != 'next': say(symQ, 'en') if symp1 == 0 and symQ != 'remove': sym2add = symQ symp1 += 1 elif symp1 != 0 and symQ != 'remove': sym2add = sym2add + '/' + symQ elif symQ == 'remove': if '/' in sym2add: sym2add = sym2add.rpartition('/')[0] else: sym2add = '' symp1 = 0 RecordDict.update({"Symptoms" : sym2add}) # Update data in record StrRecord = 'Your symptoms are: ' + RecordDict['Symptoms'] im.executeModality('TEXT_default', StrRecord) elif symQ == 'done': symDone = False elif symQ == 'next': nextSy = True # Add location of pain: im.executeModality('TEXT_default', 'Enter the location of your pain(s):') say('enter your pain locations', 'en') locDone = True loc1 = 0 while locDone == True: im.executeModality('BUTTONS',[ ['foot', 'Foot(x2)'], ['legs', 'Leg(s)'], ['arms', 'Arm(s)'], ['hands', 'Hand(s)'], ['abdomen', 'Abdomen'], ['chest', 'Chest'], ['back', 'Back'], ['head', 'Head/Face'], ['remove', 'Remove last item'], ['done', 'Done']]) im.executeModality('ASR',['foot', 'leg(s)', 'arm(s)', 'hand(s)', 'abdomen', 'chest', 'back', 'head/face', 'done']) locQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if not locQ == 'done': say(locQ, 'en') if loc1 == 0 and locQ != 'remove': loc2add = locQ loc1 += 1 elif loc1 != 0 and locQ != 'remove': loc2add = loc2add + '/' + locQ elif locQ == 'remove': if '/' in loc2add: loc2add = loc2add.rpartition('/')[0] else: loc2add = '' loc1 = 0 RecordDict.update({"LocationofPain" : loc2add}) # Update data in record StrRecord = 'Your pain location are: ' + RecordDict['LocationofPain'] im.executeModality('TEXT_default', StrRecord) elif locQ == 'done': locDone = False # Add level of consciousness: im.executeModality('TEXT_default', 'Pick ONE of your level of consciousness:') say('enter one of your level of consciousness', 'en') consDone = True while consDone == True: im.executeModality('BUTTONS',[ ['fully', 'Fully (awake, aware)'], ['medium', 'Medium (some confusion)'], ['barely', 'Barely (feeling of sleeping or fainting)'], ['unconscious', 'Unconscious (fainted)'], ['confirm', 'Confirm']]) im.executeModality('ASR',['fully', 'medium', 'barely', 'none']) consQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if consQ != 'confirm': say(consQ, 'en') cons2add = consQ RecordDict.update({"LevelofConsciousness" : cons2add}) # Update data in record StrRecord = 'Your consciousness level is: ' + RecordDict['LevelofConsciousness'] im.executeModality('TEXT_default', StrRecord) else: consDone = False # Add pain lavel: im.executeModality('TEXT_default', 'Pick ONE to describe your pain level:') say('pick one of your pain level', 'en') painDone = True while painDone == True: im.executeModality('BUTTONS',[ ['some', 'Some'], ['moderate', 'Moderate'], ['intense', 'Intense'], ['very intense', 'Very Intense'], ['excruciating', 'Excruciating'], ['confirm', 'Confirm']]) im.executeModality('ASR',['some', 'moderate', 'intense', 'very intense', 'abdomen', 'excruciating']) painQ = im.ask(actionname=None, timeoutvalue=10000000) im.display.remove_buttons() if painQ != 'confirm': say(painQ, 'en') pain2add = painQ RecordDict.update({"PainLevel" : pain2add}) # Update data in record StrRecord = 'Your pain level is: ' + RecordDict['PainLevel'] im.executeModality('TEXT_default', StrRecord) else: painDone = False # Add time admitted: curr_sec = time.time() loc_time = time.localtime(curr_sec) curr_date = ((time.ctime(curr_sec)).split(':')[0])[:-3] curr_time = str(loc_time.tm_hour) + 'h ' + str(loc_time.tm_min) + 'm' RecordDict.update({"TimeAdmitted" : curr_sec}) # Update data in record StrRecord = 'Your date admitted is: ' + curr_date + ', ' + str(loc_time.tm_year) im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(2) StrRecord = 'Your time admitted is: ' + str(loc_time.tm_hour) + 'h:' + str(loc_time.tm_min) + 'm' StrSay = 'Your time admitted is: ' + str(loc_time.tm_hour) + 'hours ' + str(loc_time.tm_min) + 'minutes' im.executeModality('TEXT_default', StrRecord) say(StrSay, 'en') time.sleep(2) # Add info about urgency level and wait time for the patient # Calculate the urgency given the picked items of the patient agePoints = 0 if int(RecordDict["Age"]) < 10: # if it is a young patient, higher urgency agePoints += 3 elif int(RecordDict["Age"]) > 70: # if it's an old patient, higher urgency agePoints += 2 else: agePoints += 1 histPoints = 0 if 'smoke cigarettes' in RecordDict['PastMedicalHistory']: if 'chest' in RecordDict['LocationofPain'] or len([e for e in ['breathing', 'chest pain', 'coughing'] if e in RecordDict['EmergencySymptoms']]) > 0: histPoints += 1.5 else: histPoints += 1 checkHist = [e for e in ['overweight or obese', 'high cholesterol', 'hypertension', 'diabetes'] if e in RecordDict['PastMedicalHistory']] if len(checkHist) > 0: histPoints += (1.5 * len(checkHist)) if 'recurring symptoms' in RecordDict['PastMedicalHistory']: histPoints += 2 painPoints = 0 if 'some' in RecordDict['PainLevel']: painPoints = 1 elif 'moderate' in RecordDict['PainLevel']: painPoints = 2 elif 'intense' in RecordDict['PainLevel']: painPoints = 3 elif 'very intense' in RecordDict['PainLevel']: painPoints = 5 elif 'excruciating' in RecordDict['PainLevel']: painPoints = 7 emergPoints = 0 listEmerg = ['bleeding','breathing','unusual behavior','chest pain','choking','coughing','severe vomiting','fainting','serious injury','deep wound','sudden severe pain','sudden dizziness','swallowing poisonous','severe abdominal','head spine','feeling suicide murder'] checkEmerg = [e for e in listEmerg if e in RecordDict['EmergencySymptoms']] if len(checkEmerg) > 0: emergPoints += (10 * len(checkEmerg) * painPoints) symPoints = 0 listSym = ['fever or chills','nausea or vomit','limited movement','loss senses','cut','pain','inflammation','dizzy','recurring'] checkSym = [e for e in listSym if e in RecordDict['Symptoms']] if len(checkSym) > 0: symPoints += (2 * len(checkSym) * painPoints) locPoints = 0 listLoc = ['foot', 'legs', 'arms', 'hands', 'back'] listLoc2 = ['abdomen', 'chest', 'head'] checkLoc = [e for e in listLoc if e in RecordDict['LocationofPain']] checkLoc2 = [e for e in listLoc2 if e in RecordDict['LocationofPain']] if len(checkLoc) > 0: locPoints += (1.5 * len(checkLoc)) if len(checkLoc2) > 0: locPoints += (2 * len(checkLoc2)) conscPoints = 0 if 'medium' in RecordDict['LevelofConsciousness']: conscPoints += 2 elif 'barely' in RecordDict['LevelofConsciousness']: conscPoints += 7 elif 'unconscious' in RecordDict['LevelofConsciousness']: conscPoints += 15 totalPoints = agePoints + histPoints + emergPoints + symPoints + locPoints + conscPoints if totalPoints < 30: stringPoints = str(totalPoints) + '-low' if totalPoints > 30 and totalPoints < 70: stringPoints = str(totalPoints) + '-medium' if totalPoints > 70: stringPoints = str(totalPoints) + '-high' RecordDict.update({"UrgencyLevel" : stringPoints}) # Update data in record RecordDict.update({"ChangeinWaitTime" : 'has not'}) # Update data in record urgencyStr = RecordDict["UrgencyLevel"].split('-')[1] StrRecord = 'Your total urgency score is: ' + str(totalPoints) + '. Your urgency level is: ' + urgencyStr im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(2) # Calculate wait time for patient StrRecord = 'Calculating your wait time based on your urgency level and other patients waiting' im.executeModality('TEXT_default', StrRecord) say(StrRecord, 'en') time.sleep(1) directory = "/home/ubuntu/playground/HumanRobotInteraction_ER/patientInfo" files = os.listdir(directory) drAppointTime = 15 # Time for a Dr to check each patient # Get wait, order, and urgency level from each patient to see if any change is necessary NameList = [] levelList = [] waitList = [] orderList = [] for file in files: if file[0].isdigit(): NameList.append(file) with open(os.path.join(directory, file), "r") as record: for line in record.readlines(): if line[-1:] == '\n': line = line[:-1] if line.startswith('UrgencyLevel'): levelList.append(float(line.split('=')[1].split('-')[0])) elif line.startswith('WaitTime'): hr, minute = line.split('=')[1].split('-') waitMin = 60*int(hr) + int(minute) waitList.append(waitMin) elif line.startswith('OrderNum'): orderList.append(int(line.split('=')[1])) # Check if order of patients has to change (total points has to be 10 points greater # than another patient and at least a medium-high to change the patient's order) NoChange = False orderedLevel = sorted(levelList, reverse=True) for level in orderedLevel: if totalPoints > level + 10 and totalPoints > 50: index = levelList.index(level) newOrder = [] newWait = [] orderOld = orderList[index] for orders in orderList: if orders >= orderOld: orders += 1 newOrder.append(orders) newWait.append(orders*drAppointTime) break else: orderOld = len(orderList) + 1 NoChange = True # update info about new patient waitPat = orderOld*drAppointTime remain_min = round(waitPat) % 60 remain_hr = round(waitPat) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) waitStr = 'A doctor will be with you in ' + str(int(remain_hr)) + ' hours and ' + str(int(remain_min)) + ' minutes.' im.executeModality('TEXT_default', waitStr) say(waitStr, 'en') time.sleep(3) RecordDict.update({"WaitTime" : remain_str}) RecordDict.update({"OrderNum" : str(orderOld)}) stringDic = str(RecordDict) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') # Check the tickets in the system RecordTxt = ticketNumber + ".txt" recFile = open(os.path.join(directory, RecordTxt), "w+") recFile.write(stringDic) recFile.close() ticketFile = open(os.path.join(directory, "PatientTicketNum.txt"), "r") ticketStr = ticketFile.read() if ticketStr[-1:] == '\n': ticketStr = ticketStr[:-1] ticketStr = ticketStr + '\n' + ticketNumber recFile = open(os.path.join(directory, "PatientTicketNum.txt"), "w") recFile.write(ticketStr) recFile.close() ticketNums = [] with open(os.path.join(directory, "PatientTicketNum.txt"), "r") as patientTicketNums: for ticket in patientTicketNums.readlines(): ticket = ticket.split('\n')[0] ticketNums.append(ticket) im.executeModality('TEXT_default', str(ticketNums)) if len(ticketNums) > 0 and ticketNumber in ticketNums: im.executeModality('TEXT_default', 'Your record has been saved in the database') say('Thank you for adding the information.', 'en') time.sleep(1) elif ticketNumber not in ticketNums: im.executeModality('TEXT_default', 'Sorry an error occured, please re-enter your information.') say('Sorry some of the information you entered is incorrect, please enter them again carefully', 'en') # Add other patient's information to their record if NoChange == False: for file in files: for index, name in enumerate(NameList): if file == name: with open(os.path.join(directory, file), "r") as record: TempDic = dict() for line in record.readlines(): line = line.replace('\n', '') item, info = line.split('=') TempDic.update({item : info}) remain_min = round(newWait[index]) % 60 remain_hr = round(newWait[index]) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) TempDic.update({'WaitTime' : remain_str}) TempDic.update({'OrderNum' : str(newOrder[index])}) if orderList[index] != newOrder[index]: TempDic.update({'ChangeinWaitTime' : 'has'}) stringDic = str(TempDic) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') recFile = open(os.path.join(directory, file), "w") recFile.write(stringDic) recFile.close() im.display.loadUrl('ERstart.html') im.executeModality('TEXT_default', 'All records are updated, please wait for your turn.') say('Thank you, please now wait for your turn', 'en') time.sleep(3) end() # Main code to run: mc.setDemoPath('/home/ubuntu/playground/HumanRobotInteraction_ER') # store the interactions so the robot knows to run it later mc.store_interaction(i2) mc.store_interaction(i1) mc.store_interaction(i3) mc.run_interaction(i1) <file_sep># HumanRobotInteraction_ER Human Robot Interaction (HRI) with Marrtino robot to help people arriving at the Emergency Room (ER). Video Result of User interactions can be seen at: https://www.youtube.com/watch?v=B4sg4iSE8-Q&t=2s Hospital Emergency Rooms (ER) suffer of many deficiencies that cause issues such as overcrowding, possible malpractice, and even mortality. To reduce and potentially remove these issues, technology such as robots can be implemented at the beginning of the process. The robot in this implementation is capable of interacting with humans using a software that also simplifies the process of adding new patients into the database with information regarding their emergency, it provides an urgency level calculated based on the entered information, and their estimated wait time. Patients can also return to the robot at any time to ask for their remaining wait time and update their information (e.g. symptoms, pain level) in case their emergency worsens and could require a more urgent appointment and a faster evaluation from a doctor. For a new patient or an existing one that has a high level urgency, their appointment is calculated to be shorter in order to avoid the possibility of malpractice or mortality due to extended wait time for potentially dangerous circumstances. On the other hand, patients with lower urgency level are taken in order, but are communicated if their wait time has changed due to other urgent priorities. This increased direct communication with the patients reduces the stress and confusion with both patients and practitioners. Therefore, increasing the efficiency and reliability of the most important step in the ER - prioritization of patients given the severity of their symptoms and pain level and the correct initial calculation of their urgency level. To run the implementation go to folder /scripts and in the command line write: python2 ER_modim.py <file_sep>import os, sys pdir = os.getenv('PNP_HOME') sys.path.insert(0, pdir+'/PNPnaoqi/py') import pnp_cmd_naoqi from pnp_cmd_naoqi import * def checkConditions(p): p.set_condition('mycondition', True) # Start action server if __name__ == "__main__": p = PNPCmd() p.begin() checkConditions(p) # sequence p.exec_action('say', 'hello') # blocking p.exec_action('say', 'Good_morning') # blocking p.exec_action('wait', '2') # blocking # interrupt p.exec_action('wait', '5', interrupt='timeout_2.5', recovery='wait_3;skip_action') # blocking p.exec_action('wait', '5', interrupt='mycondition', recovery='wait_3;skip_action') # blocking # concurrency p.start_action('wait', '2') # non-blocking p.start_action('wait', '5') # non-blocking status = 'run' while status == 'run': status = p.action_status('wait') print(status) time.sleep(0.5) p.interrupt_action('wait') p.end() <file_sep>import os, sys pdir = os.getenv('MODIM_HOME') sys.path.append(pdir + '/src/GUI') from ws_client import * import ws_client cmdsever_ip = '10.3.1.1' cmdserver_port = 9101 mc = ModimWSClient() mc.setCmdServerAddr(cmdsever_ip, cmdserver_port) def f(): return 1 def i1(): # im.setDemoPath("/home/ubuntu/playground/HumanRobotInteraction_ER") # im.gitpull() im.display.loadUrl('HRIER/slide.html') im.executeModality('TEXT_title','Welcome to Wellness Hosptal!') im.executeModality('TEXT_default','Hello!') im.executeModality('TTS','Welcome') im.executeModality('IMAGE','img/hri2.jpg') im.display.remove_buttons() im.executeModality('BUTTONS',[['yes','Yes'],['no','No']]) im.executeModality('ASR',['yes','no']) a = im.ask(actionname=None, timeoutvalue=10) im.executeModality('TEXT_default',a) time.sleep(3) im.display.loadUrl('index.html') def i2(): # im.setDemoPath("/home/ubuntu/playground/HumanRobotInteraction_ER") im.display.loadUrl('slide.html') im.execute('ciao') time.sleep(3) im.display.loadUrl('index.html') def i3(): # im.setDemoPath("/home/ubuntu/playground/HumanRobotInteraction_ER") im.display.loadUrl('slide.html') im.askUntilCorrect('question') time.sleep(3) im.display.loadUrl('index.html') f() mc.setDemoPath('/home/ubuntu/playground/HumanRobotInteraction_ER') mc.run_interaction(i1) # mc.store_interaction(f) # mc.run_interaction(i3) <file_sep>import os, sys pdir = os.getenv('PNP_HOME') sys.path.insert(0, pdir+'/PNPnaoqi/actions/') import action_base from action_base import * pdir = os.getenv('PEPPER_TOOLS_HOME') sys.path.append(pdir+ '/cmd_server') import pepper_cmd from pepper_cmd import * class SayAction(NAOqiAction_Base): def __init__(self, actionName, session, robot): NAOqiAction_Base.__init__(self,actionName, session) self.robot = robot def actionThread_exec (self, params): # action init # action exec print "Action "+self.actionName+" "+params+" exec..." self.robot.say(params) # action end action_termination(self.actionName,params) class WaitAction(NAOqiAction_Base): def actionThread_exec (self, params): # action init dt = 0.25 tmax = float(params) t = 0 # action exec while (self.do_run and t<tmax): print "Action "+self.actionName+" "+params+" exec..." time.sleep(dt) t += dt # action end action_termination(self.actionName,params) def initActions(): pepper_cmd.begin() app = pepper_cmd.robot.app # action_base.initApp() SayAction('say', app.session, pepper_cmd.robot) WaitAction('wait', app.session) return app # Start action server if __name__ == "__main__": print("Starting action server (CTRL+C to quit)") app = initActions() app.run() <file_sep># -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ directory = "/home/ccapontep/Documents/1_AIRO/Y2S2/Elective_in_AI/HRI/ER_Robot/HumanRobotInteraction_ER/patientInfo" import os ticketNumber = '012' RecordTxt = ticketNumber + ".txt" RecordDict = dict() # Creating the ticket dictionary from record with open(os.path.join(directory, RecordTxt), "r") as record: for line in record.readlines(): line = line.replace('\n', '') item, info = line.split('=') RecordDict.update({item : info}) # Get the remaining time # Test import time #seconds = time.time() #print"Seconds since epoch =", seconds # #curr_time = time.localtime(seconds) #print"Current time is: ", curr_time #print"The hour: ", curr_time.tm_hour #print"The minutes: ", curr_time.tm_min #print"The seconds: ", curr_time.tm_sec # From the code admit_time = float(RecordDict["TimeAdmitted"]) curr_sec = time.time() waittingTime = RecordDict["WaitTime"] wHour, wMin = waittingTime.split('-') waitTimeSec = int(wHour)*60*60 + int(wMin)*60 remain_time_sec = waitTimeSec - (curr_sec - admit_time) remain_min = (round(remain_time_sec) // 60) % 60 remain_hr = round(remain_time_sec) // 3600 if remain_min < 0 or remain_hr < 0: # if no more remaining time remain_str = '0h0m' else: remain_str = str(int(remain_hr)) + 'h' + str(int(remain_min)) + 'm' stringDic = str(RecordDict) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': ','=') recFile = open(os.path.join(directory, RecordTxt), "w") recFile.write(stringDic) recFile.close() # Add time admitted: curr_sec = time.time() loc_time = time.localtime(curr_sec) curr_date = ((time.ctime(curr_sec)).split(':')[0])[:-3] curr_time = str(loc_time.tm_hour) + ' hours and ' + str(loc_time.tm_min) + ' minutes' RecordDict.update({"TimeAdmitted" : curr_sec}) # Update data in record StrRecord = 'Your date admitted is: ' + curr_date StrRecord2 = 'Your time admitted is: ' + curr_time # Calculate the urgency given the picked items of the patient agePoints = 0 if int(RecordDict["Age"]) < 10: # if it is a young patient, higher urgency agePoints += 3 elif int(RecordDict["Age"]) > 70: # if it's an old patient, higher urgency agePoints += 2 else: agePoints += 1 histPoints = 0 if 'smoke cigarettes' in RecordDict['PastMedicalHistory']: if 'chest' in RecordDict['LocationofPain'] or len([e for e in ['breathing', 'chest pain', 'coughing'] if e in RecordDict['EmergencySymptoms']]) > 0: histPoints += 1.5 else: histPoints += 1 checkHist = [e for e in ['overweight or obese', 'high cholesterol', 'hypertension', 'diabetes'] if e in RecordDict['PastMedicalHistory']] if len(checkHist) > 0: histPoints += (1.5 * len(checkHist)) if 'recurring symptoms' in RecordDict['PastMedicalHistory']: histPoints += 2 painPoints = 0 if 'some' in RecordDict['PainLevel']: painPoints = 1 elif 'moderate' in RecordDict['PainLevel']: painPoints = 2 elif 'intense' in RecordDict['PainLevel']: painPoints = 3 elif 'very intense' in RecordDict['PainLevel']: painPoints = 5 elif 'excruciating' in RecordDict['PainLevel']: painPoints = 7 emergPoints = 0 listEmerg = ['bleeding','breathing','unusual behavior','chest pain','choking','coughing','severe vomiting','fainting','serious injury','deep wound','sudden severe pain','sudden dizziness','swallowing poisonous','severe abdominal','head spine','feeling suicide murder'] checkEmerg = [e for e in listEmerg if e in RecordDict['EmergencySymptoms']] if len(checkEmerg) > 0: emergPoints += (10 * len(checkEmerg) * painPoints) symPoints = 0 listSym = ['fever or chills','nausea or vomit','limited movement','loss senses','cut','pain','inflammation','dizzy','recurring'] checkSym = [e for e in listSym if e in RecordDict['Symptoms']] if len(checkSym) > 0: symPoints += (2 * len(checkSym) * painPoints) locPoints = 0 listLoc = ['foot', 'legs', 'arms', 'hands', 'back'] listLoc2 = ['abdomen', 'chest', 'head'] checkLoc = [e for e in listLoc if e in RecordDict['LocationofPain']] checkLoc2 = [e for e in listLoc2 if e in RecordDict['LocationofPain']] if len(checkLoc) > 0: locPoints += (1.5 * len(checkLoc)) if len(checkLoc2) > 0: locPoints += (2 * len(checkLoc2)) conscPoints = 0 if 'medium' in RecordDict['LevelofConsciousness']: conscPoints += 2 elif 'barely' in RecordDict['LevelofConsciousness']: conscPoints += 7 elif 'unconscious' in RecordDict['LevelofConsciousness']: conscPoints += 15 totalPoints = agePoints + histPoints + emergPoints + symPoints + locPoints + conscPoints emerg2add = 'your bla bla: 7/pain/breathing' if '/' in emerg2add: emerg2add = emerg2add.rpartition('/')[0] else: emerg2add = emerg2add.split(':')[0] ticketFile = open(os.path.join(directory, "PatientTicketNum.txt"), "r") ticketStr = ticketFile.read() if ticketStr[-1:] == '\n': ticketStr = ticketStr[:-1] ticketStr = ticketStr + '\n' + ticketNumber recFile = open(os.path.join(directory, "PatientTicketNum.txt"), "w+") recFile.write(ticketStr) recFile.close() ticketNums = [] with open(os.path.join(directory, "PatientTicketNum.txt"), "r") as patientTicketNums: for ticket in patientTicketNums.readlines(): ticket = ticket.split('\n')[0] ticketNums.append(ticket) ticketNumber in ticketNums #int(ticketNumber) in (map(int, ticketNums)) wrong # Calculate wait time for patient files = os.listdir(directory) NameList = [] levelList = [] waitList = [] orderList = [] for file in files: if file[0].isdigit(): NameList.append(file) with open(os.path.join(directory, file), "r") as record: for line in record.readlines(): if line.startswith('UrgencyLevel'): levelList.append(float(line.split('=')[1].split('-')[0])) elif line.startswith('WaitTime'): hr, minute = line.split('=')[1].split('-') waitMin = 60*int(hr) + int(minute) waitList.append(waitMin) elif line.startswith('OrderNum'): orderList.append(int(line.split('=')[1])) drAppointTime = 15 # Time for a Dr to check each patient totalPoints = 50 # temp orderedLevel = sorted(levelList, reverse=True) for level in orderedLevel: if totalPoints > level + 10 and totalPoints > 45: index = levelList.index(level) newOrder = [] newWait = [] orderOld = orderList[index] for indexO, orders in enumerate(orderList): if orders >= orderOld: orders += 1 newOrder.append(orders) newWait.append(orders*drAppointTime) break waitPat = orderOld*drAppointTime remain_min = round(waitPat) % 60 remain_hr = round(waitPat) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) RecordDict.update({"WaitTime" : remain_str}) RecordDict.update({"OrderNum" : str(orderOld)}) for file in files: for index, name in enumerate(NameList): if file == name: with open(os.path.join(directory, file), "r") as record: TempDic = dict() for line in record.readlines(): line = line.replace('\n', '') item, info = line.split('=') TempDic.update({item : info}) remain_min = round(newWait[index]) % 60 remain_hr = round(newWait[index]) // 60 remain_str = str(int(remain_hr)) + '-' + str(int(remain_min)) TempDic.update({'WaitTime' : remain_str}) TempDic.update({'OrderNum' : str(newOrder[index])}) if orderList[index] != newOrder[index]: print('before', TempDic['ChangeinWaitTime']) TempDic.update({'ChangeinWaitTime' : 'has'}) print(TempDic['ChangeinWaitTime']) stringDic = str(TempDic) stringDic = stringDic.replace(', ','\n').replace("'","").replace('{','').replace('}','').replace(': u','=').replace(': ','=') recFile = open(os.path.join(directory, file), "w") recFile.write(stringDic) recFile.close() <file_sep> class PDDLPlanOutputIterator: def __init__(self, planfilename): self.iter=0 f = open(planfilename,'r') self.line = f.read() i = self.line.find('(output)') if i>=0: self.line = self.line[i+8:] # remove heading text print(self.line) f.close() def next(self): i1 = self.line[self.iter:].find('(') i2 = self.line[self.iter:].find(')') if (i1<0 or i2<0): return '' r = self.line[self.iter+i1:self.iter+i2+1] self.iter += i2+1 return r def executeAction(a,p): # Implement exection of action a with parameters p print("Execute: action %s with parameters %s" %(a,p)) if __name__=='__main__': planfilename = '../plans/plan1.pddloutput' # name of file containing the plan output pit = PDDLPlanOutputIterator(planfilename) pp = '' # Python program r = '*' while (r!=''): r = pit.next() # get next PDDL action (A p1 p2 ... pn) from plan file if r!='': a = r[1:len(r)-1] # remove parenthesis v = a.split(' ') # split parameters if (v[0]==':action'): # remove final stuff in the file break p = '' # build parameters list separated by _ -> p1_p2_..._pn if (len(v)>1): for i in range(1,len(v)-1): p = p + v[i] + "_"; p = p + v[-1]; pp += "executeAction('%s','%s')\n" %(v[0],p) # add Python statement print('Python program:') print(pp) exec(pp)
401a03896f05313cc06297760aedfc44499d60e7
[ "Markdown", "Python" ]
7
Python
ccapontep/HumanRobotInteraction_ER
b74c225cd4700566d3a2aca00b8861ddacddec56
6d4d3b4440532c1774d964ca4deddb3086083f9e
refs/heads/master
<file_sep> # gfx2col graphic converter for Colecovision PVcollib development ## Usage ``` gfx2col [options] png/bmp/pcx/tga filename ... ``` where filename is a 256 color PNG, BMP, PCX or TGA file with only 1st palette used with default 16 colors of Coleco ## Options ### General options - `-c[no|rle|ple|dan]` Compression method [no] ### Graphique options - `-s` Sprite mode - `-b` Bitmap mode (no more 256 tiles limits) - `-g[m1|m2]` TMS9918 Graphic mode (mode 2 or mode 1) [m2] - `-e[0|1|2|3]` Enhanced Color Mode (F18A only) [0] - `-t` Enable transparent tiles (color 0) ### Map options - `-m!` Exclude map from output - `-m` Convert the whole picture - `-mR!` No tile reduction (not advised) - `-mn#` Generate the whole picture with an offset for tile number where # is the offset in decimal (0 to 2047) ### Palette options - `-p!` Exclude palette from output - `-po` Export palette (16 colors (ecm0) or 64 colors(ecm1-3) - `-pR` Palette rounding ### File options - `-f[bmp|pcx|tga|png]` Convert a bmp or pcx or tga or png file [bmp] ### Misc options - `-q` Quiet mode ## Example ``` gfx2col -crle -fpng -m myimage.png ``` This will will convert a myimage png file to a inc file with 8x8 tiles, rle compressed. ## History V1.2.0 : add f18a features V1.1.0 : add bitmap mode V1.0.0 : initial release <file_sep>/*--------------------------------------------------------------------------------- Generic pad & spinner functions. Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file pad.h * \brief coleco generic pad & spinner support. * * This unit provides methods to read controller state.<br> *<br> * Here is the list of supported controller devices:<br> * - coleco default pad <br> * - coleco spinner<br> */ #ifndef COL_PAD_H #define COL_PAD_H #include <coleco/coltypes.h> #define PAD_UP 1 #define PAD_RIGHT 2 #define PAD_DOWN 4 #define PAD_LEFT 8 #define PAD_FIRE4 16 #define PAD_FIRE3 32 #define PAD_FIRE2 64 #define PAD_FIRE1 128 #define PAD_FIRES (PAD_FIRE1 | PAD_FIRE2) #define PAD_KEY0 0 #define PAD_KEY1 1 #define PAD_KEY2 2 #define PAD_KEY3 3 #define PAD_KEY4 4 #define PAD_KEY5 5 #define PAD_KEY6 6 #define PAD_KEY7 7 #define PAD_KEY8 8 #define PAD_KEY9 9 #define PAD_KEYSTAR 10 #define PAD_KEYSHARP 11 #define PAD_KEYNONE 15 /** * \brief PAD 1 value */ extern volatile u8 joypad_1; /** * \brief PAD 2 value */ extern volatile u8 joypad_2; /** * \brief SPINNER 1 value<br> * <b>/!\ spinner 1 value is reversed</b> */ extern volatile char spinner_1; /** * \brief SPINNER 2 value */ extern volatile char spinner_2; /** * \brief KEYBOARD from PAD 1 values */ extern volatile u8 keypad_1; /** * \brief KEYBOARD from PAD 2 values */ extern volatile u8 keypad_2; /** * \fn void pad_resetspin(void) * \brief reset spinners 1 & 2 values */ void pad_resetspin(void); /** * \fn void pad_disablespin(void) * \brief enable spinners functions */ void pad_disablespin(void); /** * \fn void pad_enablespin(void) * \brief enable spinners functions to get their values */ void pad_enablespin(void); #endif <file_sep>/*--------------------------------------------------------------------------------- coltypes.h -- Common types (and a few useful macros) Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /*! \file coltypes.h \brief Custom types used by pvcollib */ #ifndef _COLTYPES_INCLUDE #define _COLTYPES_INCLUDE //! bit field #define BIT(n) (1<<n) //! 8 bit and 16 bit signed and unsigned. typedef signed char s8; typedef unsigned char u8; typedef signed s16; typedef unsigned u16; //! boolean definitions typedef unsigned char bool; #define FALSE 0 #define TRUE 0xff #define false 0 #define true 0xff // stdio definitions #ifndef NULL #define NULL 0 #endif #endif <file_sep>## Configuring tools We will begin with a Programmer's Notepad Tools menu configuration to have the make command with **Alt+&** shortcut on our keyboard (but you are free to use something else :-D). First of all, go to **Tools/Options** Menu and select Tools entry to the left. On the **Scheme** dropdown list, select **None** to have the "global tools" selections. ![PNT1](http://www.portabledev.com/wp-content/uploads/2018/02/pn_tools_01.jpg) Click on **Add** button to the right and type text as in the following screen. ![PNT2](http://www.portabledev.com/wp-content/uploads/2018/02/pn_tools_02.jpg) Do same thing for the **make clean** entry, you just have to add the word **clean** in **parameters** text box, and add shortcut **Alt+é** on your keyboard (or what you want ;-)). That's all, now you have the _make_ and _make clean_ command defined. ![PNT3](http://www.portabledev.com/wp-content/uploads/2018/02/pn_tools_03.jpg) ## Editing Path and compiling With Programmer's Notepad menu **File/Open project(s)**, open the //helloworld.pnproj// file that is in the pvcollib **helloworld** directory example. You will see 3 files on the Project Window. * helloworld.c is the C source file. * helloworld.h is the header file of the helloworld.c source file. * Makefile is the file used to make the .rom file. Open **Makefile** and change the path to use the correct directory for your colecodev installation. Example below show a **c:/colecodev/** root entry for my coleco developments, if you have **c:\colecodev**, you just have to change it to **/c/colecodev**. Same thing for your devkitcol entry. ``` # path to colecodev root directory (for emulators, devkitcol, pvcollib) export DEVKITCOL := /c/colecodev/ # path to devkitcol root directory for compiler export DEVKITSDCC := /c/colecodev/devkitcol ``` Now, just do a //make clean// command (with the shortcut you configured below, for example Alt+é for me). You must see a new Output window with the result of your make clean command. ``` > "make" clean clean ... > Process Exit Code: 0 > Time Taken: 00:00 ``` If an error occurs, that's because your installation is not good, sorry about that. You can post your problem in our [Portabledev Forum](http://www.portabledev.com/smf/index.php) or here in [Issues Part](https://github.com/alekmaul/pvcollib/issues), we will help you as soon as possible. Ok, now your template directory is cleaned, you can run the //make// command (with shortcut, remember ). You will have the following things in your Programmer's Notepad output window. ``` > "make.exe" Compiling C to .rel ... helloworld.c sdcc -mz80 -c -I/c/colecodev//include -I/c/colecodev/devkitcol/include --std-c99 --opt-code-size --fverbose-asm --max-allocs-per-node 20000 --vc -I/c/colecodev/coleco-examples/helloworld/ helloworld.c Linking ... helloworld.rom sdcc -mz80 --no-std-crt0 --code-loc 0x8048 --data-loc 0x7000 /c/colecodev//lib/collib.lib /c/colecodev//lib/crtcol.rel helloworld.rel sdobjcopy -R .sec5 -I ihex -O binary --pad-to 0xffff --gap-fill 0xff crtcol.ihx helloworld.rom _CODE 00008048 000003B5 = 949. bytes (REL,CON) _GSINIT 000083FD 0000000F = 15. bytes (REL,CON) _GSFINAL 0000840C 00000001 = 1. bytes (REL,CON) _DATA 00007000 000000F5 = 245. bytes (REL,CON) _HEADER0 00000000 00000024 = 36. bytes (ABS,CON) _CODE = 0x8048 _DATA = 0x7000 Generate rom ... all > Process Exit Code: 0 > Time Taken: 00:06 ``` That's all, you've compiled your first program that does nothing except display the fantastic "Hello World!" message but it's a first step !. Welcome to PVcollib world and enjoy doing some homebrews for your Colecovision :-P !<file_sep>/*--------------------------------------------------------------------------------- Generic sgm system functions Copyright (C) 2021 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file sgm.h * \brief contains the basic definitions for controlling the sgm system device. * * This unit provides generic features related to sgm device.<br> *<br> * Here is the list of features:<br> * - enable and disable sgm<br> */ #ifndef COL_SGM_INCLUDE #define COL_SGM_INCLUDE #include <coleco/coltypes.h> /** * \brief sys_sgmok is set if sgm module is present<br> * when calling sys_sgminit function<br> */ extern volatile u8 sys_sgmok; /** * \fn void sys_sgminit(void) * \brief Activate sgm device<br> * Activate SGM and init sys_sgmok variable with 1 if it is ok<br> */ void sys_sgminit(void); #endif <file_sep>/*--------------------------------------------------------------------------------- Generic sound functions. Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file sound.h * \brief coleco generic sound support. */ #ifndef COL_SOUND_H #define COL_SOUND_H #include <coleco/coltypes.h> /** \brief definition of sound area */ typedef struct { void *sound_data; unsigned sound_area; } sound_t; /** \brief sound areas 1 to 6 available pour channels */ #define SOUNDAREA1 0x702b #define SOUNDAREA2 0x702b+10 #define SOUNDAREA3 0x702b+20 #define SOUNDAREA4 0x702b+30 #define SOUNDAREA5 0x702b+40 #define SOUNDAREA6 0x702b+50 /** \brief definition of music area. music_duration, [NBR-1 sounds to start | sound_no1 in 6 bits ], sound_no2*, sound_no2*, sound_no2* So, for 1 channel, channel_data will have directly the sound entry (ex: 0x01), for 2 channels, it will be 0x41,0x02 for example for 3 channels, it will be 0x81,02,03 for 4 channels (maximum), it will be 0xc1,02,03,04 these sound_no are not essential, it depends on the value of NBR. IF music_duration = 0000, END MARKER. IF music_duration > 7FFF, SET MUSIC TABLE POINTER TO THIS NEW LOCATION TO CONTINUE. */ typedef struct { unsigned music_duration; char channel_data[]; } music_t; /** * \brief * put 1 to snd_mute to disable sound update. */ extern volatile u8 snd_mute; /** * \fn snd_settable (void *snd_table) * \brief define the sound table used for playing sound * * \param snd_table address of sound table */ void snd_settable (void *snd_table); /** * \fn snd_startplay (u8 sound_number) * \brief play a sound specified but sound_number * * \param sound_number aid of sound in sound table */ void snd_startplay(u8 sound_number); /** * \fn snd_stopplay (u8 sound_number) * \brief stop a sound specified but sound_number * * \param sound_number aid of sound in sound table */ void snd_stopplay(u8 sound_number); /** * \fn snd_stopall (void) * \brief mute all channels * */ void snd_stopall(void); /** * \fn snd_isplaying (u8 sound_number) * \brief retrieve if channel is playing or not * * \param sound_number aid of sound in sound table * \return 0xff is sound_number is still playing, 0x00 if not */ u8 snd_isplaying(u8 sound_number); /** * \fn mus_startplay(void *mudata) * \brief play a music specified but mudata. * * \param mudata entry point of music data (see music_t) */ void mus_startplay(void *mudata); /** * \fn mus_nextplay (void *mudata) * \brief stop the current music and play the music specified but mudata. * * \param mudata entry point of music data (see music_t) */ void mus_nextplay(void *mudata); /** * \fn mus_stopplay (void) * \brief Stop the current music. */ void mus_stopplay(void); /** * \fn mus_update (void) * \brief This routine can be called at the end of the NMI routine, in project code. * To use this routine, the program should not use the first 4 SOUNDAREAs to play sound effects, because they are reserved for the music. * Because the first 4 AREAs are low priotity and because of that the sound effect in AREAs 5+ will play while continuing playing logically the music in the background. */ void mus_update(void); #endif <file_sep>.SECONDARY: #--------------------------------------------------------------------------------- .SUFFIXES: #--------------------------------------------------------------------------------- ifeq ($(strip $(PVCOLLIB_HOME)),) $(error "Please create an environment variable PVCOLLIB_HOME with path to its folder and restart application. (you can do it on windows with <setx PVCOLLIB_HOME "/c/colecodev">)") endif include ${PVCOLLIB_HOME}/devkitcol/col_rules #--------------------------------------------------------------------------------- # options for code generation #--------------------------------------------------------------------------------- C_SRC := CFLAGS := S_SRC := console.s console1.s console1_1.s console2.s console3.s console4.s console5.s console5_1.s console6.s \ console7.s \ pad.s \ sound0.s sound.s sound1.s sound2.s sound3.s sound4.s \ sprite.s sprite1.s sprite2.s sprite3.s sprite4.s sprite5.s sprite6.s sprite7.s sprite8.s \ score.s score1.s score2.s score3.s score4.s \ video.s video1.s video1_1.s video1_2.s video2.s video3.s video3_1.s video4.s video5.s video6.s video7.s video8.s video9.s \ video10.s video11.s video11_1.s video12.s video13.s video13_1.s video14.s video15.s video16.s video17.s video18.s video19.s \ video20.s video21.s video22.s video23.s video24.s video25.s video26.s video27.s video28.s \ video29.s ASFLAGS := INCLUDES := . ../include #--------------------------------------------------------------------------------- # any extra libraries we wish to link with the project #--------------------------------------------------------------------------------- LIBS := #--------------------------------------------------------------------------------- # list of directories containing libraries, this must be the top level containing # include and lib #--------------------------------------------------------------------------------- LIBDIRS := $(DEVKITSDCC) export INCLUDE := $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ -I$(CURDIR)/$(BUILD) CFLAGS += $(INCLUDE) export COLOBJS = collib.lib crtcol.rel export OFILES := $(C_SRC:.c=.rel) $(S_SRC:.s=.rel) #--------------------------------------------------------------------------------- crtcol.rel: crtcol.s # @echo Making entry point ... $(notdir $<) $(AS) $(ASFLAGS) -o crtcol.rel $< collib.lib: $(OFILES) # @echo Making lib ... $(notdir $@) $(LK) r collib.lib $(OFILES) all: $(COLOBJS) @mv *.lib ../lib @mv crtcol.rel ../lib #--------------------------------------------------------------------------------- clean: @echo clean ... @rm -f *.rel *.sym *.lst @rm -f ../lib/* <file_sep># ColecoVision Specifications This is a **WIP**, I will completed it as long I'm working on the lib and EmulTwo emulator :) About this Document ==== **Colecovision Doc Version 1.0, last updated 12 December 2019 by Alekmaul** This document describes the I/O Map of Colecovision console, attempting to supply a very compact and mostly complete document about COLECO hardware. **Portar doc of MSX by <NAME> for layout, sentences inspiration and MSX info too** http://problemkaputt.de/portar.htm **Datasheet for the TMS9918A and TMS9928A** http://www.cs.columbia.edu/~sedwards/papers/TMS9918.pdf **TMS9918 Programmer's Guide** http://www.madrigaldesign.it/creativemu/files/tms9918_guide.pdf **F18 support thread** https://atariage.com/forums/topic/207586-f18a-programming-info-and-resources/ **"The new COLECOVISION FAQ" - Version 3.6** Copyright (c) 1994, 1995, 1996 <NAME> and <NAME>. **"CV programming guide" - Version 1-k** Last update: October 26, 2005 Amy Purple. **Copyright** This text may not be sold, or included in commercial software/hardware or firmware packages, or used or duplicated for other commercial purposes without the authors permission. I/O Port Summary ==== Most internal Coleco hardware is accessed by I/O instructions. In all cases only the lower 8 bits of the I/O addresses are relevant. ### I/O Ports <pre> 80-9F (W) = Controls _ Set to keypad mode 80-9F (R) = Not Connected A0-BF (W) = Video \___ A0 also decoded by video chip A0-BF (R) = Video / C0-DF (W) = Controls _ Set to joystick mode C0-DF (R) = Not Connected E0-FF (W) = Sound E0-FF (R) = Controls _ A1 also decoded by chips (A1=0 ctrl 1; A1=1 ctrl 2) </pre> Memory ==== The CV uses 2 74138 3-8 line decoders to generate the memory and IO maps. As you would expect, memory is broken up into 8 8K blocks. ### Memory Map <pre> 0000-1FFF = BIOS ROM 2000-3FFF = Expansion port 4000-5FFF = Expansion port 6000-7FFF = RAM (1K mapped into an 8K spot) 8000-9FFF = Cart ROM A000-BFFF = Cart ROM C000-DFFF = Cart ROM E000-FFFF = Cart ROM </pre> VDP I/O Ports === Port BE-BF are used by the internal VDP TMS9918a ### Internal VDP <pre> Port BE VRAM Data (Read/Write) Port BF VDP Status Registers (Read Only) Port BF 2nd Byte b7=0: VRAM Address setup (Write Only) Port BF 2nd Byte b7=1: VDP Register write (Write Only) </pre> ### External VDP F18A to do Video Modes === This chapter describes the standard VRAM map for the different Colecovision video modes. Note that these default addresses can be changed by modifying VDP registers 2-6. The VDP Video Modes is selected by the Bits M1-M3 of VDP Register 0 and 1. The relationship between the bits and the screen is: <pre> M1 M2 M3 Screen format 0 0 0 Half text 32x24 (Mode 0 - Graphic 1) 1 0 0 Text 40x24 (Mode 1 - Text) 0 0 1 Hi resolution 256x192 (Mode 2 - Graphic 2) 0 1 0 Multicolour 4x4pix blocks (Mode 3 - Multicolor) </pre> **Mode 0**: 256x192 pixels total, as 32x24 characters, pulled from 1 character set of 256 8x8 pixel characters. Each group of 8 characters in the character set has a 2-color limitation. For example, the characters "0" through "7" will all have the same color attributes. **Mode 1**: 240x192 pixels total, as 40x24 characters, pulled from 1 character set of 256 6x8 pixel characters. The entire character set has a 2-color limitation. This mode doesn't support sprites. **Mode 2**: 256x192 pixels total, as 32x24 characters, pulled from 3 character sets of 256 8x8 pixel characters. Each 8-pixel-wide line of a character in the character sets has a 2-color limitation. This mode provides a unique character for every character location on screen, allowing for the display of bitmapped images. **Mode 3**: 256x192 pixels total, 64x48 changeable virtual pixels, as 32x24 "semi-graphics" characters. These semi-graphics are defined in a special character set of 256 characters defined by 2x2 "fat-pixels". There are 4x4 pixels in each fat-pixel, but the pixels within a fat-pixel cannot be individually defined, although each fat-pixel can have its own color, hence the name of this mode (Multicolor). This mode is very blocky, and rarely used. Foreground Sprites === OBJ Attributes (Sprite attribute) define 'OAM' data for up to 32 foreground sprites. Each entry consists of four bytes: <pre> 0: Y-pos, Vertical position (FFh is topmost, 00h is second line, etc.) 1: X-pos, Horizontal position (00h is leftmost) 2: Pattern number 3: Attributes. b0-3:Color, b4-6:unused, b7:EC (Early Clock) </pre> If EC is set to 1, the X-pos is subtracted by 32 (can be used to place sprites particulary offscreen to the left. When using 16x16 pixel sprites the lower two bits of the sprite number are ignored (should be zero). A 16x16 sprite logically consists of four 8x8 sprites, whereas the first 8x8 sprite is displayed in upperleft, the second one in lower left, the third in upper right, and the fourth in lower right. If Y-pos is set to 208 (D0h), the sprite AND ALL FOLLOWING sprites are hidden! This behavior is the same with F18A device, in locked mode (compatible with original VDP). In F18A unlocked mode, for all modes and ECM modes settings: <pre> Bit Name Expl. 0-3 PS3-0 Palette select per sprite (b0=PS3, b3=PS0) 4 SIZE Size: 0 = global VR1 setting, 1 = 16x16 5 FLIPY Sprite flip Y axis 6 FLIPX Sprite flip X axis 7 EC Early Clock </pre> VRAM Data Read/Write === Port BE VRAM Data (Read/Write) Port BF VRAM Address setup (2nd Byte b7=0) (Write Only) **Port BEh, Accessing VRAM Data** Read data from VRAM, or write data to VRAM. In either case the VRAM read/write pointer is automatically incremented, allowing to read/write a stream of bytes without having to setup the pointer each time. **Port BFh, VRAM Address Pointer Setup** The VRAM read/write pointer is initalized by writing TWO BYTES to port BEh with BIT 7 CLEARED in the second byte. <pre> Byte 1/Bit 0-7 Lower bits of VRAM Pointer Byte 2/Bit 0-5 Upper bits of VRAM Pointer Byte 2/Bit 6 Desired VRAM Direction (0=Reading, 1=Writing) Byte 2/Bit 7 Must be "0" for VRAM Pointer setup </pre> This 14bit Pointer value allows to address 16Kbytes of VRAM VDP Status Registers === Port BF VDP Status Registers (Read Only) The Colecovision includes only one VDP Status Register (Register 0), for F18A device VDP Status Registers 0-Fh exist. Status register 0 (default): <pre> Bit Name Expl. 0-4 SP4-0 Number for the 5th sprite (9th in screen 4-8) on a line (b0=SP4, b4=SP0) 5 C 1 if overlapping sprites 6 5S 1 if more than 4 sprites on a horizontal line (8 in screen 4-8) 7 F V-Blank IRQ Flag (1=interrupt) (See also IE0 flag) </pre> In mode 1-3 only 4 sprites can be displayed per line. Bit 6 indicates if too many sprites have been (attempted to be) displayed. If the bit is set, Bit 0-4 indicate the number of the sprite that wasn't displayed properly. If more than one sprite haven't displayed properly, then Bit 0-4 specify the first of these bad sprites. A sprite is overlapping another if a non-transparent pixel of a sprite hits a non-transparent pixel of another sprite. The IRQ flag in bit 7 gets set at the beginning of the VBlank period, if IE0 in VDP Register 1 is set (or gets set at a later time, while the IRQ flag is still set) then an interrupt is generated. The IRQ flag (bit 7) and the collision flag (bit 5) get cleared after reading Status register 0. VDP Register Write === ### VDP Registers 00h-07h: Basic Colecovision Video Registers **Register 00: VR0** <pre> Bit Name Expl. 0 EXTVID External video input (0=input disable, 1=enable) 1-2 M3-4 Mode M4 M3 (M4 only for F18A) 3 0 Not Used 4 IE1 H-Blank Interrupt Enable (F18A, see also VDP Reg 13h) 5-7 0 Not Used </pre> **Register 01: VR1** <pre> Bit Name Expl. 0 MAG Sprite zoom (0=x1, 1=x2) 1 SZ Sprite size (0=8x8, 1=16x16) 2 0 Not Used 3-4 M1-2 Mode M2 M1 5 IE0 V-Blank Interrupt Enable (0=Disable, 1=Enable) 6 BLK Screen output control (0=Disable, 1=Enable) 7 4K16K VRAM size control (0=4K, 1=16K, ignored for F18A) </pre> The video modes are: <pre> Mode=M4 M3 M2 M1 GM1 = 0 0 0 0 GM2 = 0 1 0 0 MCM = 0 0 1 0 T40 = 0 0 0 1 (40 col) T80 = 1 0 0 1 (80 col) </pre> M4 is only available for F18A device. **Register 2: VR2 Name Table Base Address, 1K boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name 0 0 0 0 A00 A01 A02 A03 </pre> 768-bytes per table for 24 rows 960-bytes per table for 30 rows Multiply this value by 400h to have the real address **Register 3: VR3 Color Table Base Address, 64-byte boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name A00 A01 A02 A03 A04 A05 A06 A07 </pre> 32-bytes long for original color mode (default) For the F18A enhanced color modes, this becomes Tile Attribute Table Base Address The Tile Attribute Table is 256 bytes long 768 to 4K when in position-attribute mode depending on the size of the horz / vert pages. Multiply this value by 40h to have the real address **Register 4: VR4 Pattern Generator Base Address, 2K boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name 0 0 0 0 0 A00 A01 A02 </pre> 2K for 256 tiles 4K for 2-bit color mode, 6K for 3-bit color mode Multiply this value by 800h to have the real address **Register 5: VR5 Sprite Attribute Table Base Address, 128-byte boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name 0 A00 A01 A02 A03 A04 A05 A06 </pre> 128-bytes (32 sprites, 4 bytes each) Multiply this value by 80h to have the real address **Register 6: VR6 Sprite Pattern Generator Base Address, 2K boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name 0 0 0 0 0 A00 A01 A02 </pre> 2K for 256 patterns 4K for 2-bit color mode, 6K for 3-bit color mode Multiply this value by 800h to have the real address **Register 7: VR7 Text color / background color** <pre> Bit Name Expl. 0-3 BG0-3 Background colour 4-7 FG0-3 Foreground colour </pre> The bits 0-3 and 4-7 can hold a number in the range of 0-15. The corresponding colours are: <pre> 0 = Transparent 8 = Medium red 1 = Black 9 = Light red 2 = Medium green 10= Dark yellow 3 = Light green 11= Light yellow 4 = Dark blue 12= Dark green 5 = Light blue 13= Magenta 6 = Dark red 14= Gray 7 = Cyan 15= White </pre> ### VDP Registers 0Ah-39h: Additional VR10-VR57 F18A Video Registers **Register 0A: VR10 Name Table 2 Base Address, 1K boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name 0 0 0 0 A00 A01 A02 A03 </pre> 768-bytes per table for 24 rows 960-bytes per table for 30 rows **Register 0B: VR11 Color Table 2 Base Address, 64-byte boundaries** <pre> Bit 7 6 5 4 3 2 1 0 Name A00 A01 A02 A03 A04 A05 A06 A07 </pre> Works the same as VR3 in Enhanced Color Modes / Position-Attribute Mode **Register 18: VR24 Extra palette-select bits for original color modes** <pre> Bit Name Expl. 0-1 T1PS0-1 Tile 1 layer palette selector 2-3 T2PS0-1 Tile 2 layer palette selector 4-6 SPS0-1 Sprite palette selector 6-7 0 Not used </pre> **Register 1D: VR29 Page size for scrolling** <pre> Bit Name Expl. 0 VPSIZE1 VPSIZE = vertical page size layer 1, 0 = 1 page, 1 = 2 pages 1 HPSIZE1 HPSIZE = horizontal page size layer 1, 0 = 1 page, 1 = 2 pages 2-3 TPGS0-1 TPGS = tile pattern generator offset size, 11=256, 10=512, 01=1K, 00=2K 4 VPSIZE2 VPSIZE = vertical page size layer 2, 0 = 1 page, 1 = 2 pages 5 HPSIZE2 HPSIZE = horizontal page size layer 2, 0 = 1 page, 1 = 2 pages 6-7 SPGS0-1 SPGS = sprite pattern generator offset size, 11=256, 10=512, 01=1K, 00=2K </pre> **Register 1E: VR30 Max sprite per scan line** <pre> Bit Name Expl. 0-4 SPRTMAX0-4 Max sprites per scan line 5-7 0 Not used </pre> Max sprites per scan line are set to 0 to reset sprite max to jumper setting **Register 2F: VR47** <pre> Bit Name Expl. 0-5 PR0-5 Palette register # 6 AUTO INC Auto inc palette index after each write 7 DPM Data-port mode, 1 to enable </pre> **Register 30: VR48 SIGNED two's-complement increment amount for VRAM address, defaults to 1** <pre> Bit Name Expl. 0-6 INC0-6 Value 7 SIGN-BIT Signed bit </pre> **Register 31: VR49** <pre> Bit Name Expl. 0-1 ECMS0-1 ECM (S)prite 2 0 Not Used 3 Y_REAL Real sprite Y-coord 4-5 ECMT0-1 ECM (T)ile 6 ROW30 24 / 30 tile rows (30 rows disables 0xD0 in SAL) 7 TILE2_EN Tile Map 2 enable, 1 to enable </pre> ECM = enhanced color mode for (T)ile and (S)prite <pre> 0=nomal/original color 1=1-bit color mode, tile attributes 2=2-bit color mode, tile attributes 3=3-bit color mode, tile attributes </pre> **Register 32: VR50** <pre> Bit Name Expl. 0 TILE2_PRI 0 = TL2 always on top, 1 = TL2 vs sprite priority is considered 1 POS_ATTR Position vs name attributes 0 = per name attributes in ECMs, 1 = per position attributes 2 SCANLINES Show virtual scan lines 0 = no virtual scan lines, 1 = enable virtual scan lines 3 RPTMAX Report sprite max vs 5th sprite 0 = report 5th sprite, 1 = report max sprite (VR30) 4 TL1_OFF 0 = normal, 1 = disable GM1, GM2, MCM, T40, T80 5 GPU_VTRIG 0 = disable, 1 = trigger GPU on VSYNC 6 GPU_HTRIG 0 = disable, 1 = trigger GPU on HSYNC 7 VR_RESET 0 = ignored, 1 = reset all VDP registers to power-on defaults </pre> **Register 36: VR54** <pre> Bit Name Expl. 0-7 GPU0-7 GPU address MSB </pre> **Register 37: VR55** <pre> Bit Name Expl. 0-7 GPU8-15 GPU address LSB, writing resets and loads, then triggers the GPU </pre> **Register 38: VR56** <pre> Bit Name Expl. 0-6 0 Not used 7 GPUOP GPU Operation performed when register is written: 0 = reset and load PC, 1 = trigger GPU to begin execution </pre> **Register 39: VR57** <pre> Bit Name Expl. 0-7 VALUE Unlock: Enable registers over 7, write 000111xx to VR57 twice </pre> F18A Tile attribute byte in Enhanced Color Modes === Color Table becomes Tile Attribute Table Base Address and goes from 32 to 256 or 2K (same as name table) bytes long. <pre> Bit Name Expl. 0-3 PS3-0 Palette selection (b3=PS0, b0=PS3) 4 TRANS When 1, colors with 0, 00 or 000 will be transparent instead of a palette index 5 FLIPY Tile flip over Y 6 FLIPX Tile flip over X 7 PRI Tile priority over sprite </pre> When T40/T80 Mode, ECM0, and Position-Based Attributes is Enabled <pre> Bit 7 6 5 4 3 2 1 0 Name FG0 FG1 FG2 FG3 BG0 BG1 BG2 BG3 T40/80 fg / bg color </pre> SN76489 sound chip === The sound chip in the CV is a SN76489AN manufactured by Texas Instruments. It has 4 sound channels- 3 tone and 1 noise. The volume of each channel can be controlled seperately in 16 steps from full volume to silence. A byte written into the sound chip determines which register is used, along with the frequency/ attenuation information. The frequency of each channel is represented by 10 bits. 10 bits won't fit into 1 byte, so the data is written in as 2 bytes. Here's the control word: <pre> +--+--+--+--+--+--+--+--+ |1 |R2|R1|R0|D3|D2|D1|D0| +--+--+--+--+--+--+--+--+ </pre> 1: This denotes that this is a control word R2-R0 the register number: 000 Tone 1 Frequency 001 Tone 1 Volume 010 Tone 2 Frequency 011 Tone 2 Volume 100 Tone 3 Frequency 101 Tone 3 Volume 110 Noise Control 111 Noise Volume D3-D0 is the data Here's the second frequency register: <pre> +--+--+--+--+--+--+--+--+ |0 |xx|D9|D8|D7|D6|D5|D4| +--+--+--+--+--+--+--+--+ </pre> 0: This denotes that we are sending the 2nd part of the frequency D9-D4 is 6 more bits of frequency To write a 10-bit word for frequenct into the sound chip you must first send the control word, then the second frequency register. Note that the second frequency register doesn't have a register number. When you write to it, it uses which ever register you used in the control word. So, if we want to output 11 0011 1010b to tone channel 1: First, we write the control word: <pre> LD A,1000 1010b OUT (F0h),A </pre> Then, the second half of the frequency: <pre> LD A,0011 0011b OUT (F0h),A </pre> To tell the frequency of the wave generated, use this formula: 3579545 f= ------- 32n Where f= frequency out, and n= your 10-bit binary number in To control the Volume: <pre> +--+--+--+--+--+--+--+--+ |1 |R2|R1|R0|V3|V2|V1|V0| +--+--+--+--+--+--+--+--+ </pre> R2-R0 tell the register V3-V0 tell the volume: 0000=Full volume . . . 1111=Silence The noise source is quite intresting. It has several modes of operation. Here's a control word: +--+--+--+--+--+--+--+--+ |1 |1 |1 |0 |xx|FB|M1|M0| +--+--+--+--+--+--+--+--+ FB= Feedback: 0= 'Periodic' noise 1= 'white' noise The white noise sounds, well, like white noise. The periodic noise is intresting. Depending on the frequency, it can sound very tonal and smooth. M1-M0= mode bits: 00= Fosc/512 Very 'hissy'; like grease frying 01= Fosc/1024 Slightly lower 10= Fosc/2048 More of a high rumble 11= output of tone generator #3 You can use the output of gen. #3 for intresting effects. If you sweep the frequency of gen. #3, it'll cause a cool sweeping effect of the noise. The usual way of using this mode is to attenuate gen. #3, and use the output of the noise source only. The attenuator for noise works in the same way as it does for the other channels. Colecovision Models === **ColecoVision:** <pre> Resolution: 256 x 192 CPU: Z-80A Bits: 8 Speed: 3.58 MHz RAM: 8K Video RAM: 16K (8x4116) Video Display Processor: Texas Instruments TMS9928A Sprites: 32 Colors: 16 Sound: Texas Instruments SN76489AN; 3 tone channels, 1 noise Cartridge ROM: 8K/16K/24K/32K </pre> **ADAM:** <pre> Resolution: 256 x 192 CPU: Z-80A Bits: 8 Speed: 3.58 MHz Video Speed: 10.7 MHz RAM: 64K (128K optional) Video RAM: 16K (8x4116) ROM: 8K Video Display Processor: Texas Instruments TMS9928A Sprites: 32 Colors: 16 Sound: Texas Instruments SN76489AN; 3 tone channels, 1 noise Cartridge ROM: 8K/16K/24K/32K Disk Drives: 2 * 160K (opt) Digital Data Drives: 2 * 256K Modem: 300 Baud (opt) Printer: 120 wpm Daisy Wheel, 16K buffer Other: Serial/Parallel Port (opt), Auto Dialer (opt) </pre> JUMP functions === ColecoVision BIOS is also refered as OS 7prime, also refered simply as OS7. Because it was the 7th revision of the BIOS when the console was released. OS 7prime BIOS Jump table Legend: P (at the end): function specifically done for Pascal programs. <pre> 1F61 > 0300 : PLAY_SONGS 1F64 > 0488 : ACTIVATEP 1F67 > 06C7 : PUTOBJP 1F6A > 1D5A : REFLECT_VERTICAL 1F6D > 1D60 : REFLECT_HORIZONTAL 1F70 > 1D66 : ROTATE_90 1F73 > 1D6C : ENLARGE 1F76 > 114A : CONTROLLER_SCAN 1F79 > 118B : DECODER 1F7C > 1979 : GAME_OPT 1F7F > 1927 : LOAD_ASCII 1F82 > 18D4 : FILL_VRAM 1F85 > 18E9 : MODE_1 1F88 > 116A : UPDATE_SPINNER 1F8B > 1B0E : INIT_TABLEP 1F8E > 1B8C : GET_VRAMP 1F91 > 1C10 : PUT_VRAMP 1F94 > 1C5A : INIT_SPR_ORDERP 1F97 > 1C76 : WR_SPR_NM_TBLP 1F9A > 0F9A : INIT_TIMERP 1F9D > 0FB8 : FREE_SIGNALP 1FA0 > 1044 : REQUEST_SIGNALP 1FA3 > 10BF : TEST_SIGNALP 1FA6 > 1CBC : WRITE_REGISTERP 1FA9 > 1CED : WRITE_VRAMP 1FAC > 1D2A : READ_VRAMP 1FAF > 0655 : INIT_WRITERP 1FB2 > 0203 : SOUND_INITP 1FB5 > 0251 : PLAY_ITP 1FB8 > 1B08 : INIT_TABLE 1FBB > 1BA3 : GET_VRAM 1FBE > 1C27 : PUT_VRAM 1FC1 > 1C66 : INIT_SPR_ORDER 1FC4 > 1C82 : WR_SPR_NM_TBL 1FC7 > 0FAA : INIT_TIMER 1FCA > 0FC4 : FREE_SIGNAL 1FCD > 1053 : REQUEST_SIGNAL 1FD0 > 10CB : TEST_SIGNAL 1FD3 > 0F37 : TIME_MGR 1FD6 > 023B : TURN_OFF_SOUND 1FD9 > 1CCA : WRITE_REGISTER 1FDC > 1D57 : READ_REGISTER 1FDF > 1D01 : WRITE_VRAM 1FE2 > 1D3E : READ_VRAM 1FE5 > 0664 : INIT_WRITER 1FE8 > 0679 : WRITER 1FEB > 11C1 : POLLER 1FEE > 0213 : SOUND_INIT 1FF1 > 025E : PLAY_IT 1FF4 > 027F : SOUND_MAN 1FF7 > 04A3 : ACTIVATE 1FFA > 06D8 : PUTOBJ 1FFD > 003B : RAND_GEN </pre> RAM MAP === Complete OS 7prime RAM Map <pre> Address Name Description 7020-7021 PTR_LST_OF_SND_ADDRS Pointer to list (in RAM) of sound addrs 7022-7023 PTR_TO_S_ON_0 Pointer to song for noise 7024-7025 PTR_TO_S_ON_1 Pointer to song for channel#1 7026-7027 PTR_TO_S_ON_2 Pointer to song for channel#2 7028-7029 PTR_TO_S_ON_3 Pointer to song for channel#3 702A SAVE_CTRL CTRL data (byte) 73B9 STACK Beginning of the stack 73BA-73BF PARAM_AREA Common passing parameters area (PASCAL) 73C0-73C1 TIMER_LENGTH Length of timer 73C2 TEST_SIG_NUM Signal Code 73C3-73C4 VDP_MODE_WORD Copy of data in the 1st 2 VDP registers 73C5 VDP_STATUS_BYTE Contents of default NMI handler 73C6 DEFER_WRITES Defered sprites flag 73C7 MUX_SPRITES Multiplexing sprites flag 73C8-73C9 RAND_NUM Pseudo random number value 73CA QUEUE_SIZE Size of the defered write queue 73CB QUEUE_HEAD Indice of the head of the write queue 73CC QUEUE_TAIL Indice of the tail of the write queue 73CD-73CE HEAD_ADDRESS Address of the queue head 73CF-73D0 TAIL_ADDRESS Address of the queue tail 73D1-73D2 BUFFER Buffer pointer to defered objects 73D3-73D4 TIMER_TABLE_BASE Timer base address 73D5-73D6 NEXT_TIMER_DATA_BYTE Next available timer address 73D7-73EA DBNCE_BUFF Debounce buffer. 5 pairs (old and state) of fire, joy, spin, arm and kbd for each player. 73EB SPIN_SW0_CT Spinner counter port#1 73EC SPIN_SW1_CT Spinner counter port#2 73ED (reserved) 73EE S0_C0 Segment 0 data, Controller port #1 73EF S0_C1 Segment 0 data, Controller port #2 73F0 S1_C0 Segment 1 data, Controller port #1 73F1 S1_C1 Segment 1 data, Controller port #2 73F2-73FB VRAM_ADDR_TABLE Block of VRAM table pointers 73F2-73F3 SPRITENAMETBL Sprite name table offset 73F4-73F5 SPRITEGENTBL Sprite generator table offset 73F6-73F7 PATTERNNAMETBL Pattern name table offset 73F8-73F9 PATTERNGENTBL Pattern generator table offset 73FA-73FB COLORTABLE Color table offset 73FC-73FD SAVE_TEMP (no more used - in VRAM routines) 73FE-73FF SAVED_COUNT Copy of COUNT for PUT_VRAM and GET_VRAM </pre> ROM Header === All carts start at 8000h with a header that tells the BIOS what to do. <pre> 8000 - 8001: If bytes are AAh and 55h, the CV will show a title screen and game name, etc. If bytes are 55h and AAh, the CV will jump directly to the start of code vector. 8002 - 8003: Pointer to RAM copy of the sprite name table 8004 - 8005: Pointer to RAM sprite table 8006 - 8007: Pointer to free buffer space in RAM 8008 - 8009: Pointer to controller memory map 800A - 800B: Pointer to start of code 800C - 800E: Jmp to: RST 08h 800F - 8011: Jmp to: RST 10h 8012 - 8014: Jmp to: RST 18h 8015 - 8017: Jmp to: RST 20h 8018 - 801A: Jmp to: RST 28h 801B - 801D: Jmp to: RST 30h 801E - 8020: Jmp to: RST 38h 8021 - 8023: JMP to: NMI (Vertical Blanking Interrupt from video chip) 8024 - nnnn: String with two delemiters "/" as "LINE2/LINE1/YEAR" </pre> Data for the title screen is composed of 4 lines in the format: <pre> +--------------+ | COLECOVISION | | | | LINE 2 | | LINE 3 | |(c)xxxx COLECO| +--------------+ </pre> **Typical Screen** The '**ColecoVision**' line cannot be changed, as well as the '(C)xxxx Coleco' part of the bottom line. Only the xxxx part can be changed. The data is stored as one string with the '/' character (2Fh) used as a delimiter. It signals the end of a line, and isn't printed. The lines are stored out of order like so: "LINE 3/LINE 2/xxxx" There isn't an end-of-line delimiter, because the last line is always 4 characters (it's meant for a year like 1983) So, if we want to see the following: <pre> +--------------+ | COLECOVISION | | | | MY GAME! | | BY: ME | |(c)1995 COLECO| +--------------+ </pre> We would use the string: <pre> "BY: ME!/MY GAME!/1995" </pre> Remember, we cannot change the "(c)xxxx COLECO" part, only the xxxx in the middle of the line. The lines are self-centering on the screen. Altho the BIOS ROM has both upper-case and lower-case characters in the character set, only upper-case is supported. All printable characters are based on the ASCII character set: (all values in hex) <pre> 00-1C: Blank 1D : (c) (Copyright symbol) 1E-1F: tm (TradeMark symbol, uses 2 chars side-by-side) 20-2E: (respectively) space ! " # $ % & ' ( ) * + , - . 2F : Delimiter- used to end a line, not printable 30-39: 0-9 3A-40: (respectively) : ; < = > ? @ 41-5A: A-Z 5B-5F: (respectively) [ \ ] ^ _ </pre> The chars # 60-8F are the 4-char blocks that make up the '**COLECOVISION**' name at the top, arranged like so: <pre> 6062 6466 686A 6C6E 7072 7476 787A 7C7E 8082 8486 888A 8C8E 6163 6567 696B 6D6F 7173 7577 797B 7D7F 8183 8587 898B 8D8F C O L E C O V I S I O N (purple) (orange) (pink) (yellow) (green) (blue) </pre> What's intresting, is when these are in the title lines, they show up in their respective colours! All other printable chars are white. Chars 90-FF are all blank Cartridge Memory Mappers === **Magecart from <NAME>** (created in August 2005) Megacart EPROMs are broken up into 16k pages, and are banked by accessing the last 64 addresses of the cartridge space (0xFFC0 - 0xFFFF). Accessing 0xFFFF maps the top 16k of the EPROM (or page 0), 0xFFFE maps the second-to-last 16k (or page 1), 0xFFFD maps the third-to-last 16k (or page 2), etc. Megacarts are limited to a maximum size of 1MB. The first 16K of the cartridge (CV 8000h-BFFFh) is fixed and will always contain the highest/last 16K segment of the EPROM. Therefore, this data will appear twice (CV 8000h-BFFFh and C000h-FFFFh) if the last bank is selected. It is recommended that the following addresses be read to select banks: <pre> 128K - 8 banks - FFF8h-FFFFh. 256K - 16 banks - FFF0h-FFFFh. 512K - 32 banks - FFE0h-FFFFh. 1MB - 64 banks - FFC0h-FFFFh. </pre> Remember that strobing FFFFh places the same data in both halves of the cartridge memory # END <file_sep>#ifndef __SDCC_STDNORETURN_H #define __SDCC_STDNORETURN_H 1 #define noreturn _Noreturn #endif <file_sep># Installation # 1. **[Installation with Windows](https://github.com/alekmaul/pvcollib/wiki/Installation-with-Windows)** 1. **[PVcollib and Programmer Notepad](https://github.com/alekmaul/pvcollib/wiki/PVcollib-and-Programmer-Notepad)** # Programming # # Tips # 1. **[Colecovision Specs](https://github.com/alekmaul/pvcollib/wiki/Complete-Colecovision-Specs)**<file_sep>// this file contains only graphics generated by gfx2col // it's here because we need a file to compile for pvcollib, // not one auto generated #include "pacspritegfx.inc" // generetad by gfx2col <file_sep>#ifndef COMPDAN2_H #define COMPDAN2_H #include <stdio.h> #include <stdlib.h> #include <mem.h> #define bool unsigned char #define byte unsigned char #define false 0 #define true 0xff extern int dan2Compress(byte *src,byte *dst,int n); #endif<file_sep>#ifndef _SCORING_MAIN_ #define _SCORING_MAIN_ #include <coleco.h> #endif <file_sep>/*--------------------------------------------------------------------------------- Generic video functions Copyright (C) 2018-2020 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file video.h * \brief contains the basic definitions for controlling the video hardware. * * This unit provides generic features related to video management.<br> *<br> * Here is the list of features:<br> * - enable and disable screen or vdp or nmi<br> * - clear, fill vram <br> * - retreive or set some vram area<br> * - update vram with some specific algorithm like Run Length, Pletter or Amy Purple DAN1 compression algorithm<br> */ #ifndef COL_VIDEO_INCLUDE #define COL_VIDEO_INCLUDE #include <coleco/coltypes.h> #define FNTNORMAL 0 #define FNTITALIC 1 #define FNTBOLD 2 #define FNTBOLD_ITALIC (FNTITALIC | FNTBOLD) #define chrgen 0x0000 #define coltab 0x2000 #define chrtab 0x1800 #define chrtab2 0x1B00 #define sprtab 0x3800 #define sprgen 0x1f00 #define COLTRANSP 0 #define COLBLACK 1 #define COLMEDGREEN 2 #define COLLITGREEN 3 #define COLDRKBLUE 4 #define COLLITBLUE 5 #define COLDRKRED 6 #define COLCYAN 7 #define COLMEDRED 8 #define COLLITRED 9 #define COLDRKYELLOW 10 #define COLLITYELLOW 11 #define COLDRKGREEN 12 #define COLMAGENTA 13 #define COLGREY 14 #define COLWHITE 15 /** * \fn void vdp_setreg(u8 reg,u8 val) * \brief Set a value to a TMS9918 register * * \param reg register number * \param val value to assign */ void vdp_setreg(u8 reg,u8 val); /** * \fn void vdp_waitvblank(u16 numtime) * \brief Waits for a vertical blank interrupt a number of time * * \param numtime number of vblank to wait */ void vdp_waitvblank(u16 numtime); /** * \fn void vdp_enablenmi(void) * \brief Enable NMI interruption * */ void vdp_enablenmi(void); /** * \fn void vdp_disablenmi(void) * \brief Disable NMI interruption */ void vdp_disablenmi(void); /** * \fn void vdp_enablevdp(void) *\brief Allows VDP to work (so screen is now active) */ void vdp_enablevdp(void); /** * \fn void vdp_disablevdp(void) * \brief Disallows VDP to work (so screen is not active) */ void vdp_disablevdp(void); /** * \fn void vdp_enablescr(void) * \brief Allows VDP to work and NMI to be catch */ void vdp_enablescr(void); /** * \fn void vdp_disablescr(void) * \brief Disallows VDP to work and NMI to occur */ void vdp_disablescr(void); /** * \fn void vdp_setmode1txt(void) * \brief Activate mode 1 in text mode<br> * Activate Mode 1 of TMS in text mode, 16K of VRAM, sprites 16x16<br> * 1 VRAM (duplicated each for 8 lines) that can be populate<br> * CHRGEN is located at $0000, COLTAB is located at $2000<br> */ void vdp_setmode1txt(void); /** * \fn void vdp_setmode2txt(void) * \brief Activate mode 2 in text mode<br> * Activate Mode 2 of TMS in text mode, 16K of VRAM, sprites 16x16<br> * 3 VRAM areas (each for 8 lines) that can be populate<br> */ void vdp_setmode2txt(void); /** * \fn void vdp_setmode2bmp(void) * \brief Activate mode 2 in bitmap mode<br> * Activate Mode 2 of TMS in bitmap mode, 16K of VRAM, sprites 16x16<br> * 1 VRAM area (complete screen of 24 lines) that can be populate<br> */ void vdp_setmode2bmp(void); /** * \fn void vdp_setcharex(u8 first,u8 count, unsigned offset,u8 flags) * \brief Put some chars of default font * * \param first 1st char to put * \param count number of chars * \param offset address location in video memory for the chararter patterns * \param flags type of font<br> * FNTNORMAL for the normal font<br> * FNTITALIC for the italic font<br> * FNTBOLD for the bold font<br> * FNTBOLD_ITALIC fot both italic and bold font<br> */ void vdp_setcharex(u8 first,u8 count, unsigned offset,u8 flags); /** * \fn void vdp_putchar (u8 x, u8 y, char value) * \brief Put a single char on screen * * \param x colum to print * \param y line to print * \param value ascii value of char to print */ void vdp_putchar (u8 x, u8 y, char value); /** * \fn u8 vdp_getchar (u8 x, u8 y) * \brief Get a single char from screen * * \param x column of the char * \param y line of the char * \return char value from screen */ u8 vdp_getchar (u8 x, u8 y); /** * \fn void vdp_getarea (void *table, u8 x, u8 y, u8 width, u8 height) * \brief Get an area of chars from screen * * \param table area in ram to save chars * \param x column of the chars * \param y line of the chars * \param width length of x chars to get * \param height length of y chars to get */ void vdp_getarea (void *table, u8 x, u8 y, u8 width, u8 height); /** * \fn void vdp_putarea (void *table, u8 x, u8 y, u8 width, u8 height) * \brief Put an area of chars to screen * * \param table area in ram to load chars * \param x column of the chars * \param y line of the chars * \param width length of x chars to put * \param height length of y chars to put */ void vdp_putarea (void *table, u8 x, u8 y, u8 width, u8 height); /** * \fn void vdp_setdefaultchar(u8 flags) * \brief Put default font * * \param flags character format<br> * FNTNORMAL for the normal font<br> * FNTITALIC for the italic font<br> * FNTBOLD for the bold font<br> * FNTBOLD_ITALIC fot both italic and bold font<br> */ void vdp_setdefaultchar(u8 flags); /** * \fn void vdp_putstring(u8 x, u8 y, char* text) * \brief Put a string on screen at coordinates x,y * * \param x column x * \param y line y * \param text text to display */ void vdp_putstring(u8 x, u8 y, char* text); /** * \fn void vdp_fillvram(u16 offset,u8 value,u16 count) * \brief Change VRAM with a specific value * * \param offset address in VRAM * \param value value to set * \param count number of time we set value */ void vdp_fillvram(u16 offset,u8 value,u16 count); /** * \fn void vdp_putvram_repeat(unsigned offset,void *table, u8 count, u8 times) * \brief Repeat n times an area of chars to screen * * \param offset address in VRAM * \param table area in ram to load chars * \param count number of chars to repeat * \param times number of time we set chars */ void vdp_putvram_repeat(unsigned offset,void *table, u8 count, u8 times); /** * \fn void vdp_duplicatevram(void) * \brief Put 1st area of pattern vram to the 2nd and 3rd one */ void vdp_duplicatevram(void); /** * \fn void vdp_putvram (unsigned offset,void *data,unsigned count) * \brief Fill the VRAM with some non compressed data * * \param offset address in VRAM of 1st data to fill * \param data address of data to use * \param count number of data */ void vdp_putvram (unsigned offset,void *data,unsigned count); /** * \fn void vdp_getvram (unsigned offset,void *data,unsigned count) * \brief Get from VRAM to a RAM pointer with some non compressed data * * \param offset address in VRAM of 1st data to get * \param data address of RAM to use * \param count number of data */ void vdp_getvram (unsigned offset,void *data,unsigned count); /** * \fn void *vdp_rle2vram (void *rledata,unsigned offset) * \brief Fill the VRAM with some RLE compressed data * * \param rledata address of data to use * \param offset address in VRAM of 1st data to fill * \return pointer to first unused free */ void *vdp_rle2vram (void *rledata,unsigned offset); /** * \fn void vdp_ple2vram(void *pledata, unsigned offset) * \brief Put data in VRAM with some Pletter compressed data * * \param pledata address of data to use * \param offset address in VRAM of 1st data to fill */ void vdp_ple2vram(void *pledata, unsigned offset); /** * \fn void vdp_dan12vram(void *dan1data, unsigned offset) * \brief Put data in VRAM with some DAN1 compressed data * * \param dan1data address of data to use * \param offset address in VRAM of 1st data to fill */ void vdp_dan12vram(void *dan1data, unsigned offset); /** * \fn void vdp_dan22vram(void *dan2data, unsigned offset) * \brief Put data in VRAM with some DAN2 compressed data * * \param dan2data address of data to use * \param offset address in VRAM of 1st data to fill */ void vdp_dan22vram(void *dan2data, unsigned offset); /** * \fn void vdp_dan32vram(void *dan3data, unsigned offset) * \brief Put data in VRAM with some DAN2 compressed data * * \param dan3data address of data to use * \param offset address in VRAM of 1st data to fill */ void vdp_dan32vram(void *dan3data, unsigned offset); /*! \fn vdp_blocknmi \brief set no_nmi flag to avoid nmi */ #define vdp_blocknmi() { __asm__("\tpush hl\n\tld hl,#_no_nmi\n\tset 0,(hl)\n\tpop hl"); } /*! \fn vdp_releasenmi \brief reset no_nmi flag to allow nmi */ #define vdp_releasenmi() { __asm__("\tpush hl\n\tld hl,#_no_nmi\n\tres 0,(hl)\n\tpop hl"); } #endif <file_sep>/*--------------------------------------------------------------------------------- Simple console 'hello world' demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "helloworld.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Helloworld example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Print at 10,text as we are not going to do something else vdp_putstring(10,10,"HELLO WORLD!"); // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>/*--------------------------------------------------------------------------------- Copyright (C) 2018-2020 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Image converter for colecovision. BMP BI_RLE8 compression support by <NAME> palette rounded option from <NAME> Dan1 & Dan2 & Dan3 compression support from Amy Purple aka newcoleco ***************************************************************************/ //INCLUDES #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <malloc.h> #include <string.h> #include "gfx2col.h" #include "lodepic.h" #include "lodepng.h" #include "comptool.h" #include "comprle.h" #include "compdan1.h" #include "compdan2.h" #include "compdan3.h" enum FILE_TYPE { BMP_FILE = 1, PCX_FILE, TGA_FILE, PNG_FILE }; int output_palette=-1; // 64 colors output (F18A only) palettes int palette_rnd=0; // 1 = round palette up & down (F18A only) int quietmode=0; // 0 = not quiet, 1 = i can't say anything :P int compress=0; // 0 = not compressed, 1 = rle compression, 2 = ple compression, 3 = dan1 compression, // 4 = dan2 compression, 5 = dan3 compression int sprmode=0; // 0 = background 1 = sprite int bmpmode=0; // 0 = normal tile mode, 1=bitmap mode int gramode=0; // 0 = TMS9918a graphic mode 2, 1 = graphic mode 1 int ecmmode=0; // 0 = noactive, 1=ecm0,2=ecm1, etc ... (F18A only, will generate a palette) int offset_tile=0; // n = offset in tile number int transmode=0; // 0 = not transparent, 1 = transprent tiles activated int highpriority=0; // 1 = high priority for map //--------------------------------------------------------------------------- void PutWord(int data, FILE *fp) { putc(LOW_BYTE(data),fp); putc(HI_BYTE(data),fp); } //end of PutWord //--------------------------------------------------------------------------- unsigned char *ArrangeBlocks( unsigned char *img, int width, int height, int size, int *xsize, int *ysize, int new_width) { /* ** img = image buffer ** width = width (in pixels) of image buffer ** height = height (in pixels) of image buffer ** ** size = size (in pixels) of image blocks in the image ** *xsize = number of image block horizontally in image block grid ** *ysize = number of image block vertically in image block grid ** ** new_width = how wide (in pixels) you want the new buffer to be ** must be a multiple of size ** ** ** returns: ** pointer to new buffer, and updates xsize and ysize ** */ unsigned char *buffer; int rows, num; int i,j, line; int x,y; //get number of full image block rows in the new buffer rows = (*xsize)*(*ysize)/(new_width/size); // rows = num_blocks / new_xsize //if it doesn't divide evenly, add another full row if ( ((*xsize)*(*ysize))%(new_width/size) != 0 ) rows++; if (quietmode == 0) printf("\nrows=%d",rows); //get memory for the new buffer buffer = (unsigned char *) malloc( rows*size*new_width*sizeof(char) ); if(buffer == NULL) { return 0; } // Initially clear the buffer, so if there are empty image blocks or incomplete blocks, the empty parts will be blank memset(buffer,0,(size_t) rows*size*new_width*sizeof(char) ); //position in new buffer (x,y) where x and y are in pixel co-ordinates x=0; y=0; //go through each image block(i,j) where i and j are in block co-ordinates for(j=0; j < *ysize; j++) { for(i=0; i < *xsize; i++) { //move each line of the block into the new buffer //don't worry about reading past the end of the image here //there is an extra 64 lines to read in. for(line=0;line<size;line++) { //find out how much to copy //this is needed because the screen mode files may not be //a multiple of 8 pixels wide //or no-border files may have the wrong width num = width - (i*(size)); if(num>size) num=size; memcpy( &buffer[ (y+line)*new_width + x ], &img[ (j*(size) + line )*width + i*(size) ], num); } // move to the next location in the new buffer x+=size; if(x >= new_width) { x=0; y+=size; } } } *xsize = new_width/size; *ysize = rows; return buffer; } //end of ArrangeBlocks() //--------------------------------------------------------------------------- unsigned int MakeCol(unsigned char *buffer, unsigned int *tilemap, unsigned char *num_col, unsigned int *colmap,int *num_tiles,int mapw, int maph) { int colval,nbcol; int i,j, t,x,y; int colidx, tilidx; unsigned char minv,maxv,actminv,actmaxv; unsigned char valtil[8]; unsigned char newcol; unsigned char *tilreorg; unsigned int *mapreorg; unsigned int idxcoltil[256]; // init color values newcol=0; for (t=0;t<32;t++) colmap[t]=0x100; // outside scope value for (t=0;t<256;t++) idxcoltil[t]= 32; // outside score value //loop through tiles for (t=0;t<*num_tiles;t++) { actminv=1; actmaxv=0xF; for(y=0;y<8;y++) { minv=0xFF; maxv=0x00; // get the 8 values for (x=0;x<8;x++) { valtil[x]=buffer[t*64 + y*8 + x]; // get min and max value if (valtil[x]<minv) minv=valtil[x]; if (valtil[x]>maxv) maxv=valtil[x]; } // put 1 if max color if (maxv <= 0x01) maxv=0xF; if (minv == 0xff) minv=1; // if 1st time,assign it if (y==0) { if ( (minv!=1) && (maxv!=minv) ) actminv=minv; if (maxv!=0xF) actmaxv=maxv; } else { if ( (actminv!=minv) && (actmaxv!=maxv) ) { printf("\nERROR: Too much color (4) for 8x8 tile #%d\n",t); return 0; } if ( (actminv!=minv) && (actminv!=1) && (maxv!=minv) ) { printf("\nERROR: Too much color (min) for 8x8 tile #%d\n",t); return 0; } else if (maxv!=minv) actminv=minv; if ( (actmaxv!=maxv) && (actmaxv!=0xF) && (maxv!=0xF) ) { printf("\nERROR: Too much color (max) for 8x8 tile #%d\n",t); return 0; } else if (maxv!=0xF) actmaxv=maxv; } colval=(actmaxv<<4) | (actminv); // FG color | BG color } // try to assign for a color for the 8x8 square colidx=-1; for (i=0;i<32;i++) { if (colmap[i]==0x100) { colmap[i]=colval; colidx=i; newcol++; break; } else if (colmap[i]==colval) { colidx=i; break; } } // if not assigned, huston, we have a problem ;) if (colidx==-1) { printf("\nERROR: Too much colors assigned (more than 32) encountered for 8x8 tile #%d\n",t); return 0; } idxcoltil[t]=colval; } // try to alloc for new tiles arrangement tilreorg=(unsigned char *) malloc((size_t)256*64); if(tilreorg==NULL) { return 0; } mapreorg=(unsigned int *) malloc((size_t)mapw*maph*sizeof(int)); if(mapreorg==NULL) { return 0; } memset(tilreorg,0,256*64); memset(mapreorg,0,mapw*maph*sizeof(int)); // Rearrange tiles & map to fit with colors (1 colors for 8 tiles) printf("\nRearrange tiles & map to fit with colors (1 colors for 8 tiles)...");fflush(stdout); tilidx=0; for (i=0;i<32;i++) { // check all tiles nbcol=0; for (t=0;t<*num_tiles;t++) { // if we find the color, just put the tile if (idxcoltil[t]==colmap[i]) { // if we have now more than 8 tiles, need to go next color entry if (nbcol==8) { nbcol=0; newcol++; for (j=31;j>i;j--) { colmap[j]=colmap[j-1]; } i++; colmap[i]=colmap[i-1]; } // Put the tile memcpy(&tilreorg[tilidx],&buffer[t*64],64); // Adapt the map for (j=0;j<mapw*maph;j++) { if (*(tilemap+j)==t) { *(mapreorg+j)=(tilidx/64); } } tilidx+=64; nbcol++; } } // one color is finished, if we are not near a 8 tiles border, need to adapt if (nbcol & 7) { tilidx+=(8-nbcol)*64; } } // now put back to buffer & map printf("\nNew number of tiles is %d...",tilidx/64);fflush(stdout); for (i=0;i<tilidx;i++) *(buffer+i)=*(tilreorg+i); for (i=0;i<mapw*maph;i++) *(tilemap+i)=*(mapreorg+i); free(mapreorg); free(tilreorg); // keep track of number of colors & number of tiles *num_col=newcol; *num_tiles=tilidx/64; return 1; } //--------------------------------------------------------------------------- unsigned int *MakeMap(unsigned char *img, unsigned int *colf18a, int *num_tiles, int xsize, int ysize, int tile_x, int tile_y, unsigned char optimize) { unsigned int *map; int newtiles; int current,palette,oldpal; //the current tile we're looking at int i,t; int x,y; //allocate map map=(unsigned int *) malloc((size_t)tile_x*tile_y*sizeof(int)); if(map==NULL) { return 0; } //clear map memset(map,0,tile_x*tile_y*sizeof(int)); current=0; t=0; newtiles=0; oldpal=-1; for(y=0;y<ysize;y++) { for(x=0;x<xsize;x++) { //get the palette number if (ecmmode==4) // ecm 3 palette = (img[current*64] >> 3) & 0x07; else if (ecmmode==3) // ecm 2 palette = (img[current*64] >> 2) & 0x0F; else // ecm 1 and others palette = (img[current*64] >> 1) & 0x1F; /* test purpose if (ecmmode>1) { if (oldpal!=palette) { printf("\npalette=%04x",palette);fflush(stdout); oldpal=palette; } }*/ //check for matches with previous tiles if tile_reduction on if (optimize) { for(i=0;i<newtiles;i++) if( memcmp(&img[i*64],&img[current*64],64) == 0 ) break; } else i=newtiles; // if ecm mode, put in color table for the tile attributre if (ecmmode>1) { // How colors are managed: // ps = palette select from VR24 // cs = color value from color table (256 bytes for ECM1..3) // px0 = pixel from byte from pattern table 0 (original mode and EMC1) // px1 = pixel from byte from pattern table 1 (ECM2) // px2 = pixel from byte from pattern table 2 (ECM3) // Bit Name Expl. // 0-3 PS3-0 Palette selection (b3=PS0, b0=PS3) // 4 TRANS When 1, colors with 0, 00 or 000 will be transparent instead of a palette index // 5 FLIPY Tile flip over Y // 6 FLIPX Tile flip over X // 7 PRI Tile priority over sprite if (ecmmode==2) colf18a[newtiles]=(palette); // ECM1 : ps0 cs0 cs1 cs2 cs3 px0 else if (ecmmode==3) colf18a[newtiles]=(palette); // ECM2 : cs0 cs1 cs2 cs3 px1 px0 else if (ecmmode==4) colf18a[newtiles]=(palette<<1)& 0xFE; // ECM3 : cs0 cs1 cs2 px2 px1 px0 colf18a[newtiles]|=(transmode<<4) | (highpriority<<7); } //is it a new tile? if(i==newtiles) { // yes -> add it memcpy(&img[newtiles*64],&img[current*64],64); t=newtiles; newtiles++; } else { // no -> find what tile number it is t=i; } //put tile number in map map[y*tile_x+x] = t+offset_tile; } //goto the next tile current++; } //also return the number of new tiles *num_tiles = newtiles; return map; }//end of MakeMap //--------------------------------------------------------------------------- void ConvertPalette(RGB_color *palette, unsigned int *new_palette) { int i,data; int rounded; int temp; //Convert the colors and put them in the new array // //alternate rounding down and rounding up //this is an attempt to preserve the brightness of a color //which the human eye notices easier than a change in color rounded=0; for(i=0;i<64;i++) { if(palette_rnd) { data=0; //get red portion and round it temp = (palette[i].red & 0x01); //see if this needs rounding if(palette[i].red == 31) //if value == 63, then we can't round up { temp = 0; rounded = 1; } data = (palette[i].red >> 1) + (temp & rounded); //round up if necessary rounded = (temp ^ rounded); //reset rounded down flag after rounding up //get green portion and round it temp = (palette[i].green & 0x01); //see if this needs rounding if(palette[i].green == 31) //if value == 63, then we can't round up { temp = 0; rounded = 1; } data = (data<<4) + (palette[i].green >> 1) + (temp & rounded); //round up if necessary rounded = (temp ^ rounded); //reset rounded down flag after rounding up //get blue portion and round it off temp = (palette[i].blue & 0x01); //see if this needs rounding if(palette[i].blue == 31) //if value == 63, then we can't round up { temp = 0; rounded = 1; } data = (data<<4) + (palette[i].blue >> 1) + (temp & rounded); //round up if necessary rounded = (temp ^ rounded); //reset rounded down flag after rounding up //store converted color new_palette[i] = data; } else { data=0; data = (palette[i].red >> 1); data = (data<<4) + (palette[i].green >> 1); data = (data<<4) + (palette[i].blue >> 1); //store converted color new_palette[i] = data; } }//loop through all colors } //end of ConvertPalette //--------------------------------------------------------------------------- void addcomment(FILE *fp, unsigned int ratio,unsigned int size,unsigned int compress) { if (compress==1) fprintf(fp, "// rle compression %d bytes (%d%%)\n", size,ratio); else if (compress==2) fprintf(fp, "// ple compression %d bytes (%d%%)\n", size,ratio); else if (compress==3) fprintf(fp, "// dan1 compression %d bytes (%d%%)\n", size,ratio); else if (compress==4) fprintf(fp, "// dan2 compression %d bytes (%d%%)\n", size,ratio); else if (compress==5) fprintf(fp, "// dan3 compression %d bytes (%d%%)\n", size,ratio); } int Convert2Pic(char *filebase, unsigned char *buffer, unsigned int *tilemap, unsigned int *palet, unsigned int *tilecol, int num_tiles, int mapw, int maph, int savemap, int savepal) { char filenamec[256],filenameh[256],filenamef[256]; unsigned int val16b; unsigned char bufsw1[8]; unsigned char value, minv,maxv; unsigned char valtil[8]; unsigned char *tiMem,*tiMemEncode,*coMem,*coMemEncode, *maMem, *maMemEncode; int x,y,t,b; int lenencode,lenencode1,lenencode2; int lenencodet1,lenencodet2,lenencodet3; FILE *fpc,*fph; unsigned char bitplanes,mask; int len = strlen(filebase)-1; int i; for (i = len; i >= 0; i--) { if (filebase[i] == '/') { break; } } if (i==-1) { sprintf(filenamef,"%sgfx",filebase); } else { sprintf(filenamef,"%sgfx",&filebase[i+1]); } sprintf(filenamec,"%sgfx.inc",&filebase[i+1]); sprintf(filenameh,"%sgfx.h",&filebase[i+1]); sprintf(filenamec,"%sgfx.inc",filebase); sprintf(filenameh,"%sgfx.h",filebase); if (quietmode == 0) { printf("\nSaving gfx source file: [%s]",filenamec); printf("\nSaving gfx header file: [%s]",filenameh); } fpc = fopen(filenamec,"wb"); fph = fopen(filenameh,"wb"); if(fpc==NULL) { printf("\nERROR: Can't open file [%s] for writing\n",filenamec); return 0; } if(fph==NULL) { printf("\nERROR: Can't open file [%s] for writing\n",filenameh); return 0; } if (bmpmode) num_tiles=768; //tiMem = (unsigned char *) malloc(num_tiles*8); //tiMemEncode = (unsigned char *) malloc(num_tiles*8); tiMem = (unsigned char *) malloc(256*8*3); // max number for bitmap mode or f18a emc3 mode tiMemEncode = (unsigned char *) malloc(256*8*3); // max number for bitmap mode or f18a emc3 mode coMem = (unsigned char *) malloc(num_tiles*8); coMemEncode = (unsigned char *) malloc(num_tiles*8); maMem = (unsigned char *) malloc(mapw*maph); maMemEncode = (unsigned char *) malloc(mapw*maph); if ( (tiMem==NULL) || (coMem==NULL) || (maMem==NULL) || (tiMemEncode==NULL) || (coMemEncode==NULL) || (maMemEncode==NULL) ) { printf("\nERROR: Could not allocate enough memory\n"); return 0; } if (quietmode == 0) { printf("\nDecode for %d tiles...\n",num_tiles); } // different check for ecm1-3 if (ecmmode>1) { // grab number of planes bitplanes=(ecmmode-1); for(t=0;t<num_tiles;t++) //loop through tiles { for(b=0;b<bitplanes;b++) //loop through bitplane pairs { //get bit-mask mask = 1 << b; for(y=0;y<8;y++) { value = 0; //get row of bit-plane and save row for(x=0;x<8;x++) { value = value << 1; if(buffer[t*64 + y*8 + x] & mask) value = value+1; } *(tiMem+y+t*8+(b*256*8))=value; } } *(coMem+t)=*(tilecol+t); // tile priority } } else { for(t=0;t<num_tiles;t++) { //loop through tiles for(y=0;y<8;y++) { value=0; minv=0xFF; maxv=0x00; // get the 8 values for (x=0;x<8;x++) { valtil[x]=buffer[t*64 + y*8 + x]; // get min and max value if (valtil[x]<minv) minv=valtil[x]; if (valtil[x]>maxv) maxv=valtil[x]; } // put 1 if max color if (maxv <= 0x01) maxv=0xF; if (minv == 0xff) minv=1; for (x=0;x<8;x++) { if (valtil[x]==maxv) value=value | (1<<(7-x)); } *(tiMem+y+t*8)=value; if (gramode!=1) *(coMem+y+t*8)=(maxv<<4) | (minv); // FG color | BG color } } if (gramode==1) { for (t=0;t<32;t++) *(coMem+t)=*(tilecol+t); } } // sprites are 16x16 but we need to swap tile 2<>3 if (sprmode) { // different check for ecm1-3 if (ecmmode>1) { // grab number of planes bitplanes=(ecmmode-1); for(t=0;t<num_tiles;t+=4) //loop through tiles { for(b=0;b<bitplanes;b++) //loop through bitplane pairs { memcpy(bufsw1,(tiMem+(t+1)*8+(b*256*8)),8); memcpy((tiMem+(t+1)*8+(b*256*8)),(tiMem+(t+2)*8+(b*256*8)),8); memcpy((tiMem+(t+2)*8+(b*256*8)),bufsw1,8); } } } else { for(t=0;t<num_tiles;t+=4) { //loop through tiles memcpy(bufsw1,(tiMem+(t+1)*8),8); memcpy((tiMem+(t+1)*8),(tiMem+(t+2)*8),8); memcpy((tiMem+(t+2)*8),bufsw1,8); } } } // Get map if possible (so not in sprite mode) if (tilemap!=NULL) { for (t=0;t<mapw*maph;t++) { // if bitmap mode, adapt it if (bmpmode) { if (tilemap[t]>=256*2) *(maMem+t)=tilemap[t]-256*2; else if (tilemap[t]>=256) *(maMem+t)=tilemap[t]-256; else *(maMem+t)=tilemap[t]; } else *(maMem+t)=tilemap[t]; } } // write files regarding compression type lenencode=num_tiles*8;lenencode1=num_tiles*8;lenencode2=mapw*maph; lenencodet1=lenencodet2=lenencodet3=num_tiles*8; if (ecmmode>1) { lenencode1=num_tiles; } if (compress==0) { // no compression memcpy(tiMemEncode,tiMem,lenencode); if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else memcpy(coMemEncode,coMem,lenencode1); memcpy(maMemEncode,maMem,lenencode2); } else if (compress==1) { // rle compression if (ecmmode>1) { lenencodet1=rleCompress( tiMem,tiMemEncode,lenencode); lenencodet2=rleCompress( tiMem+256*8,tiMemEncode+256*8,lenencode); lenencodet3=rleCompress( tiMem+256*8*2,tiMemEncode+256*8*2,lenencode); } else lenencode=rleCompress( tiMem,tiMemEncode,lenencode); if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else lenencode1=rleCompress(coMem,coMemEncode,lenencode1); if (savemap) lenencode2=rleCompress(maMem,maMemEncode,lenencode2); else memcpy(maMemEncode,maMem,lenencode2); } else if (compress==2) { // ple compression if (ecmmode>1) { lenencodet1=pleCompress( tiMem,tiMemEncode,lenencode); lenencodet2=pleCompress( tiMem+256*8,tiMemEncode+256*8,lenencode); lenencodet3=pleCompress( tiMem+256*8*2,tiMemEncode+256*8*2,lenencode); } else lenencode=pleCompress( tiMem,tiMemEncode,lenencode); if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else lenencode1=pleCompress(coMem,coMemEncode,lenencode1); if (savemap) lenencode2=pleCompress(maMem,maMemEncode,lenencode2); else memcpy(maMemEncode,maMem,lenencode2); } else if (compress==3) { // dan1 compression if (ecmmode>1) { lenencodet1=dan1Compress( tiMem,tiMemEncode,lenencode); lenencodet2=dan1Compress( tiMem+256*8,tiMemEncode+256*8,lenencode); lenencodet3=dan1Compress( tiMem+256*8*2,tiMemEncode+256*8*2,lenencode); } else { lenencode=dan1Compress( tiMem,tiMemEncode,lenencode); } if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else { lenencode1=dan1Compress(coMem,coMemEncode,lenencode1); } if (savemap) { lenencode2=dan1Compress(maMem,maMemEncode,lenencode2); } else { memcpy(maMemEncode,maMem,lenencode2); } } else if (compress==4) { // dan2 compression if (ecmmode>1) { lenencodet1=dan2Compress( tiMem,tiMemEncode,lenencode); lenencodet2=dan2Compress( tiMem+256*8,tiMemEncode+256*8,lenencode); lenencodet3=dan2Compress( tiMem+256*8*2,tiMemEncode+256*8*2,lenencode); } else { lenencode=dan2Compress( tiMem,tiMemEncode,lenencode); } if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else { lenencode1=dan2Compress(coMem,coMemEncode,lenencode1); } if (savemap) { lenencode2=dan2Compress(maMem,maMemEncode,lenencode2); } else { memcpy(maMemEncode,maMem,lenencode2); } } else if (compress==5) { // dan3 compression if (ecmmode>1) { lenencodet1=dan3Compress( tiMem,tiMemEncode,lenencode); lenencodet2=dan3Compress( tiMem+256*8,tiMemEncode+256*8,lenencode); lenencodet3=dan3Compress( tiMem+256*8*2,tiMemEncode+256*8*2,lenencode); } else { lenencode=dan3Compress( tiMem,tiMemEncode,lenencode); } if (gramode==1) { memcpy(coMemEncode,coMem,32); lenencode1=32; } else { lenencode1=dan3Compress(coMem,coMemEncode,lenencode1); } if (savemap) { lenencode2=dan3Compress(maMem,maMemEncode,lenencode2); } else { memcpy(maMemEncode,maMem,lenencode2); } } // write to files fprintf(fpc,"// Generated by gfx2col\n\n"); if (ecmmode>1) { addcomment(fpc, (((num_tiles*8)-lenencodet1)*100)/(num_tiles*8),lenencodet1,compress); fprintf(fpc, "const unsigned char TILP1%s[%d]={\n", filenamef,lenencodet1); // write characters & colors for (t = 0; t < lenencodet1; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(tiMemEncode+t)); } fprintf(fpc, "\n};\n\n"); if (ecmmode>2) { addcomment(fpc, (((num_tiles*8)-lenencodet2)*100)/(num_tiles*8),lenencodet2,compress); fprintf(fpc, "const unsigned char TILP2%s[%d]={\n", filenamef,lenencodet2); // write characters & colors for (t = 0; t < lenencodet2; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(tiMemEncode+t+256*8)); } fprintf(fpc, "\n};\n\n"); } if (ecmmode>3) { addcomment(fpc, ((num_tiles*8-lenencodet3)*100)/(num_tiles*8),lenencodet3,compress); fprintf(fpc, "const unsigned char TILP3%s[%d]={\n", filenamef,lenencodet3); // write characters & colors for (t = 0; t < lenencodet3; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(tiMemEncode+t+256*8*2)); } fprintf(fpc, "\n};\n\n"); } } else { addcomment(fpc, ((num_tiles*8-lenencode)*100)/(num_tiles*8),lenencode,compress); fprintf(fpc, "const unsigned char TIL%s[%d]={\n", filenamef,lenencode); // write characters & colors for (t = 0; t < lenencode; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(tiMemEncode+t)); } fprintf(fpc, "\n};\n\n"); } // do that only if it is not a sprite if (sprmode==0) { if (gramode!=1) { if (ecmmode>1) { addcomment(fpc, ((num_tiles-lenencode1)*100)/(num_tiles),lenencode1,compress); } else addcomment(fpc, ((num_tiles*8-lenencode1)*100)/(num_tiles*8),lenencode1,compress); } fprintf(fpc, "const unsigned char COL%s[%d]={\n", filenamef,lenencode1); for (t = 0; t < lenencode1; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(coMemEncode+t)); } fprintf(fpc, "\n};\n\n"); // write map if needed if (savemap) { addcomment(fpc, ((mapw*maph-lenencode2)*100)/(mapw*maph),lenencode2,compress); fprintf(fpc, "const unsigned char MAP%s[%d]={\n", filenamef,lenencode2); for (t = 0; t < lenencode2; t++) { if(t) { if((t & 31) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } fprintf(fpc, "0x%02X", *(maMemEncode+t)); } fprintf(fpc, "\n};\n\n"); } } // do that only if we need palette if (savepal) { if (output_palette==64) { fprintf(fpc, "const unsigned char PAL%s[%d]={\n", filenamef,(ecmmode==1) ? 16*2 : 64*2); if (ecmmode==1) { y=15; for (t = 0; t < 16; t++) { if (t) { if((t & 15) == 0) fprintf(fpc, ",\n"); else fprintf(fpc, ", "); } val16b=*(palet+t); fprintf(fpc, "0x%02X", (val16b & 0xF00)>>8); fprintf(fpc, ",0x%02X", (val16b & 0xFF)); } } else { y = (1<<(ecmmode-1))-1; for (t = 0; t < 64; t++) { if (t) { if((t & y) == 0) fprintf(fpc, ", // PAL %d\n",(t/(y+1))-1); else fprintf(fpc, ", "); } val16b=*(palet+t); fprintf(fpc, "0x%02X", (val16b & 0xF00)>>8); fprintf(fpc, ",0x%02X", (val16b & 0xFF)); } } fprintf(fpc, " // PAL %d\n};\n\n",(t/(y+1))-1); } } // write hearder file fprintf(fph, "#ifndef %s_INC_\n", filenamef); fprintf(fph, "#define %s_INC_\n\n", filenamef); if (ecmmode>1) { fprintf(fph, "#define SZTILP1%s %d\n", filenamef,lenencodet1); fprintf(fph, "#define SZTILP2%s %d\n", filenamef,lenencodet2); fprintf(fph, "#define SZTILP3%s %d\n", filenamef,lenencodet3); } else fprintf(fph, "#define SZTIL%s %d\n", filenamef,lenencode); // do that only if it is not a sprite if (sprmode==0) { fprintf(fph, "#define SZCOL%s %d\n", filenamef,lenencode1); if (savemap) fprintf(fph, "#define SZMAP%s %d\n", filenamef,lenencode2); fprintf(fph,"\n"); } if (ecmmode>1) { fprintf(fph, "extern const unsigned char TILP1%s[];\n", filenamef); fprintf(fph, "extern const unsigned char TILP2%s[];\n", filenamef); fprintf(fph, "extern const unsigned char TILP3%s[];\n", filenamef); } else fprintf(fph, "extern const unsigned char TIL%s[];\n", filenamef); // do that only if it is not a sprite if (sprmode==0) { fprintf(fph, "extern const unsigned char COL%s[];\n", filenamef); if (savemap) fprintf(fph, "extern const unsigned char MAP%s[];\n", filenamef); } if (savepal) { if (output_palette==64) { fprintf(fph, "extern const unsigned char PAL%s[];\n", filenamef); } } fprintf(fph, "\n\n"); fprintf(fph, "#endif\n"); fclose(fpc);fclose(fph); // free memory if (maMemEncode) free(maMemEncode); if (maMem) free(maMem); if (coMemEncode) free(coMemEncode); if (coMem) free(coMem); if (tiMemEncode) free(tiMemEncode); if (tiMem) free(tiMem); return -1; } //end of Convert2Pic //--------------------------------------------------------------------------- void PrintOptions(char *str) { printf("\n\nUsage : gfx2col [options] bmp/pcx/tga filename ..."); printf("\n where filename is a 256 color PNG, BMP, PCX or TGA file"); printf("\n and palette is only the 1st 16 colors in bitmap or"); printf("\n the 1st 64 colors in bitmap for F18A mode."); if(str[0]!=0) printf("\nThe [%s] parameter is not recognized.",str); printf("\n\nOptions are:"); printf("\n\n--- General options ---"); printf("\n-c[no|rle|ple|dan1|dan2|dan3] Compression method [no]"); printf("\n\n--- Graphic options ---"); printf("\n-s Generate sprite graphics"); printf("\n-b Bitmap mode (no more 256 tiles limit)"); printf("\n-g[m1|m2] TMS9918 Graphic mode (mode 2 or mode 1) [m2]"); printf("\n-e[0|1|2|3] Enhanced Color Mode (F18A only) [0]"); printf("\n-t Enable transparent tiles (color 0)"); printf("\n\n--- Map options ---"); printf("\n-m! Exclude map from output"); printf("\n-m Convert the whole picture"); printf("\n-mR! No tile reduction (not advised)"); printf("\n-mn# Generate the whole picture with an offset for tile number"); printf("\n where # is the offset in decimal (0 to 2047)"); printf("\n\n--- Palette options ---"); printf("\n-p! Exclude palette from output"); printf("\n-po Export palette (16 colors (ecm0) or 64 colors(ecm1-3)"); printf("\n-pR Palette rounding"); printf("\n\n--- File options ---"); printf("\n-f[bmp|pcx|tga|png] Convert a bmp or pcx or tga or png file [bmp]"); printf("\n\n--- Misc options ---"); printf("\n-q Quiet mode"); printf("\n"); printf("\nExample:"); printf("\ngfx2col -crle -fpng -m myimage.png"); printf("\n will convert a myimage png file to a inc file with 8x8 tiles, rle compressed"); printf("\n and a map."); } //end of PrintOptions() //--------------------------------------------------------------------------- // M A I N int main(int argc, char **arg) { unsigned int palette[64]; unsigned int colorspal[256];//,coltilopt[256]; unsigned char colornumbers; int height, width; int xsize, ysize,xsize1, ysize1; pcx_picture image; unsigned char *buffer, *buff=NULL; unsigned int *tilemap,*timap=NULL; char filebase[256]=""; char filename[256]; int i, x,y; int file_type=BMP_FILE; int tile_reduction=1; // 0 = no tile reduction (warning !) int savemap=1; // 1 = save the map int savepal=1; // 1 = save the palette // Show something to begin :) if (quietmode == 0) { printf("\n=============================="); printf("\n---gfx2col v"GFX2COLVERSION" "GFX2COLDATE"---"); printf("\n------------------------------"); printf("\n(c) 2018-2020 Alekmaul"); printf("\n==============================\n"); } //parse the arguments for(i=1;i<argc;i++) { if(arg[i][0]=='-') { if(arg[i][1]=='q') //quiet mode { quietmode=1; } else if(arg[i][1]=='t') // transparent tile mode { transmode=1; } else if(arg[i][1]=='s') // sprite mode { sprmode=1; tile_reduction=0; savemap=0; // Fix 200318 , no need for sprite } else if(arg[i][1]=='b') // bitmap mode { bmpmode=1; } else if(arg[i][1]=='m') //map options { if( strcmp(&arg[i][1],"m") == 0) { } else if( strcmp(&arg[i][1],"m!") == 0) { savemap=0; } else if( strcmp(&arg[i][1],"mp") == 0) { highpriority=1; } else if(arg[i][2]=='n') //offset for tiles { offset_tile = atoi(&arg[i][3]); } else if( strcmp(&arg[i][1],"mR!") == 0) { tile_reduction=0; } else { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='g') // graphic mode { if( strcmp(&arg[i][1],"gm1") == 0) { gramode = 1; } else //invalid option { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='p') //palette options { if( strcmp(&arg[i][1],"p!") == 0) { savepal=0; } else if(arg[i][2]=='o') //palette output (64 colors) { output_palette=64; } else if(arg[i][2]=='R') // color rounded { palette_rnd=1; } else //invalid option { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='e') //ecm mode { if(arg[i][2]=='o') //palette output (64 colors) { output_palette=64; } else if(arg[i][2]=='R') // color rounded { palette_rnd=1; } else if ( (arg[i][2]>='0') && (arg[i][2]<='3') ) { ecmmode=1+arg[i][2]-48; output_palette=64; } else { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='c') //compression method { if( strcmp(&arg[i][1],"crle") == 0) { compress = 1; } else if( strcmp(&arg[i][1],"cple") == 0) { compress = 2; } else if( strcmp(&arg[i][1],"cdan1") == 0) { compress = 3; // DAN1 compression } else if( strcmp(&arg[i][1],"cdan2") == 0) { compress = 4; // DAN2 compression } else if( strcmp(&arg[i][1],"cdan3") == 0) { compress = 5; // DAN3 compression } else //invalid option { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='f') //file type specification { if( strcmp(&arg[i][1],"fpcx") == 0) { file_type = 2; // PCX, } else if( strcmp(&arg[i][1],"ftga") == 0) { file_type = 3; // TGA } else if( strcmp(&arg[i][1],"fpng") == 0) { file_type = 4; // PNG, evething else is bmp } else //invalid option { PrintOptions(arg[i]); return 1; } } else //invalid option { PrintOptions(arg[i]); return 1; } } else { //its not an option flag, so it must be the filebase if(filebase[0]!=0) // if already defined... there's a problem { PrintOptions(arg[i]); return 1; } else strcpy(filebase,arg[i]); } } if( filebase[0] == 0 ) { printf("\nERROR: You must specify a base filename."); PrintOptions(""); return 1; } //Load picture if (filebase[strlen(filebase)-4] == '.') { filebase[strlen(filebase)-4] = '\0'; } switch (file_type) { case 2 : // PCX sprintf(filename,"%s.pcx",filebase); if (quietmode == 0) printf("\nOpening graphics file: [%s]",filename); if(!PCX_Load(filename,(pcx_picture_ptr) &image)) return 1; break; case 3 : // TGA sprintf(filename,"%s.tga",filebase); if (quietmode == 0) printf("\nOpening graphics file: [%s]",filename); if(!TGA_Load(filename,(pcx_picture_ptr) &image)) return 1; break; case 4 : // PNG sprintf(filename,"%s.png",filebase); if (quietmode == 0) printf("\nOpening graphics file: [%s]",filename); if(!PNG_Load(filename,(pcx_picture_ptr) &image)) return 1; break; default : // BMP for everithing else sprintf(filename,"%s.bmp",filebase); if (quietmode == 0) printf("\nOpening graphics file: [%s]",filename); if(!BMP_Load(filename,(pcx_picture_ptr) &image)) return 1; break; } //convert the palette if (output_palette==64) ConvertPalette(image.palette, palette); height = image.header.height; width = image.header.width; xsize = width>>3; ysize = height>>3; //Print what the user has selected if (quietmode == 0) { printf("\n****** O P T I O N S ***************"); if (sprmode) printf("\nSprite mode=ON"); else { printf("\nSprite mode=OFF"); if (transmode) printf("\nF18A Tile transparent mode=ON"); else printf("\nF18A Tile transparent mode=OFF"); if (highpriority) printf("\nF18A Tile highpriority mode=ON"); else printf("\nF18A Tile highpriority mode=OFF"); if (ecmmode==0) { if (bmpmode) printf("\nTMS9918 Bitmap mode2=ON"); else { printf("\nTMS9918 Bitmap mode2=OFF"); if (gramode == 0) printf("\nTMS9918 Graphic mode 2"); else if (gramode == 1) printf("\nTMS9918 Graphic mode 1"); } } if (tile_reduction) printf("\nOptimize tilemap=ON"); else printf("\nOptimize tilemap=OFF"); } if (ecmmode!=0) { printf("\nF18A Enhanced Color Mode=%d",ecmmode-1); } if (file_type == 2) printf("\nPCX file: %dx%d pixels",width,height); else if (file_type == 3) printf("\nTGA file: %dx%d pixels",width,height); else if (file_type == 4) printf("\nPNG file: %dx%d pixels",width,height); else printf("\nBMP file: %dx%d pixels",width,height); if (compress == 0) printf("\nNo compression"); else if (compress == 1) printf("\nRLE compression"); else if (compress == 2) printf("\nPLE compression"); else if (compress == 3) printf("\nDAN1 compression"); else if (compress == 4) printf("\nDAN2 compression"); else if (compress == 5) printf("\nDAN3 compression"); if (output_palette) printf("\nPalette output=ON"); else printf("\nPalette output=OFF"); printf("\n************************************"); } fflush(stdout); if ( (bmpmode==1) && (width != 256) && (height != 192) ) { printf("\nERROR : Image must have 256x192 pixel size in bitmap mode (%d,%d here).\n",width, height); return 1; } if (bmpmode) { // prepare global map & tiles tilemap=(unsigned int *) malloc(32*24*sizeof(int)); buffer = (unsigned char *) malloc( 768*8*8*sizeof(char) ); ysize=0; // 3 parts for tiles in bitmap mode for (i=0;i<3;i++) { ysize1=8;xsize1=32; // Get tiles if (buff) free(buff); buff=ArrangeBlocks(image.buffer+i*256*64,256,64,8,&xsize1,&ysize1,8); if(buff==NULL) { printf("\nERROR:Not enough memory to do image operations...\n"); return 1; } // Optimize map with current tile set if (timap) free (timap); timap=MakeMap(buff, colorspal, &ysize1, xsize1, ysize1, xsize1, ysize1, tile_reduction ); if(timap==NULL) { free(buff); printf("\nERROR:Not enough memory to do tile map optimizations..\n"); return 1; } // load tiles ysize+=ysize1; if ( (ysize1>0)) { memcpy(buffer+i*256*8*8,buff,256*8*8); // change map at the end for (y=0;y<8;y++) for (x=0;x<32;x++) tilemap[x+y*32+i*256]=timap[x+y*32]+i*256; } // if ( (ysize>0)) } // for (i=0;i<3;i++) { free(image.buffer); free(buff); free(timap); } else { // now re-arrange into a list of 8x8 blocks for easy conversion buffer=ArrangeBlocks( image.buffer, width, height, 8, &xsize, &ysize, 8); free(image.buffer); if(buffer==NULL) { printf("\nERROR:Not enough memory to do image operations...\n"); return 1; } //make the tile map now tilemap=MakeMap(buffer, colorspal, &ysize, xsize, ysize, xsize, ysize, tile_reduction ); if(tilemap==NULL) { free(buffer); printf("\nERROR:Not enough memory to do tile map optimizations..\n"); return 1; } // make color map now for mode 1 and if not F18A enhanced mode 1-3 (will erase colorspal, but don't care) if ( (ecmmode<=1) && (gramode==1) ) { if ( MakeCol(buffer, tilemap,&colornumbers, colorspal, &ysize,width/8, height/8) == 0) { return 1; } if (quietmode == 0) printf("\nScreen uses %d colors.",colornumbers); } } if (ysize>0) { if (quietmode == 0) { if (tile_reduction) printf("\nReduced screen to %d tiles.",ysize); else printf("\nComputed screen with %d tiles.",ysize); } if ( (ysize>256) && (bmpmode==0) && (sprmode==0) ) // fix 200318 no control if in sprite mode { printf("\nERROR : Image must have less than 256 tiles (%d here).\n",ysize); return 1; } //convert pictures and save to file if(!Convert2Pic(filebase, buffer, tilemap, palette, colorspal, ysize, width/8, height/8,savemap,savepal)) { //free up image & tilemap memory free(tilemap); free(buffer); return 1; } } //free up image & tilemap memory free(tilemap); free(buffer); if (quietmode == 0) printf("\nDone !\n\n"); return 0; } <file_sep>#ifndef COMPTOOL_H #define COMPTOOL_H #include <stdio.h> #include <stdlib.h> #include <mem.h> #define bool unsigned char #define byte unsigned char #define false 0 #define true 0xff extern int pleCompress(byte *src,byte *dst,int n); extern void addevent(void); extern void claimevent(void); #endif<file_sep>/*--------------------------------------------------------------------------------- f18a test with no specific feature -- alekmaul ---------------------------------------------------------------------------------*/ #include "f18atest.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Check if f18a is available vdp_f18ainit(); // display a message regarding result of test if (vdp_f18aok==1) { // put screen in mode 1 with no specific f18a stuffs vdp_f18asetmode1(0); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 8, it is in the first area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xF1,128*8); vdp_enablescr(); // Print text as we are not going to do something else vdp_putstring(8,5,"F18A SUPPORT OK !"); } else { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 8, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Print text as we are not going to do something else vdp_putstring(8,5,"NO F18A SUPPORT..."); } // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>#include "compdan3.h" //--------------------------------------------------------------------------- #define DAN3RAW_MIN 1 #define DAN3RAW_RANGE (1<<8) #define DAN3RAW_MAX DAN3RAW_MIN + DAN3RAW_RANGE - 1 #define DAN3BIT_GOLOMG_MAX 7 #define DAN3BIT_OFFSET_MIN 9 #define DAN3BIT_OFFSET_MAX 16 #define DAN3MAX 256*1024 #define DAN3MAX_GAMMA (1<<(DAN3BIT_GOLOMG_MAX+1)) - 2 #define DAN3BIT_OFFSET00 0 #define DAN3BIT_OFFSET0 1 #define DAN3BIT_OFFSET1 5 #define DAN3BIT_OFFSET2 8 #define DAN3MAX_OFFSET00 (1<<DAN3BIT_OFFSET00) #define DAN3MAX_OFFSET0 (1<<DAN3BIT_OFFSET0) + DAN3MAX_OFFSET00 #define DAN3MAX_OFFSET1 (1<<DAN3BIT_OFFSET1) #define DAN3MAX_OFFSET2 (1<<DAN3BIT_OFFSET2) + DAN3MAX_OFFSET1 #define DAN3MAX_OFFSET (1<<DAN3BIT_OFFSET_MAX) + DAN3MAX_OFFSET2 #define DAN3BIT_OFFSET_NBR DAN3BIT_OFFSET_MAX - DAN3BIT_OFFSET_MIN + 1 // MATCHES - struct t_match { int index; struct t_match *next; }; struct t_match dan3matches[65536]; struct t_optimal { int bits[DAN3BIT_OFFSET_NBR]; /* COST */ int offset[DAN3BIT_OFFSET_NBR]; int len[DAN3BIT_OFFSET_NBR]; } dan3optimals[DAN3MAX]; int DAN3BIT_OFFSET_NBR_ALLOWED; int DAN3BIT_OFFSET_MAX_ALLOWED; int DAN3BIT_OFFSET3; int DAN3MAX_OFFSET3; int dan3bit_index; int dan3index_dest; int dan3index_src; int dan3bit_mask; // - INITIALIZE MATCHES TABLE - void dan3reset_matches(void) { int i; for (i = 0;i < 65536;i++) { dan3matches[i].next = NULL; } } // REMOVE MATCHE(S) FROM MEMORY - void dan3flush_match(struct t_match *match) { struct t_match *node; struct t_match *head = match->next; while ((node = head) != NULL) { head = head->next; free(node); } match->next = NULL; } // - INSERT A MATCHE IN TABLE - void dan3insert_match(struct t_match *match, int index) { struct t_match *new_match = (struct t_match *) malloc( sizeof(struct t_match) ); new_match->index = match->index; new_match->next = match->next; match->index = index; match->next = new_match; } void set_BIT_OFFSET3(int i) { DAN3BIT_OFFSET3 = DAN3BIT_OFFSET_MIN + i; DAN3MAX_OFFSET3 = (1 << DAN3BIT_OFFSET3) + DAN3MAX_OFFSET2; } // WRITE DATA - void dan3write_byte(byte value, byte *data_dest) { data_dest[dan3index_dest++] = value; } void dan3write_bit(int value, byte *data_dest) { if (dan3bit_mask == 0) { dan3bit_mask = (unsigned char) 128; dan3bit_index = dan3index_dest; dan3write_byte((unsigned char) 0, data_dest); } if (value) data_dest[dan3bit_index] |= dan3bit_mask; dan3bit_mask >>= 1 ; } void dan3write_bits(int value, int size, byte *data_dest) { int i; int mask = 1; for (i = 0 ; i < size ; i++) { mask <<= 1; } while (mask > 1) { mask >>= 1; dan3write_bit (value & mask,data_dest); } } void dan3write_golomb_gamma(int value, byte *data_dest) { int i; value++; for (i = 4; i <= value; i <<= 1) { dan3write_bit(0,data_dest); } while ((i >>= 1) > 0) { dan3write_bit(value & i,data_dest); } } void dan3write_offset(int value, int option,byte *data_dest) { value--; if (option == 1) { if (value >= DAN3MAX_OFFSET00) { dan3write_bit(1,data_dest); value -= DAN3MAX_OFFSET00; dan3write_bits(value, DAN3BIT_OFFSET0,data_dest); } else { dan3write_bit(0,data_dest); dan3write_bits(value, DAN3BIT_OFFSET00,data_dest); } } else { if (value >= DAN3MAX_OFFSET2) { dan3write_bit(1,data_dest); dan3write_bit(1,data_dest); value -= DAN3MAX_OFFSET2; dan3write_bits(value >> DAN3BIT_OFFSET2, DAN3BIT_OFFSET3 - DAN3BIT_OFFSET2,data_dest); dan3write_byte((unsigned char) (value & 255),data_dest);; /* BIT_OFFSET2 = 8 */ } else { if (value >= DAN3MAX_OFFSET1) { dan3write_bit(0,data_dest);; value -= DAN3MAX_OFFSET1; dan3write_byte((unsigned char) (value & 255),data_dest); /* BIT_OFFSET2 = 8 */ } else { dan3write_bit(1,data_dest); dan3write_bit(0,data_dest); dan3write_bits(value, DAN3BIT_OFFSET1,data_dest); } } } } void dan3write_literal(unsigned char c,byte *data_dest) { dan3write_bit(1,data_dest); dan3write_byte(c,data_dest); } void dan3write_literals_length(int length,byte *data_dest) { dan3write_bit(0,data_dest); dan3write_bits(0, DAN3BIT_GOLOMG_MAX,data_dest); dan3write_bit(1,data_dest); length -= DAN3RAW_MIN; dan3write_byte((unsigned char) length,data_dest); } void dan3write_doublet(int length, int offset,byte *data_dest) { dan3write_bit(0,data_dest); dan3write_golomb_gamma(length,data_dest); dan3write_offset(offset, length,data_dest); } void dan3write_end(byte *data_dest) { dan3write_bit(0,data_dest); dan3write_bits(0, DAN3BIT_GOLOMG_MAX,data_dest); dan3write_bit(0,data_dest); } void dan3write_lz(byte *data_src, byte *data_dest,int subset) { int i, j; int index; dan3index_dest = 0; dan3bit_mask = 0; dan3write_bits(0xFE, subset + 1,data_dest); dan3write_byte(data_src[0],data_dest); for (i = 1;i < dan3index_src;i++) { if (dan3optimals[i].len[subset] > 0) { index = i - dan3optimals[i].len[subset] + 1; if (dan3optimals[i].offset[subset] == 0) { if (dan3optimals[i].len[subset] == 1) { dan3write_literal(data_src[index],data_dest); } else { dan3write_literals_length(dan3optimals[i].len[subset],data_dest); for (j = 0;j < dan3optimals[i].len[subset];j++) { dan3write_byte(data_src[index + j], data_dest); } } } else { dan3write_doublet(dan3optimals[i].len[subset], dan3optimals[i].offset[subset],data_dest); } } } dan3write_end(data_dest); //write_destination(); } // - GOLOMB GAMMA LIMIT TO 254 - int golomb_gamma_bits(int value) { int bits = 0; value++; while (value > 1) { bits += 2; value >>= 1; } return bits; } int dan3count_bits(int offset, int len) { int bits = 1 + golomb_gamma_bits(len); if (len == 1) { if (DAN3BIT_OFFSET00 == -1) { return bits + DAN3BIT_OFFSET0; } else { return bits + 1 + (offset > DAN3MAX_OFFSET00 ? DAN3BIT_OFFSET0 : DAN3BIT_OFFSET00); } } return bits + 1 + (offset > DAN3MAX_OFFSET2 ? 1 + DAN3BIT_OFFSET3 : (offset > DAN3MAX_OFFSET1 ? DAN3BIT_OFFSET2 : 1 + DAN3BIT_OFFSET1)); } void update_optimal(int index, int len, int offset) { int i; int cost; i = DAN3BIT_OFFSET_NBR_ALLOWED - 1; while (i >= 0) { if (offset == 0) { if (index > 0) { if (len == 1) { dan3optimals[index].bits[i] = dan3optimals[index-1].bits[i] + 1 + 8; dan3optimals[index].offset[i] = 0; dan3optimals[index].len[i] = 1; } else { cost = dan3optimals[index-len].bits[i] + 1 + DAN3BIT_GOLOMG_MAX + 1 + 8 + len * 8; if (dan3optimals[index].bits[i] > cost) { dan3optimals[index].bits[i] = cost; dan3optimals[index].offset[i] = 0; dan3optimals[index].len[i] = len; } } } else { dan3optimals[index].bits[i] = 8; dan3optimals[index].offset[i] = 0; dan3optimals[index].len[i] = 1; } } else { if (offset > DAN3MAX_OFFSET1) { set_BIT_OFFSET3(i); if (offset > DAN3MAX_OFFSET3) break; } cost = dan3optimals[index-len].bits[i] + dan3count_bits(offset, len); if (dan3optimals[index].bits[i] > cost) { dan3optimals[index].bits[i] = cost; dan3optimals[index].offset[i] = offset; dan3optimals[index].len[i] = len; } } i--; } } // - REMOVE USELESS FOUND OPTIMALS - void dan3cleanup_optimals(int subset) { int j; int i = dan3index_src - 1; int len; while (i > 1) { len = dan3optimals[i].len[subset]; for (j = i - 1; j > i - len;j--) { dan3optimals[j].offset[subset] = 0; dan3optimals[j].len[subset] = 0; } i = i - len; } } // - LZ ENCODE - void dan3lzss_slow(byte *data_src,byte *data_dest) { //int temp_bits; int best_len; int len; int i, j, k; int offset; int match_index, prev_match_index = -1; int bits_minimum_temp, bits_minimum; struct t_match *match; dan3reset_matches(); update_optimal(0, 1, 0); i = 1; while (i < dan3index_src) { // TRY LITERALS update_optimal(i, 1, 0); // STRING OF LITERALS if (i >= DAN3RAW_MIN) { j = DAN3RAW_MAX; if (j > i) j = i; if (DAN3RAW_MIN == 1) { for (k = j ; k > DAN3RAW_MIN; k--) { update_optimal(i, k, 0); } } else { // RAW MINIMUM > 1 for (k = j ; k >= DAN3RAW_MIN; k--) { update_optimal(i, k, 0); } } } // LZ MATCH OF 1 j = (DAN3BIT_OFFSET00 == -1 ? (1 << DAN3BIT_OFFSET0) : DAN3MAX_OFFSET0); if (j > i) j = i; for (k = 1; k <= j; k++) { if (data_src[i] == data_src[i-k]) { update_optimal(i, 1, k); } } // LZ MATCH OF 2+ match_index = ((int) data_src[i-1]) << 8 | ((int) data_src[i] & 255); match = &dan3matches[match_index]; if (prev_match_index == match_index /*&& bFAST == TRUE*/ && dan3optimals[i-1].offset[0] == 1 && dan3optimals[i-1].len[0] > 2) { len = dan3optimals[i-1].len[0]; if (len < DAN3MAX_GAMMA) update_optimal(i, len + 1, 1); } else { best_len = 1; for (;match->next != NULL; match = match->next) { offset = i - match->index; if (offset > DAN3MAX_OFFSET) { dan3flush_match(match); break; } for (len = 2;len <= DAN3MAX_GAMMA;len++) { update_optimal(i, len, offset); //best_len = len; if (i < offset + len || data_src[i-len] != data_src[i-len-offset]) { break; } } //if (bFAST && best_len > 255) break; if (best_len > 255) break; } } //prev_match_index = match_index; dan3insert_match(&dan3matches[match_index], i); i++; } bits_minimum = dan3optimals[dan3index_src-1].bits[0]; j = 0; for (i = 0;i < DAN3BIT_OFFSET_NBR_ALLOWED;i++) { bits_minimum_temp = dan3optimals[dan3index_src-1].bits[i]; if (bits_minimum_temp < bits_minimum) { bits_minimum = bits_minimum_temp; j = i; } } set_BIT_OFFSET3(j); dan3cleanup_optimals(j); dan3write_lz(data_src,data_dest,j); len = (1 + j + bits_minimum + 2 + DAN3BIT_GOLOMG_MAX + 7) / 8; } // - SET MAXIMUM BITS ALLOWED TO ENCODE OFFSET void set_max_bits_allowed(int bits) { if (bits > DAN3BIT_OFFSET_MAX) bits = DAN3BIT_OFFSET_MAX; if (bits < DAN3BIT_OFFSET_MIN) bits = DAN3BIT_OFFSET_MIN; DAN3BIT_OFFSET_MAX_ALLOWED = bits; DAN3BIT_OFFSET_NBR_ALLOWED = DAN3BIT_OFFSET_MAX_ALLOWED - DAN3BIT_OFFSET_MIN + 1; } int dan3Compress(byte *src,byte *dst,int n) { size_t count; // SET MAX BITS FOR BIG OFFSET VALUES - set_max_bits_allowed(DAN3BIT_OFFSET_MAX); // Initialize Matches Array dan3index_src=n; // Apply compression dan3lzss_slow(src,dst); // compute ratio count=dan3index_dest; return count; } <file_sep>/*--------------------------------------------------------------------------------- scoring functions demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "scoring.h" score_t scoretst,scoretst1; //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Clear the score scoretst.hi=18;scoretst.lo=900; sys_scoclear(&scoretst); vdp_putstring(2,2,"score hi xxxxx score lo xxxx"); vdp_putstring(11,2,sys_str(scoretst.hi));vdp_putstring(26,2,sys_str(scoretst.lo)); // Add a value sys_scoadd(&scoretst,0x4DB); vdp_putstring(2,4,"score hi xxxxx score lo xxxx"); vdp_putstring(11,4,sys_str(scoretst.hi));vdp_putstring(26,4,sys_str(scoretst.lo)); // Add more than 10000 sys_scoadd(&scoretst,0x2710); vdp_putstring(2,6,"score hi xxxxx score lo xxxx"); vdp_putstring(11,6,sys_str(scoretst.hi));vdp_putstring(26,6,sys_str(scoretst.lo)); vdp_putstring(11,7,sys_scostr(&scoretst,8)); // Compare two scores scoretst.hi=18;scoretst.lo=900; scoretst1.hi=17;scoretst1.lo=900; if (sys_scocmp(&scoretst,&scoretst1)==0xFF) vdp_putstring(2,12,"1 scores equals"); else if (sys_scocmp(&scoretst,&scoretst1)==0) vdp_putstring(2,12,"1 scoretst higher"); else if (sys_scocmp(&scoretst,&scoretst1)==1) vdp_putstring(2,12,"1 scoretst lower"); scoretst1.hi=18;scoretst1.lo=901; if (sys_scocmp(&scoretst,&scoretst1)==0xFF) vdp_putstring(2,13,"2 scores equals"); else if (sys_scocmp(&scoretst,&scoretst1)==0) vdp_putstring(2,13,"2 scoretst higher"); else if (sys_scocmp(&scoretst,&scoretst1)==1) vdp_putstring(2,13,"2 scoretst lower"); scoretst1.hi=19;scoretst1.lo=900; if (sys_scocmp(&scoretst,&scoretst)==0xFF) vdp_putstring(2,14,"3 scores equals"); else if (sys_scocmp(&scoretst,&scoretst1)==0) vdp_putstring(2,14,"3 scoretst higher"); else if (sys_scocmp(&scoretst,&scoretst1)==1) vdp_putstring(2,14,"3 scoretst lower"); // Wait for nothing :P while(1) { vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>cmake_minimum_required (VERSION 3.1) project(gfx2col C) set(gfx2col_major_version 1) set(gfx2col_minor_version 4) set(gfx2col_path_version 0) set(gfx2col_version "${gfx2col_major_version}.${gfx2col_minor_version}.${gfx2col_path_version}") if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug") endif() set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}") set(CMAKE_C_STANDARDS 11) configure_file(config.h.in config.h) set(gfx2col_sources compdan1.c compdan2.c compdan3.c comprle.c comptool.c gfx2col.c lodepng.c lodepic.c ) set(gfx2col_headers compdan1.h compdan2.h compdan3.h comprle.h gfx2col.h lodepng.h lodepic.h config.h ) add_executable(gfx2col ${gfx2col_sources} ${gfx2col_headers}) target_compile_options(gfx2col PRIVATE -Wall -Wshadow -Wextra) target_include_directories(gfx2col PRIVATE ${CMAKE_BINARY_DIR}) install(TARGETS gfx2col RUNTIME DESTINATION bin) <file_sep>/*--------------------------------------------------------------------------------- Simple sound demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "ssound.h" //--------------------------------------------------------------------------------- // sound declaration const u8 dummysound[]={ // no sound, for soundtable, see below 0x90 }; const u8 dksound[]={ // from Donkey Kong sound item 9 0x81,0x3d,0x00,0x50,0x11,0x01, // tone freq 1833,8Hz swept down - vol 15 (max) - length 80 0x90 // end }; const u8 btsound[]={ // from Burger time sound item 12 0x00,0x00,0x02,0x05, // periodic noise - freq 125 Hz - vol 15 (max) - length 5 0x10 // end }; const u8 shsound[]={ // from spy hunter sound item 13 0x02,0x26,0x1e,0x1d,0x24, // white noise - freq 874 Hz - vol 13 swept down - length 30 0x10 // end }; const u8 sfsound[]={ // from space fury sound item 4 0x43,0x97,0x00,0x08,0x11, 0x2d,0x1f,0x11, // tone freq 740,8Hz swept down - vol 15 (max) swept down - length 8 0x10 // end /* */ }; //--------------------------------------------------------------------------------- // mandatory soundtable declaration // For some reason the very first entry MUST be SOUNDAREA1. SOUNDAREA1 is the lowest priority sound effect. // I recommend using SOUNDAREA1-SOUNDAREA3 to be music track. SOUNDAREA4-6 to be sound effects. const sound_t snd_table[]={ { dummysound, SOUNDAREA1}, // sound entry 1 { dksound, SOUNDAREA4}, // sound entry 2 { btsound, SOUNDAREA5}, // sound entry 3 { shsound, SOUNDAREA6}, // sound entry 4 { sfsound, SOUNDAREA4}, // sound entry 5 }; //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put sound table and mute all channel snd_settable(snd_table); snd_stopall(); // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_putstring(7,6,"PUSH PAD FOR SOUNDS"); // display screen and enable sound vdp_enablescr(); vdp_enablenmi(); // Wait for nothing :P while(1) { // Update display with current pad 1 values if (joypad_1 & PAD_RIGHT) { vdp_putstring(9,10,"DK SND"); snd_startplay(2); } if (joypad_1 & PAD_LEFT) { vdp_putstring(9,10,"BT SND"); snd_startplay(3); } if (joypad_1 & PAD_DOWN) { vdp_putstring(9,10,"SH SND"); snd_startplay(4); } if (joypad_1 & PAD_UP) { vdp_putstring(9,10,"SF SND"); snd_startplay(5); } while (joypad_1) vdp_waitvblank(1); // Wait Vblank while joy pressed vdp_waitvblank(1); // default wait vblank } // startup module will issue a soft reboot if it comes here } <file_sep>/*--------------------------------------------------------------------------------- Graphic mode 1 example with a bitmap -- alekmaul ---------------------------------------------------------------------------------*/ #include "mode1plecompress.h" #include "gfxs.h" // to add definition of graphics //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { vdp_disablescr(); // put screen in mode 1 vdp_setmode1txt(); vdp_ple2vram (TILourvisiongfx, chrgen); // characters vdp_putvram (coltab,COLourvisiongfx,32); // colors (not compressed as it is only 32 bytes) vdp_ple2vram (MAPourvisiongfx, chrtab); // map vdp_enablescr(); // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>/*--------------------------------------------------------------------------------- Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Hex checker / BIN creator for colecovision. Based on : hex2bin converts an Intel hex file to binary. Copyright (C) 2012, <NAME> checksum extensions Copyright (C) 2004 Rockwell Automation All rights reserved. ***************************************************************************/ //INCLUDES #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <malloc.h> #include <string.h> //DEFINES #define CVMKCARTVERSION __BUILD_VERSION #define CVMKCARTDATE __BUILD_DATE #define MAX_LINE_SIZE 1024 // The data records can contain 255 bytes: this means 512 characters. #define MEMORY_SIZE 1024*1024 // size in bytes (max = 1Mb) #define NO_ADDRESS_TYPE_SELECTED 0 #define LINEAR_ADDRESS 1 #define SEGMENTED_ADDRESS 2 int quietmode=0; // 0 = not quiet, 1 = i can't say anything :P unsigned int maxlength = 64*1024; // max rom length size unsigned int nobanks = 2; // number of banks unsigned int padbyte = 0xFF; // padding byte unsigned char *memblocks; // This will hold binary codes translated from hex file unsigned int norecord; // record number for tracing unsigned char datastring[MAX_LINE_SIZE]; char dataline[MAX_LINE_SIZE]; // line inputted from file unsigned int nobytes; unsigned int firstword, address, segment, upperaddr; unsigned int lowaddr, highaddr, startaddr, lowbank; /* This mask is for mapping the target binary inside the binary buffer. If for example, we are generating a binary file with records starting at FFF00000, the bytes will be stored at the beginning of the memory buffer. */ unsigned int maskaddr; unsigned int physaddr, recordtype; unsigned int temp; int temp2; unsigned int norecord; // We will assume that when one type of addressing is selected, it will be valid for all the // current file. Records for the other type will be ignored. unsigned int seglinselect = NO_ADDRESS_TYPE_SELECTED; char *p; //-- Read a line from file -------------------------------------------------------- int Getdataline(char* str,FILE *in) { char *result; result = fgets(str,MAX_LINE_SIZE,in); if ((result == NULL) && !feof (in)) { printf("\nERROR: Can't read from file\n"); return 0; } return 1; } //-- Print option of program ------------------------------------------------------ void PrintOptions(char *str) { printf("\n\nUsage: cvmkcart [options] romfilename ..."); printf("\n where romfilename is the COLECOVISION rom file to generate."); if(str[0]!=0) printf("\nThe [%s] parameter is not recognized.",str); printf("\n\nOptions are:"); printf("\n\n--- Rom options ---"); printf("\n-b[bank] Number of 16k banks of finale rom (default is 2 for 64k rom, max is 64 for 1Mb rom)."); printf("\n-p[value] Padding byte value (default is 255)."); printf("\n-iihxfilename Name of HEX ihx filename."); printf("\n"); printf("\n\n--- Misc options ---"); printf("\n-q quiet mode"); printf("\n"); } //end of PrintOptions() /// M A I N //////////////////////////////////////////////////////////// int main(int argc, char **arg) { FILE *fpi, *fpo; char romfile[256]; char ihxfile[256]; int i; // Show something to begin :) if (quietmode == 0) { printf("\n================================="); printf("\n--- CVMKCART v"CVMKCARTVERSION" "CVMKCARTDATE" ---"); printf("\n---------------------------------"); printf("\n(c) 2014-2019 Alekmaul "); printf("\n=================================\n"); } // Init vars romfile[0] = '\0'; ihxfile[0] = '\0'; //parse the arguments for(i=1;i<argc;i++) { if(arg[i][0]=='-') { if(arg[i][1]=='q') //quiet mode { quietmode=1; } else if(arg[i][1]=='b') // number of banks { nobanks=atoi(&arg[i][2]); if ( (nobanks<2) || (nobanks>64)) { PrintOptions(arg[i]); return 1; } maxlength=(nobanks+3)*16*1024; // 3 because we begin writing at 0xc000 } else if(arg[i][1]=='p') // padding byte { padbyte=atoi(&arg[i][2]); if (padbyte>255) { PrintOptions(arg[i]); return 1; } } else if(arg[i][1]=='i') // ihx filename { strcpy(ihxfile,&arg[i][2]); } else //invalid option { PrintOptions(arg[i]); return 1; } } else { //its not an option flag, so it must be the filebase if(romfile[0]!=0) // if already defined... there's a problem { PrintOptions(arg[i]); return 1; } else { strcpy(romfile,arg[i]); } } } //make sure options are valid if( romfile[0] == 0 ) { printf("\nERROR: You must specify a rom filename."); PrintOptions(""); return 1; } if (strlen(ihxfile) == 0) { printf("\nERROR: You must specify an ihx file."); PrintOptions(""); return 1; } // open the file fpi = fopen(ihxfile,"r"); if (fpi==NULL) { printf("\nERROR: Can't open ihx file [%s]",ihxfile); return 0; } // open the file fpo = fopen(romfile,"wb"); if (fpo==NULL) { printf("\nERROR: Can't create rom file [%s]",romfile); return 0; } // allocate a buffer if ((memblocks = malloc (maxlength+0x8000)) == NULL) { printf("\nERROR: Can't allocate memory for output.\n"); exit(1); } if (quietmode == 0) { printf("\n****** O P T I O N S ***************"); printf("\nReading file %s ...",ihxfile); printf("\nWriting rom file %s...",romfile); printf("\nRom size %dk",(maxlength-0x4000)/1024); printf("\nNumber of banks %d",nobanks); printf("\nPadding byte %02x\n",padbyte); } // begining of reading file startaddr = 0; maxlength+=0x8000; // rom 0..8000 if coleco bios and ram // fill unused bytes with FF or the value specified by the p option (or 255 for default value) memset (memblocks,padbyte,maxlength); // To begin, assume the lowest address is at the end of the memory. // While reading each records, subsequent addresses will lower this number. // At the end of the input file, this value will be the lowest address. // A similar assumption is made for highest address. It starts at the // beginning of memory. While reading each records, subsequent addresses will raise this number. // At the end of the input file, this value will be the highest address. lowaddr = maxlength - 1 - 0x8000; highaddr = 0; segment = 0; upperaddr = 0; norecord = 0; lowbank=0; /* Max length must be in powers of 2: 1,2,4,8,16,32, etc. */ maskaddr = maxlength;// -1; if (quietmode == 0) { printf("\nMaximum address set to %06x\n",maskaddr); } // Read the file & process the lines. do // repeat until EOF(fpi) { //Read a line from input file. Getdataline(dataline,fpi); norecord++; //Remove carriage return/line feed at the end of line. i = strlen(dataline); if (--i != 0) { if (dataline[i] == '\n') dataline[i] = '\0'; // Scan the first two bytes and nb of bytes. // The two bytes are read in firstword since its use depend on the // record type: if it's an extended address record or a data record. sscanf (dataline, ":%2x%4x%2x%s",&nobytes,&firstword,&recordtype,datastring); p = (char *) datastring; // If we're reading the last record, ignore it. switch (recordtype) { // Data record case 0: if (nobytes == 0) { printf("\nWARNING: 0 byte length Data record ignored"); break; } address = firstword; // check bank number to update if new bank if (address==0xc000) { lowbank++; if (quietmode == 0) { printf("\nBank %d detected ...",lowbank); } } // add bank number if in bank if (address>=0xc000) address+=(lowbank-1)*0x4000; if (seglinselect == SEGMENTED_ADDRESS) physaddr = (segment << 4) + address; else // LINEAR_ADDRESS or NO_ADDRESS_TYPE_SELECTED //upperaddr = 0 as specified in the Intel spec. until an extended address record is read. physaddr = ((upperaddr << 16) + address) % maskaddr; // change & to % // Check that the physical address stays in the buffer's range. if ((physaddr + nobytes) <= maxlength) { // Set the lowest address as base pointer. if (physaddr < lowaddr) lowaddr = physaddr; // Same for the top address. temp = physaddr + nobytes -1; if (temp > highaddr) highaddr = temp; // Read the Data bytes. // Bytes are written in the Memory block even if checksum is wrong. i = nobytes; do { sscanf (p, "%2x",&temp2); p += 2; // Overlapping record will erase the pad bytes if (memblocks[physaddr] != padbyte) printf("\nWARNING: Overlapped record (%d) detected %06x=%02x",norecord-1, physaddr,memblocks[physaddr]); memblocks[physaddr++] = temp2; } while (--i != 0); // Read the Checksum value. sscanf (p, "%2x",&temp2); } else { if (seglinselect == SEGMENTED_ADDRESS) printf("\nWARNING: Data record (%d) skipped at %6X:%6X",norecord-1, segment,address); else printf("\nWARNING: Data record (%d) skipped at %6X",norecord-1, physaddr); } break; // End of file record case 1: // Simply ignore checksum errors in this line. break; // Extended segment address record case 2: // firstword contains the offset. It's supposed to be 0000 so we ignore it. // First extended segment address record ? if (seglinselect == NO_ADDRESS_TYPE_SELECTED) seglinselect = SEGMENTED_ADDRESS; // Then ignore subsequent extended linear address records if (seglinselect == SEGMENTED_ADDRESS) { sscanf (p, "%4x%2x",&segment,&temp2); // Update the current address. physaddr = (segment << 4) % maskaddr; } break; // Start segment address record case 3: // Nothing to be done since it's for specifying the starting address for execution of the binary code break; // Extended linear address record case 4: // firstword contains the offset. It's supposed to be 0000 so we ignore it. // First extended linear address record ? if (seglinselect == NO_ADDRESS_TYPE_SELECTED) seglinselect = LINEAR_ADDRESS; // Then ignore subsequent extended segment address records if (seglinselect == LINEAR_ADDRESS) { sscanf (p, "%4x%2x",&upperaddr,&temp2); // Update the current address. physaddr = (upperaddr << 16) % maskaddr; } break; // Start linear address record case 5: // Nothing to be done since it's for specifying the starting address for execution of the binary code break; default: printf("\nWARNING: Unknown record type"); break; } } } while (!feof (fpi)); // maxlength is set; the memory buffer is already filled with pattern before // reading the hex file. The padding bytes will then be added to the binary file. highaddr = startaddr + maxlength-1; startaddr=0xc000; lowaddr = startaddr; // change 0x8000 to last bank // and manage start adress to 0x8000 memcpy(&memblocks[highaddr-0x4000+1],&memblocks[0x8000],0x4000); if (quietmode == 0) { printf("\n\nLowest address = %08X",lowaddr); printf("\nHighest address = %08X",highaddr); printf("\nPad Byte = %X", padbyte); printf("\nRom size wrote = %08X (%dk)",highaddr - lowaddr +1,(highaddr - lowaddr +1)/1024); printf("\nBanks detected = %X\n", lowbank); } // write binary file fwrite (&memblocks[lowaddr], 1, highaddr - lowaddr +1, fpo); free (memblocks); // close the files fclose(fpi); fclose(fpo); if (quietmode == 0) printf("\nDone!\n"); // display map file if (quietmode == 0) { // open the map file strcpy(romfile,ihxfile); i = strlen(romfile); romfile[i-3]='m';romfile[i-2]='a';romfile[i-1]='p'; fpi = fopen(romfile,"r"); if (fpi==NULL) { printf("\nERROR: Can't open map file [%s]",romfile); return 0; } printf("\nArea Addr Size Decimal Bytes (Attributes)"); printf("\n-------------------------------- ---- ---- ------- ----- ------------\n"); do { //Read a line from input file. Getdataline(dataline,fpi); // if line begin with _, print it (I know it is bad ...) if (dataline[0]=='_') { printf(dataline); } } while (!feof (fpi)); fclose(fpi); printf("\n"); } return 0; } <file_sep>ifeq ($(strip $(PVCOLLIB_HOME)),) $(error "Please create an environment variable PVCOLLIB_HOME with path to its folder and restart application. (you can do it on windows with <setx PVCOLLIB_HOME "/c/snesdev">)") endif export TOPDIR := $(CURDIR) # create version number which will be used everywhere export PVCOLLIB_MAJOR := 1 export PVCOLLIB_MINOR := 6 export PVCOLLIB_PATCH := 0 # Directory with docs config and output (via doxygen) export PVCDOCSDIR = $(TOPDIR)/docs .PHONY: release clean all docs all: include/coleco/libversion.h pvcollibversion release docs #------------------------------------------------------------------------------- release: lib make -C source all #------------------------------------------------------------------------------- lib: mkdir lib #------------------------------------------------------------------------------- examples: cd ../coleco-examples && \ make && \ make install #------------------------------------------------------------------------------- clean: make -C source clean rm -rf $(PVCDOCSDIR)/html rm -f pvcollib_version.txt #--------------------------------------------------------------------------------- doxygenInstalled := $(shell command -v doxygen 2> /dev/null) docs: ifndef doxygenInstalled @echo "doxygen is not installed, documentation will be not generated."; else @rm -rf $(PVCDOCSDIR)/html; \ PVCDOCSDIR="$(PVCDOCSDIR)" PVCVERSION="$(PVCOLLIB_MAJOR).$(PVCOLLIB_MINOR).$(PVCOLLIB_PATCH)" doxygen "$(PVCDOCSDIR)/pvcollib.dox" @if [ "$(DOCS_PDF_ON)" = "YES" ]; then\ $(MAKE) -C $(PVCDOCSDIR)/latex;\ cp $(PVCDOCSDIR)/latex/refman.pdf $(PVCDOCSDIR)/PVCOLLIB_manual.pdf;\ fi @if [ -f 'warn.log' ]; then \ @cat warn.log; \ fi @rm -rf $(PVCDOCSDIR)/latex endif # Turn on Latex -> PDF conversion to run run at end of regular docs build # (which includes latex output but deletes it at the end). # # The conversion process requires a Latex install. # For Windows there are various Latex packages to choose from. # For Linux this appears to be the minimum: # sudo apt install texlive-latex-base # sudo apt install texlive-latex-recommended # sudo apt install texlive-latex-extra # docspdf: DOCS_PDF_ON=YES docspdf: docs #--------------------------------------------------------------------------------- include/coleco/libversion.h : Makefile @echo "#ifndef __PVCOLLIBVERSION_H__" > $@ @echo "#define __PVCOLLIBVERSION_H__" >> $@ @echo >> $@ @echo "#define _PVCOLLIB_MAJOR_ $(PVCOLLIB_MAJOR)" >> $@ @echo "#define _PVCOLLIB_MINOR_ $(PVCOLLIB_MINOR)" >> $@ @echo "#define _PVCOLLIB_PATCH_ $(PVCOLLIB_PATCH)" >> $@ @echo >> $@ @echo '#define _PVCOLLIB_STRING "PVCOLLIB Release '$(PVCOLLIB_MAJOR).$(PVCOLLIB_MINOR).$(PVCOLLIB_PATCH)'"' >> $@ @echo >> $@ @echo "#endif // __PVCOLLIBVERSION_H__" >> $@ # to ease installation for users, the version is no more in folder name (which require to update PVCOLLIB_HOME) but in specific file pvcollibversion: @echo $(PVCOLLIB_MAJOR).$(PVCOLLIB_MINOR).$(PVCOLLIB_PATCH) > pvcollib_version.txt<file_sep>ifeq ($(strip $(PVCOLLIB_HOME)),) $(error "Please create an environment variable PVCOLLIB_HOME with path to its folder and restart application. (you can do it on windows with <setx PVCOLLIB_HOME "/c/colecodev">)") endif include ${PVCOLLIB_HOME}/devkitcol/col_rules #--------------------------------------------------------------------------------- # ROMNAME is used in col_rules file ROMNAME := simplesprite .PHONY: bitmaps all #--------------------------------------------------------------------------------- all: bitmaps $(ROMNAME).rom clean: cleanRom cleanGfx #--------------------------------------------------------------------------------- pacsprite.inc: pacsprite.png @echo convert sprite ... $(notdir $@) $(GFXCONV) -fpng -s $< bitmaps: pacsprite.inc <file_sep>#ifndef __SDCC_STDALIGN_H #define __SDCC_STDALIGN_H 1 #ifndef __alignas_is_defined #define __alignas_is_defined 1 #define alignas _Alignas #endif #ifndef __alignof_is_defined #define __alignof_is_defined 1 #define alignof _Alignof #endif #endif <file_sep>/*--------------------------------------------------------------------------------- Generic f18a video functions Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file f18a.h * \brief contains the basic definitions for controlling the f18a video device. * * This unit provides generic features related to f18a device.<br> *<br> * Here is the list of features:<br> * - enable and disable f18a<br> * - update palette<br> */ #ifndef COL_F18A_INCLUDE #define COL_F18A_INCLUDE #include <coleco/coltypes.h> #define sprtab_f18a 0x2800 //f18a colour only requires 1/3 the colour data so til 0x2800 #define sprtab_f18a_2 0x3000 #define sprtab_f18a_3 0x3800 #define mapvram 0x1b00 #define F18A_ECMS_0P (0<<0) #define F18A_ECMS_1B (1<<0) #define F18A_ECMS_2B (2<<0) #define F18A_ECMS_3B (3<<0) #define F18A_ECMT_0P (0<<4) #define F18A_ECMT_1B (1<<4) #define F18A_ECMT_2B (2<<4) #define F18A_ECMT_3B (3<<4) #define F18A_ECM_R30 (1<<6) #define F18A_ECM_TM2 (1<<7) #define F18A_ECM_YRE (1<<3) /** * \brief vdp_f18aok is set if f18a module is present<br> * when calling vdp_f18ainit function<br> */ extern volatile u8 vdp_f18aok; /** * \fn void vdp_f18ainit(void) * \brief Activate f18a device<br> * Activate f18a and init vdp_f18aok variable with 1 if it is ok<br> */ void vdp_f18ainit(void); /** * \fn void vdp_f18asetpalette(void *data,unsigned char count) * \brief Send a palette RGB 12bits color entries to f18a device<br> * * \param data address of data to use * \param count number of data <b>in words (each entry is two bytes)</b> */ void vdp_f18asetpalette(void *data,unsigned char count); /** * \fn void vdp_f18asetpaletteentry(void *data,u8 entry,unsigned char count) * \brief Send a palette RGB 12bits color entries to f18a device<br> * * \param data address of data to use * \param offset 1st entry in the palette (0..64) * \param count number of data <b>in words (each entry is two bytes)</b> */ void vdp_f18asetpaletteentry(void *data,unsigned offset,unsigned char count); /** * \fn vdp_f18asetmode1(u8 flags) * \brief Activate mode 1 in bitmap mode for f18a ONLY<br> * * \param flags ecm mode definition<br> * F18A_ECMS_0P or F18A_ECMS_1..3B for sprite color mode<br> * F18A_ECMT_0P or F18A_ECMT_1..3B for tile color mode<br> * F18A_ECM_R30 for 30 lines mode <br> * F18A_ECM_TM2 to activate tile map 2 <br> * F18A_ECM_YRE to activate Y real coordinates <br> */ void vdp_f18asetmode1(u8 flags); /** * \fn vdp_f18asetscrollx(u8 bgnum, u8 x) * \brief Sets the horizontal scroll offset to the specified location * * \param bgnum background number (1 or 2 for TL1 and TL2) * \param x the horizontal scroll offset <br> * (5 bits of scroll | 3 bits for planes : HTO0 HTO1 HTO2 HTO3 HTO4 HPO0 HPO1 HPO2) */ void vdp_f18asetscrollx(u8 bgnum, u8 x); /** * \fn vdp_f18asetscrolly(u8 bgnum, u8 y) * \brief Sets the vertical scroll offset to the specified location * * \param bgnum background number (1 or 2 for TL1 and TL2) * \param y the vertical scroll offset <br> * (5 bits of scroll | 3 bits for planes : VTO0 VTO1 VTO2 VTO3 VTO4 VPO0 VPO1 VPO2) */ void vdp_f18asetscrolly(u8 bgnum, u8 y); #endif <file_sep>/*--------------------------------------------------------------------------------- simple sprite demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "simplesprite.h" #include "gfxs.h" // to add definition of graphics //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { // update sprite display during nmi, if you enable sprites if (spr_enable) spr_update(); } //--------------------------------------------------------------------------------- void main (void) { u8 xp,yp,idpac; // Put screen in text mode 2 vdp_disablescr(); vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) // Put sprite character vdp_putvram (sprtab,TILpacspritegfx,SZTILpacspritegfx); // sprite characters // Enable screen and nmi to allow display and sprite management vdp_enablescr(); vdp_enablenmi(); // Put sprite in middle of screen with color light yellow, 0 because we have only one pattern (index 0) xp=8*16;yp=8*12; idpac=spr_getentry(); spr_set(idpac,xp,yp,11,0); // enable sprite display spr_enable = 1; // Wait for nothing :P while(1) { if (joypad_1 & PAD_RIGHT) { if (xp<(256-16)) { xp++; spr_setx(idpac,xp); } } if (joypad_1 & PAD_LEFT) { if (xp>0) { xp--; spr_setx(idpac,xp); } } if (joypad_1 & PAD_DOWN) { if (yp<(192-16)) { yp++; spr_sety(idpac,yp); } } if (joypad_1 & PAD_UP) { if (yp>0) { yp--; spr_sety(idpac,yp); } } // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>ifeq ($(strip $(PVCOLLIB_HOME)),) $(error "Please create an environment variable PVCOLLIB_HOME with path to its folder and restart application. (you can do it on windows with <setx PVCOLLIB_HOME "/c/colecodev">)") endif include ${PVCOLLIB_HOME}/devkitcol/col_rules #--------------------------------------------------------------------------------- # ROMNAME is used in col_rules file ROMNAME := ssound .PHONY: all #--------------------------------------------------------------------------------- all: $(ROMNAME).rom clean: cleanRom cleanGfx <file_sep>#ifndef COMPDAN3_H #define COMPDAN3_H #include <stdio.h> #include <stdlib.h> #include <mem.h> #define bool unsigned char #define byte unsigned char #define false 0 #define true 0xff extern int dan3Compress(byte *src,byte *dst,int n); #endif<file_sep>#ifndef _COSMOC_MAIN_ #define _COSMOC_MAIN_ #include <coleco.h> extern void vdp_putvramex (unsigned offset,void *ptr,unsigned count,u8 and_mask,u8 xor_mask); extern u8 check_collision (sprite_t *sprite1,sprite_t *sprite2, unsigned sprite1_size_hor,unsigned sprite1_size_vert, unsigned sprite2_size_hor,unsigned sprite2_size_vert); extern const sound_t snd_table[]; /* various RLE-encoded tables (in tables.c) */ extern const u8 title_screen[]; extern const u8 intro_screen[]; extern const u8 stone_characters[]; extern const u8 sprite_patterns[]; #endif<file_sep> # bin2txt binary to text converter for Colecovision PVcollib development ## Usage ``` bin2txt [options] filename ... ``` where filename is a binary file ## Options ### General options - `-c[no|rle|ple|dan]` Compression method [no] ### Convert options - `-cc` Output in c style format - `-ca` Output in assembly style format ### Misc options - `-q` Quiet mode ## Example ``` bin2txt -cc myimage.bin ``` This will will convert a myimage bin file to a h file. ## History V1.0.0 : initial release <file_sep>/*--------------------------------------------------------------------------------- f18a test with a bitmap -- alekmaul ---------------------------------------------------------------------------------*/ #include "f18abitmap1.h" #include "gfxs.h" // to add definition of graphics //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Check if f18a is available vdp_f18ainit(); // display a message regarding result of test if (vdp_f18aok==1) { // put screen in mode 1 with no specific f18a stuffs vdp_f18asetmode1(0x30); vdp_ple2vram (TILourvisiongfx, chrgen); // characters vdp_ple2vram (MAPourvisiongfx, chrtab); // map vdp_ple2vram (COLourvisiongfx, coltab); // colours vdp_f18asetpalette(PALourvisiongfx,64); vdp_enablescr(); } else { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 8, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Print text as we are not going to do something else vdp_putstring(8,5,"NO F18A SUPPORT..."); } // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>/********************************************/ /* */ /* GRAPHICS TABLES - WIN ICVGM v3.00 */ /* */ /* WARNING : RLE COMPRESSION */ /* */ /********************************************/ #include <coleco.h> const u8 NAMERLE[] = { 0x01, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x86, 0x20, 0x00, 0x98, 0x93, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x87, 0x20, 0x0B, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x87, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x87, 0x20, 0x0B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x87, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x93, 0x20, 0x00, 0x98, 0x86, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x8C, 0x20, 0x01, 0xD6, 0xD7, 0x8C, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x92, 0x20, 0x00, 0xC8, 0x87, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x86, 0x20, 0x05, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x84, 0x20, 0x01, 0xC9, 0xCA, 0x87, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x86, 0x20, 0x04, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0x82, 0x20, 0x04, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0x87, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x87, 0x20, 0x03, 0xA4, 0xA5, 0xA6, 0xA7, 0x82, 0x20, 0x03, 0xD0, 0xD1, 0xD2, 0xD3, 0x88, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x86, 0x20, 0x06, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0x82, 0x20, 0x01, 0xD4, 0xD5, 0x88, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x86, 0x20, 0x09, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xC7, 0xC7, 0x8A, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x87, 0x20, 0x09, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0x20, 0xC7, 0xC7, 0x89, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x87, 0x20, 0x08, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0x20, 0xC7, 0x8A, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x8A, 0x20, 0x05, 0xC5, 0xC6, 0xC4, 0x20, 0xC7, 0xC7, 0x8A, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x89, 0x20, 0x07, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0x89, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x03, 0x25, 0x26, 0x24, 0x23, 0x9B, 0x20, 0x01, 0x25, 0x26, 0xFF}; const u8 PATTERNRLE[] = { 0x0A, 0xC3, 0x24, 0xA5, 0x66, 0x3C, 0x5A, 0xDB, 0xE7, 0x00, 0xC3, 0x42, 0x83, 0x00, 0x1C, 0x18, 0x00, 0x24, 0x7E, 0xE7, 0xC3, 0xE7, 0x7E, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x3C, 0x18, 0x00, 0x00, 0xE0, 0x90, 0x48, 0x28, 0x1C, 0x3A, 0x7A, 0x7C, 0x00, 0x60, 0x30, 0x10, 0x82, 0x00, 0x1C, 0x03, 0x08, 0x18, 0x3F, 0x79, 0xF0, 0xF9, 0x7F, 0x3E, 0x06, 0x06, 0xC0, 0x86, 0x0F, 0x06, 0x00, 0x00, 0x07, 0x09, 0x12, 0x14, 0x38, 0x5C, 0x5E, 0x3E, 0x00, 0x06, 0x0C, 0x08, 0x82, 0x00, 0x0E, 0xC0, 0x10, 0x18, 0xFC, 0x9E, 0x0F, 0x9F, 0xFE, 0x7C, 0x60, 0x60, 0x03, 0x61, 0xF0, 0x60, 0xB9, 0x00, 0x44, 0x99, 0x66, 0xDD, 0x77, 0xDD, 0x77, 0x99, 0xBB, 0x99, 0x66, 0xDD, 0x77, 0xDD, 0x77, 0xEE, 0xBB, 0x99, 0x66, 0xDD, 0x77, 0xDD, 0xBB, 0xEE, 0x33, 0x99, 0x66, 0xDD, 0x77, 0xEE, 0xBB, 0xCC, 0x33, 0x99, 0x66, 0xDD, 0xBB, 0xEE, 0x33, 0xCC, 0x22, 0x99, 0x66, 0xEE, 0xBB, 0xCC, 0x33, 0x88, 0x22, 0x99, 0xBB, 0xEE, 0x33, 0xCC, 0x22, 0x88, 0x00, 0xEE, 0xBB, 0xCC, 0x33, 0x88, 0x22, 0x00, 0x00, 0xEE, 0x33, 0xCC, 0x22, 0x88, 0x82, 0x00, 0x03, 0xCC, 0x33, 0x88, 0x22, 0x83, 0x00, 0x02, 0xCC, 0x22, 0x88, 0x84, 0x00, 0x01, 0x88, 0x22, 0x85, 0x00, 0x00, 0x88, 0x90, 0x00, 0x01, 0x0C, 0x1E, 0x82, 0x3E, 0x37, 0x1C, 0x46, 0xAD, 0xDB, 0x76, 0x44, 0x12, 0x00, 0x00, 0xF3, 0xCC, 0x30, 0xCC, 0xF3, 0xCC, 0x30, 0xCC, 0xF3, 0xCC, 0x30, 0xCC, 0xF3, 0xCC, 0x30, 0xCC, 0xCF, 0x33, 0x0C, 0x33, 0xCF, 0x33, 0x0C, 0x33, 0xCF, 0x33, 0x0C, 0x33, 0xCF, 0x33, 0x0C, 0x33, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x7E, 0x3C, 0x18, 0x82, 0x00, 0x03, 0x18, 0x3C, 0x3C, 0x18, 0x84, 0x00, 0x81, 0x18, 0x8A, 0x00, 0x21, 0x30, 0x18, 0x88, 0xFE, 0x7F, 0x18, 0x38, 0x70, 0x00, 0xE0, 0x30, 0xFE, 0x7F, 0x30, 0xE0, 0x00, 0x0C, 0x18, 0x11, 0x7F, 0xFE, 0x18, 0x1C, 0x0E, 0x00, 0x07, 0x0C, 0x7F, 0xFE, 0x0C, 0x07, 0x00, 0xE7, 0x66, 0x85, 0x00, 0x01, 0x18, 0x3C, 0x85, 0x00, 0x81, 0x66, 0x00, 0x24, 0xFE, 0x00, 0xFE, 0x00, 0xFE, 0x00, 0xFE, 0x00, 0xF2, 0x00, 0x00, 0x1C, 0x82, 0x3F, 0x01, 0x7B, 0x70, 0x83, 0x00, 0x03, 0x80, 0x83, 0x3F, 0x7F, 0x85, 0x00, 0x01, 0x1E, 0x3F, 0x83, 0x00, 0x81, 0x38, 0x01, 0xF8, 0xFD, 0x85, 0x00, 0x01, 0xF0, 0xFD, 0x85, 0x00, 0x01, 0xD8, 0xF8, 0x82, 0x00, 0x04, 0x1F, 0x3F, 0x3F, 0x39, 0x39, 0x82, 0x00, 0x04, 0x80, 0xC0, 0xC0, 0xC6, 0xCE, 0x84, 0x00, 0x02, 0x01, 0x33, 0x73, 0x84, 0x00, 0x02, 0x80, 0xF1, 0xFD, 0x84, 0x00, 0x02, 0xC0, 0xF8, 0xFF, 0x84, 0x00, 0x0B, 0x0C, 0x1C, 0x9C, 0x7E, 0x7F, 0x7F, 0xF0, 0xF0, 0xFE, 0xFE, 0x1E, 0xFF, 0x82, 0xE3, 0x1D, 0xF7, 0x7F, 0x7F, 0x1C, 0xFE, 0xE0, 0xFF, 0x7F, 0xA3, 0xFF, 0x7F, 0x3E, 0x7F, 0x73, 0x73, 0xF3, 0xE3, 0xE1, 0xE1, 0x00, 0xFF, 0x9F, 0xFF, 0xF7, 0xCF, 0xFF, 0xFD, 0x78, 0xF8, 0xE0, 0x84, 0xC0, 0x38, 0x00, 0x3F, 0x3F, 0x1F, 0x1C, 0x1D, 0x1F, 0x1F, 0x0F, 0xCE, 0xEE, 0xFE, 0x7E, 0xFF, 0xEF, 0xE7, 0x83, 0x73, 0x73, 0x7B, 0x7F, 0x7F, 0xF7, 0xF2, 0xE0, 0xFD, 0x9D, 0x9D, 0x9F, 0x1F, 0x3B, 0x39, 0x18, 0xFF, 0xCF, 0xCF, 0xCE, 0x8E, 0x9C, 0x1C, 0x0C, 0xDC, 0xDC, 0xFC, 0xFC, 0x7C, 0x38, 0xF8, 0xF0, 0x10, 0x18, 0x3F, 0xFE, 0x7C, 0x3E, 0x32, 0x20, 0x84, 0x00, 0x0D, 0x01, 0x03, 0x07, 0x00, 0x00, 0x03, 0x3F, 0xF0, 0xC0, 0x80, 0x0F, 0x00, 0x00, 0xFF, 0x82, 0x00, 0x0D, 0x7E, 0xFF, 0x00, 0x00, 0x80, 0xFE, 0x03, 0x01, 0x03, 0xFE, 0x00, 0x00, 0x1F, 0xFF, 0x82, 0x7F, 0x04, 0xC0, 0x00, 0x00, 0xC0, 0xFE, 0x82, 0xFF, 0x20, 0x7E, 0x07, 0x0E, 0x0E, 0x0F, 0x0F, 0x07, 0x07, 0x03, 0x3F, 0xF8, 0xE0, 0xC0, 0x83, 0x87, 0x8F, 0xCD, 0x00, 0x00, 0x7D, 0xFF, 0xC7, 0xBF, 0xF3, 0xC1, 0x00, 0xF8, 0xE0, 0x80, 0xC0, 0xE0, 0xF0, 0xFB, 0x85, 0x00, 0x03, 0xE0, 0xF8, 0xEB, 0x7B, 0x82, 0x3F, 0x82, 0x1F, 0x08, 0x86, 0x07, 0x33, 0x38, 0x18, 0x80, 0xC3, 0xFF, 0xFF, 0x82, 0x7F, 0x0B, 0xFF, 0xF1, 0xE0, 0xC0, 0xFC, 0xF2, 0xFC, 0xFF, 0xFC, 0xF0, 0xE0, 0xE0, 0x82, 0x00, 0x06, 0x01, 0x03, 0x07, 0x06, 0x0D, 0x0F, 0x3F, 0x82, 0xFF, 0x00, 0x7F, 0x83, 0xFF, 0x09, 0xF7, 0xBF, 0xFB, 0xDF, 0xFF, 0xFF, 0xC2, 0xC5, 0xE3, 0xFF, 0x82, 0xFE, 0x10, 0xFC, 0xE0, 0xE0, 0xE7, 0x0F, 0x03, 0x00, 0x00, 0x08, 0x00, 0x00, 0xC0, 0xF0, 0xFC, 0xFE, 0x7F, 0xFF, 0x86, 0x00, 0x04, 0x9E, 0x0B, 0x03, 0x06, 0x04, 0x83, 0x00, 0x3B, 0xFF, 0xBF, 0x7C, 0xF0, 0xC3, 0x87, 0x0F, 0x0F, 0xF0, 0x0F, 0x3F, 0xFC, 0xFB, 0xF7, 0x87, 0x7B, 0x03, 0xFF, 0xFF, 0x3F, 0xDF, 0xEF, 0x8F, 0x73, 0x85, 0xC3, 0xC7, 0xEF, 0xFE, 0xFD, 0xFD, 0xFE, 0xBF, 0x9F, 0xBF, 0x7F, 0xFF, 0xBF, 0x7F, 0xEF, 0xE1, 0xC0, 0xE4, 0xE1, 0xE8, 0xE5, 0xC1, 0x97, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0x80, 0x80, 0x00, 0x1E, 0x1E, 0x3E, 0x3E, 0x82, 0x3F, 0x05, 0x1F, 0xFC, 0xFD, 0xFB, 0xE7, 0x1F, 0x82, 0xFF, 0x12, 0xED, 0xDD, 0xFA, 0xF6, 0xFE, 0xFD, 0xFB, 0xF3, 0xFE, 0x87, 0x03, 0x81, 0xC0, 0xE1, 0xFF, 0xFF, 0xDF, 0x3C, 0xC2, 0x83, 0xFF, 0x08, 0xDF, 0x7C, 0x00, 0xF0, 0xFC, 0xFF, 0xFF, 0xEF, 0xEF, 0x84, 0x00, 0x05, 0xC0, 0xF0, 0xFF, 0x1F, 0x0F, 0x03, 0x84, 0x00, 0x81, 0xFF, 0x01, 0xFE, 0xF0, 0x83, 0x00, 0x01, 0xE1, 0x80, 0x85, 0x00, 0x01, 0xFF, 0xFE, 0x84, 0xFF, 0x15, 0x7F, 0x8F, 0x0F, 0xE7, 0xF8, 0xFE, 0xFF, 0xDF, 0xDF, 0xE7, 0xC7, 0x83, 0x03, 0x01, 0x81, 0xE1, 0xFF, 0xBF, 0x77, 0xF8, 0xF8, 0xB8, 0x82, 0xC0, 0x02, 0x7F, 0x3F, 0x1F, 0x84, 0x00, 0x03, 0xCF, 0x8F, 0x07, 0x07, 0x83, 0x03, 0x81, 0x00, 0x00, 0x3F, 0x82, 0x00, 0x19, 0xFC, 0x00, 0x01, 0x02, 0x07, 0x0F, 0x1F, 0x3E, 0x7E, 0xFC, 0x01, 0x02, 0x07, 0x0D, 0x1B, 0x36, 0x2B, 0x55, 0xFC, 0xF8, 0xF8, 0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x84, 0x00, 0x02, 0x01, 0xFF, 0x7E, 0x82, 0x00, 0x21, 0x03, 0x1A, 0xBB, 0xC7, 0xD5, 0x00, 0x00, 0x01, 0x83, 0xC6, 0xFD, 0xFE, 0xFD, 0x6B, 0xD7, 0xAB, 0x57, 0xAA, 0x56, 0xAC, 0x54, 0x84, 0x88, 0x08, 0x10, 0x10, 0x20, 0x04, 0x08, 0x1F, 0x03, 0x00, 0x00, 0x01, 0x82, 0x00, 0x1A, 0xAA, 0xD5, 0x3A, 0x07, 0xC1, 0x30, 0x00, 0x0C, 0xFE, 0x5F, 0xFF, 0x5F, 0xFF, 0x2F, 0x1F, 0x3D, 0xE8, 0xB0, 0xC0, 0xFC, 0xFC, 0x7C, 0xBC, 0xD8, 0x1D, 0x0E, 0x02, 0x84, 0x00, 0x12, 0xD0, 0xE0, 0x08, 0x8E, 0xE6, 0x63, 0x30, 0x00, 0x44, 0xAA, 0x2A, 0x4A, 0x8A, 0x8A, 0xE4, 0x00, 0x4E, 0xA2, 0xA2, 0x82, 0xA4, 0x1A, 0x44, 0x00, 0x73, 0xDB, 0xC3, 0x73, 0x1B, 0xDB, 0x73, 0x00, 0xCF, 0x6C, 0x6C, 0x6F, 0xCC, 0x0C, 0x0F, 0x00, 0xBE, 0x30, 0x30, 0x3C, 0x30, 0x30, 0xBE, 0x00, 0xF0, 0x84, 0xD8, 0x0B, 0xF0, 0x00, 0x70, 0xD8, 0x18, 0x30, 0x60, 0x00, 0x60, 0x00, 0x06, 0x0E, 0x83, 0x06, 0x00, 0x0F, 0x83, 0x00, 0x00, 0x1C, 0x83, 0x00, 0x06, 0x38, 0x6C, 0x0C, 0x18, 0x0C, 0x6C, 0x38, 0xFE, 0x00, 0xFE, 0x00, 0x82, 0x00, 0xFF}; const u8 COLORRLE[] = { 0xDF, 0x41, 0x83, 0xEF, 0x83, 0xE7, 0x83, 0x23, 0x83, 0x2C, 0x83, 0xAB, 0x81, 0xA9, 0x01, 0xA8, 0xA6, 0x83, 0x86, 0x81, 0x89, 0x81, 0x8B, 0x83, 0x23, 0x83, 0x2C, 0x83, 0x23, 0x83, 0x2C, 0x83, 0x23, 0x83, 0x2C, 0x83, 0x23, 0x82, 0x2C, 0x00, 0xC1, 0x83, 0x23, 0x81, 0x2C, 0x81, 0xC1, 0x83, 0x23, 0x00, 0x2C, 0x82, 0xC1, 0x83, 0x23, 0x83, 0xC1, 0x82, 0x23, 0x00, 0x21, 0x83, 0xC1, 0x81, 0x23, 0x81, 0x21, 0x83, 0xC1, 0x02, 0x23, 0x21, 0x21, 0x84, 0xC1, 0x81, 0x21, 0x85, 0xC1, 0x00, 0x21, 0xA6, 0xC1, 0x87, 0x41, 0x81, 0xF1, 0x00, 0xA1, 0x82, 0xF1, 0x04, 0xE1, 0xA1, 0x61, 0x69, 0x6A, 0x84, 0x61, 0x87, 0x2A, 0x87, 0x42, 0x87, 0x2A, 0x87, 0x42, 0xFE, 0x41, 0xFE, 0x41, 0xFE, 0x41, 0xFE, 0x41, 0xFE, 0x41, 0xCC, 0x41, 0xFE, 0xF1, 0xC0, 0xF1, 0x87, 0xB1, 0x8B, 0xE1, 0x83, 0xED, 0x82, 0xE1, 0x83, 0xED, 0x84, 0xE1, 0x82, 0xED, 0xA6, 0xE1, 0x81, 0xEF, 0x97, 0xE1, 0x04, 0x5F, 0x1F, 0x5F, 0x1F, 0x5F, 0x87, 0xEF, 0x82, 0xED, 0x97, 0xE1, 0x87, 0xE8, 0x82, 0xED, 0x00, 0xE1, 0x82, 0xEF, 0x83, 0xE1, 0x84, 0xEF, 0x85, 0xE1, 0x00, 0xEF, 0xA8, 0xE1, 0x83, 0xEF, 0x8B, 0xE1, 0x87, 0xEF, 0xA0, 0xE1, 0x86, 0xEF, 0xDF, 0xE1, 0x87, 0x71, 0xA2, 0xE1, 0x02, 0xF1, 0xA1, 0xB1, 0x83, 0xE1, 0x82, 0xF1, 0xBC, 0xE1, 0x81, 0x91, 0x02, 0x81, 0x61, 0x61, 0xD0, 0xF1, 0xFE, 0x41, 0xFC, 0x41, 0x83, 0x41, 0xFF}; <file_sep>#include <coleco.h> /* Sound#1 : "beep" */ static const u8 egg_snd[] = { 0x43,0x00,0x72,5,0x11,0x90,0xF3,0x11, 0x50}; static const u8 jump_snd[] = { 0x83,0x90,0x11,0x07,0x13,0xe1,0x18,0x11, 0x90}; static const u8 fire_snd[] = { /* white noise - freq 3495 Hz - vol 9 (max) swept down - length 31 */ 0x02,0x64,0x1f,0x1e,0x54, 0x10}; static const u8 inv_snd[] = { 0xc3,0x56,0xe3,0x40,0x11,0xfa,0xc0,0x44, 0xc3,0x56,0xe3,0x30,0x11,0xf5,0xc0,0x33, 0xc3,0x56,0xe3,0x20,0x11,0xea,0xc0,0x22, 0xc2,0x97,0x20,0x4c,0x1e,0x5b, 0xd0}; static const u8 bird_snd[] = { 0x43,0xa2,0xe0,0x10,0x11,0xfa,0x90,0x11, 0x43,0x70,0xe0,0x08,0x11,0xfa,0xa0,0x12, 0x50}; extern const u8 music_ch1[]; extern const u8 music_ch2[]; const sound_t snd_table[] = { {egg_snd,SOUNDAREA1}, {jump_snd,SOUNDAREA2}, {fire_snd,SOUNDAREA3}, {inv_snd,SOUNDAREA4}, {bird_snd,SOUNDAREA5}, {music_ch1,SOUNDAREA1}, `{music_ch2,SOUNDAREA2}}; <file_sep>cmake_minimum_required (VERSION 3.1) project(cvmkcart C) set(cvmkcart_major_version 1) set(cvmkcart_minor_version 0) set(cvmkcart_path_version 0) set(cvmkcart_version "${cvmkcart_major_version}.${cvmkcart_minor_version}.${cvmkcart_path_version}") if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug") endif() set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}") set(CMAKE_C_STANDARDS 11) configure_file(config.h.in config.h) set(cvmkcart_sources cvmkcart.c ) set(cvmkcart_headers cvmkcart.h config.h ) add_executable(cvmkcart ${cvmkcart_sources} ${cvmkcart_headers}) target_compile_options(cvmkcart PRIVATE -Wall -Wshadow -Wextra) target_include_directories(cvmkcart PRIVATE ${CMAKE_BINARY_DIR}) install(TARGETS cvmkcart RUNTIME DESTINATION bin) <file_sep>/*--------------------------------------------------------------------------------- small game from coder <NAME> : Diamond Dash made by her during 2004 MiniGame Competition https://web.archive.org/web/20050204071935/http://www.ffd2.com/minigame/ -- alekmaul ---------------------------------------------------------------------------------*/ #include "diamond.h" #include "dash.h" // main file for game #include "snds.h" // to add definition of sounds const u8 game_title[] = {40,41,42,43,44,45,46,47,0}; // Char array for "DIAMOND DASH!!" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for game example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put sound table and mute all channel snd_settable(snd_table); snd_stopall(); // Put screen in text mode 2 and sprite in 8x8 pixels size vdp_disablescr(); vdp_setmode2txt(); spr_mode8x8(); // Initialise graphics and sounds init_graphics(); // Set a "stop point" to let the Video Chip knows that there is only 1 sprite to show sprites[1].y=208; // Show a new mountain & Show "DIAMOND DASH!!" in center screen new_mountain(); show_score(); vdp_putstring(12,11,game_title); vdp_enablescr(); // Wait until player press fire vdp_enablenmi(); sys_pause(); vdp_disablenmi(); // Play game game(); // END // startup module will issue a soft reboot if it comes here } <file_sep>#ifndef _SIMPLESPR_MAIN_ #define _SIMPLESPR_MAIN_ #include <coleco.h> #endif <file_sep>/*--------------------------------------------------------------------------------- Generic score functions. Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file score.h * \brief coleco generic score support. * * This unit provides methods to manage scores.<br> *<br> * Here is the list of supported features:<br> * - scores with more than 65536 values<br> * - reset, compare, add scores<br> * - convert a score to a string for display purpose<br> */ #ifndef COL_SCORE_H #define COL_SCORE_H #include <coleco/coltypes.h> /** * \struct score_t * \brief score value * Can manage score with more than 65536 values (max of an unsigned) */ typedef struct { unsigned lo; /*!< low value of the score */ unsigned hi; /*!< high value of the score */ } score_t; /** * \fn void sys_scoclear(score_t *sco) * \brief Init a score variable with value 0 * * \param sco score variable to reset */ void sys_scoclear(score_t *sco); /** * \fn void sys_scoadd(score_t *sco, unsigned value) * \brief Add a unsigned value to a score variable * * \param sco score variable * \param value value to add to score */ void sys_scoadd(score_t *sco, unsigned value); /** * \fn u16 sys_scocmp(score_t *sco1,score_t *sco2) * \brief Compare two scores and return 1 if 1st one is lower than 2nd one * * \param sco1 score variable * \param sco2 score variable * \return 1 if sco1 is lower than sco2, 0 if not, 0xFF if equals */ u16 sys_scocmp(score_t *sco1,score_t *sco2); /** * \fn void sys_scocpy(score_t *sco1,score_t *sco2) * \brief Copy a score sco1 into another score sco2 * * \param sco1 score variable * \param sco2 score variable */ void sys_scocpy(score_t *sco1,score_t *sco2); /** * \fn char *sys_scostr(score_t *sco, unsigned length) * \brief Convert a score variable to a string of specific length * * \param sco score variable * \param length number of digits for displkay (max 9) * \return char * string value of score */ char *sys_scostr(score_t *sco, unsigned length); #endif <file_sep>/*--------------------------------------------------------------------------------- Copyright (C) 2018-2019 This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /*! \file coleco.h \brief the master include file for colecovision applications. */ /*! \mainpage PVcollib Documentation \section intro Introduction Welcome to the PVcollib reference documentation. \section console_mngt Generic console feature - \ref console.h "Console management" \section sound_sn76489 sound engine API - \ref sound.h "General sound" \section video_tms9918 2D engine API - \ref video.h "General video" \section video_f18a F18A video device API - \ref f18a.h "F18A specific video" \section pad_mngt Generic pad & spinner API - \ref pad.h "General pad & spinner" \section sprite_mngt Generic sprites API - \ref sprite.h "General sprites" \section score_mngt Generic score API - \ref score.h "General scores" \section SGM Generic API - \ref sgm.h "General SGM" \section external_links Useful links - <a href="http://atariage.com/forums/forum/55-colecovision-programming/">AtariAge ColecoVision development forum.</a> - <a href="https://atariage.com/forums/topic/280138-f18a-mk2/">AtariAge F18A development topic.</a> \section special_thanks Special Thanks - <NAME> (aka newcoleco) for cvlib source code, which are parts of PVcollib. - <a href="https://sourceforge.net/projects/sdcc/files/"><NAME></a> - SDCC Release Manager. - AtariAge member <a href="http://eriscreations.com/">digress</a> for his help about F18A programming on Coleco. - AtariAge member <a href="http://codehackcreate.com/archives/592">matthew180</a> for his help on discord about F18A device, thanks for making it real matthew ;) !. */ //adding the example page. /*! <!-- EXAMPLES --> <!-- hello world --> \example helloworld/helloworld.c <!-- diamond game --> \example games/diamond/diamond.c <!-- graphic management --> \example graphics/backgrounds/dancompress/grafdancomp.c \example graphics/backgrounds/notcompress/grafnocomp.c \example graphics/backgrounds/plecompress/grafplecomp.c \example graphics/backgrounds/rlecompress/grafrlecomp.c \example graphics/sprites/simplesprite/simplesprite.c \example graphics/sprites/animatedsprite/animatedsprite.c <!-- f18a gaphic management --> \example graphics/f18a/f18abitmap1/f18abitmap1.c \example graphics/f18a/f18aecm3/f18aecm3.c \example graphics/f18a/f18atest/f18atest.c <!-- pad management --> \example input/input.c <!-- random numbers --> \example random/randvalue.c <!-- megacart management --> \example megacart/megacart.c <!-- region detection --> \example palntsc/palntsc.c <!-- score management --> \example scoring/scoring.c <!-- sgm system management --> \example sgm/sgmtest/sgmtest.c <!-- sound management --> \example audio/music/music.c \example audio/simplesound/ssound.c */ #ifndef COL_INCLUDE #define COL_INCLUDE #include <coleco/coltypes.h> #include "coleco/console.h" #include "coleco/pad.h" #include "coleco/score.h" #include "coleco/sound.h" #include "coleco/sprite.h" #include "coleco/video.h" #include "coleco/f18a.h" #include "coleco/sgm.h" #endif // COL_INCLUDE <file_sep>#ifndef _GRAFNOCMP_MAIN_ #define _GRAFNOCMP_MAIN_ #include <coleco.h> extern void init_graphics(void); extern void new_mountain(void); extern void game(void); extern void show_score(void); #endif <file_sep>#ifndef _MEGACART_GFXS1_ #define _MEGACART_GFXS1_ #include <coleco.h> #include "image1gfx.h" // generetad by gfx2col #endif <file_sep># A C library for the ColecoVision # ![PVcollib](https://www.portabledev.com/wp-content/uploads/2019/11/pvcollib_logo.png) PVcollib V1.5.1 (09, 20, 2020) PVcollib is an open and free library to develop programs for ColecoVision in C language. It contains sdcc compiler / linker and a library (sources included) which offer facilities to use backgrounds / sprites / pads / music & sound on ColecoVision system. Sdcc compiler from <NAME> - SDCC Release Manager (https://sourceforge.net/projects/sdcc/files/). C Library is based on works from Amy Purple (aka newcoleco), a great Colecovision coder and music composer (<no website currently>). A great thanks to Amy Purple continuing to help me to improve the library, thanks to her ! F18A support from matthew180 (http://codehackcreate.com/archives/592) with the help of digress (http://eriscreations.com) on Colecovision. NMI cautions in ctrcol.s from Tursi (http://www.harmlesslion.com/cgi-bin/showprog.cgi?ColecoVision), thanks to him ! It also contains examples to help how to use functions with the library. You can find the Doxygen documentation of the library in the ['docs'](pvcollib/docs/html/files.html) directory. GitHub page: https://github.com/alekmaul/pvcollib Wiki page: https://github.com/alekmaul/pvcollib/wiki Doc page: https://www.portabledev.com/pvcollib/doc You can find tutorials about how install and use PVCollib on this page: https://github.com/alekmaul/pvcollib/wiki/Introduction We now have a Discord :D, just join us with this link : https://discord.gg/8kAHJgj PVcollib and affiliated tools are distributed under the MIT license (see pvcollib_license.txt file) PVcollib is completly free and you can support it through the Paypal button: [![Paypal](https://www.paypalobjects.com/fr_FR/FR/i/btn/x-click-but04.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y5USKF23DQVLC) Thanks and happy coding =) ! <file_sep>/*--------------------------------------------------------------------------------- megacart demo with 3 banks images from Amy Purple post (newcoleco) here: https://atariage.com/forums/topic/268244-data-compression-benchmark-dan-pletter-zx7-exomizer-pucrunch-megalz/ -- alekmaul ---------------------------------------------------------------------------------*/ #include "megacart.h" #include "gfxsb1.h" // to add definition of graphics #include "gfxsb2.h" // to add definition of graphics #include "gfxsb3.h" // to add definition of graphics // Switch of the banks #define SWITCH_IN_BANK1 { dummy=(*(volatile unsigned char*) 0xFFF8); } // b1 with 16k #define SWITCH_IN_BANK2 { dummy=(*(volatile unsigned char*) 0xFFF9); } // b2 with 16k #define SWITCH_IN_BANK3 { dummy=(*(volatile unsigned char*) 0xFFFA); } // b3 with 16k #define SWITCH_IN_BANK4 { dummy=(*(volatile unsigned char*) 0xFFFB); } // b4 with 16k #define SWITCH_IN_BANK5 { dummy=(*(volatile unsigned char*) 0xFFFC); } // b5 with 16k #define SWITCH_IN_BANK6 { dummy=(*(volatile unsigned char*) 0xFFFD); } // b6 with 16k #define SWITCH_IN_BANK7 { dummy=(*(volatile unsigned char*) 0xFFFE); } // b7 with 16k #define SWITCH_IN_BANK8 { dummy=(*(volatile unsigned char*) 0xFFFF); } // b8 with 16k // var for bank switching unsigned char dummy; //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void initvramIMG1(void) { // Disable Interrupt vdp_waitvblank(1); vdp_disablescr(); SWITCH_IN_BANK1; // Put image in vram vdp_dan12vram (TILimage1gfx, chrgen); // characters vdp_dan12vram (COLimage1gfx, coltab); // colors vdp_dan12vram (MAPimage1gfx, chrtab); // map // enable interrupt vdp_enablescr(); vdp_enablenmi(); } //--------------------------------------------------------------------------------- void initvramIMG2(void) { // Disable Interrupt vdp_waitvblank(1); vdp_disablescr(); SWITCH_IN_BANK2; // Put image in vram vdp_dan12vram (TILimage2gfx, chrgen); // characters vdp_dan12vram (COLimage2gfx, coltab); // colors vdp_dan12vram (MAPimage2gfx, chrtab); // map // enable interrupt vdp_enablescr(); vdp_enablenmi(); } //--------------------------------------------------------------------------------- void initvramIMG3(void) { // Disable Interrupt vdp_waitvblank(1); vdp_disablescr(); SWITCH_IN_BANK3; // Put image in vram vdp_dan12vram (TILimage3gfx, chrgen); // characters vdp_dan12vram (COLimage3gfx, coltab); // colors vdp_dan12vram (MAPimage3gfx, chrtab); // map // enable interrupt vdp_enablescr(); vdp_enablenmi(); } //--------------------------------------------------------------------------------- void main (void) { // Put screen in bitmapmode 2 vdp_disablescr(); vdp_setmode2bmp(); // Enable screen vdp_enablescr(); // Put 1st image initvramIMG1(); // Wait for nothing :P while(1) { // change image regarding joypad if ( (joypad_1 & PAD_RIGHT) ) initvramIMG1(); if ( (joypad_1 & PAD_LEFT) ) initvramIMG2(); if ( (joypad_1 & PAD_FIRE1) ) initvramIMG3(); // Wait Vblank while (joypad_1) { vdp_waitvblank(1); } vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>#ifndef _BUNNY_MAIN_ #define _BUNNY_MAIN_ #include <coleco.h> #define NONE 0x00 #define ICE 0x01 #define GRASS 0x02 #define SAND 0x04 #define AIR 0x08 extern const sound_t snd_table[]; extern u8 read_next_code(u8 *item, u8 code); extern void invincible(u8 i); extern void player_sprite (u8 i); extern void player_color (void); /* Data from "graphics.c" to initialise graphics */ extern const u8 NAMERLE[]; extern const u8 PATTERNRLE[]; extern const u8 COLORRLE[]; extern const u8* levels[]; #endif <file_sep>/****************************************************************************/ /** **/ /** cch.c **/ /** **/ /** ColecoVision Cosmo Challenge game main module **/ /** **/ /** Copyright (C) <NAME> 1997 **/ /** You are not allowed to distribute this software commercially **/ /** Please, notify me, if you make any changes to this file **/ /****************************************************************************/ #include "cosmoc.h" /* when his health bar reaches 0, one dies */ static u8 player1_health,player2_health; /* incremented every interrupt */ static u8 nmi_count; /* if 1, the title and intro screens have been displayed */ static u8 game_running; /* 0=one player, 1=two players */ static u8 game_mode; /* scrolling stones buffer */ static u8 stone_vram[96*2]; /* next stone type to put in buffer */ static u8 stonea,stoneb; /* scroll stone stuff one character */ static void scroll_stones (void) { register u8 a; /* scroll old buffer */ sys_memcpyb (stone_vram,stone_vram+1,95); sys_memcpyb (stone_vram+97,stone_vram+96,95); /* check new stones */ if (!stonea) { a=sys_random(); if (a<16) stonea=((a&3)<<2)+128+16+32; } if (!stoneb) { a=sys_random(); if (a<16) stoneb=((a&3)<<2)+3+32; } /* put new stones in buffer */ if (stonea) { stone_vram[31]=stonea-32; stone_vram[31+32]=stonea; stone_vram[31+64]=stonea+32; stonea++; if ((stonea&3)==0) stonea=0; } else stone_vram[31]=stone_vram[31+32]=stone_vram[31+64]=96; if (stoneb) { stone_vram[96]=stoneb-32; stone_vram[128]=stoneb; stone_vram[160]=stoneb+32; stoneb--; if ((stoneb&3)==3) stoneb=0; } else stone_vram[96]=stone_vram[128]=stone_vram[160]=96; } /* The NMI routine. Gets called 50 or 60 times per second */ void nmi (void) { static u8 stone_count; register u8 i; nmi_count++; /* if intro screen is being displayed, return immediately */ if (!game_running) return; /* Update sprites */ vdp_putvram(sprgen+8*4,sprites,(32-8)*4); /* update_sprites (32-8,sprgen+8*4); */ /* update stone display */ switch (stone_count) { case 6: /* scroll 2 pixels */ vdp_putvramex (chrtab+256,stone_vram,96,0xff,128); vdp_putvramex (chrtab+384,stone_vram+96,96,0xff,128); break; case 4: /* scroll 4 pixels */ vdp_putvramex (chrtab+256,stone_vram,96,0xff,16); vdp_putvramex (chrtab+384,stone_vram+96,96,0xff,16); break; case 2: /* scroll 6 pixels */ vdp_putvramex (chrtab+256,stone_vram,96,0xff,128|16); vdp_putvramex (chrtab+384,stone_vram+96,96,0xff,128|16); break; case 1: /* update buffer, will be uploaded next call */ scroll_stones (); break; case 0: /* upload stone stuff to vram */ vdp_putvram (chrtab+256,stone_vram,96); vdp_putvram (chrtab+384,stone_vram+96,96); stone_count=8; break; } stone_count--; /* update stars */ if ((nmi_count&1)==0) { i=((nmi_count>>1)&7)+16; sprites[i].y=sys_random(); sprites[i].x=sys_random(); sprites[i].pattern=28+(sys_random()&4); sprites[i].colour=sys_random()&15; } } const sprite_t sprites_init[]= { /* ship A */ { 166,60,4,15 }, { 166,60,8,4 }, { 166,60,12,8 }, /* ship B */ { 8,180,16,15 }, { 8,180,20,4 }, { 8,180,24,8 }, /* 5 bullets each */ { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, { 207,0,0,11 }, /* 8 stars */ { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 }, { 207,0,28,14 } }; /* to prevent sprites being displayed on the status bar */ const sprite_t default_sprgen[]= { { -9,0,0,0 }, { -9,0,0,0 }, { -9,0,0,0 }, { -9,0,0,0 }, { 183,0,0,0 }, { 183,0,0,0 }, { 183,0,0,0 }, { 183,0,0,0 } // Overflow Warning Making no sense! }; void show_player1_health_bar (u8 n) { register u8 i; if (n && player1_health) { vdp_fillvram (chrtab+736,1,player1_health); i=32-player1_health; if (i) vdp_fillvram (chrtab+736+player1_health,2,i); } else vdp_fillvram (chrtab+736,2,32); } void show_player2_health_bar (u8 n) { register u8 i; if (n && player2_health) { vdp_fillvram (chrtab,1,player2_health); i=32-player2_health; if (i) vdp_fillvram (chrtab+player2_health,2,i); } else vdp_fillvram (chrtab,2,32); } void player1_is_hit (int spritenr) { sprites[spritenr].y=207; if (player1_health) { player1_health--; if (player1_health==4) { /* play sound low health */ snd_startplay(1); } snd_startplay(3); /* play shound hit */ show_player1_health_bar(1); } } void player2_is_hit (int spritenr) { sprites[spritenr].y=207; if (player2_health) { player2_health--; if (player2_health==4) { /* play sound low health */ snd_startplay(1); } snd_startplay(3); /* play shound hit */ show_player2_health_bar(1); } } void stone_is_hit (int spritenr) { sprites[spritenr].y=207; snd_startplay(4); } u8 check_stone (u8 spritenr) { register unsigned n; n=(sprites[spritenr].y)>>3; n-=8; if (n&0xf8) return 0; if (n==3 || n==7) return 0; if (n&4) --n; n<<=5; n+=(sprites[spritenr].x>>3); return stone_vram[n]!=96; } void _fill_vram (unsigned offset,u8 value,unsigned count) { vdp_disablenmi(); vdp_fillvram (offset,value,count); vdp_enablenmi(); } static void vdp_showpicture(void *picture) { vdp_disablescr(); vdp_disablenmi(); vdp_rle2vram(vdp_rle2vram(picture,coltab),chrgen); vdp_enablescr(); vdp_enablenmi(); } static void title (void) { /* initialise name table */ vdp_setmode2bmp(); /* show title screen */ vdp_showpicture(title_screen); sys_pause(); /* show intro screen */ vdp_showpicture(intro_screen); sys_pause(); } static const u8 red_font[8]= { 0x61,0x61,0x81,0x81,0x81,0x91,0x91,0x91 }; static const u8 yellow_font[8]= { 0xa1,0xa1,0xb1,0xb1,0xb1,0xf1,0xf1,0xf1 }; void init_vdp (void) { u8 i; vdp_setmode2bmp(); /* Disable Interrupt */ vdp_disablenmi(); /* special color for the middle section */ vdp_setreg(3,0xbf); /* Upload first 8 sprites */ vdp_putvram (sprgen,default_sprgen,sizeof(default_sprgen)); /* Fill colour table */ vdp_putvram_repeat (coltab,yellow_font,8,0); // 0 = 256 vdp_putvram_repeat (coltab+'0'*8,red_font,8,10); /* Clear Characters Pattern Table */ vdp_fillvram (chrgen,0x00,0x0800); /* Upload ASCII character patterns */ vdp_setdefaultchar(FNTBOLD_ITALIC); // (29,128-29,chrgen+29*8,BOLD_ITALIC); /* Health indicator */ vdp_fillvram (chrgen+9,0x55,6); vdp_fillvram (coltab+8,0x90,16); /* Duplicate Charset to the other 2 screen section */ vdp_duplicatevram(); /* Upload stones character definitions */ vdp_rle2vram (vdp_rle2vram(stone_characters,coltab+256*8),chrgen+256*8); /* Upload sprite patterns */ vdp_rle2vram (sprite_patterns,sprtab); /* clear screen display */ vdp_fillvram (chrtab,32,768); /* Fill part 2 of name table */ vdp_fillvram (chrtab+256,96,256); /* Scroll in stones */ for (i=32;i!=0;--i) scroll_stones (); /* Blue screen border */ vdp_setreg(7,0xf4); /* turn display on */ vdp_enablescr(); /* enable NMI */ vdp_enablenmi(); } void choice (void) { _fill_vram (chrtab+0,1,32); _fill_vram (chrtab+736,1,32); _fill_vram (chrtab+18*32,0,64); vdp_putstring(8,18,"1 - One player "); vdp_putstring(8,19,"2 - Two players"); /* wait until all keys released */ while (keypad_1!=0xff || keypad_2!=0xff); /* get choice */ game_mode=255; while (game_mode==255) { if (keypad_1==1 || keypad_2==1) game_mode=0; if (keypad_1==2 || keypad_2==2) game_mode=1; } _fill_vram (chrtab+18*32,0,64); } void main (void) { u8 i; u8 old_joypad_1,old_joypad_2; snd_settable(snd_table); title (); init_vdp (); /* set game_running flag, enables scrolling stones and blinking stars */ game_running=1; /* clear NMI counter */ nmi_count=255; options: choice (); play_again: player1_health=player2_health=32; show_player1_health_bar(1); show_player2_health_bar(1); sys_memcpyb (sprites,sprites_init,sizeof(sprites_init)); old_joypad_1 = 8; old_joypad_2 = (sys_randbyte(0,1) == 0) ? 2 : 8; vdp_putstring(11,18,"Get ready"); snd_startplay(9); snd_startplay(10); snd_startplay(11); vdp_waitvblank(150); _fill_vram (chrtab+18*32,0,64); old_joypad_1=0; old_joypad_2=0; while (1) { /* Wait for a VBLANK */ vdp_waitvblank(1); if ((nmi_count&31)==0) { if (player1_health<5 || player2_health<5) { if (player1_health<5) show_player1_health_bar(nmi_count&32); if (player2_health<5) show_player2_health_bar(nmi_count&32); } } /* Let computer play */ if (!game_mode) { /* direction, slightly random */ joypad_2=old_joypad_2&0x0f; i=sys_random(); if (i<24) { if (sprites[0].x<sprites[3].x) { joypad_2 = 8; } else { joypad_2 = 2; } } /* fire ? */ if ((nmi_count&7)==0) joypad_2|=0x10; } /* Parse joysticks */ if (joypad_1&2) { if (sprites[0].x<241) sprites[1].x=sprites[2].x=(++sprites[0].x); } if (joypad_1&8) { if (sprites[0].x) sprites[1].x=sprites[2].x=(--sprites[0].x); } if (joypad_2&2) { if (sprites[3].x<241) sprites[4].x=sprites[5].x=(++sprites[3].x); } if (joypad_2&8) { if (sprites[3].x) sprites[4].x=sprites[5].x=(--sprites[3].x); } if ((joypad_1^old_joypad_1)&joypad_1&0xf0) { for (i=6;i<11;++i) if (sprites[i].y==207) break; if (i<11) { sprites[i].y=sprites[0].y; sprites[i].x=sprites[0].x+7; snd_startplay(2); } } if ((joypad_2^old_joypad_2)&joypad_2&0xf0) { for (i=11;i<16;++i) if (sprites[i].y==207) break; if (i<16) { sprites[i].y=sprites[3].y+14; sprites[i].x=sprites[3].x+7; snd_startplay(2); } } old_joypad_1=joypad_1; old_joypad_2=joypad_2; if (player1_health && player2_health) { for (i=6;i<11;++i) { if (sprites[i].y!=207) { if (check_stone(i)) { stone_is_hit (i); } if (check_collision(sprites+i,sprites+3,0x303,0x303,0x1000,0x0e00)) { player2_is_hit (i); } sprites[i].y-=4; if (sprites[i].y>192) sprites[i].y=207; // the warning makes no sense } } for (i=11;i<16;++i) { if (sprites[i].y!=207) { if (check_stone(i)) stone_is_hit (i); if (check_collision(sprites+i,sprites+0,0x303,0x303,0x1000,0x0e02)) player1_is_hit (i); sprites[i].y+=4; if (sprites[i].y>192) sprites[i].y=207; // the warning makes no sense } } } else break; } i = 0; if (player1_health) { i = 3; } snd_startplay(5); snd_startplay(6); snd_startplay(7); snd_startplay(8); sprites[i].y=sprites[i+1].y=sprites[i+2].y=207; spr_clear(); // PROBLEM!!! it's supposed to be clear_sprites (start=6,count=10); vdp_putstring(9,18,"1 - Play again"); vdp_putstring(9,19,"2 - Options "); vdp_putstring(9,20,"3 - Intro "); while ((keypad_1==0 || keypad_1>3) && (keypad_2==0 || keypad_2>3)); if (keypad_1==0 || keypad_1>3) i=keypad_2; else i=keypad_1; _fill_vram (chrtab+18*32,0,3*32); if (i==1) goto play_again; if (i==2) goto options; /* startup module will issue a soft reboot */ } <file_sep>#ifndef _INPUT_MAIN_ #define _INPUT_MAIN_ #include <coleco.h> #endif <file_sep>/*------------------------------------------------------------------------- ds80c390.h - Register Declarations for the DALLAS DS80C390 Processor far from complete, e.g. no CAN Copyright (C) 2000, <NAME> <johan.knol AT iduna.nl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if you link this library with other files, some of which are compiled with SDCC, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. -------------------------------------------------------------------------*/ #ifndef DS80C390_H #define DS80C390_H __sfr __at 0x80 P4; /* ce3..ce0, a19..a16 */ __sfr __at 0x81 SP; /* stack pointer */ __sfr __at 0x82 DPL; /* data pointer 0 lsb */ __sfr __at 0x83 DPH; /* data pointer 0 msb */ __sfr __at 0x84 DPL1; /* data pointer 1 lsb */ __sfr __at 0x85 DPH1; /* data pointer 1 msb */ __sfr __at 0x86 DPS; /* data pointer select */ __sfr __at 0x87 PCON; /* power control */ __sfr __at 0x88 TCON; /* timer/counter control */ __sbit __at 0x88 IT0; __sbit __at 0x89 IE0; __sbit __at 0x8a IT1; __sbit __at 0x8b IE1; __sbit __at 0x8c TR0; __sbit __at 0x8d TF0; __sbit __at 0x8e TR1; __sbit __at 0x8f TF1; __sfr __at 0x89 TMOD; /* timer mode control */ __sfr __at 0x8a TL0; /* timer 0 lsb */ __sfr __at 0x8b TL1; /* timer 1 msb */ __sfr __at 0x8c TH0; /* timer 0 msb */ __sfr __at 0x8d TH1; /* timer 1 msb */ __sfr __at 0x8e CKCON; /* clock control */ __sfr __at 0x90 P1; __sbit __at 0x90 T2; __sbit __at 0x91 T2EX; __sbit __at 0x92 RXD1; __sbit __at 0x93 TXD1; __sbit __at 0x94 INT2; __sbit __at 0x95 INT3; __sbit __at 0x96 INT4; __sbit __at 0x97 INT5; __sfr __at 0x91 EXIF; /* external interrupt flag */ __sfr __at 0x92 P4CNT; __sfr __at 0x93 DPX; /* extended datapointer 0 */ __sfr __at 0x95 DPX1; /* extended datapointer 1 */ __sfr __at 0x98 SCON0; /* serial 0 control */ __sbit __at 0x98 RI_0; __sbit __at 0x99 TI_0; __sbit __at 0x9a RB8_0; __sbit __at 0x9b TB8_0; __sbit __at 0x9c REN_0; __sbit __at 0x9d SM2_0; __sbit __at 0x9e SM1_0; __sbit __at 0x9f SM0_0; __sbit __at 0x9f FE_0; /* depending on SMOD0 */ __sfr __at 0x99 SBUF0; /* serial 0 data buffer */ __sfr __at 0x9b ESP; /* extended stack pointer */ __sfr __at 0x9c AP; /* address page */ __sfr __at 0x9d ACON; /* address control */ __sfr __at 0xa0 P2; /* never mind the sbits */ __sfr __at 0xa1 P5; __sfr __at 0xa2 P5CNT; __sfr __at 0xa8 IE; /* interrupt enable */ __sbit __at 0xa8 EX0; __sbit __at 0xa9 ET0; __sbit __at 0xaa EX1; __sbit __at 0xab ET1; __sbit __at 0xac ES0; __sbit __at 0xad ET2; __sbit __at 0xae ES1; __sbit __at 0xaf EA; __sfr __at 0xb0 P3; __sbit __at 0xb0 RXD0; __sbit __at 0xb1 TXD0; __sbit __at 0xb2 INT0; __sbit __at 0xb3 INT1; __sbit __at 0xb4 T0; __sbit __at 0xb5 T1; __sbit __at 0xb6 WR; __sbit __at 0xb7 RD; __sfr __at 0xb8 IP; /* interupt priority */ __sbit __at 0xb8 PX0; /* external 0 */ __sbit __at 0xb9 PT0; /* timer 0 */ __sbit __at 0xba PX1; /* external 1 */ __sbit __at 0xbb PT1; /* timer 1 */ __sbit __at 0xbc PS0; /* serial port 0 */ __sbit __at 0xbd PT2; /* timer 2 */ __sbit __at 0xbe PS1; /* serial port 1 */ __sfr __at 0xc0 SCON1; /* serial 1 control */ __sbit __at 0xc0 RI_1; __sbit __at 0xc1 TI_1; __sbit __at 0xc2 RB8_1; __sbit __at 0xc3 TB8_1; __sbit __at 0xc4 REN_1; __sbit __at 0xc5 SM2_1; __sbit __at 0xc6 SM1_1; __sbit __at 0xc7 SM0_1; __sbit __at 0xc7 FE_1; /* depending on SMOD0 */ __sfr __at 0xc1 SBUF1; /* serial 1 data buffer */ __sfr __at 0xc4 PMR; /* power managment */ __sfr __at 0xc6 MCON; /* memory control register */ __sfr __at 0xc7 TA; /* timed access register */ __sfr __at 0xc8 T2CON; /* timer 2 control */ __sbit __at 0xc8 CP_RL; /* capture/reload */ __sbit __at 0xc9 C_T; /* count/timer */ __sbit __at 0xca TR2; /* stop/run */ __sbit __at 0xcb EXEN2; __sbit __at 0xcc TCLK; __sbit __at 0xcd RCLK; __sbit __at 0xce EXF2; __sbit __at 0xcf TF2; /* overflow flag */ __sfr __at 0xc9 T2MOD; /* timer 2 mode */ __sfr __at 0xca RCAP2L; /* timer 2 capture/reload */ __sfr __at 0xca RTL2; /* depends on CP_RL */ __sfr __at 0xcb RCAP2H; __sfr __at 0xcb RTH2; __sfr __at 0xcc TL2; /* timer 2 lsb */ __sfr __at 0xcd TH2; /* timer 2 msb */ __sfr __at 0xd0 PSW; /* program status word (byte actually) */ __sbit __at 0xd0 P; /* parity */ __sbit __at 0xd1 F1; /* user flag 1 */ __sbit __at 0xd2 OV; /* overflow flag */ __sbit __at 0xd3 RS0; /* register select l */ __sbit __at 0xd4 RS1; /* register select h */ __sbit __at 0xd5 F0; /* user flag 0 */ __sbit __at 0xd6 AC; /* auxiliary carry flag */ __sbit __at 0xd7 CY; /* carry flag */ __sfr __at 0xd1 MCNT0; /* arithmetic accellerator */ __sfr __at 0xd2 MCNT1; __sfr __at 0xd3 MA; __sfr __at 0xd4 MB; __sfr __at 0xd5 MC; __sfr __at 0xd8 WDCON; /* watch dog */ __sbit __at 0xd8 RWT; __sbit __at 0xd9 EWT; __sbit __at 0xda WDRF; __sbit __at 0xdb WDIF; __sbit __at 0xdc PFI; __sbit __at 0xdd EPFI; __sbit __at 0xde POR; __sbit __at 0xdf SMOD_1; __sfr __at 0xe0 ACC; /* accumulator */ __sfr __at 0xe8 EIE; /* extended interrupt enable */ __sbit __at 0xe8 EX2; __sbit __at 0xe9 EX3; __sbit __at 0xea EX4; __sbit __at 0xeb EX5; __sbit __at 0xec EWDI; __sbit __at 0xed C1IE; __sbit __at 0xee C0IE; __sbit __at 0xef CANBIE; __sfr __at 0xea MXAX; /* extended address register */ __sfr __at 0xf0 B; /* aux accumulator */ __sfr __at 0xf8 EIP; /* extended interrupt priority */ __sbit __at 0xf8 PX2; __sbit __at 0xf9 PX3; __sbit __at 0xfa PX4; __sbit __at 0xfb PX5; __sbit __at 0xfc PWDI; __sbit __at 0xfd C1IP; __sbit __at 0xfe C0IP; __sbit __at 0xff CANBIP; /* WORD/DWORD Registers */ __sfr16 __at (0x8C8A) TMR0; /* TIMER 0 COUNTER */ __sfr16 __at (0x8D8B) TMR1; /* TIMER 1 COUNTER */ __sfr16 __at (0xCDCC) TMR2; /* TIMER 2 COUNTER */ __sfr16 __at (0xCBCA) RCAP2; /* TIMER 2 CAPTURE REGISTER WORD */ #endif /* DS80C390_H */ <file_sep>Here, You will find detailed instruction for installing PVcollib To use PVcollib, you will need: * Last version from [Download section](https://github.com/alekmaul/pvcollib/wiki/Download) * An editor like Programmer's Notepad or Eclipse (if your PC is strong enough ;-)) Additional sections below will cover others OS installation like Linux and Mac OS X. Good luck! ## Installing PVcollib ### Step 1: Installing the toolchain The first thing you need to do to get you started is downloading the latest versions of PVcollib and the tools that come with it. This is the core to all/most homebrew programs on the Colecovision, as it provides the C compiler and linker and various tools. Put it wherever you like – it doesn’t affect the compilation (you will only need to define it in your PATH), as long as you don’t extract it in a directory that contains spaces (eg, ‘**C:/colecodev/**’ would be fine). #### Msys You can use msys to have a Unix like environment, but it is not mandatory. Download **msys** to use Unix like environment and extract it in your coleco directory. (eg, **C:\colecodev\** would be fine). You will have a subdirectory name **msys** with all msys distribution in it. [msys 1.0.17](http://www.portabledev.com/download/11/) Msys needs to be added to Windows Path because lots of msys binary files are needed when we are going to compile. To add the **msys\bin** directory to your PATH environment variable (eg, you will add **c:\colecodev\msys\bin** in our example). I'm French with a Windows 7 computer, so the name will not reflect your exact configuration. The goal is to have the Windows Path text box to add the msys/bin directory. Do a Right Click on "Ordinateur" icon, choose "Paramètres système avancés" and then, click on "Variables d'environnement" button. ![Path](http://www.portabledev.com/wp-content/uploads/2018/02/pn_tools_04.jpg) Choose the Path entry to add **c:\colecodev\msys\bin** at the end of the line. ![Path2](https://www.portabledev.com/wp-content/uploads/2019/11/pn_tools06.png) #### Emulators Download emulators to test your homebrews and put them in the emulators directory (see unzipped devkitcol, you will have the directory **C:/colecodev/emulators**). [bluemsx](http://www.bluemsx.com/) [bluemsx Fullpack from Emu-France](http://www.emu-france.com/?wpfb_dl=2557) [EmulTwo](https://github.com/alekmaul/pvcollib/tree/master/emulators/emultwo) [ColEM](http://fms.komkon.org/ColEm/) At the end, you must have something like that : ``` c:\colecodev .........\coleco-examples .........\devkitcol .................\bin .................\include .................\lib .................\tools .................col_rules .........\emulators .........\include .........\lib .........\bin ``` ### Step 2: Installing for windows If you're using a Windows environment, you will need to compile again the library. Go to your SDK folder and type <pre> C:\colecodev>build_pvcollib.bat </pre> When the library is compiled you should obtain the following files <pre> C:\colecodev>dir lib Répertoire de C:\colecodev\lib collib.lib crtcol.rel </pre> ##### Let's start compiling with Programmer's Notepad We will use the hello world example to test how our PVcollib library is installed. The helloworld directory is shipped with PVcollib examples. <file_sep>#include <coleco.h> static const u8 snd_dummy[] = { 0xFF }; static const u8 snd_lowhealth[] = { 0x02, 0x02, 0x03, 0x00, 0x00, 0x02, 0x01, 0x05, 0x00, 0x00, 0x27, 0x18, }; static const u8 snd_shoot[] = { 0x43, 0x97, 0x20, 0x08, 0x11, 0x2d, 0x18, 0x11, 0x50 }; static const u8 snd_block[] = { 0x83, 0xaa, 0x42, 0x04, 0x11, 0x80, 0x33, 0x12, 0x90 }; static const u8 snd_hit[] = { 0x02, 0x65, 0x03, 0x00, 0x00, 0x10 }; static const u8 snd_victory1[] = { 0x40, 0x00, 0xf0, 0x32, 0x41, 0x97, 0x50, 0x0a, 0x11, 0xfb, 0x41, 0x97, 0x50, 0x08, 0x11, 0xfb, 0x41, 0x97, 0x50, 0x06, 0x11, 0xfb, 0x41, 0x97, 0x50, 0x04, 0x11, 0xfb, 0x41, 0x97, 0x50, 0x02, 0x11, 0xfb, 0x41, 0x97, 0x50, 0x23, 0x21, 0xfc, 0x42, 0xbe, 0x30, 0x1f, 0x7f, 0x21, 0x42, 0xbe, 0x40, 0x1f, 0x6f, 0x21, 0x42, 0xbe, 0x50, 0x10, 0x5f, 0x11, 0x50 }; static const u8 snd_victory2[] = { 0x80, 0x00, 0xf0, 0x32, 0x81, 0xb4, 0x30, 0x0a, 0x11, 0xfb, 0x81, 0xb4, 0x30, 0x08, 0x11, 0xfb, 0x81, 0xb4, 0x30, 0x06, 0x11, 0xfb, 0x81, 0xb4, 0x30, 0x04, 0x11, 0xfb, 0x81, 0xb4, 0x30, 0x02, 0x11, 0xfb, 0x81, 0xb4, 0x30, 0x2d, 0x21, 0xfc, 0x90 }; static const u8 snd_victory3[] = { 0xc0, 0xcb, 0xf0, 0x32, 0xc1, 0xd6, 0x50, 0x0a, 0x11, 0xfb, 0xc1, 0xd6, 0x50, 0x08, 0x11, 0xfb, 0xc1, 0xd6, 0x50, 0x06, 0x11, 0xfb, 0xc1, 0xd6, 0x50, 0x04, 0x11, 0xfb, 0xc1, 0xd6, 0x50, 0x02, 0x11, 0xfb, 0xc1, 0xd6, 0x50, 0x2d, 0x21, 0xfc, 0xfe, 0xfe, 0xe8, 0xc0, 0xcb, 0xf0, 0xa5, 0xd0 }; static const u8 snd_victory4[] = { 0x02, 0x07, 0x32, 0x17, 0x5f, 0x02, 0xf5, 0xbd, 0x00, 0x00, 0x02, 0x07, 0xa5, 0x1f, 0xaf, 0x10 }; static const u8 snd_start1[] = { 0x42, 0x57, 0x33, 0x08, 0x19, 0x14, 0x68, 0x42, 0x81, 0x32, 0x08, 0x49, 0x15, 0x42, 0x3b, 0x32, 0x08, 0x49, 0x15, 0x42, 0xe0, 0x31, 0x30, 0x0e, 0xff, 0x42, 0xe0, 0x71, 0x10, 0x18, 0x14, 0x50 }; static const u8 snd_start2[] = { 0x82, 0xd6, 0x30, 0x08, 0x19, 0x14, 0xa8, 0x82, 0xa0, 0x30, 0x08, 0x49, 0x15, 0x82, 0x8f, 0x30, 0x08, 0x49, 0x15, 0x82, 0x78, 0x30, 0x30, 0x0d, 0xff, 0x82, 0x78, 0x70, 0x10, 0x18, 0x14, 0x90 }; static const u8 snd_start3[] = { 0xc2, 0x8f, 0x30, 0x08, 0x19, 0x14, 0xe8, 0xc2, 0x6b, 0x30, 0x08, 0x49, 0x15, 0xc2, 0x5f, 0x30, 0x08, 0x49, 0x15, 0xc2, 0x50, 0x30, 0x30, 0x0d, 0xff, 0xc2, 0x50, 0x70, 0x10, 0x18, 0x14, 0xd0 }; const sound_t snd_table[] = { {snd_lowhealth,SOUNDAREA1}, {snd_shoot,SOUNDAREA2}, {snd_hit,SOUNDAREA3}, {snd_block,SOUNDAREA4}, {snd_victory1,SOUNDAREA1}, {snd_victory2,SOUNDAREA2}, {snd_victory3,SOUNDAREA3}, {snd_victory4,SOUNDAREA4}, {snd_start1,SOUNDAREA1}, {snd_start2,SOUNDAREA2}, {snd_start3,SOUNDAREA3} }; <file_sep>#ifndef _MEGACART_GFXS3_ #define _MEGACART_GFXS3_ #include <coleco.h> #include "image3gfx.h" // generetad by gfx2col #endif <file_sep>/*--------------------------------------------------------------------------------- Pad demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "input.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Wait for nothing :P while(1) { // Update display with current pad 1 values if (joypad_1 & PAD_RIGHT) vdp_putstring(9,10,"RIGHT PRESSED"); if (joypad_1 & PAD_LEFT) vdp_putstring(9,10,"LEFT PRESSED "); if (joypad_1 & PAD_DOWN) vdp_putstring(9,10,"DOWN PRESSED "); if (joypad_1 & PAD_UP) vdp_putstring(9,10,"UP PRESSED "); if (joypad_1 & PAD_FIRE1) vdp_putstring(9,10,"FIRE1 PRESSED"); if (joypad_1 & PAD_FIRE2) vdp_putstring(9,10,"FIRE2 PRESSED"); if (joypad_1 & PAD_FIRE3) vdp_putstring(9,10,"FIRE3 PRESSED"); if (joypad_1 & PAD_FIRE4) vdp_putstring(9,10,"FIRE4 PRESSED"); // Update display with current keyboard pad 1 values if (keypad_1 == PAD_KEY0) vdp_putstring(9,12,"KEY 0 PRESSED"); if (keypad_1 == PAD_KEY1) vdp_putstring(9,12,"KEY 1 PRESSED"); if (keypad_1 == PAD_KEY2) vdp_putstring(9,12,"KEY 2 PRESSED"); if (keypad_1 == PAD_KEY3) vdp_putstring(9,12,"KEY 3 PRESSED"); if (keypad_1 == PAD_KEY4) vdp_putstring(9,12,"KEY 4 PRESSED"); if (keypad_1 == PAD_KEY5) vdp_putstring(9,12,"KEY 5 PRESSED"); if (keypad_1 == PAD_KEY6) vdp_putstring(9,12,"KEY 6 PRESSED"); if (keypad_1 == PAD_KEY7) vdp_putstring(9,12,"KEY 7 PRESSED"); if (keypad_1 == PAD_KEY8) vdp_putstring(9,12,"KEY 8 PRESSED"); if (keypad_1 == PAD_KEY9) vdp_putstring(9,12,"KEY 9 PRESSED"); if (keypad_1 == PAD_KEYSTAR) vdp_putstring(9,12,"STAR PRESSED "); if (keypad_1 == PAD_KEYSHARP) vdp_putstring(9,12,"SHARP PRESSED"); // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>#include "compdan2.h" #include "compdan1.h" //--------------------------------------------------------------------------- #define DAN2BIT_OFFSET4_MIN 10 #define DAN2BIT_OFFSET4_MAX 16 int DAN2MAX_OFFSET4; int DAN2BIT_OFFSET4; // CALCULATE BITS COST - int dan2count_bits(int offset, int len) { int bits = 1 + elias_gamma_bits(len); if (len == 1) return bits + 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1); if (len == 2) return bits + 1 + (offset > MAX_OFFSET2 ? BIT_OFFSET3 : 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1)); return bits + 1 + (offset > MAX_OFFSET3 ? DAN2BIT_OFFSET4 : 1 + (offset > MAX_OFFSET2 ? BIT_OFFSET3 : 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1))); } void update_maxoffset4(int bits) { // Update OFFSET4 BIT and MAX values DAN2BIT_OFFSET4 = bits; DAN2MAX_OFFSET4 = MAX_OFFSET3 + (1<<DAN2BIT_OFFSET4); } // - LZSS COMPRESSION - void dan2lzss(byte *data_src) { int i, j, k; int temp_bits; struct t_match *match; int len, best_len; int offset; int match_index; optimals[0].bits = 8; // FIRST ALWAYS LITERAL optimals[0].offset = 0; optimals[0].len = 1; for (i = 1;i < index_src;i++) { // TRY LITERALS optimals[i].bits = optimals[i-1].bits + 1 + 8; optimals[i].offset = 0; optimals[i].len = 1; // LZ MATCH OF ONE : LEN = 1 j = MAX_OFFSET2; if (j > i) j = i; /* temp_bits = optimals[i-1].bits + 1+1+1+2; */ for (k = 1; k <= j; k++) { /* if (k==5) temp_bits += 3; */ if (data_src[i] == data_src[i-k]) { temp_bits = optimals[i-1].bits + dan2count_bits(k, 1); if (temp_bits < optimals[i].bits) { optimals[i].bits = temp_bits; optimals[i].len = 1; optimals[i].offset = k; break; } } } // LZ MATCH OF TWO OR MORE : LEN = 2, 3 , 4 ... match_index = ((int) data_src[i-1]) << 8 | ((int) data_src[i] & 0x000000ff); match = &matches[match_index]; best_len = 1; for (/* match = &matches[match_index] */; match->next != NULL && best_len < MAX_LEN; match = match->next) { offset = i - match->index; if (offset > DAN2MAX_OFFSET4) { flush_match(match); break; } for (len = 2;len <= MAX_LEN;len++) { if (len > best_len) { if (!(len == 2 && offset > MAX_OFFSET3)) { best_len = len; temp_bits = optimals[i-len].bits + dan2count_bits(offset, len); if (optimals[i].bits > temp_bits) { optimals[i].bits = temp_bits; optimals[i].offset = offset; optimals[i].len = len; } } } if (i < offset + len || data_src[i-len] != data_src[i-len-offset]) { break; } } } insert_match(&matches[match_index], i); } len = (optimals[index_src-1].bits + 17 + 7) / 8; cleanup_optimals(); } int dan2Compress(byte *src,byte *dst,int n) { size_t count; int maxbits = DAN2BIT_OFFSET4_MIN+1; // Initialize Matches Array index_src=n; reset_matches(); // SET MAX BITS FOR BIG OFFSET VALUES - update_maxoffset4(maxbits); // Apply compression dan2lzss(src); free_matches(); // flush destination index_dest=0; rle_ntimes = 0; bRLEDATA = 0; bit_mask = 0; write_lz(src, dst); // compute ratio //index_dest = optimals[n-1].bits += 1 + 16 + 1 + 7; //index_dest /= 8; count=index_dest; return count; } <file_sep>VERSION = "1.4.0" #--------------------------------------------------------------------------------- # options for code generation #--------------------------------------------------------------------------------- CC=gcc CFLAGS=-g -O2 -Wall -D__BUILD_DATE="\"`date +'%Y%m%d'`\"" -D__BUILD_VERSION="\"$(VERSION)\"" SOURCES=gfx2col.c lodepng.c lodepic.c comptool.c comprle.c compdan1.c compdan2.c compdan3.c OBJS=gfx2col.o lodepng.o lodepic.o comptool.o comprle.o compdan1.o compdan2.o compdan3.o EXE=gfx2col DEFINES = LIBS = ifeq ($(OS),Windows_NT) EXT=.exe else EXT= endif #--------------------------------------------------------------------------------- all: $(EXE)$(EXT) #--------------------------------------------------------------------------------- $(EXE)$(EXT) : $(OBJS) @echo make exe $(notdir $<) $(CC) $(CFLAGS) $(OBJS) -o $@ gfx2col.o : gfx2col.c @echo make obj $(notdir $<) $(CC) $(CFLAGS) -c $< lodepng.o : lodepng.c @echo make obj $(notdir $<) $(CC) $(CFLAGS) -c $< lodepic.o : lodepic.c @echo make obj $(notdir $<) $(CC) $(CFLAGS) -c $< comptool.o : comptool.c @echo make obj $(notdir $<) $(CC) $(CFLAGS) -c $< #--------------------------------------------------------------------------------- clean: rm -f $(OBJS) $(EXE)$(EXT) *.tds install: mkdir -p ../../devkitcol/tools && cp $(EXE)$(EXT) ../../devkitcol/tools/$(EXE)$(EXT) <file_sep>/*--------------------------------------------------------------------------------- simple pal/ntsc dectection demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "palntsc.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Wait for nothing :P while(1) { // Update display with current value if (vid_freq==60) vdp_putstring(10,10,"NTSC CONSOLE"); else if (vid_freq==50) vdp_putstring(10,10,"PAL CONSOLE"); else { vdp_putstring(10,10,"UNKNOW"); } // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>Devkitcol 1.11 Programming Compiler and Tools for Colecovision INTRODUCTION ---------------------- Devkitcol is a set of tools built to compile C sources files and graphics files to produce homebrews for Colecovision. Users are encouraged to download the source code of PVcollib and submit bug fixes and patches as well as new features for inclusion in the Devkitcol & PVcollib distribution. SPECIAL THANKS ---------------------- <NAME> for sdcc - SDCC Release Manager https://sourceforge.net/projects/sdcc/files/ <NAME> (aka newcoleco) for cvlib : <no website> matthew180 for F18A support (http://codehackcreate.com/archives/592) digress (http://eriscreations.com) for F18A support on Colecovision. CHANGE LOG ---------------------- VERSION 1.40 (October, 2020) - Add dan2 & dan3 compression to gfx2col (dan3 currently does not work) VERSION 1.30 (January, 2020) - Add lots of feature in gfx2col for f18a VERSION 1.20 (December, 2019) - Add graphic mode 1 in gfx2col VERSION 1.11 (November, 2019) - Fix bitmap mode issues in gfx2col - Remove O2 compiler option - Add cvmkart alias in col_rules VERSION 1.10 (November, 2019) - Added doxygen, gfx2col - Added cvmkcart VERSION 1.00 (November, 2018) - Initial release If you have questions, please email Alekmaul at <EMAIL>. EOF<file_sep>#ifndef _RANDOM_MAIN_ #define _RANDOM_MAIN_ #include <coleco.h> #endif <file_sep># do not forget that to build pvcollib, you have to install compiler and tools first ! #--------------------------------------------------------------------------------- all: cd tools && \ make && \ make install && \ cd ../pvcollib && \ make && \ cd ../coleco-examples && \ make && \ make install && \ echo && \ echo Build finished successfully ! && \ echo clean: cd tools ; \ make clean ; \ cd ../pvcollib ; \ make clean ; \ cd ../devkitcol ; \ rm -f ./tools/* ; \ cd ../coleco-examples ; \ make clean ; \ rm -rf release # requirements to launch the "release" rule doxygenInstalled := $(shell command -v doxygen 2> /dev/null) operatingSystem= ifeq ($(OS),Windows_NT) operatingSystem=windows else # only for linux platforms, we use the os-release file ifneq (,$(wildcard /etc/os-release)) include /etc/os-release # convert to lower case the result operatingSystem=linux_$(shell echo $(NAME) | tr A-Z a-z) else ifeq ($(shell uname -s),Darwin) operatingSystem=darwin else $(error "Unable to detect your operating system, please update the code in global pvcollib Makefile to continue") endif endif endif #--------------------------------------------------------------------------------- # to create the release version for github containing binaries and all coleco-examples : release: all ifndef doxygenInstalled $(error "doxygen is not installed but is mandatory to create the release version.") endif ifeq ($(operatingSystem),) $(error "Unable to detect your operating system to create the release version.") endif rm -rf release && mkdir -p release/pvcollib && \ cp -r devkitcol release/pvcollib/devkitcol && \ mkdir release/pvcollib/pvcollib && cp -r pvcollib/include release/pvcollib/pvcollib/include && \ cp -r pvcollib/lib release/pvcollib/pvcollib/lib && \ mkdir release/pvcollib/pvcollib/docs && cp -r pvcollib/docs/html release/pvcollib/pvcollib/docs/html && \ cp pvcollib/pvcollib_Logo.png release/pvcollib/pvcollib/pvcollib_Logo.png && \ cp pvcollib/pvcollib_license.txt release/pvcollib/pvcollib/pvcollib_license.txt && \ cp pvcollib/pvcollib_version.txt release/pvcollib/pvcollib/pvcollib_version.txt && \ cp -r coleco-examples release/pvcollib/coleco-examples && \ cd release && zip -r -m pvcollib_32b_$(operatingSystem).zip pvcollib && \ echo && echo Release created successfully ! && echo .PHONY: all <file_sep>#include "compdan1.h" //--------------------------------------------------------------------------- struct t_match matches[65536]; t_optimal optimals[MAXINFILE]; int index_src,index_dest; int bit_index; int rle_ntimes; int bRLEDATA; byte bit_mask; // REMOVE USELESS FOUND OPTIMALS - void cleanup_optimals(void) { int j; int i = index_src - 1; int len; while (i > 1) { len = optimals[i].len; for (j = i - 1; j > i - len;j--) { optimals[j].offset = 0; optimals[j].len = 0; } i = i - len; } } // REMOVE MATCHE(S) FROM MEMORY - void flush_match(struct t_match *match) { struct t_match *node; struct t_match *head = match->next; while ((node = head) != NULL) { head = head->next; free(node); } match->next = NULL; } // FREE MATCHE(S) FROM TABLE - void free_matches(void) { int i; for (i = 0;i < 65536;i++) { flush_match(&matches[i]); } } // INITIALIZE MATCHES TABLE - void reset_matches(void) { int i; for (i = 0;i < 65536;i++) { matches[i].next = NULL; } } // INSERT A MATCHE IN TABLE - void insert_match(struct t_match *match, int index) { struct t_match *new_match = (struct t_match *) malloc( sizeof(struct t_match) ); new_match->index = match->index; new_match->next = match->next; match->index = index; match->next = new_match; } // ELIAS GAMMA - int elias_gamma_bits(int value) { int bits = 1; while (value > 1) { bits += 2; value >>= 1; } return bits; } // CALCULATE BITS COST - int count_bits(int offset, int len) { int bits = 1 + elias_gamma_bits(len); if (len == 1) return bits + 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1); if (len == 2) return bits + 1 + (offset > MAX_OFFSET2 ? BIT_OFFSET3 : 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1)); return bits + 1 + (offset > MAX_OFFSET3 ? BIT_OFFSET4 : 1 + (offset > MAX_OFFSET2 ? BIT_OFFSET3 : 1 + (offset > MAX_OFFSET1 ? BIT_OFFSET2 : BIT_OFFSET1))); } // LZSS COMPRESSION - void dan1lzss(byte *data_src) { int i, j, k; int temp_bits; struct t_match *match; int len, best_len;//, old_best_len; int offset; int match_index; optimals[0].bits = 8; // FIRST ALWAYS LITERAL optimals[0].offset = 0; optimals[0].len = 1; for (i = 1;i < index_src;i++) { // TRY LITERALS optimals[i].bits = optimals[i-1].bits + 1 + 8; optimals[i].offset = 0; optimals[i].len = 1; // LZ MATCH OF ONE j = MAX_OFFSET2; if (j > i) j = i; for (k = 1; k <= j; k++) { if (data_src[i] == data_src[i-k]) { temp_bits = optimals[i-1].bits + count_bits(k, 1); if (temp_bits < optimals[i].bits) { optimals[i].bits = temp_bits; optimals[i].len = 1; optimals[i].offset = k; break; } } } // LZ MATCH OF TWO OR MORE match_index = (((int) data_src[i-1]) << 8) | ((int) data_src[i] & 0x000000ff); match = &matches[match_index]; best_len = 1; for (/* match = &matches[match_index] */; (match->next != NULL) && (best_len < MAX_LEN); match = match->next) { offset = i - match->index; if (offset > MAX_OFFSET) { flush_match(match); break; } for (len = 2;len <= MAX_LEN;len++) { if (len > best_len) { if (!((len == 2) && (offset > MAX_OFFSET3) )) { best_len = len; temp_bits = optimals[i-len].bits + count_bits(offset, len); if (optimals[i].bits > temp_bits) { optimals[i].bits = temp_bits; optimals[i].offset = offset; optimals[i].len = len; } } } if ((i < offset + len) || (data_src[i-len] != data_src[i-len-offset]) ) { break; } } // SKIP SOME TESTS if ( (len > 6) && (len == best_len - 1) && (match->index == match->next->index + 1) ) { j = 1; while (match->next != NULL) { match = match->next; if (i - match->index > MAX_OFFSET) { flush_match(match); break; } j++; if (j == len) { break; } } if (match->next == NULL) break; } } insert_match(&matches[match_index], i); } len = (optimals[index_src-1].bits + 18 + 7) / 8; cleanup_optimals(); } // WRITE DATA - void write_byte(byte value, byte *data_dest) { data_dest[index_dest++] = value; } void write_bit(int value, byte *data_dest) { if (bit_mask == 0) { bit_mask = (unsigned char) 128; bit_index = index_dest; write_byte((unsigned char) 0,data_dest); } if (value) data_dest[bit_index] |= bit_mask; bit_mask >>= 1 ; } void write_bits(int value, int size, byte *data_dest) { int i; int mask = 1; for (i = 0 ; i < size ; i++) { mask <<= 1; } while (mask > 1) { mask >>= 1; write_bit (value & mask,data_dest); } } void write_literals_length(int length, byte *data_dest) { write_bit(0,data_dest); write_bits(0, 16,data_dest); write_bit(1,data_dest); length -= 27; write_byte((unsigned char) length,data_dest); } void write_literal(byte c, byte *data_dest) { write_bit(1,data_dest); write_byte(c,data_dest); } void write_elias_gamma(int value, byte *data_dest) { int i; for (i = 2; i <= value; i <<= 1) { write_bit(0,data_dest); } while ((i >>= 1) > 0) { write_bit(value & i,data_dest); } } void write_offset(int value, int option, byte *data_dest) { value--; if (value >= MAX_OFFSET3) { write_bit(1,data_dest); value -= (MAX_OFFSET3); write_bits((value >> 8), BIT_OFFSET4 - 8,data_dest); write_byte((unsigned char) (value & 0x000000ff),data_dest); } else if (value >= MAX_OFFSET2) { if (option > 2) write_bit(0,data_dest); write_bit(1,data_dest); value -= (MAX_OFFSET2); write_byte((unsigned char) (value & 0x000000ff),data_dest); } else if (value >= MAX_OFFSET1) { if (option > 2) write_bit(0,data_dest); if (option > 1) write_bit(0,data_dest); write_bit(1,data_dest); value -= MAX_OFFSET1; write_bits(value, BIT_OFFSET2,data_dest); } else { if (option > 2) write_bit(0,data_dest); if (option > 1) write_bit(0,data_dest); write_bit(0,data_dest); write_bits(value, BIT_OFFSET1,data_dest); } } void write_doublet(int length, int offset, byte *data_dest) { write_bit(0,data_dest); write_elias_gamma(length,data_dest); write_offset(offset, length,data_dest); } void write_end(byte *data_dest) { write_bit(0,data_dest); write_bits(0, 16,data_dest); write_bit(0,data_dest); } void write_lz(byte *data_src, byte *data_dest) { int i, j; int index; // FIRST IS LITERAL write_byte(data_src[0],data_dest); for (i = 1;i < index_src;i++) { if (optimals[i].len > 0) { index = i - optimals[i].len + 1; if (optimals[i].offset == 0) { if (optimals[i].len == 1) { write_literal(data_src[index],data_dest); } else { write_literals_length(optimals[i].len,data_dest); for (j = 0;j < optimals[i].len;j++) { write_byte(data_src[index + j],data_dest); } rle_ntimes++; bRLEDATA = 1; } } else { write_doublet(optimals[i].len, optimals[i].offset,data_dest); } } } write_end(data_dest); } int dan1Compress(byte *src,byte *dst,int n) { size_t count; // Initialize Matches Array index_src=n; reset_matches(); // Apply compression dan1lzss(src); free_matches(); // flush destination index_dest=0; rle_ntimes = 0; bRLEDATA = 0; bit_mask = 0; write_lz(src, dst); // compute ratio //index_dest = optimals[n-1].bits += 1 + 16 + 1 + 7; //index_dest /= 8; count=index_dest; return count; }<file_sep>// this file contains sounds // converted from asm to C #include "snds.h" const u8 sound1[]={ 0x40,0x25,0x62,1, 0x40,0x74,0x51,1, 0x40,0x86,0x00,2, 0x50, }; const u8 sound2[]={ 0x80,0xdb,0x01,1, 0x80,0x7b,0x02,1, 0x80,0xf0,0x21,1, 0x80,0x2c,0x22,1, 0x80,0x4c,0x32,1, 0x80,0x98,0x52,1, 0x80,0xfe,0x81,1, 0x80,0x7f,0xa1,1, 0x90, }; const u8 sound3[]={ 0xc0,0xcc,0x50,1, 0xc0,0xdc,0x00,1, 0xc0,0x3f,0x01,1, 0xc0,0xac,0x01,1, 0xc0,0x13,0x02,1, 0xc0,0x82,0x02,1, 0xc0,0xde,0x02,1, 0xc0,0x33,0x03,1, 0xc0,0x91,0x03,1, 0xed, 0xc0,0xbb,0xa0,1, 0xc0,0xb8,0x90,1, 0xc0,0x3d,0x91,1, 0xc0,0xb4,0x91,1, 0xc0,0x54,0x92,1, 0xc0,0xbe,0x92,1, 0xc0,0x44,0xa3,1, 0xc0,0xb1,0xa3,1 , 0xd0, }; const u8 sound4[]={ 0x02,0x14,64,0x12,0x42, 0x10, }; const u8 sound5[]={ 0x40,0x1d,0x51,6, 0x40,0xd5,0x50,6, 0x40,0xa9,0x50,6, 0x40,0xd5,0x50,6, 0x40,0xa9,0x50,6, 0x40,0x8e,0x50,6, 0x40,0xa9,0x50,6, 0x40,0x8e,0x50,6, 0x40,0x6a,0x50,24, 0x50, }; const u8 sound6[]={ 0x80,0x3a,0x52,6, 0x80,0xab,0x51,6, 0x80,0x53,0x51,6, 0x80,0x1d,0x51,6, 0x80,0xd5,0x50,6, 0x80,0xa9,0x50,6, 0x80,0xd5,0x50,6, 0x80,0xa9,0x50,6, 0x80,0x8e,0x50,24, 0x90, }; //--------------------------------------------------------------------------------- // mandatory soundtable declaration // For some reason the very first entry MUST be SOUNDAREA1. SOUNDAREA1 is the lowest priority sound effect. // I recommend using SOUNDAREA1-SOUNDAREA3 to be music track. SOUNDAREA4-6 to be sound effects. const sound_t snd_table[]={ { sound1, SOUNDAREA1}, // sound entry 1 { sound2, SOUNDAREA2}, // sound entry 2 { sound3, SOUNDAREA3}, // sound entry 3 { sound4, SOUNDAREA4}, // sound entry 4 { sound5, SOUNDAREA5}, // sound entry 5 { sound6, SOUNDAREA6}, // sound entry 6 }; <file_sep>#ifndef _MEGACART_GFXS2_ #define _MEGACART_GFXS2_ #include <coleco.h> #include "image2gfx.h" // generetad by gfx2col #endif <file_sep>/*--------------------------------------------------------------------------------- small grame from coder <NAME> : Diamond Dash -- alekmaul ---------------------------------------------------------------------------------*/ #include "dash.h" #include "gfxs.h" // to add definition of graphics #include "snds.h" // to add definition of sounds const signed char holes1_dx[]={-1,0,1,-2,-1,0,1,2,-2,-1,0,1,0}; // holes type #1 const signed char holes1_dy[]={-2,-2,-2,-1,-1,-1,-1,-1,0,0,0,0,1}; const signed char holes2_dx[]={-2,-1,0,-2,-1,0,1,-2,-1,0,1,0,1}; // holes type #2 const signed char holes2_dy[]={-2,-2,-2,-1,-1,-1,-1,0,0,0,0,1,1}; const char *const holes_dx[]={holes1_dx,holes2_dx}; // holes type table const char *const holes_dy[]={holes1_dy,holes2_dy}; const char holes_size = 13; // holes size const u8 game_over[] = {33,34,35,36,37,38,0}; // Char array for "GAME OVER" int dynamite; // Number of dynamite unsigned diamant; // Score unsigned timer; // Timer const unsigned int diamant_score[] = {1,3,5}; // Diamonds value u8 nombre_diamants; // Number of diamonds needed to finish the level const u8 minimum_diamants[]={85,75,60,45,35}; typedef struct { // Classic coordinate structure char x; char y; signed char dx; signed char dy; } coorxy; coorxy player; // Player : coordinate coorxy one_dynamite; // Dynamite : coordinate u8 dynamite_countdown; // Dynamite : countdown before explosion //--------------------------------------------------------------------------------- // Initialise characters graphics in VideoRAM void init_graphics(void) { // Load characters pattern and color vdp_rle2vram(PATTERNRLE,0x0000); vdp_duplicatevram(); vdp_rle2vram(COLORRLE,0x2000); // Set sprites pattern as characters pattern vdp_setreg(6,0); } //--------------------------------------------------------------------------------- // Show score, timer and number of dynamites void show_score(void) { vdp_putstring(6,23,sys_str(diamant)); vdp_putstring(14,23,sys_str(timer)); vdp_putstring(23,23,sys_str(dynamite)); } //--------------------------------------------------------------------------------- // Add diamonds function void add_diamond(u8 nombre, u8 diamond_type) { char x,y,k; signed char dx,dy; loop2: x = sys_randbyte(1,30); y = sys_randbyte(4,21); if (vdp_getchar(x,y)!=1) goto loop2; for (dx=-1;dx<2;dx++) { for (dy=-1;dy<2;dy++) { k = vdp_getchar(x+dx,y+dy); if (k==2) goto loop2; } } vdp_putchar(x,y,2+diamond_type); nombre--; if (nombre!=0) goto loop2; } //--------------------------------------------------------------------------------- // Add holes function void add_holes(u8 nombre) { char x,y,k,type; char dx,dy,size; loop3: x = sys_randbyte(3,28); y = sys_randbyte(8,21); type = sys_random()&1; size=holes_size; while(size--!=0) { dx=(holes_dx[type])[size]; dy=(holes_dy[type])[size]; k = vdp_getchar(x+dx,y+dy); if (k!=1) goto loop3; } size=holes_size; while(size--!=0) { dx=(holes_dx[type])[size]; dy=(holes_dy[type])[size]; vdp_putchar(x+dx,y+dy,2); } nombre--; // add dynamite pack in the last two holes if (nombre==2) vdp_putchar(x,y,7); if (nombre<2) vdp_putchar(x,y,31); // loop if (nombre!=0) goto loop3; } //--------------------------------------------------------------------------------- // Draw a new mountain void new_mountain(void) { // Blank screen vdp_disablevdp(); vdp_rle2vram(NAMERLE,0x1800); // Load default mountain screen // Initialise player's coordinate and sprite pattern player.x = 22; player.y = 2; player.dx = 0; player.dy = 0; spr_setpat(0,64); spr_setcol(0,15); add_holes(6); // Add 6 holes add_diamond(51,1); // Add 51 green diamonds add_diamond(23,2); // Add 23 red diamonds add_diamond(11,3); // Add 11 white diamonds // Show screen vdp_enablevdp(); } //--------------------------------------------------------------------------------- // Show sprite void show_sprite(void) { // wait 3 vertical retrace to slowdown the execution vdp_enablenmi(); vdp_waitvblank(3); vdp_disablenmi(); // Put sprites table directly in VideoRAM vdp_putvram(sprgen,sprites,8); } //--------------------------------------------------------------------------------- // Update player on screen void show_player(u8 n) { u8 x,y; u8 j; // convert player's x and y position for normal sprite's position x = player.x<<3; y = (player.y<<3)-1; // Switch player's sprite pattern sprites[0].pattern ^=1; // If it's during game if (n==0) { // Then animate sprites player movement for (j=0;j<2;j++) { if (sprites[0].x<x) sprites[0].x +=4; if (sprites[0].x>x) sprites[0].x -=4; if (sprites[0].y<y) sprites[0].y +=4; if (sprites[0].y>y) sprites[0].y -=4; show_sprite(); } } else { // Otherwise, simply set sprites table with player's coordinate sprites[0].x=x; sprites[0].y=y; show_sprite(); } } char move_player(void) { u8 j,k; char x,y; // Animate player show_player(0); // Put a "cavern" character on player vdp_putchar(player.x, player.y,2); // Get joystick in port#1 j = joypad_1; // Reset player's direction x and y player.dx = 0; player.dy = 0; // Set new player's direction x and y if (j & PAD_UP) player.dy=-1; if (j & PAD_DOWN) player.dy=1; if (j & PAD_LEFT) player.dx=-1; if (j & PAD_RIGHT) player.dx=1; // If player doesn't move then set 2nd player's sprite pattern, otherwise, set 1st player's sprite pattern if ((player.dx==0) && (player.dy==0)) sprites[0].pattern |= 2; else sprites[0].pattern &= 0xfd; // If player press fire if ( (j & PAD_FIRE1) && (dynamite_countdown==0)) { // Set new countdown and dynamite coordinate dynamite_countdown=10; one_dynamite.x=player.x; one_dynamite.y=player.y; // Decrease number of player's dynamite dynamite--; // If player had no dynamite then return "stop game" flag if (dynamite<0) return 0; // Play sound#4 : "schhhhhh" snd_startplay(4); } // Check if there is something in front of the player x = player.x + player.dx; y = player.y + player.dy; k = vdp_getchar(x,y); if ((k>1 && k<7)|| k==31) { // Update player's coordinate player.x = x; player.y=y; // If it's a diamond, increase score and play sound #1 : "beep" if (k>2 && k<6) { diamant += diamant_score[k-3]; snd_startplay(1); if (--nombre_diamants==0) { vdp_putchar(23,2,6); snd_startplay(5); snd_startplay(6); } } // If it's a dynamite pack, increase number of player's dynamite by 3 and play sound #2 if (k==31) { dynamite += 3; snd_startplay(2); } // If it's the exit, return "stop game" flag if (k==6) { return 0; } } // Return "continue game" flag return -1; } // Do a square hole void square_hole(u8 x, u8 y, u8 size) { u8 i,j,k; char dx=0,dy=0; char n = size >> 1; // Play sound #2 : "bonk" snd_startplay(2); // Add rocks in mountain vdp_enablenmi(); for (k=0;k<5;k++) { while (vdp_getchar(dx,dy)!=2) { dx = sys_randbyte(0,31); dy = sys_randbyte(2,22); } vdp_disablenmi(); vdp_putchar(dx,dy,1); vdp_enablenmi(); } vdp_disablenmi(); dx = 0; // Erase whatever it was directly in the center of this futur hole vdp_putchar(x,y,2); // Do square hole x -= n; y -= n; for (i=0;i<size;i++) { for (j=0;j<size;j++) { k = vdp_getchar(x,y); // If detect a barrel of powder, keep note of its coordinate if (k==7) {dx=x; dy=y;} if (k==1) vdp_putchar(x,y,2); y++; } x++; y-=size; } /* If a barrel of powder was detected, do a big square hole */ if (dx!=0) square_hole(dx, dy, 7); } // Update dynamite countdown and effect void update_dynamite(void) { // If a dynamite is on screen if (dynamite_countdown!=0) { // Decrease countdown counter dynamite_countdown--; // Update dynamite animation on screen if (dynamite_countdown&1) { vdp_putchar(one_dynamite.x,one_dynamite.y,29); } else { vdp_putchar(one_dynamite.x,one_dynamite.y,30); } // If dynamite countdown = 0, then do a small square hole if (dynamite_countdown==0) { square_hole(one_dynamite.x,one_dynamite.y,3); } } } // Game engine void game(void) { u8 mountains_limit = 5; dynamite=0; diamant=0; while(1) { dynamite = 20; new_mountain(); // Decrease number of mountain to do mountains_limit--; // Set number of diamonds needed to exit level nombre_diamants = minimum_diamants[mountains_limit]; timer=2000; show_player(1); // Game loop while(move_player()) { if (timer!=0) timer--; show_score(); update_dynamite(); } // Animate player for the last time show_player(0); // "Game Over" when player had no more dynamite if (dynamite<0) { snd_startplay(3); vdp_putstring(13,11,game_over); vdp_enablenmi(); sys_pause(); vdp_disablenmi(); } else { // If there still a timer bonus while (timer>9) { // Update timer and score timer-=10; diamant++; // Play sound#1 : "beep" snd_startplay(1); // Update score and timer on screen show_score(); // Wait a short time to slowdown the execution and to let the "beep" sound playing a bit vdp_enablenmi(); vdp_waitvblank(2); vdp_disablenmi(); } // If there still a timer bonus while (dynamite--!=0) { // Update score diamant+=5; // Play sound#1 : "bonk" snd_startplay(2); // Update score and timer on screen show_score(); // Wait a short time to slowdown the execution and to let the "beep" sound playing a bit vdp_enablenmi(); vdp_waitvblank(12); vdp_disablenmi(); } // Play winner music snd_startplay(5); snd_startplay(6); // Wait until music ends vdp_enablenmi(); vdp_waitvblank(75); vdp_disablenmi(); // Go to next mountain : if it's the last mountain, redo the last one if (mountains_limit==0) mountains_limit++; } } } <file_sep>#ifndef _DIAMOND_SNDS_ #define _DIAMOND_SNDS_ #include <coleco.h> extern const sound_t snd_table[]; #endif<file_sep>#ifndef __PVCOLLIBVERSION_H__ #define __PVCOLLIBVERSION_H__ #define _PVCOLLIB_MAJOR_ 1 #define _PVCOLLIB_MINOR_ 6 #define _PVCOLLIB_PATCH_ 0 #define _PVCOLLIB_STRING "PVCOLLIB Release 1.6.0" #endif // __PVCOLLIBVERSION_H__ <file_sep>#ifndef _SIMPLESPR_GFXS_ #define _SIMPLESPR_GFXS_ #include <coleco.h> #include "pacspritegfx.h" // generetad by gfx2col #endif <file_sep>#include "comprle.h" //--------------------------------------------------------------------------- int rleCompress(byte *src,byte *dst,int n) { byte *p,*q,*run,*dataend; int count,maxrun; dataend = src + n; for( run = src,q = dst ; n > 0 ; run = p, n -= count ){ maxrun = n < 127 ? n : 127; if(run <= (dataend-3) && run[1] == run[0] && run[2] == run[0]) { for( p = run+3 ; p < (run+maxrun) && *p == run[0] ; ) ++p; count = p-run; *q++ = 127+count; /* flag byte */ *q++ = run[0]; } else { for( p = run ; p < (run+maxrun) ; ) if(p <= (dataend-3) && p[1] == p[0] && p[2] == p[0]) break; // 3 bytes repeated end verbatim run else ++p; count = p-run; *q++ = count-1; /* flag byte */ memcpy(q,run,count); q += count; } } // end marker *q++=0xff; return q-dst; } <file_sep>#ifndef _MUSICSFX_MAIN_ #define _MUSICSFX_MAIN_ #include <coleco.h> #endif <file_sep>ifeq ($(strip $(PVCOLLIB_HOME)),) $(error "Please create an environment variable PVCOLLIB_HOME with path to its folder and restart application. (you can do it on windows with <setx PVCOLLIB_HOME "/c/colecodev">)") endif include ${PVCOLLIB_HOME}/devkitcol/col_rules #--------------------------------------------------------------------------------- # ROMNAME is used in col_rules file ROMNAME := megacart #--------------------------------------------------------------------------------- # each file must be export with correct bank sorting export OFILES := megacart.rel \ gfxsb1.rel gfxsb2.rel gfxsb3.rel export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ -I$(CURDIR)/$(BUILD) #--------------------------------------------------------------------------------- # BANKs - all defined the same way, we just need to declare them BANKS = -Wl-b_bank1=0xc000 -Wl-b_bank2=0xc000 -Wl-b_bank3=0xc000 LDFLAGS += $(BANKS) #--------------------------------------------------------------------------------- # For 64K Megacart start on $fffc upto SLOT_4 $ffff # For 128K Megacart start on $fff8 upto SLOT_7 $ffff # for 256K one I start on $fff0 upto SLOT_15 at $ffff .PHONY: bitmaps all #--------------------------------------------------------------------------------- all: bitmaps $(ROMNAME).rom @echo Linking Megarom ... @cp $(ROMNAME).map crtcol.map $(LDMEGA) -icrtcol.ihx -b6 $(ROMNAME).rom clean: cleanRom cleanGfx #--------------------------------------------------------------------------------- image1gfx.inc: image1.png @echo convert graphic 1 ... $(notdir $@) $(GFXCONV) -cdan1 -fpng -b -m $< image2gfx.inc: image2.png @echo convert graphic 2 ... $(notdir $@) $(GFXCONV) -cdan1 -fpng -b -m $< image3gfx.inc: image3.png @echo convert graphic 3 ... $(notdir $@) $(GFXCONV) -cdan1 -fpng -b -m $< bitmaps: image1gfx.inc image2gfx.inc image3gfx.inc #--------------------------------------------------------------------------------- gfxsb1.rel: gfxsb1.c $(CC) $(CFLAGS) -c -mz80 --vc --no-std-crt0 --constseg bank1 gfxsb1.c gfxsb2.rel: gfxsb2.c $(CC) $(CFLAGS) -c -mz80 --vc --no-std-crt0 --constseg bank2 gfxsb2.c gfxsb3.rel: gfxsb3.c $(CC) $(CFLAGS) -c -mz80 --vc --no-std-crt0 --constseg bank3 gfxsb3.c <file_sep>/*--------------------------------------------------------------------------------- sgm test with no specific feature -- alekmaul ---------------------------------------------------------------------------------*/ #include "sgmtest.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Check if sgm is available sys_sgminit(); // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 8, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Check now if we were ok with SGM initialization if (sys_sgmok==1) { // Print text as we are not going to do something else vdp_putstring(4,5,"YEAH SGM SUPPORT IS OK !"); } else { // Print text as we are not going to do something else vdp_putstring(8,5,"NO SGM SUPPORT..."); } // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>SUBDIRS := gfx2col cvmkcart bin2txt all: $(SUBDIRS) $(SUBDIRS): make -C $@ clean: for f in $(SUBDIRS); do \ cd $$f ; \ make clean ; \ cd .. ; \ done install: for f in $(SUBDIRS); do \ cd $$f ; \ make install ; \ cd .. ; \ done .PHONY: all $(SUBDIRS) <file_sep>#ifndef _GRAFPLECMP_MAIN_ #define _GRAFPLECMP_MAIN_ #include <coleco.h> #endif <file_sep>/*------------------------------------------------------------------------- time.h Copyright (C) 2001, <NAME> <johan.knol AT iduna.nl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if you link this library with other files, some of which are compiled with SDCC, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. -------------------------------------------------------------------------*/ #ifndef TINIBIOS_H #define TINIBIOS_H #include <ds80c390.h> #include <time.h> void Serial0Init (unsigned long baud, unsigned char buffered); char Serial0GetChar(void); void Serial0PutChar(char); char Serial0CharArrived(void); void Serial0Baud(unsigned long baud); void Serial0SendBreak(void); void Serial0Flush(void); void Serial0SwitchToBuffered(void); /* ds400 only. */ void Serial1Init (unsigned long baud, unsigned char buffered); char Serial1GetChar(void); void Serial1PutChar(char); char Serial1CharArrived(void); void Serial1Baud(unsigned long baud); void Serial1SendBreak(void); void Serial1Flush(void); unsigned long ClockTicks(); void ClockMilliSecondsDelay(unsigned long ms); void ClockMicroSecondsDelay(unsigned int us); #define SERIAL_0_BAUD 115200L #define SERIAL_1_BAUD 9600L /* these need to be binary numbers */ #define SERIAL_0_RECEIVE_BUFFER_SIZE 1024 #define SERIAL_1_RECEIVE_BUFFER_SIZE 64 /* I know someone is fooling with the crystals */ #if defined(__SDCC_ds400) # define OSCILLATOR 14745600L #else # define OSCILLATOR 18432000L #endif /* Set the cpu speed in clocks per machine cycle, valid values are: 1024: Divide-by-1024 (power management) mode (screws ALL timers and serial) 4: Standard 8051 divide-by-4 mode 2: Use 2x xtal multiplier 1: Use 4x xtal multiplier (Don't do this with a TINI at 18.432MHz) */ #define CPU_SPEED 2 void CpuSpeed(unsigned int speed); /* The MOVX stretch cycles, see datasheet */ #define CPU_MOVX_STRETCH 0x01 /* from rtc390.c */ #define HAVE_RTC unsigned char RtcRead(struct tm *rtcDate); void RtcWrite(struct tm *rtcDate); /* from lcd390.c */ extern void LcdInit(void); extern void LcdOn(void); extern void LcdOff(void); extern void LcdClear(void); extern void LcdHome(void); extern void LcdGoto(unsigned int collumnRow); extern void LcdPutChar(char c); extern void LcdPutString(char *string); extern void LcdLPutString(unsigned int collumnRow, char *string); extern void LcdPrintf(const char *format, ...) __reentrant; extern void LcdLPrintf(unsigned int collumnRow, const char *format, ...) __reentrant; /* from i2c390.c */ #define I2C_BUFSIZE 128 extern char I2CReset(void); extern char I2CStart(void); extern char I2CStop(void); extern char I2CSendStop(char addr, char count, char send_stop); extern char I2CReceive(char addr, char count); extern char I2CSendReceive(char addr, char tx_count, char rx_count); /*extern char I2CByteOut(char);*/ /*extern void I2CDumpError(char);*/ /* global transfer buffers */ extern char i2cTransmitBuffer[I2C_BUFSIZE]; extern char i2cReceiveBuffer[I2C_BUFSIZE]; /* Macro for normal send transfer ending with a stop condition */ #define I2CSend(addr, count) I2CSendStop(addr, count, 1) /* internal functions used by tinibios.c */ unsigned char _sdcc_external_startup(void); void Serial0IrqHandler (void) __interrupt 4; void Serial1IrqHandler (void) __interrupt 7; #if !defined(__SDCC_ds400) void ClockInit(); void ClockIrqHandler (void) __interrupt 1 __naked; #endif #if defined(__SDCC_ds400) /* functions for dealing with the ds400 ROM firmware. */ /* A wrapper which calls rom_init allocating all available RAM in CE0 to the heap, sets the serial port to SERIAL_0_BAUD, sets up the millisecond timer, and diddles the clock multiplier. */ /* Values for the romInit "speed" parameter. */ #define SPEED_1X 0 /* no clock multiplier, normal speed. */ #define SPEED_2X 1 /* 2x clock multiplier. */ #define SPEED_4X 2 /* 4x clock, DOESN'T WORK ON TINIm400! */ unsigned char romInit(unsigned char noisy, char speed); /* Install an interrupt handler. */ void installInterrupt(void (*isrPtr)(void), unsigned char offset); #endif #endif /* TINIBIOS_H */ <file_sep>/*--------------------------------------------------------------------------------- Generic phoenix functions Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file phoenix.h * \brief contains the basic definitions for controlling the Phoenix console. * * This unit provides generic features related to Phoenix console.<br> *<br> * Here is the list of features:<br> * - Test phoenix console<br> */ #ifndef COL_F18A_INCLUDE #define COL_F18A_INCLUDE #include <coleco/coltypes.h> #include <coleco/f18a.h> /** * \brief vdp_f18aok is set if f18a module is present<br> * when calling vdp_f18ainit function<br> */ #define sys_phoenixok vdp_f18aok; /** * \fn void sys_phoenixinit(void) * \brief Test Phoenix console<br> * Activate f18a and init vdp_f18aok/sys_phoenixok variable with 1 if it is ok<br> * Testing sys_phoenixok variable to know if on Phoenix console<br> */ #define sys_phoenixinit vdp_f18ainit; #endif <file_sep>#ifndef _F18ABMPM1_MAIN_ #define _F18ABMPM1_MAIN_ #include <coleco.h> #endif <file_sep>#ifndef _F18ABMPM1_GFXS_ #define _F18ABMPM1_GFXS_ #include <coleco.h> #include "ourvisiongfx.h" // generetad by gfx2col #endif <file_sep>VERSION = "1.0.0" #--------------------------------------------------------------------------------- # options for code generation #--------------------------------------------------------------------------------- #CC=/d/MinGW32/bin/gcc CC=gcc CFLAGS=-g -O2 -Wall -D__BUILD_DATE="\"`date +'%Y%m%d'`\"" -D__BUILD_VERSION="\"$(VERSION)\"" SOURCES=cvmkcart.c OBJS=cvmkcart.o EXE=cvmkcart DEFINES = LIBS = ifeq ($(OS),Windows_NT) EXT=.exe else EXT= endif #--------------------------------------------------------------------------------- all: $(EXE)$(EXT) #--------------------------------------------------------------------------------- $(EXE)$(EXT) : $(OBJS) @echo make exe $(notdir $<) $(CC) $(CFLAGS) $(OBJS) -o $@ cvmkcart.o : cvmkcart.c @echo make obj $(notdir $<) $(CC) $(CFLAGS) -c $< #--------------------------------------------------------------------------------- clean: rm -f $(OBJS) $(EXE)$(EXT) *.tds install: mkdir -p ../../devkitcol/tools && cp $(EXE)$(EXT) ../../devkitcol/tools/$(EXE)$(EXT) <file_sep>/*--------------------------------------------------------------------------------- Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Image converter for colecovision. BMP BI_RLE8 compression support by <NAME> ***************************************************************************/ #ifndef GFX2COL_H #define GFX2COL_H #ifndef __BUILD_VERSION #include "config.h" #else #define GFX2COLVERSION __BUILD_VERSION #define GFX2COLDATE __BUILD_DATE #endif /* __BUILD_VERSION */ //MACROS #define HI_BYTE(n) (((int)n>>8) & 0x00ff) // extracts the hi-byte of a word #define LOW_BYTE(n) ((int)n & 0x00ff) // extracts the low-byte of a word #define HIGH(n) ((int)n<<8) // turn the char into high part of int #endif <file_sep># PVcollib is an open and free library to develop programs for your Coleco (Connecticut Leather Company) Colecovision ![PVcollib](https://www.portabledev.com/wp-content/uploads/2019/11/pvcollib_logo.png) PVcollib is split in 3 parts * The library itself provided with full code sources, obj files of each function and a Doxygen documentation (in the docs folder). * The tools and compiler (for Windows system only) * The examples (sprites, sound, graphics, debug) Download the complete archive in [Download Section](https://github.com/alekmaul/pvcollib/wiki/Download). After you downloaded the PVcollib archive, check the Wiki Section to get installation instructions and basics tutorials. Welcome to PVcollib world and enjoy doing some homebrews for your Coleco :-P ! <file_sep>#ifndef COMPDAN1_H #define COMPDAN1_H #include <stdio.h> #include <stdlib.h> #include <mem.h> #define bool unsigned char #define byte unsigned char #define false 0 #define true 0xff #define BIT_OFFSET1 1 #define BIT_OFFSET2 4 #define BIT_OFFSET3 8 #define BIT_OFFSET4 12 #define MAX_OFFSET1 (1<<BIT_OFFSET1) #define MAX_OFFSET2 MAX_OFFSET1 + (1<<BIT_OFFSET2) #define MAX_OFFSET3 MAX_OFFSET2 + (1<<BIT_OFFSET3) // - INITIALIZE MATCHES TABLE - #define MAXINFILE 512*1024 // COMPRESSION CONSTANTS #define MAX_ELIAS_GAMMA (1<<16) #define MAX_LEN (1<<16)-1 #define MAX_OFFSET MAX_OFFSET3 + (1<<BIT_OFFSET4) //--------------------------------------------------------------------------- typedef struct { int bits; //COST int offset; int len; } t_optimal; struct t_match { int index; struct t_match *next; }; extern t_optimal optimals[MAXINFILE]; extern struct t_match matches[65536]; extern int index_src,index_dest; extern int rle_ntimes; extern int bRLEDATA; extern byte bit_mask; //--------------------------------------------------------------------------- extern int elias_gamma_bits(int value); extern void cleanup_optimals(void); extern void reset_matches(void); extern void free_matches(void); extern void write_lz(byte *data_src, byte *data_dest); extern void flush_match(struct t_match *match); extern void insert_match(struct t_match *match, int index); extern int dan1Compress(byte *src,byte *dst,int n); #endif<file_sep>/*--------------------------------------------------------------------------------- Simple sound demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "music.h" //--------------------------------------------------------------------------------- // sound declaration const u8 musicch1[]={ // From Smurf rescue, channel 1 0x38, // rest - length 24 0x38, // rest - length 24 0xc2,0x47,0x40,0x40,0x18,0x38, // tone freq 1575,5Hz - vol 11 swept down - length 64 0xc2,0x55,0x40,0x40,0x18,0x38, // tone freq 1316,0Hz - vol 11 swept down - length 64 0xc0,0x50,0x40,0x20, // tone freq 1398,3Hz - vol 11 - length 32 0xc0,0x5f,0x40,0x20, // tone freq 1177,5Hz - vol 11 - length 32 0xc2,0x55,0x40,0x40,0x18,0x38, // tone freq 1316,0Hz - vol 11 swept down - length 64 0xc2,0x5f,0x40,0x40,0x18,0x38, // tone freq 1177,5Hz - vol 11 swept down - length 64 0xc2,0x71,0x40,0x40,0x18,0x38, // tone freq 989,9Hz - vol 11 swept down - length 64 0xc0,0x6b,0x40,0x20, // tone freq 1045,4Hz - vol 11 - length 32 0xc0,0x7f,0x50,0x20, // tone freq 880,8Hz - vol 10 - length 32 0xc0,0x5f,0x50,0x10, // tone freq 1177,5Hz - vol 10 - length 16 0x18 // repeat }; const u8 musicch2[]={ // From Smurf rescue, channel 2 0x30, // rest - length 16 0x80,0x1d,0x41,0x0e, // tone freq 392,5Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0x1d,0x41,0x0e, // tone freq 392,5Hz - vol 11 - length 14 0x22, // rest - length 2 0x82,0xd6,0x40,0x18,0x15,0x38, // tone freq 522,7Hz - vol 11 swept down - length 24 0x80,0xd6,0x40,0x06, // tone freq 522,7Hz - vol 11 - length 6 0x22, // rest - length 2 0x80,0xd6,0x40,0x0e, // tone freq 522,7Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0xbe,0x40,0x0e, // tone freq 588,7Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0xaa,0x40,0x10, // tone freq 658,0Hz - vol 11 - length 16 0x80,0xd6,0x40,0x10, // tone freq 522,7Hz - vol 11 - length 16 0x80,0xaa,0x40,0x10, // tone freq 658,0Hz - vol 11 - length 16 0x80,0xa0,0x40,0x10, // tone freq 699,1Hz - vol 11 - length 16 0x82,0x8f,0x40,0x18,0x15,0x38, // tone freq 782,2Hz - vol 11 swept down - length 24 0x80,0x8f,0x40,0x06, // tone freq 782,2Hz - vol 11 - length 6 0x22, // rest - length 2 0x80,0x8f,0x40,0x0e, // tone freq 782,2Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0xa0,0x40,0x10, // tone freq 699,1Hz - vol 11 - length 16 0x80,0xaa,0x40,0x20, // tone freq 658,0Hz - vol 11 - length 32 0x80,0xbe,0x40,0x10, // tone freq 588,7Hz - vol 11 - length 16 0x80,0xd6,0x40,0x10, // tone freq 522,7Hz - vol 11 - length 16 0x82,0xbe,0x40,0x18,0x15,0x38, // tone freq 588,7Hz - vol 11 swept down - length 24 0x80,0xbe,0x40,0x06, // tone freq 588,7Hz - vol 11 - length 6 0x22, // rest - length 2 0x80,0xbe,0x40,0x0e, // tone freq 588,7Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0xd6,0x40,0x10, // tone freq 522,7Hz - vol 11 - length 16 0x80,0xbe,0x40,0x10, // tone freq 588,7Hz - vol 11 - length 16 0x80,0xaa,0x40,0x10, // tone freq 658,0Hz - vol 11 - length 16 0x80,0xbe,0x40,0x10, // tone freq 588,7Hz - vol 11 - length 16 0x80,0xd6,0x40,0x10, // tone freq 522,7Hz - vol 11 - length 16 0x82,0xbe,0x40,0x18,0x15,0x38, // tone freq 588,7Hz - vol 11 swept down - length 24 0x80,0xbe,0x40,0x06, // tone freq 588,7Hz - vol 11 - length 6 0x22, // rest - length 2 0x80,0xbe,0x40,0x0e, // tone freq 588,7Hz - vol 11 - length 14 0x22, // rest - length 2 0x80,0xe2,0x50,0x10, // tone freq 495,0Hz - vol 10 - length 16 0x80,0x1d,0x51,0x10, // tone freq 392,5Hz - vol 10 - length 16 0x18, // repeat }; const u8 musicch3[]={ // From Smurf rescue, channel 3 0x40,0x55,0x30,0x10, // tone freq 1316,0Hz - vol 12 - length 16 0x40,0x50,0x20,0x10, // tone freq 1398,3Hz - vol 13 - length 16 0x40,0x40,0x30,0x10, // tone freq 1747,8Hz - vol 12 - length 16 0x40,0x47,0x20,0x10, // tone freq 1575,5Hz - vol 13 - length 16 0x40,0x50,0x20,0x08, // tone freq 1398,3Hz - vol 13 - length 8 0x40,0x55,0x30,0x08, // tone freq 1316,0Hz - vol 12 - length 8 0x40,0x5f,0x30,0x10, // tone freq 1177,5Hz - vol 12 - length 16 0x40,0x8f,0x30,0x10, // tone freq 782,2Hz - vol 12 - length 16 0x40,0x6b,0x20,0x10, // tone freq 1045,4Hz - vol 13 - length 16 0x40,0x5f,0x30,0x10, // tone freq 1177,5Hz - vol 12 - length 16 0x40,0x55,0x20,0x10, // tone freq 1316,0Hz - vol 13 - length 16 0x40,0x50,0x30,0x08, // tone freq 1398,3Hz - vol 12 - length 8 0x40,0x55,0x30,0x08, // tone freq 1316,0Hz - vol 12 - length 8 0x40,0x5f,0x20,0x10, // tone freq 1177,5Hz - vol 13 - length 16 0x40,0x55,0x30,0x10, // tone freq 1316,0Hz - vol 12 - length 16 0x40,0x50,0x20,0x10, // tone freq 1398,3Hz - vol 13 - length 16 0x40,0x47,0x30,0x08, // tone freq 1575,5Hz - vol 12 - length 8 0x40,0x50,0x30,0x08, // tone freq 1398,3Hz - vol 12 - length 8 0x40,0x55,0x20,0x10, // tone freq 1316,0Hz - vol 13 - length 16 0x40,0x47,0x20,0x08, // tone freq 1575,5Hz - vol 13 - length 8 0x68, // rest - length 8 0x40,0x47,0x20,0x08, // tone freq 1575,5Hz - vol 13 - length 8 0x68, // rest - length 8 0x40,0x47,0x20,0x08, // tone freq 1575,5Hz - vol 13 - length 8 0x68, // rest - length 8 0x40,0x47,0x20,0x20, // tone freq 1575,5Hz - vol 13 - length 32 0x40,0x50,0x20,0x08, // tone freq 1398,3Hz - vol 13 - length 8 0x40,0x55,0x20,0x08, // tone freq 1316,0Hz - vol 13 - length 8 0x40,0x5f,0x20,0x08, // tone freq 1177,5Hz - vol 13 - length 8 0x40,0x6b,0x40,0x08, // tone freq 1045,4Hz - vol 11 - length 8 0x40,0x71,0x30,0x10, // tone freq 989,9Hz - vol 12 - length 16 0x40,0x6b,0x40,0x10, // tone freq 1045,4Hz - vol 11 - length 16 0x40,0x5f,0x40,0x10, // tone freq 1177,5Hz - vol 11 - length 16 0x40,0x55,0x40,0x08, // tone freq 1316,0Hz - vol 11 - length 8 0x40,0x5f,0x40,0x08, // tone freq 1177,5Hz - vol 11 - length 8 0x40,0x6b,0x30,0x10, // tone freq 1045,4Hz - vol 12 - length 16 0x40,0x5f,0x40,0x10, // tone freq 1177,5Hz - vol 11 - length 16 0x40,0x55,0x40,0x10, // tone freq 1316,0Hz - vol 11 - length 16 0x40,0x50,0x40,0x08, // tone freq 1398,3Hz - vol 11 - length 8 0x40,0x55,0x40,0x08, // tone freq 1316,0Hz - vol 11 - length 8 0x40,0x5f,0x30,0x10, // tone freq 1177,5Hz - vol 12 - length 16 0x40,0x50,0x40,0x08, // tone freq 1398,3Hz - vol 11 - length 8 0x28, // rest - length 8 0x40,0x50,0x40,0x08, // tone freq 1398,3Hz - vol 11 - length 8 0x28, // rest - length 8 0x40,0x50,0x40,0x08, // tone freq 1398,3Hz - vol 11 - length 8 0x28, // rest - length 8 0x42,0x50,0x30,0x20,0x18,0x44, // tone freq 1398,3Hz - vol 12 swept down - length 32 0x10, // end }; //--------------------------------------------------------------------------------- // mandatory soundtable declaration // For some reason the very first entry MUST be SOUNDAREA1. SOUNDAREA1 is the lowest priority sound effect. // I recommend using SOUNDAREA1-SOUNDAREA3 to be music track. SOUNDAREA4-6 to be sound effects. const sound_t snd_table[]={ { musicch1, SOUNDAREA1}, // sound entry 1 { musicch2, SOUNDAREA2}, // sound entry 1 { musicch3, SOUNDAREA3}, // sound entry 1 }; //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put sound table and mute all channel snd_settable(snd_table); snd_stopall(); // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_putstring(7,6,"PUT RIGHT FOR MUSIC"); // Display screen and enable audio vdp_enablescr(); vdp_enablenmi(); // Wait for nothing :P while(1) { // Update display with current pad 1 values if (joypad_1 & PAD_RIGHT) { vdp_putstring(11,10,"MUSIC"); snd_startplay(1); snd_startplay(2); snd_startplay(3); } while (joypad_1) vdp_waitvblank(1); // Wait Vblank while joy pressed vdp_waitvblank(1); // default wait vblank } // startup module will issue a soft reboot if it comes here } <file_sep>/*--------------------------------------------------------------------------------- bitmap demo with less than 256 tiles -- alekmaul ---------------------------------------------------------------------------------*/ #include "grafnocomp.h" #include "gfxs.h" // to add definition of graphics //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for bitmap example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_disablescr(); vdp_setmode2txt(); // Put image in vram and duplicate to the 2nd & 3rd zone vdp_putvram (chrgen,TILourvisiongfx,SZTILourvisiongfx); // characters vdp_putvram (coltab,COLourvisiongfx,SZCOLourvisiongfx); // colors vdp_putvram (chrtab,MAPourvisiongfx,SZMAPourvisiongfx); // map vdp_duplicatevram(); vdp_enablescr(); // Wait for nothing :P while(1) { // Wait Vblank vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>#include "comptool.h" //--------------------------------------------------------------------------- unsigned char *d; // Maximum offset for each mode unsigned int maxlen[7] = { 128, 128 + 128, 512 + 128, 1024 + 128, 2048 + 128, 4096 + 128, 8192 + 128 }; // Cost of coding a constant unsigned int varcost[65536]; // Metadata per byte struct metadata { unsigned int reeks; /* Total times that byte is repeated */ unsigned int cpos[7]; unsigned int clen[7]; } *m; // Compression per byte for each mode struct pakdata { unsigned int cost; unsigned int mode; unsigned int mlen; } *p[7]; int savelength; unsigned int source_size; unsigned int offset; struct saves { unsigned char *buf; int ep, dp, p, e; } s; // Inits output buffer void init(void) { s.ep = s.dp = s.p = s.e = 0; s.buf = malloc(source_size * 2); } // Adds a zero bit to output void add0(void) { if (s.p == 0) claimevent(); s.e *= 2; ++s.p; if (s.p == 8) addevent(); } // Adds an one bit to output void add1(void) { if (s.p == 0) claimevent(); s.e *= 2; ++s.p; ++s.e; if (s.p == 8) addevent(); } // Add a X bit to output void addbit(int b) { if (b) add1(); else add0(); } /* ** Add three bits to output */ void add3(int b) { addbit(b & 4); addbit(b & 2); addbit(b & 1); } /* ** Add a variable number to output */ void addvar(int i) { int j = 0x8000; /* ** Looks for the first bit set at one */ while ((i & j) == 0) j >>= 1; /* ** Like in floating point, the uncompressed adds an extra one */ while (j != 1) { j >>= 1; add1(); if ((i & j) != 0) add1(); else add0(); } add0(); /* Ending signal */ } // Add a data to output void adddata(unsigned char d) { s.buf[s.dp++] = d; } // Dump bits buffer void addevent(void) { s.buf[s.ep] = s.e; s.e = s.p = 0; } // Take note where it will save the following 8 bits void claimevent(void) { s.ep = s.dp; ++s.dp; } /* ** Take note of cost of using a variable number */ void initvarcost(void) { int v = 1; int b = 1; int r = 1; int j; /* ** Depict a one costs one bit (0) ** 2-3 costs three bits (1x0) ** 4-7 costs five bits. (1x1x0) */ while (r != 65536) { for (j = 0; j != r; ++j) varcost[v++] = b; b += 2; r *= 2; } } /* ** Pre-compresses the source file */ void createmetadata(void) { unsigned int i; unsigned int j; unsigned int *last = malloc(65536 * sizeof(unsigned int)); unsigned int *prev = malloc((source_size + 1) * sizeof(unsigned int)); unsigned int r; unsigned int t; int bl; /* ** For speeding up the search for pairing strings: ** ** as it advances, prev[byte] points to the string immediately previous ** that starts with the same two current bytes, it doesn't matter to link ** by individual bytes as each offset needs at least one byte. ** ** last is a kind of hash table pointing to each two-byte string found. */ memset(last, -1, 65536 * sizeof(unsigned int)); for (i = 0; i != source_size; ++i) { m[i].cpos[0] = m[i].clen[0] = 0; prev[i] = last[d[i] + d[i + 1] * 256]; last[d[i] + d[i + 1] * 256] = i; } /* ** Counts the bytes repeated from each starting position */ r = -1; t = 0; for (i = source_size - 1; i != -1; --i) { if (d[i] == r) m[i].reeks = ++t; else { r = d[i]; m[i].reeks = t = 1; } } /* ** Now for each possible mode */ for (bl = 0; bl != 7; ++bl) { /* ** Process the input file */ for (i = 0; i < source_size; ++i) { unsigned int l; unsigned int p; p = i; if (bl) { m[i].clen[bl] = m[i].clen[bl - 1]; m[i].cpos[bl] = m[i].cpos[bl - 1]; p = i - m[i].cpos[bl]; } /* ** For each repeated string */ while ((p = prev[p]) != -1) { if (i - p > maxlen[bl]) /* Exceeded possible offset? */ break; /* Yes, finish */ l = 0; while (d[p + l] == d[i + l] && (i + l) < source_size) { /* ** Speed up trick: ** If the string that is going to replace has repeated bytes... ** and the replacing string has less repeated bytes... ** then it can take only existing ones and avoids the ** classic problem o(n2) */ if (m[i + l].reeks > 1) { if ((j = m[i + l].reeks) > m[p + l].reeks) j = m[p + l].reeks; l += j; } else ++l; } if (l > m[i].clen[bl]) { /* Look for the longest string */ m[i].clen[bl] = l; /* Longitude */ m[i].cpos[bl] = i - p; /* Position (offset) */ } } } putchar('.'); } putchar(' '); free(prev); free(last); } // Get the final size of file with a mode int getlen(struct pakdata *p, unsigned int mode) { unsigned int i; unsigned int j; unsigned int cc; unsigned int ccc; unsigned int kc; unsigned int kmode; unsigned int kl; p[source_size].cost = 0; /* ** Trick: goes from onwards to backwards, this way can know all ** possible combinations for compressing. */ for (i = source_size - 1; i != -1; --i) { kmode = 0; /* Literal */ kl = 0; kc = 9 + p[i + 1].cost; /* Test every size until getting the most short */ j = m[i].clen[0]; while (j > 1) { cc = 9 + varcost[j - 1] + p[i + j].cost; if (cc < kc) { kc = cc; kmode = 1; /* Short offset */ kl = j; } --j; } /* Test all sizes until getting the most short */ j = m[i].clen[mode]; if (mode == 1) ccc = 9; else ccc = 9 + mode; while (j > 1) { cc = ccc + varcost[j - 1] + p[i + j].cost; if (cc < kc) { kc = cc; kmode = 2; /* Long offset */ kl = j; } --j; } p[i].cost = kc; p[i].mode = kmode; p[i].mlen = kl; } return p[0].cost; } // Save the compressed file int save(struct pakdata *p, unsigned int mode,byte *dstcomp) { unsigned int i; unsigned int j; init(); if (savelength) { adddata(source_size & 255); adddata(source_size >> 8); } add3(mode - 1); adddata(d[0]); i = 1; while (i < source_size) { switch (p[i].mode) { case 0: /* Literal */ add0(); adddata(d[i]); ++i; break; case 1: /* Short offset */ add1(); addvar(p[i].mlen - 1); j = m[i].cpos[0] - 1; //if (j > 127) // printf("-j>128-"); adddata(j); i += p[i].mlen; break; case 2: /* Long offset */ add1(); addvar(p[i].mlen - 1); j = m[i].cpos[mode] - 1; //if (j < 128) // printf("-j<128-"); adddata(128 | (j & 127)); j -= 128; switch (mode) { case 6: addbit(j & 4096); case 5: addbit(j & 2048); case 4: addbit(j & 1024); case 3: addbit(j & 512); case 2: addbit(j & 256); addbit(j & 128); case 1: break; default: //printf("-2-"); break; } i += p[i].mlen; break; default: //printf("-?-"); break; } } for (i = 0; i != 34; ++i) add1(); //done(); if (s.p != 0) { while (s.p != 8) { s.e *= 2; s.p++; } addevent(); } fflush(stdout); memcpy(dstcomp,s.buf,s.dp); return s.dp; } int pleCompress(byte *src,byte *dst,int n) { int i,count; int l; int minlen; int minbl; offset = 0; source_size = n; d = malloc(source_size + 1); m = malloc(sizeof(struct metadata) * (source_size + 1)); memcpy(d,src,source_size); d[source_size] = 0; initvarcost(); createmetadata(); minlen = source_size * 1000; minbl = 0; for (i = 1; i != 7; ++i) { p[i] = malloc(sizeof(struct pakdata) * (source_size + 1)); l = getlen(p[i], i); if (l < minlen && i) { minlen = l; minbl = i; } putchar('.'); } count=save(p[minbl], minbl,dst); for (i = 1; i != 7; ++i) free(p[i]); free(m); free(d); return count; }<file_sep>#ifndef _GRAFNOCMP_GFXS_ #define _GRAFNOCMP_GFXS_ #include <coleco.h> #include "ourvisiongfx.h" // generetad by gfx2col #endif <file_sep>/*--------------------------------------------------------------------------------- Generic console functions. Copyright (C) 2018-2020 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file console.h * \brief coleco generic console support. * * This unit provides generic features related to the console.<br> *<br> * Here is the list of features:<br> * - variable with 32 bytes long in RAM<br> * - video frequency<br> * - string management<br> */ #ifndef COL_CONSOLE_H #define COL_CONSOLE_H #include <coleco/coltypes.h> /** * \brief * buffer32 used for some functions.<br> * can be used by program too. */ extern u8 buffer32[32]; /** * \brief * vid_freq is set with video frequency (50 or 60) hz. */ extern volatile u8 vid_freq; /** * \fn u16 sys_random(void) * \brief Generate and return a randomized 16 bit number * * \return unsigned short of a randomized number */ u16 sys_random(void); /** * \fn u8 sys_randbyte(u8 A, u8 B) * \brief Generate and return a randomized a 8 bit number between two numbers named A and B * * \param A minimum value of random number * \param B maximum value of random number * \return unsigned char of a randomized number */ u8 sys_randbyte(u8 A, u8 B); /** * \fn void sys_pause(void) * \brief Wait until a fire button is pressed (do a pause) */ void sys_pause(void); /** * \fn void sys_pause_delay(unsigned cycles) * \brief Wait until delay is over or a fire button is pressed * * \param cycles number of cycles to wait */ void sys_pause_delay(unsigned cycles); /** * \fn u16 sys_strlen(char *text) * \brief return the length of a string * * \param text text to analyze * \return unsigned short of string length */ u16 sys_strlen(char *text); /** * \fn void sys_utoa(unsigned value,char *buffer) * \brief Convert an unsigned value to ascii text. Leading zeros are put in buffer * * \param value value to convert to text * \param buffer text that will receive vvalue converted */ void sys_utoa(unsigned value,char *buffer); /** * \fn char *sys_str(unsigned value) * \brief return a converted value in string * * \param value number to convert * \return pointer to converted string */ char *sys_str(unsigned value); /** * \fn void sys_memcpyb (void *dest,void *src,unsigned num) * \brief Copy memory backward * * \param dest destination memory * \param src source memory * \param num number of bytes to copy */ void sys_memcpyb (void *dest,void *src,unsigned num); /** * \fn void sys_memcpyf (void *dest,void *src,unsigned num) * \brief Copy memory forward * * \param dest destination memory * \param src source memory * \param num number of bytes to copy */ void sys_memcpyf(void *dest,void *src,unsigned num); /** * \fn sys_choice_keypad1(u8 minval, u8 maxval) * \brief Wait until a key between two values if pressed on keypad 1 * * \param minval minimum value of key pressed * \param maxval maximum value of key pressed * \return value of key pressed */ u8 sys_choice_keypad1(u8 minval, u8 maxval); /** * \fn sys_choice_keypad2(u8 minval, u8 maxval) * \brief Wait until a key between two values if pressed on keypad 2 * * \param minval minimum value of key pressed * \param maxval maximum value of key pressed * \return value of key pressed */ u8 sys_choice_keypad2(u8 minval, u8 maxval); #endif <file_sep>#include <coleco.h> static const u8 level2[] = { 1,0xff, 50, 0, 20,0xff, 4,0xa8,0xe0, 45, 0xe1,0xb9, 47,0xff, 2,0xff, 30,0xb4 }; static const u8 level1[] = { 1,0xff, 2,0xff, 2,0xff, 2,0xff, 2,0xff, 2,0xff, 32,0x8c,0xcc, 55,0x82, 83,0xff,0x82, 17,0xff, 64,0xff,0xce, 56, 0, 2,0xdc }; static const u8 level5[] = { 87,0xff, 7,0xff, 8,0xff, 53,0x85, 10,0x85, 10,0x85, 58,0x00, 25,0xc2}; static const u8 level7[] = { 38,0xff, 2,0xff, 9,0xa1, 31,0xff, 32,0xa1, 0xe2,0xa1, 4,0xff, 7,0xc2, 42,0x82, 37,0xa2, 36,0xff, 9,0xff, 7,0xff, 42,0xff, 9,0x81, 2,0xc2, 29,0xff, 9,0xff, 2,0xe1, 20,0x00, 11,0xff, 2,0xa2, 6,0xa2, 19,0xff, 16,0x82, 18,0xff, 13,0xe2, 28,0xff, 6,0xa2, 7,0xff, 0xc2, 6,0xff, 10,0xe3, 8,0xe2, 27,0xc1, 1}; static const u8 level6[] = { 56,0xff, 2,0xff, 15,0xff, 2,0xff, 11,0xff, 3,0xff, 11,0xc0, 2,0xc0, 15,0xc0, 2,0xc0, 3,0xff, 2,0xff, 11,0xff, 2,0xff, 14,0xc3, 11, 0, 26,0xa8, 9,0xa8, 55,0xff, 2,0xff, 2,0xff, 9,0xff, 2,0xff, 2,0xff, 10,0xa1, 0xe1,0xa1, 38,0xa9, 7,0xa9}; static const u8 level8[] = { 40,0xff,0xff, 45,0xff, 2,0xff, 2,0x81, 2, 0xff, 2,0xff, 68,0x82, 5,0x82, 36,0x82, 19, 0x82, 61,0x82, 11,0x82, 6,0xff, 21,0xff, 12, 0xff, 3,0xff, 14,0x84, 9,0x84, 16,0x81, 13, 0xff, 23,0xff, 10,0xff, 5,0xff, 9,0x83, 19, 0x83, 11,0x83, 67, 0, 26,0x8b, 3,0x8b}; const u8* const levels[]={ level1,level2, level7,level8, level5,level6, level7,level8}; <file_sep>/*--------------------------------------------------------------------------------- Generic sprites functions. Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ---------------------------------------------------------------------------------*/ /** * \file sprite.h * \brief coleco generic sprites support. * * This unit provides methods to display / remove sprites on screen.<br> */ #ifndef COL_SPRITE_H #define COL_SPRITE_H #include <coleco/coltypes.h> #define SPHIDE 0xCF #define SPHIDE1 0xCE #define MAXSPRITE 32 #define MAXSPRITE4 (MAXSPRITE*4) #define MAXSPRITE2 (MAXSPRITE*2) /** * \brief * sprite entry : * y,x : coordinates (y,x) with y 0..191 and x 0..255 * pattern : pattern number of sprite * colour : colour between 0..15 */ typedef struct { u8 y; u8 x; u8 pattern; u8 colour; } sprite_t; /** * \brief * 32 sprites entries */ extern volatile sprite_t sprites[MAXSPRITE]; // sprites entries /** * \brief * 0 or 1 if sprites can be displayed or not */ extern volatile u8 spr_enable; /** * \fn void spr_clear(void) * \brief Remove all sprite from screen and init their positions */ void spr_clear(void); /** * \fn void spr_clear30r(void) * \brief Remove all sprite from screen and init their positions in F18a 30 rows mode */ void spr_clear30r(void); /*! \fn spr_update(void) \brief put sprite on screen Put all 32 sprites on screen. <b>Must be call in NMI routine.</b> */ void spr_update(void); /*! \fn spr_updatefast(void) \brief put sprite on screen without checking order Put all 32 sprites on screen. <b>Must be call in NMI routine.</b> */ void spr_updatefast(void); /*! \fn spr_getentry(void) \brief get a sprite id in sprite list \return sprite entry (0..31) Must be used to allocate sprite because we swap sprite each NMI to <b>avoid 4 sprites limit per line.</b><br> <b>Warning, it uses 0xcf Y attribute to know if sprite is used or not.</b> */ u8 spr_getentry(void); /*! \fn spr_getentry30r(void) \brief get a sprite id in sprite list \return sprite entry (0..31) Must be used to allocate sprite because we swap sprite each NMI to <b>avoid 4 sprites limit per line.</b><br> <b>Warning, it uses 0xf0 Y attribute to know if sprite is used or not.</b> */ u8 spr_getentry30r(void); /*! \fn spr_mode8x8(void) \brief put sprite in 8x8 pix mode Put all 32 sprites on screen in 8x8 pixels depth. */ void spr_mode8x8(void); /*! \fn spr_mode16x16(void) \brief put sprite in 16x16 pix mode Put all 32 sprites on screen in 16x16 pixels depth. */ void spr_mode16x16(void); /*! \fn spr_set(id,xp,yp,col,pat) \brief sets an sprite entry to the supplied values \param id the sprite number to be get [0 - 31] \param xp the x location of the sprite in pixels \param yp the y location of the sprite in pixels \param col the sprite color (0 to 15) \param pat the pattern number of sprite (must be a multiple of 4) */ #define spr_set(id, xp, yp, col, pat) \ { \ sprites[id].x=xp; \ sprites[id].y=yp; \ sprites[id].colour=col; \ sprites[id].pattern=pat; \ } /*! \fn spr_setxy(id,xp,yp) \brief sets an sprite coordinate to the supplied values \param id the sprite number to be get [0 - 31] \param xp the x location of the sprite in pixels \param yp the y location of the sprite in pixels */ #define spr_setxy(id, xp, yp) \ { \ sprites[id].x=xp; \ sprites[id].y=yp; \ } /*! \fn spr_setx(id) \brief set the x sprite coordinate \param id the sprite number to be get [0 - 31] \param xp the x location of the sprite in pixels */ #define spr_setx(id,xp) { sprites[id].x=xp; } /*! \fn spr_sety(id,yp) \brief set the y sprite coordinate \param id the sprite number to be get [0 - 31] \param yp the y location of the sprite in pixels */ #define spr_sety(id,yp) { sprites[id].y=yp; } /*! \fn spr_setpat(id) \brief set the sprite pattern \param id the sprite number to be get [0 - 31] \param pat the pattern of the sprite (multiple of 4) */ #define spr_setpat(id,pat) { sprites[id].pattern=pat; } /*! \fn spr_setcol(id) \brief set the sprite color \param id the sprite number to be get [0 - 31] \param col the sprite color (0 to 15) */ #define spr_setcol(id,col) { sprites[id].colour=col; } /*! \fn spr_getx(id) \brief get the x sprite coordinate \param id the sprite number to be get [0 - 31] */ #define spr_getx(id) (sprites[id].x) /*! \fn spr_gety(id) \brief get the y sprite coordinate \param id the sprite number to be get [0 - 31] */ #define spr_gety(id) (sprites[id].y) /*! \fn spr_collide (sprite_t *sp1,sprite_t *sp2,unsigned sp1width,unsigned sp1height,unsigned sp2width,unsigned sp2height) \brief check collision between two sprites \param sp1 the first sprite structure \param sp2 the second sprite structure \param sp1width width of first sprite \param sp1height height of first sprite \param sp2width width of second sprite \param sp2height height of second sprite \return lobyte - first pixel set, hibyte - number of pixels set */ u8 spr_collide (sprite_t *sp1,sprite_t *sp2,unsigned sp1width,unsigned sp1height,unsigned sp2width,unsigned sp2height); #endif <file_sep>#ifndef _DIAMOND_GFXS_ #define _DIAMOND_GFXS_ #include <coleco.h> extern const u8 NAMERLE[]; extern const u8 PATTERNRLE[]; extern const u8 COLORRLE[]; #endif <file_sep>/*--------------------------------------------------------------------------------- random value demo -- alekmaul ---------------------------------------------------------------------------------*/ #include "randvalue.h" //--------------------------------------------------------------------------------- // The NMI routine. Gets called 50 or 60 times per second // nothing to update for Input example void nmi (void) { } //--------------------------------------------------------------------------------- void main (void) { // Put screen in text mode 2 vdp_setmode2txt(); // Put default char in VRAM and duplicate to all areas // as we are going to write to line 10, it is in the second area vdp_setdefaultchar(FNTNORMAL); vdp_duplicatevram(); vdp_fillvram(0x2000,0xf1,128*8); // Change color (or we will see nothing) vdp_enablescr(); // Print at 10,text for the random number vdp_putstring(4,10,"RANDOM NUMBER="); // Wait for nothing :P while(1) { // Update display with random number and wait pad 1 sys_utoa(sys_random(),buffer32); vdp_putstring(18,10,buffer32); // Wait Fire and then Vblank while ((joypad_1 & PAD_FIRE1)==0) { vdp_waitvblank(1); } vdp_waitvblank(1); } // startup module will issue a soft reboot if it comes here } <file_sep>#ifndef _GRAFNOCMP_MAIN_ #define _GRAFNOCMP_MAIN_ #include <coleco.h> #endif <file_sep>#ifndef _DIAMOND_MAIN_ #define _DIAMOND_MAIN_ #include <coleco.h> #endif <file_sep>#ifndef _ANIMATEDSPR__MAIN_ #define _ANIMATEDSPR__MAIN_ #include <coleco.h> #endif <file_sep>/*--------------------------------------------------------------------------------- Copyright (C) 2018-2019 Alekmaul This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Image converter for colecovision. BMP BI_RLE8 compression support by <NAME> ***************************************************************************/ //INCLUDES #include "lodepic.h" //--------------------------------------------------------------------------- int PCX_Load(char *filename, pcx_picture_ptr image) { // this function loads a pcx file into a picture structure, the actual image // data for the pcx file is decompressed and expanded into a secondary buffer // within the picture structure, the separate images can be grabbed from this // buffer later. also the header and palette are loaded long num_bytes,index; long count; long x,y; unsigned char data; pcx_header *header; FILE *fp; // open the file fp = fopen(filename,"rb"); if(fp==NULL) { printf("\nERROR: Can't open file [%s]",filename); return 0; } // load the header header = &image->header; fread(header, 1, 128, fp); header->width++; header->height++; // check to make sure this is a 256 color PCX if( (header->manufacturer != 10) || (header->encoding != 1) || (header->bits_per_pixel != 8) || (header->num_color_planes != 1) || (header->palette_type != 1) ) { printf("\nERROR: File [%s] is not recognized as a 256 color PCX.",filename); fclose(fp); return 0; } //allocate memory for the picture + 64 empty lines image->buffer = malloc( (size_t)(header->height+64)*header->width ); if(image->buffer == NULL) { printf("\nERROR: Can't allocate enough memory for the picture."); fclose(fp); return 0; } //initally clear the memory (to make those extra lines be blank) memset(image->buffer,0,(size_t)(header->height+64)*header->width); // load the data and decompress into buffer count=0; for(y=0; y < header->height; y++) { for(x=0; x < header->width; x++) { // get the first piece of data data = getc(fp); // is this a rle? //if ( (data>=192) && (data<=255)) if (data>=192) { // how many bytes in run? num_bytes = data-192; x += (num_bytes-1); // get the actual data for the run data = getc(fp); // replicate data in buffer num_bytes times while( num_bytes-- > 0) image->buffer[count++] = data; } // end if rle else { // actual data, just copy it into buffer at next location image->buffer[count++] = data; } // end else not rle } //end of x loop //get rid of the padding byte if there is one if( x < header->bytes_per_line) data = getc(fp); } //end of y loop //Get the Palette header (one byte, should equal 12) data = getc(fp); if(data != 12) { printf("\nERROR: Couldn't find palette header [%s]",filename); free(image->buffer); fclose(fp); return 0; } //get the pallete data for (index=0; index<256; index++) { image->palette[index].red = (getc(fp) >> 3); image->palette[index].green = (getc(fp) >> 3); image->palette[index].blue = (getc(fp) >> 3); } //check to make sure there weren't errors while reading the file if(ferror(fp)) { printf("\nERROR: Error reading file [%s]",filename); free(image->buffer); fclose(fp); return 0; } fclose(fp); return -1; } // end PCX_Load //--------------------------------------------------------------------------- void BMP_BI_RLE8_Load(pcx_picture_ptr image, const bmp_header* const bmphead, const bmp_info_header* const bmpinfohead, FILE* fp) { // BI_RLE8 decompress according to: // https://technet.microsoft.com/ru-ru/dd183383 unsigned long line, i, count; // offset in image buffer where current line starts unsigned int pos; unsigned char ch, ch2; // start from bottom line line = bmpinfohead->biHeight; pos = (line-1) * bmpinfohead->biWidth; count = 0; // read all image bytes while (count < bmpinfohead->biSizeImage) { ch = getc(fp); ++count; if (ch) { // repeat byte ch2 = getc(fp); ++count; for (i = 0; i < ch; ++i) image->buffer[pos++] = ch2; continue; } // escape char ch = getc(fp); ++count; if (ch == 0) { // End of line. // go one line up --line; // start of this line. pos = (line-1) * bmpinfohead->biWidth; } else if (ch == 1) { // End of bitmap. break; } else if (ch == 2) { // Delta. // The two bytes following the escape contain unsigned values // indicating the horizontal and vertical offsets of the next pixel // from the current position. ch = getc(fp); ++count; // go right in the buffer pos += ch; ch = getc(fp); ++count; // go given lines up line -= ch; pos -= bmpinfohead->biWidth * ch; } else { // Absolute mode. // The second byte represents the number of bytes that follow, // each of which contains the color index of a single pixel. ch = getc(fp); ++count; for (i = 0; i < ch; ++i) { image->buffer[pos++] = getc(fp); ++count; } if (i%2) { // Each run must be aligned on a word boundary. // Read and throw away the placeholder. ch2 = getc(fp); ++count; } } } } // end BMP_BI_RLE8_Load //--------------------------------------------------------------------------- int BMP_Load(char *filename, pcx_picture_ptr image) { // this function loads a bmp file into a picture structure, the actual image // data for the bmp file is decompressed and expanded into a secondary buffer // within the picture structure, the separate images can be grabbed from this // buffer later. also the header and palette are loaded FILE *fp; int index,i; pcx_header *header; bmp_header bmphead; bmp_info_header bmpinfohead; // open the file fp = fopen(filename,"rb"); if(fp==NULL) { printf("\nERROR: Can't open file [%s]",filename); return 0; } // check to see if it is a valid bitmap file if (fread(&bmphead, sizeof(bmp_header), 1, fp) < 1) { printf("\nERROR: File [%s] has no correct BMP header.",filename); fclose(fp); return 0; } if (bmphead.bfType != BF_TYPE) { printf("\nERROR: File [%s] is not recognized as a BMP file.",filename); fclose(fp); return 0; } // check to see if it is a valid bitmap file if (fread(&bmpinfohead, sizeof(bmpinfohead), 1, fp) < 1) { printf("\nERROR: File [%s] has no correct BMP info header.",filename); fclose(fp); return 0; } if (bmpinfohead.biBitCount != 8 || (bmpinfohead.biCompression != 0 && bmpinfohead.biCompression != 1 /*BI_RLE8*/)) { printf("\nERROR: File [%s] is not a valid BMP file: 256 colors, non-compressed or BI_RLE8 supported.",filename); fclose(fp); return 0; } // seek to palette fseek(fp, sizeof(bmp_header) + bmpinfohead.biSize, 0); // initally clear the palette if there are less then 256 colors in the file memset(image->palette, 0, (size_t)(256 * sizeof(RGB_color))); // read the palette information for (index = 0; index<256; index++) { image->palette[index].blue = getc(fp) >> 3; image->palette[index].green = getc(fp) >> 3; image->palette[index].red = getc(fp) >> 3; //data=getc(fp); getc(fp); } header = &image->header; header->width = bmpinfohead.biWidth; header->height = bmpinfohead.biHeight; // allocate memory for the picture + 64 empty lines image->buffer = malloc( (size_t)(header->height+64) * header->width ); if(image->buffer == NULL) { printf("\nERROR: Can't allocate enough memory for the picture."); fclose(fp); return 0; } // initally clear the memory (to make those extra lines be blank) memset(image->buffer,0,(size_t)(header->height+64) * header->width); // seek to image data fseek(fp, bmphead.bfOffBits, 0); // read the bitmap if (bmpinfohead.biCompression == 0) { for(index=(header->height-1) * header->width;index>=0;index-=header->width) for(i=0;i<header->width;i++) image->buffer[index+i] = getc(fp); } else if (bmpinfohead.biCompression == 1) { // BI_RLE8 BMP_BI_RLE8_Load(image, &bmphead, &bmpinfohead, fp); } // check to make sure there weren't errors while reading the file if(ferror(fp)) { printf("\nERROR: Error reading file [%s]",filename); free(image->buffer); fclose(fp); return 0; } fclose(fp); return -1; } // end BMP_Load //--------------------------------------------------------------------------- int TGA_Load(char *filename, pcx_picture_ptr image) { // this function loads a tga file into a picture structure, the actual image // data for the bmp file is decompressed and expanded into a secondary buffer // within the picture structure, the separate images can be grabbed from this // buffer later. also the header and palette are loaded FILE *fp; long index,i; tga_header tgahead; pcx_header *header; // open the file fp = fopen(filename,"rb"); if(fp==NULL) { printf("\nERROR: Can't open file [%s]",filename); return 0; } // check to see if it is a valid bitmap file if (fread(&tgahead, sizeof(tga_header), 1, fp) < 1) { printf("\nERROR: File [%s] has no correct TGA header.",filename); fclose(fp); return 0; } //check to make sure there weren't errors while reading the file if(ferror(fp)) { printf("\nERROR: Error reading file [%s]",filename); free(image->buffer); fclose(fp); return 0; } if (tgahead.BPP != 8 || tgahead.ImageType != 1) { printf("\nERROR: File [%s] is not a valid indexed 256 colors TGA file.",filename); fclose(fp); return 0; } header = &image->header; header->width = tgahead.Width; header->height = tgahead.Height; //allocate memory for the picture + 64 empty lines image->buffer = malloc( (size_t)(header->height+64) * header->width ); if(image->buffer == NULL) { printf("\nERROR: Can't allocate enough memory for the picture."); fclose(fp); return 0; } //initally clear the memory (to make those extra lines be blank) memset(image->buffer,0,(size_t)(header->height+64) * header->width); // read the palette information for(index=0;index<256;index++) { image->palette[index].blue = getc(fp) >> 3; image->palette[index].green = getc(fp) >> 3; image->palette[index].red = getc(fp) >> 3; } // read the bitmap for(index=(header->height-1) * header->width;index>=0;index-=header->width) for(i=0;i<header->width;i++) image->buffer[index+i] = getc(fp); fclose(fp); return -1; } // end TGA_Load //--------------------------------------------------------------------------- int PNG_Load(char *filename, pcx_picture_ptr image) { unsigned error,sz,bpp; long i,index; unsigned char *pngimage; unsigned char* png = 0; size_t pngsize; LodePNGState state; unsigned int width, height;// , wal,hal; pcx_header *header; /*optionally customize the state*/ lodepng_state_init(&state); // no conversion of color (to keep palette mode) state.decoder.color_convert = 0; error = lodepng_load_file(&png, &pngsize, filename); if (!error) { error = lodepng_decode(&pngimage, &width, &height, &state, png, pngsize); } if(error) { printf("\nERROR: Decoder error %u: %s\n", error, lodepng_error_text(error)); free(png); lodepng_state_cleanup(&state); free(pngimage); return 0; } bpp = state.info_raw.bitdepth; if ( (bpp != 4) && (bpp != 8)) { printf("\nERROR: File [%s] is not a valid bbp value (%d bpp).",filename,bpp); free(png); lodepng_state_cleanup(&state); free(pngimage); return 0; } if (state.info_raw.colortype != LCT_PALETTE) { printf("\nERROR: File [%s] is not a valid indexed palette mode (mode %d).",filename,state.info_raw.colortype); free(png); lodepng_state_cleanup(&state); free(pngimage); return 0; } // read the palette information sz=state.info_png.color.palettesize; for(index=0;index<sz;index++) { image->palette[index].red = state.info_png.color.palette[(index*4) + 0]>>3; image->palette[index].green = state.info_png.color.palette[(index*4) + 1]>>3; image->palette[index].blue = state.info_png.color.palette[(index*4) + 2]>>3; } // get png information header = &image->header; header->width = width; header->height = height; printf("\nWidth %d Height %d",header->width,header->height); //allocate memory for the picture + 64 empty lines image->buffer = malloc( (size_t)(header->height+64) * header->width ); if(image->buffer == NULL) { printf("\nERROR: Can't allocate enough memory for the picture."); return 0; } //initally clear the memory (to make those extra lines be blank) memset(image->buffer,0,(size_t)(header->height+64) * header->width); // 4 bpps conversion if (bpp==4) { for (index = 0; index < header->height; index++) { for(i=0;i<header->width;i++) image->buffer[index+i] = pngimage[i +index*header->height]; } /* // get buffer size *size = (wAligned / 2) * hAligned; // and alloc result = malloc(*size); srcPix = 0; for (i = 0; i < h; i++) { unsigned char *dst = &result[i * (wAligned / 2)]; memset(dst, 0, wAligned / 2); for (j = 0; j < w; j++) { unsigned char v; if (srcPix & 1) v = (out[srcPix / 2] >> 4) & 0xF; else v = (out[srcPix / 2] >> 0) & 0xF; srcPix++; if (j & 1) dst[j / 2] = (dst[j / 2] & 0x0F) | (v << 4); else dst[j / 2] = (dst[j / 2] & 0xF0) | (v << 0); } } for(;i < hAligned; i++) memset(&result[i * (wAligned / 2)], 0, wAligned / 2); */ } // 8 bpps conversion else { for (index = 0; index < header->height; index++) { for(i=0;i<header->width;i++) { image->buffer[i+(header->width*index)] = pngimage[i+(header->width*index)]; } } } free(png); lodepng_state_cleanup(&state); free(pngimage); return -1; } // end PNG_Load <file_sep>/*--------------------------------------------------------------------------------- small game from coder <NAME> : Easter Bunny made by her during 2007 MiniGame Competition -- alekmaul ---------------------------------------------------------------------------------*/ #include "bunny.h" volatile u8 color_offset; volatile u8 flag_effect; /* game levels */ static u8 no_level; /* game properties */ u8 speed; const int gravity = 384; const int friction[] = {0,80,320,200,500,290,410,300,1024}; const int vy_min = -2048; const int vy_max = 2048; const int vx_min = -1024; const int vx_max = 1024; typedef struct { unsigned y; unsigned x; int vy; int vx; int speed; u8 state; } player_t; player_t player; u8 nbr_keys_left; static void updatey_(u8 y) { sprites[0].y = y; sprites[1].y = y; y-=8; sprites[2].y = y; sprites[3].y = y; } static void updatey(void) { u8 y; y = player.y>>8; updatey_(y); } static void updatex_(u8 x) { sprites[0].x = x; sprites[1].x = x; sprites[2].x = x; sprites[3].x = x; } static void updatex(void) { u8 x; x = player.x>>8; updatex_(x); } static void slide_sprite(void) { u8 i = sprites[0].x; u8 j = player.x>>8; if (i<j) i++; if (i>j) i--; updatex_(i); i = sprites[0].y; j = player.y>>8; if (i<j) i++; if (i>j) i--; updatey_(i); } static void smoke(void) { sprites[4].y = (player.y>>8)+2; sprites[4].pattern = 0x26; sprites[4].colour = 0x0f; } static void update_smoke(void) { if (sprites[4].pattern == 0x2a) { sprites[4].y = (u8) 0xf0; } else { sprites[4].y -= 4; sprites[4].x = player.x>>8; sprites[4].pattern++; } } static void bird(void) { sprites[5].x = 128; sprites[5].y = 0; sprites[5].pattern = 44; sprites[5].colour = 0x0f; } static void update_bird(void) { u8 i; u8 j; i = sprites[5].y; j = sprites[0].y; if (i<j) i++; if (i>j) i--; sprites[5].y=i; i = sprites[5].x; j = sprites[0].x; if (i<j) { i++; sprites[5].pattern=44+(i&1); } if (i>j) { i--; sprites[5].pattern=46+(i&1); } sprites[5].x=i; } char bird_kill(void) { u8 kill = 0; u8 dx = (sprites[0].x-sprites[5].x); u8 dy = (sprites[0].y-sprites[5].y); dx = (dx>0x7f) ? dx : dx&0x7f; dy = (dy>0x7f) ? dy : dy&0x7f; if ( dx < 3 && dy < 5) kill = (u8)-1; return kill; } static void update_state() { u8 i; u8 c[2]; u8 cx[2]; u8 cy; int rest_y; u8 nbr = 2; cx[0] = sprites[0].x + 2; cx[0] >>= 3; cx[1] = sprites[0].x + 5; cx[1] >>= 3; if (cx[0]==cx[1]) nbr=1; cy = sprites[0].y+9; rest_y = cy & 7; rest_y <<=8; cy >>= 3; player.state = AIR; for (i=0;i<nbr;i++) { c[i] = vdp_getchar(cx[i],cy); if ((c[i]&0xf0)==0x10) { c[i]++; vdp_putchar(cx[i],cy,c[i]); if ((player.state & AIR) && (player.vy>=0)) { player.state = NONE; player.y -= rest_y; player.y &= 0xff00; updatey(); } player.state |= GRASS; } else { if ((c[i]&0xfc)==0x0c) { if ((player.state & AIR) && (player.vy>=0)) { player.state = NONE; player.y -= rest_y; player.y &= 0xff00; updatey(); } if (c[i]==0x0c) { player.state |= ICE; } if (c[i]==0x0d) { player.state |= GRASS; } if (c[i]==0x0e) { player.state |= SAND; } if (c[i]==0x0f) { player.vy = vy_min<<1; player.state = AIR; smoke(); snd_startplay(3); i = nbr; } } } } i = sprites[0].x + 3; i >>= 3; cy = sprites[0].y - 6; cy >>= 3; c[0] = vdp_getchar(i,cy); c[1] = vdp_getchar(i,cy+1); if (c[0]==0x21) { vdp_putchar(i,cy,0x20); nbr_keys_left--; snd_startplay(1); } if (c[1]==0x21) { vdp_putchar(i,cy+1,0x20); nbr_keys_left--; snd_startplay(1); } } static void update_player_y(void) { if (player.state & AIR) { player.vy += gravity; if (player.vy > vy_max) player.vy = vy_max; } else { player.vy = 0; if (joypad_1 & PAD_FIRE1) { player.vy = vy_min; player.state = AIR; snd_startplay(2); } } player.y += player.vy; updatey(); } static void update_player_x(void) { int abs_vx = player.vx & 0x7fff; if (joypad_1 & (PAD_LEFT | PAD_RIGHT)) { if (joypad_1 & PAD_LEFT) player.vx -= player.speed; if (joypad_1 & PAD_RIGHT) player.vx += player.speed; } else { if (abs_vx > 0) { if ((player.state & AIR)!=AIR) { int f = friction[player.state]; if (player.vx<0) { if (abs_vx > f) { player.vx += f; } else { player.vx = 0; } } else { if (abs_vx > f) { player.vx -= f; } else { player.vx = 0; } } } } } if (player.vx < vx_min) player.vx = vx_min; if (player.vx > vx_max) player.vx = vx_max; player.x += player.vx; if (player.x < 0x1000 || player.x > 0xE800) { player.vx = -player.vx; player.x += player.vx; } } static void update_player(void) { update_player_x(); update_player_y(); update_state(); /* Set Player Sprite Pattern */ if (player.vx>128) { player_sprite(4); } if (player.vx<128) { player_sprite(8); } if (player.vx==0) { player_sprite(0); } /* Set Player Sprite Position */ updatey(); updatex(); /* update smoke animation */ update_smoke(); /* update bird animation */ update_bird(); /* update_eggs(); */ /* Update Sprites on Screen */ vdp_putvram(sprgen, sprites, 25); } static const u8 floor_pattern[] = {0x99,0x66,0xdd,0x77,0xdd,0x77,0x99,0x66}; /* Initialise characters graphics in VideoRAM */ static void init_graphics(void) { /* Load characters pattern and color */ vdp_rle2vram(PATTERNRLE,chrgen); vdp_putvram_repeat (0x0060,floor_pattern,8,7); vdp_duplicatevram(); vdp_rle2vram(COLORRLE,0x2000); /* Set sprites pattern as characters pattern */ vdp_setreg(6,0); } const u8 left_border[]={0x24,0x23}; const u8 right_border[]={0x25,0x26}; static void decode_level(u8 *level) { u8 x; u8 count; u8 item; u8 y=0; u8 *offset = level; nbr_keys_left = 0; count = read_next_code(&item, *offset++); loop_y: vdp_waitvblank(1); vdp_putchar(0,y,left_border[0]); vdp_putchar(1,y,left_border[1]); x = 2; loop_x: if (y==23 && item==0x20) item=0xf; if (item==0x22) { vdp_putchar(x,y-1,0x21); nbr_keys_left++; } if (item==0) { item=0x20; player.x = (unsigned) x; player.x <<= 11; player.y = (unsigned) y; player.y <<= 3; player.y--; player.y <<= 8; player.vx = 0; player.vy = 0; player.speed = 128; player.state = NONE; } vdp_putchar(x,y,item); count--; if (count==0) count = read_next_code(&item, *offset++); x++; if (x<30) goto loop_x; vdp_putchar(30,y,right_border[0]); vdp_putchar(31,y,right_border[1]); y++; if (y<24) goto loop_y; } static void anim_getready(void) { u8 i; player_sprite(0); for (i=0;i<224;i++) { vdp_waitvblank(1); slide_sprite(); invincible(i); vdp_putvram(sprgen, sprites, 25); } vdp_waitvblank(1); sprites[4].y = 0xd0; sprites[5].y = 0xd0; vdp_putvram(sprgen, sprites, 25); } static void game(void) { u8 level_done = 0; decode_level((char*) levels[no_level&7]); snd_startplay(4); anim_getready(); bird(); /* Start BGSound */ while(!level_done) { vdp_waitvblank(speed); update_player(); if (nbr_keys_left == 0) {no_level++; level_done = (u8)-1;} if (bird_kill()) {snd_startplay(5); level_done=(u8)-1;} /* if (player.y >= 0xE000 && player.y <= 0xF000) level_done = -1; */ } vdp_waitvblank(30); /* Stop All Sounds */ snd_stopplay(1); snd_stopplay(2); snd_stopplay(3); vdp_waitvblank(1); } /* main function : starting point of any C program */ void main(void) { snd_settable(snd_table); /* Default screen mode 2 setting is done in crtcv.as file */ vdp_setmode2txt(); /* Set Sprites to 8x8 pixels */ spr_mode8x8(); /* Initialise graphics and sounds */ init_graphics(); vdp_rle2vram(NAMERLE,0x1800); vdp_enablevdp(); snd_startplay(6); snd_startplay(7); flag_effect = (u8)-1; vdp_enablenmi(); // NMI running from now till the end of the game! speed = 5 - sys_choice_keypad1(1,3); //choice_keypad1(1,3); flag_effect = 0; snd_stopplay(6); snd_stopplay(7); speed = 2; /* Set Player Sprite Color */ player_color(); /* Play game */ no_level=0; while(1) game(); /* END */ } static const u8 colors[] = { 0xd1,0xd1,0xd1,0x51, 0xd1,0x51,0x51,0x51, 0xc1,0x51,0xc1,0xc1, 0xc1,0x21,0xc1,0x21, 0x21,0x21,0x31,0x21, 0x31,0x31,0x31,0xa1, 0x31,0xa1,0xa1,0xa1, 0x91,0xa1,0x91,0x91, 0x91,0x81,0x91,0x81, 0x81,0x81,0xd1,0x81, 0xd1,0xd1,0xd1,0x51, 0xd1,0x51,0x51,0x51, 0xc1,0x51,0xc1,0xc1, 0xc1,0x21,0xc1,0x21, }; void nmi(void) { if (flag_effect) { color_offset++; if (color_offset > 39) color_offset = 0; vdp_putvram_repeat (0x2400,&colors[color_offset],8,12); vdp_putvram_repeat (0x2460,&colors[color_offset+8],8,12); } } <file_sep>#ifndef LODEPIC_H #define LODEPIC_H #include <stdio.h> #include <malloc.h> #include <string.h> #include "lodepng.h" #pragma pack(1) // for bmp header to avoid data alignment //STRUCTURES typedef struct RGB_color_typ { unsigned char red; //Red component if color 0-63 unsigned char green; //Green component of color 0-63 unsigned char blue; //Blue component of color 0-63 } RGB_color, *RGB_color_ptr; typedef struct pcx_header_typ { char manufacturer; // Always 10. char version; // 0-Ver 2.5 Paintbrush, 2-Ver 2.8 with // palette, 3-Ver 2.8 use the default palette, // 5-Ver 3.0 or higher of Paintbrush char encoding; // Always 1, meaning RLE encoding. char bits_per_pixel; // Bits per pixel; in our case, eight short x,y; // Upper-left corner of the image short width, height; // Size of the image short horv_res; // Pixels in the x direction short vert_res; // Pixels in the y direction char ega_palette[48]; // The EGA palette; we can ignore it char reserved; // Nothing char num_color_planes; // The number of planes in the image short bytes_per_line; // Bytes per one horizontal line short palette_type; // 1 = Color or B&W 2 = Grayscale char padding[58]; // Extra bytes for a rainy day } pcx_header, *pcx_header_ptr; typedef struct pcx_picture_typ { pcx_header header; // The header RGB_color palette[256]; // The VGA palette unsigned char *buffer; // The buffer to hold the image } pcx_picture, *pcx_picture_ptr; typedef struct bmp_header_typ // *** BMP file header structure *** { unsigned short bfType; // Magic number for file unsigned int bfSize; // Size of file unsigned short bfReserved1; // Reserved unsigned short bfReserved2; // ... unsigned int bfOffBits; // Offset to bitmap data } bmp_header; # define BF_TYPE 0x4D42 // "MB" typedef struct bmp_info_header_typ { unsigned int biSize; // Size of info header int biWidth; // Width of image int biHeight; // Height of image unsigned short biPlanes; // Number of color planes unsigned short biBitCount; // Number of bits per pixel unsigned int biCompression; // Type of compression to use unsigned int biSizeImage; // Size of image data int biXPelsPerMeter; // X pixels per meter int biYPelsPerMeter; // Y pixels per meter unsigned int biClrUsed; // Number of colors used unsigned int biClrImportant; // Number of important colors } bmp_info_header; typedef struct tga_hearder_type { unsigned char Offset; // Usually 0, add 18 to this value to find the start of the palette/image data. unsigned char ColorType; // Image type. 0 = RGB, 1 = Indexed. unsigned char ImageType; // 0 = None, 1 = Indexed, 2 = RGB, 3 = Greyscale, +8 = RLE encoded. unsigned short PaletteStart; // Start of palette. unsigned short PaletteLen; // Number of palette entries. unsigned char PalBits; // Bits per colour entry. unsigned short XOrigin; // Image X Origin unsigned short YOrigin; // Image Y Origin unsigned short Width; // Image width (Pixels). unsigned short Height; // Image height (Pixels) unsigned char BPP; // Bits per pixel (8,16,24 or 32) unsigned char Orientation; // If Bit 5 is set, the image will be upside down (like BMP) } tga_header; //--------------------------------------------------------------------------- extern int PCX_Load(char *filename, pcx_picture_ptr image); extern int BMP_Load(char *filename, pcx_picture_ptr image); extern int TGA_Load(char *filename, pcx_picture_ptr image); extern int PNG_Load(char *filename, pcx_picture_ptr image); #endif <file_sep>#ifndef _HELLOWORLD_MAIN_ #define _HELLOWORLD_MAIN_ #include <coleco.h> #endif <file_sep>#ifndef _SGMTEST_MAIN_ #define _SGMTEST_MAIN_ #include <coleco.h> #endif <file_sep>cmake_minimum_required (VERSION 3.1) project(bin2txt C) set(bin2txt_major_version 1) set(bin2txt_minor_version 0) set(bin2txt_path_version 0) set(bin2txt_version "${bin2txt_major_version}.${bin2txt_minor_version}.${bin2txt_path_version}") if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug") endif() set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}") set(CMAKE_C_STANDARDS 11) configure_file(config.h.in config.h) set(bin2txt_sources bin2txt.c ) set(bin2txt_headers config.h ) add_executable(bin2txt ${bin2txt_sources} ${bin2txt_headers}) target_compile_options(bin2txt PRIVATE -Wall -Wshadow -Wextra) target_include_directories(bin2txt PRIVATE ${CMAKE_BINARY_DIR}) install(TARGETS bin2txt RUNTIME DESTINATION bin) <file_sep>#ifndef _MEGACART_MAIN_ #define _MEGACART_MAIN_ #include <coleco.h> #endif
830edf29f4f05858ac7fb91f676d65de371b5983
[ "CMake", "Markdown", "Makefile", "Text", "C" ]
99
Markdown
alekmaul/pvcollib
fb6eff5fe6ddff630c24aa947b70fa9ca990613d
debee725a0984ef6db5a9a3dd5a07577b1159d3b
refs/heads/main
<file_sep>import React from 'react'; import '../App.css'; import Navbar from './Navbar'; function Products() { return ( <> <Navbar/> {/*<h4 style={{"color":"white","textAlign":"center"}}>Read The Article about Synchronous Online Learning</h4> */} <p className='products'><a style={{"color":"white" }} href="https://er.educause.edu/articles/2008/11/asynchronous-and-synchronous-elearning">Article For Synchronous Online Learning</a></p>; </> ); } export default Products;<file_sep>import * as actionCreators from "../action/action"; const initialState = { returnedMessage: "", studentObj: "", registrationSuccess: "", studentList: [], questionList: [], questionObj: { questionId: "", question: "", option1: "", option2: "", option3: "", option4: "", correctAnswer: "", } } const reducer = (state = initialState, action) => { switch (action.type) { case actionCreators.REQUEST_REGISTRATION: let message = action.payload; return { registrationStatus: message, }; case actionCreators.CLEAR_STATE: return { returnedMessage: "", studentObj: "", studentList : [] } case actionCreators.GET_ALL_QUESTIONS: let listOfQuestions = action.payload; return { returnedMessage: "Course Details!", questionList: listOfQuestions, }; case actionCreators.DELETE_QUESTION: let listAfterDeletion = action.payload; return { returnedMessage: "Question Deleted", questionList: listAfterDeletion, }; case actionCreators.ADD_QUESTION: let listAfterAdditionQuestion = action.data.questions; return { returnedMessage: "Question Added", questionList: listAfterAdditionQuestion, }; case actionCreators.UPDATE_QUESTION: let listAfterUpdationQuestion = action.data.questions; return { returnedMessage: "Question Updated", questionList: listAfterUpdationQuestion, }; case actionCreators.GET_QUESTION_BY_ID: let listOfQuestionById = action.payload; return { questionObj: listOfQuestionById, }; default: return state; } }; export default reducer;<file_sep>import axios from 'axios'; const STUDENT_API_BASE_URL = "http://ec2-18-191-253-178.us-east-2.compute.amazonaws.com:8080/api/educationsystem/student"; class StudentService { getStudents(){ return axios.get(STUDENT_API_BASE_URL + "/view-all-studnets"); } registerStudent(student){ return axios.post(STUDENT_API_BASE_URL + "/add-student", student ); } findStudentById(sId){ return axios.get(STUDENT_API_BASE_URL + '/view-studnet/' + sId); } } export default new StudentService() <file_sep>import React from 'react'; import '../App.css'; import Navbar from './Navbar'; function Shiftings(){ return ( <> <Navbar/> {/* <h4 style={{"color":"white","textAlign":"center"}}>Read The Article about Fixed E-Learning</h4> */} <p className='shiftings'><a style={{"color":"white" }} href="https://e-student.org/types-of-e-learning/#fixed-e-learning">Article For Fixed E-Learning</a></p>; </> ); } export default Shiftings;<file_sep>import React, { Component } from 'react' import AttendanceService from '../services/AttendanceService' import '../css/Attendance.css' import TeacherNavbar from './TeacherNavbar' import Cards from './Cards' class Attendance extends Component { constructor(props) { super(props) this.state = { attendance: [] } } componentDidMount(){ AttendanceService.getAttendance().then((res) => { console.log(res.data); this.setState({ attendance: res.data}); }); } render() { return ( <div> <TeacherNavbar/> {/* <h2 className="text-center">Student List</h2> */} {/* <div className = "row"> <button className="btn btn-primary"> Add Student</button> </div> */} <br></br> <div className = "row"> <div className="attendance-table"> <h2 className="text-center">Attendance</h2> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Attendance Id</th> <th>Student Name </th> <th> Date </th> </tr> </thead> <tbody> { this.state.attendance.map( attendance => <tr key = {attendance.attendanceId}> <td> {attendance.attendanceId} </td> <td> {attendance.studentUsername} </td> <td> {attendance.date}</td> </tr> ) } </tbody> </table></div> </div> {/* <Cards/> */} </div> ) } } export default Attendance <file_sep>import React, { Component } from 'react' import StudentNavbar from './StudentNavbar' import '../css/ViewProgress.css' import ProgressService from '../services/ProgressService' class ViewProgress extends Component { constructor(props) { super(props) this.state = { score: 0, tests: [] } } componentDidMount() { ProgressService.getTestsForStudent(5).then((res) => { console.log(res.data); this.setState({ tests: res.data }); }); } render() { return ( <div> <StudentNavbar /> {/* <div className="progressBar"> <h2 className="text-center">Progress</h2> <div class="progress"> {this.state.tests.map( test => <div class="progress-bar bg-success" role="progressbar" style={{ width: "{test.score}" }} aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"></div> ) } <div class="progress-bar" role="progressbar" style={{ width: "15%" }} aria-valuenow="15" aria-valuemin="0" aria-valuemax="100"></div> <div class="progress-bar bg-success" role="progressbar" style={{ width: "30%" }} aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"></div> <div class="progress-bar bg-info" role="progressbar" style={{ width: "20%" }} aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div> </div> */} <br></br> <div className = "row"> <div className="progress-table"> <h2 className="text-center">Progress</h2> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Test Name</th> <th> Score</th> <th> Total Score</th> </tr> </thead> <tbody> { this.state.tests.map( test => <tr key = {test.testId}> <td> {test.t_name} </td> <td> {test.score} </td> <td> {test.totalScore}</td> {/* <td> <button className="btn btn-info">Update </button> <button style={{marginLeft: "10px"}} className="btn btn-danger">Delete </button> <button style={{marginLeft: "10px"}} className="btn btn-info">View </button> </td> */} </tr> ) } </tbody> </table> </div> </div> </div> // </div> ) } } export default ViewProgress <file_sep>import React from 'react'; import '../css/Cards.css'; import CardItem from './CardItem'; import hm1 from '../images/hm1.png' import hm2 from '../images/hm2.png' import hm3 from '../images/hm3.png' function HmCard() { return ( <div className='cards'> <h3 className= 'studentdash'> Welcome </h3> <div className='cards__container'> <div className='cards__wrapper'> <ul className='cards__items'> <CardItem src={hm1} text='Teachers dont just teach they prepare us for the road ahead....' label='Teachers' path="/teacher-list" /> <CardItem src={hm2} text='Strive for progress, not perfection.' label='Students' path='/hm-student-list' /> <CardItem src={hm3} text='A Session is an oral presentation to teach people.' label='Sessions' path='/hm-show-session' /> </ul> </div> </div> </div> ); } export default HmCard;<file_sep>import React, { Component } from 'react' import SessionService from '../services/SessionService'; class CreateSessionComponent extends Component { constructor(props) { super(props) this.state = { // step 2 sessionId: this.props.match.params.sessionId, coursename: '', stime: '' // emailId: '' } this.changeCoursenameHandler = this.changeCoursenameHandler.bind(this); this.changeStimeHandler = this.changeStimeHandler.bind(this); this.saveOrUpdateSession = this.saveOrUpdateSession.bind(this); } componentDidMount() { if (this.state.sessionId === '_add') { return } else { SessionService.findSessionById(this.state.sessionId).then((res) => { let sessionSchedule = res.data; this.setState({ userName:sessionSchedule.coursename, stime: sessionSchedule.stime, // quantity: sessionSchedule.quantity, //quotePrice: sessionSchedule.quotePrice, }); }); } } saveOrUpdateSession = (e) => { e.preventDefault(); let sessionSchedule = { coursename: this.state.coursename,stime: this.state.stime }; //product: this.state.product console.log('sessionSchedule => ' + JSON.stringify(sessionSchedule)); if(this.state.sessionId === '_add'){ SessionService.createSession(sessionSchedule).then(res =>{ this.props.history.push('/session'); }); }else{ SessionService.updateSession(sessionSchedule, this.state.sessionId).then( res => { this.props.history.push('/session'); }); } } changeCoursenameHandler = (event) => { this.setState({ coursename: event.target.value }); } changeStimeHandler = (event) => { this.setState({ stime: event.target.value }); } /* addSession() { this.props.history.push('/add-session/_add'); } */ cancel() { this.props.history.push('/session'); } getTitle(){ if(this.state.sessionId === '_add'){ return <h3 className="text-center">Add Session</h3> }else{ return <h3 className="text-center">Update Session</h3> } } /* componentDidMount() { fetch('http://localhost:8081/api/v1/addStudent') .then(response => response.json()) .then(student => this.setState({ student: student })) } */ render() { return ( <div> <br></br> <div className="container"> <div className="row"> <div className = "card col-md-6 offset-md-3 offset-md-3"> { this.getTitle() } <div className="card-body"> <form> <div className = "form-group"> <label> Course Name: </label> <input placeholder="Course Name" name="coursename" className="form-control" value={this.state.coursename} onChange={this.changeCoursenameHandler}/> </div> <div className = "form-group"> <label> Session Time: </label> <input placeholder="Session Time" name="stime" className="form-control" value={this.state.stime} onChange={this.changeStimeHandler}/> </div> <button className="btn btn-success" onClick={this.saveOrUpdateSession}>Save</button> <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button> </form> </div> </div> </div> </div> </div> ) } } export default CreateSessionComponent <file_sep>import React from 'react'; import '../css/Footer.css'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faPhone, faEnvelope, faLock, faUndo, faUserPlus, faUser, faUsers,faAddressCard,faMapMarker } from "@fortawesome/free-solid-svg-icons"; function Footer() { return ( <div className='footer-container'> <section className='footer-subscription'> <p className='footer-subscription-heading'> </p> <p className='footer-subscription-text'> </p> </section> <div class='footer-links'> <div className='footer-link-wrapper'> <div class='footer-link-items'> <h2>About Us</h2> <Link to='/'>Added Flexibility and Self-Paced Learning.</Link> <Link to='/'> Better Time Management </Link> <Link to='/'>Improved Virtual Communication and Collaboration</Link> <Link to='/about'>Refined Critical-thinking Skills</Link> </div> <div class='footer-link-items'> <h2><Link to="/"></Link>Contact Us</h2> <Link to='/'> <FontAwesomeIcon icon={faMapMarker} /> &nbsp;Address</Link> <Link to='/'>4321 California St, San Francisco, CA 12345</Link> <Link to='/'> <FontAwesomeIcon icon={faPhone} /> &nbsp; Phone</Link> <Link to='/'> +1 123 456 1234</Link> <Link to='/'> <FontAwesomeIcon icon={faEnvelope} /> &nbsp; Email</Link> <Link to='/'><EMAIL></Link> </div> </div> </div> <section class='social-media'> <div class='social-media-wrap'> <div class='footer-logo'> <Link to='/' className='social-logo'> Educare <i class='fab fa-typo3' /> </Link> </div> <small class='website-rights'>Educare © 2021</small> <div class='social-icons'> <Link class='social-icon-link facebook' to='/' target='_blank' aria-label='Facebook' > <i class='fab fa-facebook-f' /> </Link> <Link class='social-icon-link instagram' to='/' target='_blank' aria-label='Instagram' > <i class='fab fa-instagram' /> </Link> <Link class='social-icon-link youtube' to='/' target='_blank' aria-label='Youtube' > <i class='fab fa-youtube' /> </Link> <Link class='social-icon-link twitter' to='/' target='_blank' aria-label='Twitter' > <i class='fab fa-twitter' /> </Link> <Link class='social-icon-link twitter' to='/' target='_blank' aria-label='LinkedIn' > <i class='fab fa-linkedin' /> </Link> </div> </div> </section> </div> ); } export default Footer; <file_sep>import React, { Component } from 'react' import TeacherService from '../services/TeacherService' import '../css/ListTeachers.css' import HmNavbar from './HmNavbar' class ListTeachers extends Component { constructor(props) { super(props) this.state = { teachers: [] } } componentDidMount(){ TeacherService.getTeachers().then((res) => { console.log(res.data); this.setState({ teachers: res.data}); }); } render() { return ( <div> <HmNavbar/> {/* <h2 className="text-center">Student List</h2> */} {/* <div className = "row"> <button className="btn btn-primary"> Add Student</button> </div> */} <br></br> <div className = "row"> <div className="teacher-table"> <h2 className="text-center">Teacher List</h2> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Teacher Id</th> <th> Username</th> <th> Password</th> </tr> </thead> <tbody> { this.state.teachers.map( teacher => <tr key = {teacher.teacherId}> <td> {teacher.teacherId}</td> <td> {teacher.userName}</td> <td> {teacher.password}</td> </tr> ) } </tbody> </table> </div> </div> </div> ) } } export default ListTeachers <file_sep>import React from 'react'; import '../App.css'; import HmCard from './HmCard'; import HmNavbar from './HmNavbar'; function HmHome() { return ( <> <HmNavbar/> <HmCard/> </> ); } export default HmHome;<file_sep>import React, { Component } from 'react' import SessionService from '../services/SessionService' import "../css/ListSession.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faHome, faUserGraduate, faUserCog, faTrashAlt,faEdit,faPhone, faEnvelope, faLock, faUndo, faUserPlus, faUser, faLaptopHouse, faLaptopCode } from "@fortawesome/free-solid-svg-icons"; import { Link } from 'react-router-dom'; import HmNavbar from './HmNavbar'; class HmViewSessionListComponent extends Component { constructor(props) { super(props) this.state = { session: [] } this.addSession = this.addSession.bind(this); this.editSession = this.editSession.bind(this); this.deleteSession = this.deleteSession.bind(this); } deleteSession(sessionId) { SessionService.deleteSession(sessionId).then(res =>{ this.setState({session:this.state.session.filter(sessionSchedule => sessionSchedule.sessionId !==sessionId)}); }); } viewSession(sessionId) { this.props.history.push(`/view-session/${sessionId}`); } editSession(sessionId) { this.props.history.push(`/add-session/${sessionId}`); } componentDidMount(){ SessionService.getAllSession().then((res) => { console.log("service "); this.setState({ session: res.data }); }); } addSession(){ this.props.history.push('/add-session/_add'); } /* componentDidMount(){ //PurchaseService.getPurchase().then((res) => { // this.setState({ purchase: res.data}); SessionService.getAllTeacher().then((res) => { console.log("service "); this.setState({ session: res.data }); }); } */ addSession() { this.props.history.push('/add-session/_add'); } redirect = () => { window.location.href = 'http://ec2-18-191-253-178.us-east-2.compute.amazonaws.com:8080'; // maybe can add spinner while loading return null; } render(){ return( <div> <HmNavbar/> <div className="body_wrap "> <div> <h2 className="box_title">Session List (Timetable)</h2> <div className = "row"> {/* <button className="btn btn-primary" onClick={this.addSession}> Add Session</button> */} <button className="btn btn-primary" onClick={this.redirect}> Go to chat</button> </div> <br></br> <div className = "row"> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Session Course Name</th> <th> Session Time</th> <th> Actions</th> </tr> </thead> <tbody> { this.state.session.map( student => <tr key = {student.sessionId}> <td> { student.coursename} </td> <td> {student.stime}</td> <td> {/* <button onClick={ () => this.editSession(student.sessionId)} className="btn btn-info">Update </button> <button style={{marginLeft: "10px"}} onClick={ () => this.deleteSession(student.sessionId)} className="btn btn-danger">Delete </button> */} <button style={{marginLeft: "10px"}} onClick={ () => this.viewSession(student.sessionId)} className="btn btn-info">View </button> </td> </tr> ) } </tbody> </table> </div> </div> </div> </div> ) } } export default HmViewSessionListComponent <file_sep>import axios from 'axios'; const PROGRESS_API_BASE_URL = "http://ec2-18-191-253-178.us-east-2.compute.amazonaws.com:8080/api/educationsystem/student"; class ProgressService { getTestsForStudent(studentId){ return axios.get(PROGRESS_API_BASE_URL + "/view-tests/" + studentId); } } export default new ProgressService() <file_sep>import React from 'react'; import './App.css'; import { BrowserRouter as Router, Route } from 'react-router-dom' import Home from './components/Home'; import ListStudents from './components/ListStudents'; import ListTeachers from './components/ListTeachers'; import ViewProgress from './components/ViewProgress'; import StudentRegistration from './components/StudentRegistration'; import StudentLogin from './components/StudentLogin'; import AdminLogin from './components/AdminLogin'; import TeacherLogin from './components/TeacherLogin'; import StudentHome from './components/StudentHome'; import TeacherHome from './components/TeacherHome'; import Test from './components/Test'; import AttemptTest from './components/AttemptTest'; import TestQuestion from './components/TestQuestion'; import AddTest from './components/AddTest'; import Attendance from './components/Attendance'; import ListSessionComponent from './components/ListSessionComponent'; import HmHome from './components/HmHome'; import StudentViewSessionListComponent from './components/StudentViewSessionListComponent'; import HmViewSessionListComponent from './components/HmViewSessionListComponent'; import HmViewStudents from './components/HmViewStudents'; import Services from './components/Services'; import Products from './components/Products'; import Organics from './components/Organics'; import SignUp from './components/SignUp'; import Shiftings from './components/Shiftings'; import SubmitTest from './components/SubmitTest'; import CreateSessionComponent from './components/CreateSessionComponent'; import ViewSessionComponent from './components/ViewSessionComponent'; import UpdateSessionComponent from './components/UpdateSessionComponent'; function App() { return ( <div> <Router> <Route path='/' exact component={Home} /> <Route path='/student-list' exact component={ListStudents} /> <Route path='/hm-student-list' exact component={HmViewStudents} /> <Route path='/teacher-list' exact component={ListTeachers} /> <Route path='/progress' exact component={ViewProgress} /> <Route path='/registration' exact component={StudentRegistration} /> <Route path='/student-login' exact component={StudentLogin} /> <Route path='/admin-login' exact component={AdminLogin} /> <Route path='/teacher-login' exact component={TeacherLogin} /> <Route path='/studentdash' component={StudentHome} /> <Route path='/teacherdash' component={TeacherHome} /> <Route path='/hmdash' component={HmHome} /> <Route exact path="/add-test" component={AddTest} /> <Route exact path="/submit" component={SubmitTest} /> <Route exact path="/attempt-test" component={AttemptTest} /> <Route exact path="/test" component={Test} /> <Route exact path="/test-question" component={TestQuestion} /> <Route exact path="/attendance" component={Attendance} /> <Route exact path="/session" component={ListSessionComponent} /> <Route exact path="/show-session" component={StudentViewSessionListComponent} /> <Route exact path="/hm-show-session" component={HmViewSessionListComponent} /> <Route path='/services' component={Services} /> <Route path='/products' component={Products} /> <Route path='/organics' component={Organics} /> <Route path='/sign-up' component={SignUp} /> <Route path='/shiftings' component={Shiftings} /> <Route path = "/add-session/:sessionId" component = {CreateSessionComponent}></Route> <Route path = "/view-session/:sessionId" component = {ViewSessionComponent}></Route> <Route path = "/update-session/:sessionId" component = {UpdateSessionComponent}></Route> </Router> </div> ); } export default App;<file_sep>import React, { Component } from "react"; import logo from "../images/test.jpg"; // import avtar from "../images/avatar.svg"; import { Link } from "react-router-dom"; import StudentNavbar from "./StudentNavbar"; import Footer from "./Footer"; import "../css/Test.css"; class Test extends Component { constructor(props) { super(props); this._onButtonClick = this._onButtonClick.bind(this); } _onButtonClick() { window.open("/attempttest"); } render() { return ( <div> <StudentNavbar/> <img src={logo} className="wave" alt="logo" /> <div className="container-fluid"> <div className="row"> <div className="col"> <div className="test-container"> {/* <img src={avtar} className="avatar" alt="avtar" /> */} </div> <div className="div-welcome"> <b><h2 className="h2"> Begin the Quiz</h2></b> </div> <br /> <div className="div-instruct"> <h3 className="h3"> Instructions Before Proceeding </h3> <hr /> <ol> <li className="li"> Please read all the questions carefully. </li> <li className="li">No use of calculators are allowed.</li> <li className="li"> Do not minimize the screen or switch to other tabs. </li> <li className="li"> Total Duration of examination is 30 minutes. </li> <li className="li"> Number of Questions : 10 with <u>1 mark each.</u> </li> </ol> </div> <br /> <div className="div-btn"> <Link to="/attempt-test"> <button className="float-left btn btn-primary btn-block rounded-pill submit-button"> Begin Test </button> </Link> </div> </div> </div> </div> </div> ); } } export default Test; <file_sep>import React from 'react'; import '../App.css'; import Navbar from './Navbar'; function Services() { //<p className='services'>Read The Article about Organic Farming</p> return ( <> <Navbar/> {/*<h4 style={{"color":"white","textAlign":"center"}}>Read The Article about Computer Managed Learning</h4>*/} <p className='services'><a style={{"color":"white" }} href="https://educationaltechnologyjournal.springeropen.com/articles/10.1186/s41239-017-0063-0">Article For Computer Managed Learning</a></p>; </> ); } export default Services;<file_sep>import React, { Component } from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import Navbar from "./Navbar"; import Footer from "./Footer"; class Result extends Component{ render() { return ( <div className="div-btn"> <div className="mb-3 row"> <label htmlFor="score" className="col-sm-4 col-form-label"> Score </label> </div> </div> ); } }<file_sep>import React from 'react'; import '../css/Cards.css'; import CardItem from './CardItem'; import im8 from '../images/img8.jpg'; import im9 from '../images/img9.jpg'; import im10 from '../images/img10.jpg'; function TeacherCard() { return ( <div className='cards'> <h3 className= 'studentdash'> Welcome </h3> <div className='cards__container'> <div className='cards__wrapper'> <ul className='cards__items'> <CardItem src={im8} text='A Session is an oral presentation to teach people' label='Sessions' path="/session" /> <CardItem src={im9} text='Dont watch the clock. Do what it does....' label='Tests' path='/add-test' /> <CardItem src={im10} text='"Attend today, and achieve tomorrow.” ....' label='Attendance' path='/attendance' /> </ul> </div> </div> </div> ); } export default TeacherCard;<file_sep>import React, { Component } from 'react' import SessionService from '../services/SessionService'; class UpdateSessionComponent extends Component { constructor(props) { super(props) this.state = { sessionId: this.props.match.params.sessionId, coursename: '', stime: '', //emailId: '' } this.changeCoursenameHandler = this.changeCoursenameHandler.bind(this); this.changeStimeHandler = this.changeStimeHandler.bind(this); this.updateSession = this.updateSession.bind(this); } componentDidMount(){ SessionService.findSessionById(this.state.sessionId).then( (res) =>{ let sessionSchedule = res.data; this.setState({coursename: sessionSchedule.coursename, stime: sessionSchedule.stime, //emailId : employee.emailId }); }); } updateSession = (e) => { e.preventDefault(); let sessionSchedule = {coursename: this.state.coursename, stime: this.state.stime}; console.log('sessionSchedule => ' + JSON.stringify(sessionSchedule)); console.log('sessionId => ' + JSON.stringify(this.state.sessionId)); SessionService.updateSession(sessionSchedule, this.state.sessionId).then( res => { this.props.history.push('/session'); }); } changeCoursenameHandler= (event) => { this.setState({coursename: event.target.value}); } changeStimeHandler= (event) => { this.setState({stime: event.target.value}); } cancel(){ this.props.history.push('/session'); } render() { return ( <div> <br></br> <div className = "container"> <div className = "row"> <div className = "card col-md-6 offset-md-3 offset-md-3"> <h3 className="text-center">Update Session</h3> <div className = "card-body"> <form> <div className = "form-group"> <label> Course Name: </label> <input placeholder="course Name" name="coursename" className="form-control" value={this.state.coursename} onChange={this.changeCoursenameHandler}/> </div> <div className = "form-group"> <label> Session Time: </label> <input placeholder="Session Time" name="stime" className="form-control" value={this.state.stime} onChange={this.changeStimeHandler}/> </div> <button className="btn btn-success" onClick={this.updateSession}>Save</button> <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button> </form> </div> </div> </div> </div> </div> ) } } export default UpdateSessionComponent <file_sep>import React, { Component } from "react"; import TeacherNavbar from "./TeacherNavbar"; class SubmitTest extends Component { componentDidMount() { } componentDidUpdate() { } submit(){ this.props.history.push('/teacherdash'); } render() { return ( <div> <TeacherNavbar/> <div className="container mt-5"> <div className="row"> <div className="col"> <form className="form-group"> <div className="mb-3 row"> <label htmlFor="questionId" className="col-sm-4 col-form-label"> Test Name </label> <div className="col-sm-5"> <input type="text" className="form-control form-control-sm" ref={this.testName} id="questionId" /> </div> </div> <button style = {{"marginLeft":"380px"}} className="btn btn-success mr-5" onClick={this.submit.bind(this)} > Submit </button> </form> </div> </div> </div> </div> ); } } export default SubmitTest; <file_sep>import React from 'react'; import '../css/Cards.css'; import CardItem from './CardItem'; import a1 from '../images/a1.jpeg'; import im5 from '../images/im5.jpg'; import im4 from '../images/img4.png'; function StudentCard() { return ( <div className='cards'> <h3 className= 'studentdash'> Welcome Students </h3> <div className='cards__container'> <div className='cards__wrapper'> <ul className='cards__items'> <CardItem src={a1} text='A Session is an oral presentation to teach people' label='Sessions' path="/show-session" /> <CardItem src={im5} text='Dont watch the clock. Do what it does....' label='Tests' path='/test' /> <CardItem src={im4} text='If there is no struggle, there is no progress.' label='Progress' path='/progress' /> </ul> </div> </div> </div> ); } export default StudentCard; <file_sep>import React from 'react'; import '../css/Cards.css'; import CardItem from './CardItem'; import im1 from '../images/im1.png' import im2 from '../images/im2.png' import im6 from '../images/im6.png' import im5 from '../images/im5.png' import im4 from '../images/im4.png' function Cards() { return ( <div className='cards'> <h1>Some Interesting Fatcts Of Online Education System!</h1> <div className='cards__container'> <div className='cards__wrapper'> <ul className='cards__items'> <CardItem src={im1} text='System is a suite of computer programs for MS​-DOS' label='Computer Managed' to="https://www.britannica.com/topic/shifting-agriculture" path="/services" /> <CardItem src= {im2} text='interact in a specific virtual place at a set time' label='Synchronous Online Learning' path='/products' /> </ul> <ul className='cards__items'> <CardItem src={im6} text='Take a more non-traditional approach' label='ASynchronous Online Learning' path="/sign-up" /> <CardItem src={im5} text='Set of techniques oriented to offer online students' label='Adaptive E-Learning' path='/organics' /> <CardItem src= {im4} text='Uses a traditional structure of passing down information to students' label='Fixed E-Learning' path='/shiftings' /> </ul> </div> </div> </div> ); } export default Cards; <file_sep>import axios from 'axios'; const ATTENDANCE_API_BASE_URL = "http://ec2-18-191-253-178.us-east-2.compute.amazonaws.com:8080/api/educationsystem/attendance"; class AttendanceService { getAttendance(){ return axios.get(ATTENDANCE_API_BASE_URL + "/view-all-attendance"); } } export default new AttendanceService() <file_sep>import React from 'react'; import '../App.css'; import StudentCard from './StudentCard'; import StudentNavbar from './StudentNavbar'; function StudentHome() { return ( <> <StudentNavbar/> <StudentCard/> </> ); } export default StudentHome; <file_sep>import React, { Component } from 'react' import StudentService from '../services/StudentService' import '../css/ListStudents.css' import HmNavbar from './HmNavbar' import Cards from './Cards' class HmViewStudents extends Component { constructor(props) { super(props) this.state = { students: [] } } componentDidMount(){ StudentService.getStudents().then((res) => { console.log(res.data); this.setState({ students: res.data}); }); } render() { return ( <div> <HmNavbar/> {/* <h2 className="text-center">Student List</h2> */} {/* <div className = "row"> <button className="btn btn-primary"> Add Student</button> </div> */} <br></br> <div className = "row"> <div className="student-table"> <h2 className="text-center">Student List</h2> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Student Id</th> <th> First Name</th> <th> Middle Name</th> <th> Last Name</th> <th> Email Id</th> <th> Username</th> </tr> </thead> <tbody> { this.state.students.map( student => <tr key = {student.studentId}> <td> { student.studentId} </td> <td> { student.firstName} </td> <td> {student.middleName}</td> <td> {student.lastName}</td> <td> {student.emailId}</td> <td> {student.userName}</td> <td> {/* <button className="btn btn-info">Update </button> <button style={{marginLeft: "10px"}} className="btn btn-danger">Delete </button> */} <button style={{marginLeft: "10px"}} className="btn btn-info">View </button> </td> </tr> ) } </tbody> </table></div> </div> {/* <Cards/> */} </div> ) } } export default HmViewStudents
ed06d3839e4ea61fb586f14170c9409da5f829c8
[ "JavaScript" ]
25
JavaScript
Anjali123pa/OnlineEducation
f56f0ec75c19c6839d2a2f214be6f5f6e3dacfea
ca07ba40081e4387a295714adbf308d2010fe4a0
refs/heads/master
<file_sep>import numpy as np from numpy import array import pandas as pd import matplotlib.pyplot as plt import string import os from PIL import Image import glob from pickle import dump, load from time import time from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector,\ Activation, Flatten, Reshape, concatenate, Dropout, BatchNormalization from keras.optimizers import Adam, RMSprop from keras.layers.wrappers import Bidirectional from keras.layers.merge import add from keras.applications.inception_v3 import InceptionV3 from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.models import Model from keras import Input, layers from keras import optimizers from keras.applications.inception_v3 import preprocess_input from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical import tensorflow as tf from tensorflow.keras.preprocessing.image import load_img,img_to_array from flask import Flask, request, render_template from werkzeug.utils import secure_filename from gevent.pywsgi import WSGIServer # from gtts import gTTS # language = 'en' # from playsound import playsound model = ResNet50(weights='imagenet') model_new = Model(model.input, model.layers[-2].output) train_features = load(open("Caption/encoded_train_images.pkl", "rb")) train_descriptions = load(open("Caption/encoded_train_desc.pkl","rb")) all_train_captions = [] for key, val in train_descriptions.items(): for cap in val: all_train_captions.append(cap) #consider only words which occur at least 10 times in the corpus word_count_threshold = 10 word_counts = {} nsents = 0 for sent in all_train_captions: nsents += 1 for w in sent.split(' '): word_counts[w] = word_counts.get(w, 0) + 1 vocab = [w for w in word_counts if word_counts[w] >= word_count_threshold] ixtoword = {} wordtoix = {} ix = 1 for w in vocab: wordtoix[w] = ix ixtoword[ix] = w ix += 1 vocab_size = len(ixtoword) + 1 # one for appended 0's vocab_size # convert a dictionary of clean descriptions to a list of descriptions def to_lines(descriptions): all_desc = list() for key in descriptions.keys(): [all_desc.append(d) for d in descriptions[key]] return all_desc # calculate the length of the description with the most words def max_length(descriptions): lines = to_lines(descriptions) return max(len(d.split()) for d in lines) # determine the maximum sequence length max_length = max_length(train_descriptions) #print('Description Length: %d' % max_length) from keras.applications.imagenet_utils import preprocess_input, decode_predictions from keras.models import load_model from keras.preprocessing import image # Model saved with Keras model.save() MODEL_PATH = 'Caption/my_model_30' # Load your trained model model = load_model(MODEL_PATH) def greedySearch(photo): in_text = 'startseq' for i in range(max_length): sequence = [wordtoix[w] for w in in_text.split() if w in wordtoix] sequence = pad_sequences([sequence], maxlen=max_length) yhat = model.predict([photo,sequence], verbose=0) yhat = np.argmax(yhat) word = ixtoword[yhat] in_text += ' ' + word if word == 'endseq': break final = in_text.split() final = final[1:-1] final = ' '.join(final) return final def predict(img): #img_y = load_img(img_path,target_size=(224,224)) # plt.imshow(img_y) #plt.show() img_y1=img_to_array(img) img_y1=np.expand_dims(img_y1, axis=0) img_y1=preprocess_input(img_y1) fea_vec_test = model_new.predict(img_y1) # Get the encoding vector for the image fea_vec_test = np.reshape(fea_vec_test, fea_vec_test.shape[1]) test_reshape = fea_vec_test.reshape(1,2048) text = greedySearch(test_reshape) #speech = gTTS(text = text, lang = language, slow = False) #speech.save('text.mp3') return text # with open("Caption/encoded_test_images.pkl", "rb") as encoded_pickle: # encoding_test = load(encoded_pickle) #print("prediction is ",predict('sample_1.jpeg')) #print("prediction is ",predict('horse.jpg')) #print("prediction is ",predict('worker.jpg')) #print("prediction is ",predict('download.png')) #print("prediction is ",predict('soccer.jpg')) #print("prediction is ",predict('cat.jpg')) #print("prediction is ",predict('Ducati.jpg')) #image = Image.open('photo-1604741637599-b7e53240e1c4.jpg') #image =image.resize((224,224)) #print("prediction is ",predict(image)) #images = 'Flicker8k_Dataset/' #z=101 #pic = list(encoding_test.keys())[z] #image = encoding_test[pic].reshape((1,2048)) #x=plt.imread(images+pic) #plt.imshow(x) #plt.show() #print("Greedy:",greedySearch(image)) <file_sep># -*- coding: utf-8 -*- """ Created on Fri Nov 13 11:21:07 2020 @author: Vandhana """ import streamlit as st import os from PIL import Image from app import predict import tensorflow as tf from PIL import Image import requests import base64 from io import BytesIO main_bg = "background.jpg" main_bg_ext = "jpg" st.markdown( f""" <style> .reportview-container {{ background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, "rb").read()).decode()}) }} </style> """, unsafe_allow_html=True ) st.sidebar.info("This is an Image Captioning web deployment Model.The application identifies the objects in \ the picture and generates Caption. It was built using a Convolution Neural Network (CNN) for object identification and RNN to generate captions using sequence to sequence model (LSTM)") st.set_option('deprecation.showfileUploaderEncoding', False) #st.title("Image Captioning") st.markdown("<h1 style='text-align: center; color: green;'>Image Captioning</h1>", unsafe_allow_html=True) st.write("") #def file_selector(folder_path='.'): # filenames = os.listdir(folder_path) # selected_filename = st.selectbox('Select a file', filenames) # return os.path.join(folder_path, selected_filename) # # #if __name__ == '__main__': # # Select a file # if st.checkbox('Select a file in current directory'): # folder_path = '.' # if st.checkbox('Change directory'): # folder_path = st.text_input('Enter folder path', '.') # filename = file_selector(folder_path=folder_path) # st.write('You selected `%s`' % filename) # image = Image.open(filename) # st.image(image, caption='Selected Image.', use_column_width=True) # st.write("") # st.write("Just a second...") # label = predict('bike.jpg') # st.write("Caption for above image is : ",label) #st.write() def load_img(path_to_img): img = tf.io.read_file(path_to_img) #img = tf.image.decode_image(img, channels=3) #img = tf.image.resize(img, (224,224)) return img st.write('<style>div.Widget.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True) status = st.radio("Hello, Do you want to Upload an Image or Insert an Image URL?",("Upload Image","Insert URL")) if status == 'Upload Image': st.success("Please Upload an Image") file_up = st.file_uploader("Upload an image", type="jpg") if file_up is not None: image = Image.open(file_up) st.image(image, caption='Uploaded Image.', use_column_width=True) st.write("") image = image.resize((224,224)) st.write("Just a second...") label = predict(image) st.write("Caption for above image is : ",label) # audio_file = open("text.mp3","rb").read() # st.audio(audio_file,format='audio/mp3') else: st.success("Please Insert Web URL") url = st.text_input("Insert URL below") if url: response = requests.get(url) image = Image.open(BytesIO(response.content)) st.image(image, caption='Uploaded Image.', use_column_width=True) st.write("") image = image.resize((224,224)) st.write("Just a second...") label = predict(image) st.write("Caption for above image is : ",label) # audio_file = open("text.mp3","rb").read() # st.audio(audio_file,format='audio/mp3') <file_sep># Image_Captioning Image_Captioning <file_sep>requests==2.22.0 tensorflow-cpu==2.3.0 Werkzeug==0.16.0 gTTS==2.2.1 streamlit==0.70.0 playsound==1.2.2 Keras==2.4.3 gevent==1.4.0 matplotlib==3.1.1 pandas==0.25.1 numpy==1.16.5 Pillow==8.1.2 Flask==1.1.1
63de2dcd07103f5c1e7ee4f154d4add7f9d0b712
[ "Markdown", "Python", "Text" ]
4
Python
Shailajai6/Image_Captioning
a7167c462cf57264a259d651b9cfbed12a75673d
5ab42d6323cb129115a0b8bad6cd7e135c0225f8
refs/heads/master
<file_sep>package go_tanks import ( //log "../log" i "../interfaces" v "../validators" h "./handlers" "errors" "fmt" ) type GameController struct { Controller } func ( c *GameController ) JoinToGame () error { c.addToWorld() c.World.NewTank( c.Client ) message := *( <-c.Client.InBox() ) tank := message["Tank"].(i.Tank) c.Client.SetTank( tank ) message["Message"] = fmt.Sprint("Your tank id = ", tank.GetId()) c.Client.SendMessage( &message ) inClientBox := c.Client.InClientBox() inBox := c.Client.InBox() for { select { case message, ok := <- inClientBox: if !ok { c.removeFromWorld() return errors.New("Receive channel closed.") } err := v.ValidateUserMessage( message ) if ( err != nil ) { c.Client.SendMessage( i.ErrorMessage( err.Error() ) ); continue } c.handleMessage( message ) case message, _ := <- inBox: switch message.GetTypeId() { case i.DESTROY_TANK: c.Client.SendMessage( &i.Message{"Type":"Hit", "Message": "Your are die :("} ) return nil case i.HIT_TANK: c.Client.SendMessage( &i.Message{"Type":"Hit", "Message": "Tank hit."} ) } } } return nil } func ( c *GameController ) addToWorld () { c.World.AttachClient( c.Client ) } func ( c *GameController ) removeFromWorld () { c.World.DetachClient( c.Client ) } func ( c *GameController ) handleMessage ( m *i.Message ) error { return h.HandleMessage(c.World, c.Client, m) } <file_sep>package go_tanks import ( i "../interfaces" ) type Controller struct { Client i.Client World i.World } <file_sep>package go_tanks const ( NEW_TANK = iota NEW_CLIENT REMOVE_CLIENT TANK_COMMAND HIT_TANK DESTROY_TANK ) type Message map[string]interface{} type MessageChan chan *Message type Client interface { SendMessage ( *Message ) error ReadMessage () ( *Message, error ) SetAuthCredentials ( login, password string) SetTank ( Tank ) GetTank () Tank HasTank () bool Login () *string Password () *string OutBox () MessageChan InBox () MessageChan OutClientBox () MessageChan InClientBox () MessageChan OutBoxHasPlace () bool SendWorld ( *Message ) SetWorldDisabled( bool ) SetWorldFrequency ( val int ) ReInit() } var typeToIdMaping = map[string]int { "TankCommand": TANK_COMMAND, } func ( m *Message ) GetTypeId () interface{} { message := *m if message["TypeId"] == nil { message["TypeId"] = typeToIdMaping[ message["Type"].(string) ] } return message["TypeId"].(int) } func ErrorMessage ( message string ) *Message { return &Message{"Type":"Error", "Message": message} } <file_sep>package go_tanks import ( log "./log" ) type FrontController struct { World *World ClientsChannel <-chan *Client } func (fc *FrontController) Accept () { for { client := <- fc.ClientsChannel log.Client("New client connected ( ", client.RemoteAddr(), " )"); fc.processClient(client) } } func (fc *FrontController) processClient (client *Client) { dispatcher := Dispatcher{ Client: client, World: fc.World } go dispatcher.run() } <file_sep>package go_tanks import ( log "./log" controllers "./controllers" i "./interfaces" //"fmt" ) type Dispatcher struct { World *World Client *Client } func ( d *Dispatcher ) run () { d.dispatch() } func ( d *Dispatcher ) dispatch () error { defer d.Client.Close() var err error; for { err = d.authStep(); if ( err != nil ) { return d.sendError( err ) } err = d.gameStep(); if ( err != nil ) { return d.sendError( err ) } d.Client.ReInit() } return nil } func ( d *Dispatcher ) gameStep () error { controller := controllers.GameController{ controllers.Controller { Client: d.Client, World: d.World } } return controller.JoinToGame() } func ( d *Dispatcher ) authStep () error { controller := controllers.AuthController{ controllers.Controller{ Client: d.Client, World: d.World } } return controller.Authorize() } func ( d *Dispatcher ) sendError (err error) error { log.Error(err) d.Client.SendMessage( i.ErrorMessage(err.Error()) ) return err } <file_sep>package go_tanks import ( "github.com/gorilla/websocket" "net" i "./interfaces" "errors" log "./log" "time" ) const ( NON_AUTHORIZED = iota AUTHORIZED ) const ( INBOX_CAPACITY = 5 OUTBOX_CAPACITY = 5 CLIENT_BUFFER_CAPACITY = 5 ) type Client struct { Connection IConn State int login string password string Tank *Tank // inside message channels outBox i.MessageChan inBox i.MessageChan // client message channels inClientBox i.MessageChan outClientBox i.MessageChan // world would be receive every n ticks worldFrequency int worldFrequencyN int // do not send world messages worldDisabled bool Closed bool } func ( c *Client ) RemoteAddr () ( net.Addr ) { return c.Connection.RemoteAddr() } func NewClient ( conn IConn ) ( *Client ) { client := &Client{ Connection: conn, State: NON_AUTHORIZED, inBox: make( i.MessageChan, INBOX_CAPACITY ), outBox: make( i.MessageChan, OUTBOX_CAPACITY ), inClientBox: make( i.MessageChan, CLIENT_BUFFER_CAPACITY ), outClientBox: make( i.MessageChan, CLIENT_BUFFER_CAPACITY ), worldDisabled: false, Closed: false, } client.Init() return client } func NewWsClient ( ws *websocket.Conn ) ( *Client ) { return NewClient( NewWsConn(ws) ) } func NewNetClient ( conn *net.Conn ) ( *Client ) { return NewClient( NewNetConn(conn) ) } func ( c *Client ) Init () { go c.startSendMessageLoop() go c.startReceiveMessageLoop() } func ( c *Client ) ReInit () { c.Tank = nil c.State = NON_AUTHORIZED c.login = "" c.password = "" log.Client("Client reinitialized.") } func ( c *Client ) Close () { c.Closed = true // Wait for write all messages <- time.After(time.Second) c.Connection.Close() close(c.outClientBox) log.Client("Client closed.") } func ( c *Client ) SendMessage ( m *i.Message ) error { select { case c.outClientBox <- m: return nil default: return errors.New("Slow client.") } } func ( c *Client ) startReceiveMessageLoop () { defer close(c.inClientBox) for { message, err := c.Connection.ReadMessage() if err != nil { break } select { case c.inClientBox <- message: default: } } log.Client("Receive message finished.") } func ( c *Client ) startSendMessageLoop () { for { message, ok := <- c.outClientBox if !ok { break } c.Connection.WriteMessage( message ) } log.Client("Send message finished.") } func ( c *Client ) ReadMessage () ( *i.Message, error ) { m, ok := <- c.inClientBox if !ok { return nil, errors.New("Read channel was closed.") } return m, nil } func ( c *Client ) SetAuthCredentials ( login, password string ) { c.login = login c.password = <PASSWORD> } func ( c *Client ) Login () *string { return &c.login } func ( c *Client ) Password () *string { return &c.password } func ( c *Client ) HasTank () bool { return c.Tank != nil } func ( c *Client ) SetTank ( tank i.Tank ) { c.Tank = tank.(*Tank) } func ( c *Client ) GetTank () i.Tank { return c.Tank } func ( c *Client ) InBox () i.MessageChan { return c.inBox } func ( c *Client ) OutBox () i.MessageChan { return c.outBox } func ( c *Client ) InClientBox () i.MessageChan { return c.inClientBox } func ( c *Client ) OutClientBox () i.MessageChan { return c.outClientBox } func ( c *Client ) SendWorld ( m *i.Message ) { if( c.worldDisabled ) { return } if( c.worldFrequencyN == 0 ) { c.worldFrequencyN = c.worldFrequency err := c.SendMessage(m) if( err != nil ) { log.Error(err) } } else { c.worldFrequencyN-- } } func ( c *Client ) SetWorldDisabled ( val bool ) { c.worldDisabled = val } func ( c *Client ) SetWorldFrequency ( val int ) { c.worldFrequency = val c.worldFrequencyN = c.worldFrequency } func ( c *Client ) OutBoxHasPlace () bool { return cap(c.outBox) - len(c.outBox) > 0 } <file_sep>package go_tanks import( log "./log" ) func NewServer(cfg Config) *Server { return &Server{ config: &cfg } } type Server struct { config *Config world *World frontController *FrontController }; func (srv *Server) Run () { srv.runWorld(); log.Server("Server starting..."); srv.run() } func (srv *Server) run () { tcpServer := TCPServer { Port: srv.config.Port, Address: srv.config.Address } channel := ClientChannel go tcpServer.run( channel ) srv.frontController = &FrontController{ World: srv.world, ClientsChannel: channel } srv.frontController.Accept(); } func (srv *Server) runWorld () { srv.world = NewWorld( *srv.config.World ) srv.world.run(); } <file_sep>package go_tanks import ( "errors" log "../log" i "../interfaces" "fmt" v "../validators" ) const ( HELLO = "Hello! You should authorize befor join the game!" ) type AuthController struct { Controller } func ( c *AuthController ) Authorize () error { c.sendHello(); c.readAuth(); if ( !c.isAuthorized() ){ return errors.New( fmt.Sprintf("Authorization failed with credentials: %s / %s", *c.Client.Login(), *c.Client.Password() ) ) } return nil } func ( c *AuthController ) sendHello () { c.Client.SendMessage( &i.Message{ "Message": HELLO, "Type": "Auth", }) } func ( c *AuthController ) readAuth () error { for !c.isAuthorized() { m, err := c.Client.ReadMessage() if err != nil { log.Error("Auth failed: ", err); return err } err = v.ValidateAuthForm(m) if( err != nil ) { c.Client.SendMessage( i.ErrorMessage( err.Error() ) ); continue; } message := *m c.Client.SetAuthCredentials( message["Login"].(string) , message["Password"].(string) ) } return nil } func ( c * AuthController ) isAuthorized () bool { return len( *c.Client.Login() ) > 0 } <file_sep>package go_tanks type World interface { NewTank ( client Client ) AttachClient ( client Client ) DetachClient ( client Client ) }
44ad189e8dd7e635f4804337fdf28348f734358d
[ "Go" ]
9
Go
artempartos/go-tanks
d001902dba9d4c3548438fa97ac4443d023978ad
83ba6a9f876013dceb3c09e3ed5052c4869097c0
refs/heads/master
<file_sep><p>lokal app, oppmøte for studenter ![alt text](https://i.imgur.com/HBa0bDp.png) ![alt text](https://i.imgur.com/eoH9FlJ.png) ![alt text](https://i.imgur.com/tZ4JGxj.png) ![alt text](https://i.imgur.com/3x263dm.png) ![alt text](https://i.imgur.com/cUVbB6U.png) </p> <file_sep>from flask import Flask, flash, redirect, render_template, request, session, abort, make_response, send_file, jsonify, Response, url_for from threading import Lock, Timer import pandas as pd import numpy as np import sqlite3 as sql import sys,os from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, Unicode, UnicodeText, Date, Integer, String from sqlalchemy import create_engine, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref import tabledeff from wtforms import Form, BooleanField, StringField, PasswordField, validators import string sys.path.insert(0, os.path.realpath(os.path.dirname(__file__))) os.chdir(os.path.realpath(os.path.dirname(__file__))) app = Flask(__name__) def movingavarage(values,window): weights = np.repeat(1.0,window)/window smas = np.convolve(values,weights,'valid') return smas #remove duplicates def dup_remove(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] class RegistrationForm(Form): username = StringField('<NAME>', [validators.Length(min=4, max=25)]) class AdminForm(Form): password = PasswordField('<PASSWORD>') def loot(winner_number): link = 0 print(winner_number) if winner_number < 9: link = 'https://gbf.wiki/images/thumb/a/aa/Cosmic_Sword.png/462px-Cosmic_Sword.png' elif winner_number > 8: link = 'https://www.claires.com/dw/image/v2/BBTK_PRD/on/demandware.static/-/Sites-master-catalog/default/dwb3e89841/images/hi-res/55138_1.jpg' if winner_number > 19: link = 'https://www.claires.com/dw/image/v2/BBTK_PRD/on/demandware.static/-/Sites-master-catalog/default/dw88b9b105/images/hi-res/38215_1.jpg' if winner_number > 29: link = 'https://thumbs.dreamstime.com/z/american-legendary-pistol-white-background-military-model-47937475.jpg' if winner_number > 39: link = 'https://cdn-4.jjshouse.com/upimg/jjshouse/s1140/4a/e3/af62d123841b74b7e4bc431e0aec4ae3.jpg' if winner_number > 49: link = 'http://ukonic.com/wp-content/uploads/2017/11/WOW_PALADINE_ROBE_1-1000.jpg' if winner_number > 59: link = 'https://thebitbin.files.wordpress.com/2012/08/boots1.png' if winner_number > 69: link = 'https://cdn-media.sportamore.se/uploads/products/5711176095404_001_7a2b071ce45943269c9b78d04124f2e7.jpg' if winner_number > 79: link = 'http://www.omegaartworks.com/images/omega/490-dragonfly-knife-green-andamp;-blackandamp;-daggers.jpg' if winner_number > 89: link = 'https://www.thinkgeek.com/images/products/zoom/1f1a_kawaii_hooded_unicorn_bathrobe.jpg' if winner_number > 98: link = 'http://www.delonghi.com/Global/recipes/multifry/3_pizza_fresca.jpg' else: return "Error" return link @app.route('/system/reset') def reset_day(): try: os.remove('temp.db') tabledeff.reset_dayusers() except: tabledeff.reset_dayusers() reset = "Day list have been reset" return render_template('home_reset.html', reset = reset) reset = "Day list have been reset" return render_template('home_reset.html', reset = reset) @app.route('/') def home(): try: total_visits = [] conn = sql.connect("temp.db") df_users = pd.read_sql("SELECT * FROM users ", conn) users_defined = df_users['name'] number = df_users['number'].values intedlist = [int(i) for i in number] winner_number = max(intedlist) winner_number_student_search = pd.read_sql("SELECT * FROM users WHERE (number LIKE '%{}%') ".format(winner_number), conn) winner_number_student = winner_number_student_search.values[0][1] conn.close() conn = sql.connect("real.db") for i in users_defined: df_total_visits = pd.read_sql("SELECT * FROM users WHERE (name LIKE '{}') ".format(i), conn) total_visits.append(len(df_total_visits['name'])) conn.close() loot_item = loot(winner_number) return render_template('home.html', tripple = zip(users_defined, number, total_visits), winner = winner_number_student, loot_item = loot_item) except: return render_template('home.html') @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): conn = sql.connect('temp.db') c = conn.cursor() df_users = pd.read_sql("SELECT * FROM users", conn) random_number = int(np.random.randint(0,100,1)) print(random_number) try: form.username.data = string.capwords(str(form.username.data)) if form.username.data in df_users['name'].values: return("<NAME>") except: print("ERRRIOR") pass else: c.execute("INSERT INTO users (name, number) VALUES (?,?)", (form.username.data, str(random_number),)) conn.commit() conn.close() conn = sql.connect('real.db') c = conn.cursor() c.execute("INSERT INTO users (name) VALUES (?)", (form.username.data,)) conn.commit() conn.close() name_inserted = form.username.data form.username.data = "" return render_template('register.html', form = form, takk = '%s registert!, Lotteri-ID: %d'%(name_inserted, random_number)) return render_template('register.html', form=form) @app.route('/admin_login', methods=['GET', 'POST']) def admin_login(): form = AdminForm(request.form) if request.method == 'POST' and form.validate(): with open('pws.dat', 'r') as pws: if str(pws.read()) == str(form.password.data): total_visits = [] conn = sql.connect("real.db") df_users = pd.read_sql("SELECT * FROM users ", conn) users_defined = dup_remove(df_users['name']) print(users_defined) for i in users_defined: df_total_visits = pd.read_sql("SELECT * FROM users WHERE (name LIKE '{}') ".format(i), conn) total_visits.append(len(df_total_visits['name'])) conn.close() return render_template('admin.html', tripple = zip(users_defined, total_visits), form=form) else: error_login = "Feil passord" return render_template('admin_login.html', form = form, error_login = error_login) return render_template('admin_login.html', form = form) # @app.route('/sys/admin', methods=['GET', 'POST']) # def admin(): # try: # total_visits = [] # conn = sql.connect("real.db") # df_users = pd.read_sql("SELECT * FROM users ", conn) # users_defined = dup_remove(df_users['name']) # print(users_defined) # for i in users_defined: # df_total_visits = pd.read_sql("SELECT * FROM users WHERE (name LIKE '{}') ".format(i), conn) # total_visits.append(len(df_total_visits['name'])) # conn.close() # return render_template('admin.html', tripple = zip(users_defined, total_visits), form=form) # except: # return "Error!" # thread = threading.Thread(target=foo) # thread.start() if __name__ == "__main__": app.run() <file_sep> def reset_dayusers(): from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, Unicode, UnicodeText, Date, Integer, String from sqlalchemy import create_engine, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref engine = create_engine('sqlite:///temp.db', echo=True) Base = declarative_base() ######################################################################## class data(Base): """""" __tablename__ = "users" id = Column(Integer, primary_key=True) name = Column(String) number = Column(String) def __init__(self,name, number): """""" self.name = name self.number = number # create tables Base.metadata.create_all(engine)
9e16ea37a6855b572841de5dcee55f00d5e46823
[ "Markdown", "Python" ]
3
Markdown
MartinRovang/Absentia_Oppmote
7d7222952f90d004e7527c4d994ef45d14a839fd
7a047b2030b4dfa0c6304ab1610a770dc38e9bc6
refs/heads/master
<repo_name>Saulnjie/GroceryTask<file_sep>/readme.md # Saving the state of our grocery list ## UML - Create all files needed and link them - Gather data from the user - Validate the data - If data is not valid show the user a message. - If the data is valid build the html. - Allow the user to mark and item as completed. - Persist the data. - If a user refreshes the page the previous data should still show. - Delete everything inside a list. Module assignment: - When an Item is checked change the background color - Create a button that deleted everything from localStorage and clears the list - ` localStorage.clear();` - Submit a git link and a netlify link <file_sep>/js/libs/writeToDom.js import { saveToLocalStorage } from "./localStorageHelper.js"; export default function writeToDOM( domElementIAmGoingToPutHTMLInto, theArrayIAmGoingToCreateHTMLFrom ) { console.log(theArrayIAmGoingToCreateHTMLFrom); domElementIAmGoingToPutHTMLInto.innerHTML = ""; theArrayIAmGoingToCreateHTMLFrom.forEach(function (groceryItem, iteration) { let ischecked = ""; if (groceryItem.checked) { ischecked = "checked"; } domElementIAmGoingToPutHTMLInto.innerHTML += `<li> <span>${groceryItem.name}</span> <input ${ischecked} type="checkbox" class="checkbox" data-id=${groceryItem.id}> </li>`; }); const checkboxes = document.querySelectorAll(".checkbox"); console.log(checkboxes); checkboxes.forEach(function (checkbox) { checkbox.onclick = function () { let indexOfItem = theArrayIAmGoingToCreateHTMLFrom.findIndex(function ( groceryObject ) { return groceryObject.id === parseInt(checkbox.dataset.id); }); console.log(indexOfItem); console.log(theArrayIAmGoingToCreateHTMLFrom[indexOfItem]); if (theArrayIAmGoingToCreateHTMLFrom[indexOfItem].checked) { theArrayIAmGoingToCreateHTMLFrom[indexOfItem].checked = ""; } else { theArrayIAmGoingToCreateHTMLFrom[indexOfItem].checked = "checked"; } saveToLocalStorage("groceryArrayKey", theArrayIAmGoingToCreateHTMLFrom); }; }); } <file_sep>/js/index.js // imports always go on top import { testLengthOfInput } from "./libs/validation.js"; import writeToDOM from "./libs/writeToDom.js"; import { saveToLocalStorage, getStorageItem, } from "./libs/localStorageHelper.js"; const itemInput = document.querySelector(".itemInput"); const addItem = document.querySelector(".addItem"); const items = document.querySelector(".items"); let groceryArray = getStorageItem("groceryArrayKey"); const removeItem = document.querySelector(".reset-btn"); writeToDOM(items, groceryArray); addItem.onclick = function () { let valueOfGroceryInputBox = itemInput.value; if (testLengthOfInput(valueOfGroceryInputBox, 3)) { let groceryItem = { id: groceryArray.length, name: valueOfGroceryInputBox, }; groceryArray.push(groceryItem); saveToLocalStorage("groceryArrayKey", groceryArray); writeToDOM(items, groceryArray); } else { console.log("Input needs more characters"); } itemInput.value = ""; }; removeItem.onclick = function () { localStorage.clear(); items.innerHTML = ""; };
7024f42a62c32f4c6f7b9445ac6689569dac7236
[ "Markdown", "JavaScript" ]
3
Markdown
Saulnjie/GroceryTask
ea90b6f6bbbe3f9870e0fa432a3399bf3fe92c53
fa07a41311ce966e9492477c1ef7d867709f1076
refs/heads/master
<repo_name>hpt09/FlightSearchEngine<file_sep>/src/OneWayTicket.js import React from 'react'; class OneWayTicket extends React.Component{ render() { return ( <div class="ticket"> <h4>Rs. {this.props.price}</h4> <h5>{this.props.flightNo}</h5> <h4>Depart: {this.props.departTime}</h4> <h4>Arrive: {this.props.arriveTime}</h4> </div> ) } } export default OneWayTicket;<file_sep>/src/Search.js import React from 'react'; import axios from 'axios'; import 'bootstrap/dist/css/bootstrap.min.css'; import Tab from 'react-bootstrap/Tab' import Tabs from 'react-bootstrap/Tabs' import './Search.css' import OneWayTicket from './OneWayTicket' import ReturnTicket from './ReturnTicket' class Search extends React.Component{ constructor(){ super(); this.state = { originCity: '', destinationCity: '', departureDate: '', passengers: 0, returnDate: '', submitted: false, tabKey: 'oneway', price:100000, flights: [] }; } handleChange = (e) => { this.setState({ [e.target.name]:e.target.value}) } handleSubmit = () => { if(this.state.tabKey === 'oneway'){ this.setState({ isLoading: true }); axios.get('/flights.json') .then(result => this.setState({ flights: result.data, isLoading: false }) ) .catch(error => this.setState({ error, isLoading: false }) ); } else if(this.state.tabKey === 'return'){ axios.get('/returnFlights.json') .then(result => this.setState({ flights: result.data, isLoading: false }) ) .catch(error => this.setState({ error, isLoading: false }) ); } this.setState( {submitted:true}) } render(){ if(this.state.isLoading) { return "Loading..." } if(this.state.error) { return <p>{this.state.error.message}</p> } return ( <div> <h1>Flight Search Engine</h1><br/> <aside > <Tabs defaultActiveKey="oneway" id="uncontrolled-tab-example" onSelect={(k) => this.setState({tabKey:k})}> <Tab eventKey="oneway" title="One Way"> <div class="form-group"> <input placeholder='Enter Origin city' class="form-control" name="originCity" onChange={this.handleChange}></input> <input placeholder='Enter Destination city' class="form-control" name="destinationCity" onChange={this.handleChange}></input> <span>Departure Date</span><input type="date" class="form-control" name="departureDate" onChange={this.handleChange} ></input> <span>Passengers</span><input type="number" class="form-control" name="passengers" onChange={this.handleChange}></input> <button onClick={this.handleSubmit}>Search</button><br/> </div> <label>Refine flight search</label><br/> <label>$0</label> <span class='max'>$100000</span> <div class="slidecontainer"> <input type="range" min="1" max="100000" defaultValue="100000" class="slider" name="price" onChange={this.handleChange}></input> <br/><span class='value'>${this.state.price}</span> </div> </Tab> <Tab eventKey="return" title="Return"> <div class="form-group"> <input placeholder='Enter Origin city' class="form-control" name="originCity" onChange={this.handleChange}></input> <input placeholder='Enter Destination city' class="form-control" name="destinationCity" onChange={this.handleChange}></input> <span>Departure Date</span><input type="date" class="form-control" name="departureDate" onChange={this.handleChange} ></input> <span>Return Date</span><input type="date" class="form-control" name="returnDate" onChange={this.handleChange} ></input> <span>Passengers</span><input type="number" class="form-control" name="passengers" onChange={this.handleChange}></input> <button onClick={this.handleSubmit}>Search</button><br/> </div> <label>Refine flight search</label><br/> <label>$0</label> <span class='max'>$100000</span> <div class="slidecontainer"> <input type="range" min="1" max="100000" defaultValue="10000" class="slider" name="price" onChange={this.handleChange}></input> <br/><span class='value'>${this.state.price}</span> </div> </Tab> </Tabs> </aside> <section> <h1 align='center'>Search Results</h1> {this.state.submitted === true && this.state.tabKey === 'oneway' && <div> <h3>{this.state.originCity} > {this.state.destinationCity}</h3> <span class='dates'>Depart: {this.state.departureDate}</span> </div>} {this.state.flights.map(flight => { return flight.originCity == this.state.originCity && flight.destinationCity == this.state.destinationCity && flight.departureDate == this.state.departureDate && flight.passengers >= this.state.passengers && flight.price <= this.state.price && this.state.submitted == true && this.state.tabKey == 'oneway' ? ( <OneWayTicket price={flight.price} flightNo={flight.flightNo} departTime={flight.departTime} arriveTime={flight.arriveTime}></OneWayTicket> ) : <br/> }) } {this.state.submitted === true && this.state.tabKey === 'return' && <div> <h3>{this.state.originCity} > {this.state.destinationCity} > {this.state.originCity}</h3> <span class='dates'>Depart: {this.state.departureDate}</span><br/> <span class='dates'>Return: {this.state.returnDate}</span> </div>} {this.state.flights.map(flight => { return flight.originCity == this.state.originCity && flight.destinationCity == this.state.destinationCity && flight.departureDate == this.state.departureDate && flight.returnDate == this.state.returnDate && flight.passengers >= this.state.passengers && flight.price <= this.state.price && this.state.submitted == true && this.state.tabKey == 'return' ? ( <ReturnTicket price={flight.price} flightNo={flight.flightNo} departTime={flight.departTime} arriveTime={flight.arriveTime} returnFlightNo={flight.returnFlightNo} returnDepartTime={flight.returnDepartTime} returnArriveTime={flight.returnArriveTime}></ReturnTicket> ) : <br/> }) } </section> </div> ) } } export default Search;<file_sep>/src/ReturnTicket.js import React from 'react'; class ReturnTicket extends React.Component{ render() { return ( <div class="ticket"> <h4>Rs. {this.props.price}</h4> <div style={{float:'left'}}> <h5>{this.props.flightNo}</h5> <h4>Depart: {this.props.departTime}</h4> <h4>Arrive: {this.props.arriveTime}</h4> </div> <div style={{float:'right'}}> <h5>{this.props.returnFlightNo}</h5> <h4>Depart: {this.props.returnDepartTime}</h4> <h4>Arrive: {this.props.returnArriveTime}</h4> </div> </div> ) } } export default ReturnTicket;
e666492e4c0ff91860306839c064129ec9c90cc0
[ "JavaScript" ]
3
JavaScript
hpt09/FlightSearchEngine
d9016d3fd8f4fa5f2cf8b7cf22f67f1a5261cfd4
1c300393d49b99a1413a627d2e23537e0140e92b
refs/heads/master
<repo_name>Ruhulcse/Mycity<file_sep>/city.php <?php echo "your are successfully logged in "; ?>
ec85d69571205dedd692e193992f232093cc6da1
[ "PHP" ]
1
PHP
Ruhulcse/Mycity
bd3fedff088509956317077a1834d594b3582665
dfb15a95c8e9fd004772c3383fa202e8bb95d8f8
refs/heads/master
<repo_name>u1207426/password-retry<file_sep>/password.py # 密碼重試程式 # password = '<PASSWORD>' # 讓使用者重複輸入密碼 # 最多輸入3次 # 如果正確就印出"登入成功!" # 如果不正確就印出"密碼錯誤! 還有_次機會" try_time = 0 while True: try_time = try_time + 1 if try_time <= 3: password = input("請輸入密碼: ") if password == '<PASSWORD>': print('登入成功') break elif try_time < 3: have_time = 3 - try_time print(f'密碼錯誤! 還有{have_time}次機會') else: print('密碼錯誤') break else: break
ef65d4a9252676e4dc137d04908059d2b8bb587b
[ "Python" ]
1
Python
u1207426/password-retry
54af1775dfee7b5c9b0abbe922501d32064bbfe1
780f1355d9a0b9cfaf184434d04dfb12a5356b7a
refs/heads/master
<repo_name>piotrmrozit/honda<file_sep>/gulpfile.js /** * Created by wins on 2016-06-19. */ const gulp = require("gulp"); const less = require('gulp-less'); const cssnano = require('gulp-cssnano'); const nodemon = require('gulp-nodemon'); gulp.task('less', function () { return gulp.src('./src/less/**/*.less') .pipe(less()) .pipe(cssnano()) .pipe(gulp.dest('./public/css')); }); gulp.task('dust', function () { return gulp.src('./src/views/**/*.dust') .pipe(gulp.dest('./public/views')); }); gulp.task('js',function () { return gulp.src('./src/views/js/**/*.js') .pipe(gulp.dest('./public/views/js')); }); gulp.task('default',['less','dust','js','watch','start']); gulp.task('watch', function() { gulp.watch('./src/less/**/*.less', ['less']); gulp.watch('./src/views/**/*.dust', ['dust']); // gulp.watch('./src/js/**/*.js', ['js']); }); gulp.task('start', function () { nodemon({ script: 'bin/www', ext: 'js', watch: ['routes'] }) }); <file_sep>/lib/middleware/isAuth.js /** * Created by wins on 2016-06-19. */ module.exports = function() { return function(req, res, next) { if(req.session.logged==undefined){ req.session.logged = false; } if(req.session.logged==false){ res.redirect('/login') } else { next(); } } };<file_sep>/routes/index.js var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var isAuth = require('../lib/middleware/isAuth'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'hnd' }); connection.connect(); /* GET home page. */ router.get('/', function (req, res, next) { var dane = { title: 'Hondziarz.pl', zalogowany: false, uzytkownik: { email: 'brak' } }; if (req.session.logged != undefined) { dane.zalogowany = req.session.logged, dane.uzytkownik = req.session.user } res.render('index', dane); }); /* GET login page. */ router.get('/login', function (req, res, next) { res.render('login', {title: 'Hondziarz.pl'}); }); /* GET signup page. */ router.get('/signup', function (req, res, next) { var response = { error: false, message: null, title: 'Hondziarz.pl' }; res.render('signup', response); }); router.post('/signup', function (req, res, next) { console.log(' -> ', req.body); var response = { error: false, message: null, title: 'Hondziarz.pl' }; if (req.body.email == '' || req.body.password == '') { response.error = true; response.message = "Error! Wypełnij wszystkie pola!"; } if (req.body.password != '' && req.body.password.length < 6) { response.error = true; response.message = "Error! Hasło musi mieć więcej niż 6 znaków!!"; } var query_check = "SELECT * FROM users WHERE users_email = '" + req.body.email + "'"; connection.query(query_check, function (err, rows, fields) { if (rows[0] != undefined) { response.error = true; response.message = "Ten mail jest już zajęty."; res.render('signup', response); } else { if (response.error) { res.render('signup', response); } var query = "INSERT INTO `users`(`users_email`, `users_password`) VALUES ('" + req.body.email + "','" + req.body.password + "')"; connection.query(query, function (err, rows, fields) { if (err) { response.error = true; response.message = "Error! " + err; res.render('signup', response); } req.session.logged = true; req.session.user = { email: req.body.email, password: <PASSWORD> }; console.log("redirect"); res.redirect('/'); }); } }); }); /* GET logout page. */ router.get('/logout', function (req, res, next) { if (req.session.logged == true) { req.session.logged = false; delete req.session.user; } res.redirect('/'); }); /* GET login page. */ router.post('/login', function (req, res, next) { console.log(' -> ', req.body); var query_back = "SELECT users_email, users_password FROM users WHERE users_email = '" + req.body.email + "'"; var response = { error: false, message: null, title: 'Hondziarz.pl' }; connection.query(query_back, function (err, rows, fields) { console.log('rows -> ', rows[0]); if (rows[0] == undefined) { response.error = true; response.message = "Nie ma takiego użytkownika, zarejestruj się!" } else { if (req.body.password != rows[0].users_password) { response.error = true; response.message = "Nieprawidłowe dane"; } else { req.session.logged = true; req.session.user = { email: req.body.email, password: <PASSWORD> }; res.redirect('/'); } } if (response.error) { res.render('login', response); } }); }); router.get('/abc', isAuth(), function(req,res,next){ res.json({success: true}); }); module.exports = router;
91a2b113d3010b4dbbdab999aa7a52f9158d9d09
[ "JavaScript" ]
3
JavaScript
piotrmrozit/honda
f3dd5caf6ca3ff174cc1eb491206e4db903261b1
f94b7d71bd7eb1944938f39b1fea11645ad27544
refs/heads/master
<repo_name>martijnwijs/dmt21<file_sep>/ass1/inaccurate_values.py import pandas as pd import numpy as np df2 = pd.read_csv('dataframe_new.csv') # for x in df2['appCat.builtin']: # if x < 0: # print(x) def filter_inacc(df, category): df[(df[category] < 0)] = np.nan # for all values under 0 df[category].fillna(0, inplace=True) # replace with 0 return df categories_zero = [ 'activity', 'appCat.builtin', 'appCat.communication', 'appCat.entertainment', 'appCat.other', 'appCat.social', 'appCat.unknown', 'appCat.utilities', 'screen', 'appCat.finance', 'appCat.office', 'appCat.travel', 'appCat.weather', 'appCat.game'] # for category in categories_zero: df2 = filter_inacc(df2, category) # df2 = filter_inacc(df2 , 'appCat.builtin') # for x in df2['appCat.builtin']: # if x < 0: # print(x) def filter_inacc2(df, category): df[(df[category] < -2)] = np.nan # for all values under -2 df[(df[category] > 2)] = np.nan # for values above 2 df[category].fillna(0, inplace=True) # replace with 0 return df categories_2 = ['circumplex.arousal', 'circumplex.valence'] for category in categories_2: df2 = filter_inacc2(df2, category) print(df2['circumplex.arousal'].describe())<file_sep>/ass1/wil_exploration.py # Import import pandas as pd import numpy as np import csv from datetime import datetime import itertools import seaborn as sn import matplotlib.pyplot as plt dataset = "dataframe_new.csv" df = pd.read_csv(dataset) # df2 = df[df["t"]==3] # corrMatrix = df2.corr() # sn.heatmap(corrMatrix, annot=False) # plt.show() df_test = pd.read_csv("dataset_mood_smartphone.csv") print(df_test[(df_test["variable"]=="appCat.builtin") & (df_test["value"] == 0)])
4296453e469df9f4f68de54109398d5541666e38
[ "Python" ]
2
Python
martijnwijs/dmt21
840e60974ec2e2b279aead9f218f4839de1c03fc
3712a318f150afbf980c68eda51e56f5edff6d1e
refs/heads/master
<repo_name>SelcreSS/MyStudyUnity<file_sep>/UnityStudy/Assets/Sources/System/InspectorComment.cs using UnityEngine; /// <summary> /// コメントの意味を持たせたいクラスです。 /// クラスやprefabの使い方の意味を教えるときなどに利用して下さい /// 使い方 /// 1 AddComponentでこのクラスをアタッチする /// 2 インスペクターからコメントを記載する /// </summary> [System.Serializable] public class InspectorComment : MonoBehaviour { [Header("==== Comment ====")] [TextArea(2, 5)] public string info; } <file_sep>/UnityStudy/Assets/Sources/UI/TestPrefab.cs using System; using UnityEngine.Events; using UnityEngine; using UnityEngine.UI; public class TestPrefab : PopupSystem<TestPopupData> { [SerializeField] private Text _text; public override void Open(TestPopupData setupData) { root.SetActive(true); Setup(setupData); } protected override void Setup(TestPopupData data) { _text.text = data.text; closeButton.onClick.AddListener(data.button1); okButton.onClick.AddListener(data.button2); } } public class TestPopupData { public string text; public UnityAction button1; public UnityAction button2; public TestPopupData(string title, UnityAction button1, UnityAction button2) { text = title; this.button1 = button1; this.button2 = button2; } } <file_sep>/UnityStudy/Assets/Sources/System/PopupSystem.cs public class PopupSystem<TData> : BasePopUp { public virtual void Open(TData setupData) { } protected virtual void Setup(TData data) { } }<file_sep>/UnityStudy/Assets/Sources/System/StackPopupOpener.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class StackPopupOpener : MonoBehaviour { public static StackPopupOpener _Instance; private BasePopUp[] _stackPopups; private string _displayPopupName; // TODO // 簡易的に表示中ポップアップ名があるかでチェック public static bool IsOpened => !string.IsNullOrEmpty(_Instance._displayPopupName); void Awake() { _Instance = this; _stackPopups = GetComponentsInChildren<BasePopUp>(); } public void Open<TData>(string popupName, TData setupData) where TData : class { Close(); // 二重popupブロック foreach(var prefab in _stackPopups) { if (prefab.name == popupName) { _displayPopupName = popupName; var openPrefab = (PopupSystem<TData>)prefab; openPrefab.Open((TData)(object)setupData); } } } public void Open(string popupName) { Close(); foreach (var prefab in _stackPopups) { if (prefab.name == popupName) { _displayPopupName = popupName; prefab.Open(); } } } public void Close() { foreach (var prefab in _stackPopups) { if (prefab.name == _displayPopupName) { _displayPopupName = string.Empty; prefab.Close(); } } } private void OnDestroy() { foreach (var prefabName in _stackPopups) { prefabName.Close(); } _Instance = null; } }<file_sep>/UnityStudy/Assets/Sources/Main.cs using UnityEngine; public class Main : MonoBehaviour { void Update() { if(StackPopupOpener.IsOpened) { return; } // 外部からデータを渡すPopup if( Input.GetMouseButtonDown(0)) { var data = new TestPopupData("purchase?", () => StackPopupOpener._Instance.Close(), () => Debug.Log("OK")); StackPopupOpener._Instance.Open<TestPopupData>("A_SamplePopup", data); } // 内部で完結Popup else if(Input.GetMouseButtonDown(1)) { StackPopupOpener._Instance.Open("B_SamplePopup"); } } } <file_sep>/UnityStudy/Assets/Sources/System/BasePopUp.cs using System; using UnityEngine; using UnityEngine.UI; public class BasePopUp : MonoBehaviour { [SerializeField] protected GameObject root; [SerializeField] protected Button closeButton; [SerializeField] protected Button okButton; public virtual void Open() { } public void Close() { root.SetActive(false); } } <file_sep>/README.md # PopupSystemの構築 個別のシーンで出る可能性のあるポップアップを一括管理で表示非表示するシステムです。 <br>※Instantiateでprefabからインスタンス化する手法ではない <br>渡すデータの型が違っていても共通でPopupを開けます。 <使い方> カッコ内はこのサンプルの名称 - 1、シーンにStackPopupsを配置する。多々シーンがある場合はVariant prefabでそのシーンごと作るのも〇 - 2、StackPopups以下階層にPopupを付けます - 3、Popupごとのスクリプトを書きます(TestPrefab.cs/TestPrefab2.cs) - 4、どこかで呼び出しコードを記載します(Main.cs) <注意点> PopupのPrefabは必ずroot、SetActiveでON/OFFする階層を作成してくだい <file_sep>/UnityStudy/Assets/Sources/UI/TestPrefab2.cs using System; using UnityEngine; using UnityEngine.Events; public class TestPrefab2 : BasePopUp { private void Awake() { closeButton.onClick.AddListener(() =>StackPopupOpener._Instance.Close()); } public override void Open() { root.SetActive(true); } public void OnClick(int index) { Debug.Log("ClickF" + index); } }
61f29009a61a2b2790d4df7fc02b975accef979d
[ "Markdown", "C#" ]
8
C#
SelcreSS/MyStudyUnity
7af14e67da25d67a41966c34ace443c149bedc17
d732651bdcb4c6866eeaf98935dfe7a61ce96e97
refs/heads/master
<repo_name>vailalgatt/ruby-pilates-QA<file_sep>/app/models/answer.rb class Answer < ActiveRecord::Base include HasGravatar belongs_to :question end
e8b7e73155c9c4adf13d75da225cbab2cb6bbf95
[ "Ruby" ]
1
Ruby
vailalgatt/ruby-pilates-QA
1e9d7091d02e612d9c566edb48cd1214dbf23432
da6865441c8a2f5a2120b689d58f8f22b5218945
refs/heads/main
<repo_name>latonaio/site-controller-data-update-to-mysql<file_sep>/README.md # site-controller-data-update-to-mysql site-controller-data-update-to-mysqlは、エッジ端末からWindows端末のディレクトリを監視し、そのディレクトリに新しいサイトコントローラー連携ファイル(CSV)が作成された場合に、その情報をkanbanに渡す、エッジ端末上で動くマイクロサービスです。 ## サイトコントローラーとは サイトコントローラーとは、主に宿泊業向けに、予約情報をまとめて管理運用するサービスです。 サイトコントローラーは、サービスオーナー各社により提供されております。 ## 概要 site-controller-data-update-to-mysqlは、 一定時間おきにWindows端末ディレクトリを走査し、新しいファイルが作成されたら、以下の処理を行います。 監視するディレクトリは`services.yml`の`volumeMountPathList`で、走査間隔は`POLLING_INTERVAL`で指定します。 1. 監視しているディレクトリに新しく作成されたファイルを、`/var/lib/aion/defalt/Data/`配下にコピーする。 2. MySQLの`csv_upload_transaction`テーブルに、タイムスタンプ、1.でコピーしたファイルパス、status="before"を挿入する。 監視しているディレクトリに新しく作成されたファイルを、`/var/lib/aion/defalt/Data/`配下にコピーする。 3. kanbanに、`omotebako-sc`のconnectionKeyで、タイムスタンプと1.でコピーしたファイルパスを送る。 MySQLの`csv_upload_transaction`テーブルに、タイムスタンプ、1.でコピーしたファイルパス、status="before"を挿入する。 ## 動作環境 site-controller-data-update-to-mysqlは、aion-coreのプラットフォーム上での動作を前提としています。 使用する際は、事前に下記の通りAIONの動作環境を用意してください。 * OS: Linux OS * CPU: ARM/AMD/Intel * Kubernetes * AION のリソース ## セットアップ ### 1. エッジ端末でWindowsサーバの共有フォルダをマウント #### 1.1. エッジ端末でWindows共有フォルダをマウント 1.1.1 Windows側で共有フォルダを作成 - 任意のディレクトリに共有フォルダ用のフォルダを新規作成する - 作成したフォルダを右クリック→「プロパティ」→「共有タブ」を開く - 「共有」ボタンを押し、プルダウンから「Everyone」を選択し、追加 - 「共有」を押し、「終了」を押す - コマンドプロンプトを開き、`ipconfig`と入力 - IPv4 アドレスからwindowsサーバのIPアドレスを確認する(後で使う) ※ 参考URL https://bsj-k.com/win10-common-file/ 1.2.2 エッジ端末でWindowsの共有フォルダをマウント smbnetfsを使用します。マウントする際、ルートユーザーでないと挙動がおかしくなるため、ルートユーザーでマウント実行することを推奨します。 ``` # install smbnetfs sudo apt install smbnetfs # make folder mkdir ~/.smb cd ~/.smb # copy default config files cp /etc/samba/smb.conf . cp /etc/smbnetfs.conf . # make config files echo "host {windowsIPアドレス} WORKGROUP visible=true" > smbnetfs.host echo "auth {windowsユーザー名} {windowsユーザーパスワード}" > smbnetfs.auth # drop file permission chmod 600 smbnetfs.host smbnetfs.auth # mount mkdir /mnt/windows sudo -i smbnetfs /mnt/windows ``` マウントした後、共有フォルダがあることを確認します。デスクトップに共有フォルダを置いた場合、`/{windowsIPアドレス}/Users/{ユーザー名}/Desktop`にあると思われます。 ※ マウントを解除したい場合 ``` # unmount for root user umount /mnt/windows # unmount for non-root users fusermount -u test ``` ※ 参考URL https://ruco.la/memo/tag/fuse ### 2. Dockerイメージの作成 ``` cd site-controller-data-update-to-mysql make docker-build ``` ## 起動方法 ### デプロイ on AION `services.yml`に設定を記載し、AionCore経由でコンテナを起動します。 例) ``` site-controller-data-update-to-mysql: scale: 1 startup: yes always: yes env: KANBAN_ADDR: aion-statuskanban:10000 MYSQL_USER: MYSQL_USER_XXX MYSQL_HOST: mysql MYSQL_PASSWORD: <PASSWORD> POLLING_INTERVAL: 5 SITE_CONTOROLLER_NAME: XXX MOUNT_PATH: /mnt/windows/{共有フォルダへのパス} nextService: sc_csv: - name: omotebako-sc volumeMountPathList: - /mnt/windows:/mnt/windows/{共有フォルダへのパス} ``` {共有フォルダへのパス}の例(デスクトップにある場合):`{windowsIPアドレス}/Users/{ユーザー名}/Desktop/{フォルダ名}` ## I/O kanbanのメタデータから下記の情報を入出力します。 ### input kanbanのメタデータ ### output * outputPath: `/var/lib/aion/defalt/Data/`配下にコピーしたcsvのファイルパス * timestamp: ## エラー対処法 1. ホストのディレクトリがマウントできないと言われた時 ``` Error: failed to start container "site-controller-data-update-to-mysql-001": Error response from daemon: error while creating mount source path '/mnt/windows': mkdir /mnt/windows: file exists ``` → mac側の共有フォルダから削除 → 再度共有フォルダに追加・linuxでマウント ## ローカルからデバッグする場合 MYSQLの情報をコマンドライン引数で渡すことによって、別のローカル端末からエッジ端末のデータベースにアクセスすることができます。 <file_sep>/app/server/handlers/updateErrorStatus.go package handlers import ( "fmt" "net/http" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/models" "github.com/gin-gonic/gin" ) func UpdateErrorStatus(c *gin.Context, db *database.Database) { rows, err := models.CSVExecutionErrors( models.CSVExecutionErrorWhere.Status.EQ(0), ).All(c, db.DB) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_excution_error: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } logging.Debug(fmt.Sprintf("csv_excution_error record: %p", rows), nil) if len(rows) == 0 { logging.Info("no error csv", nil) c.JSON(http.StatusOK, gin.H{"timestamp": nil}) return } _, err = rows.UpdateAll(c, db.DB, models.M{"status": 1}) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_excution_error: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } c.JSON(http.StatusOK, gin.H{"timestamp": nil}) } <file_sep>/config/config.go package config import ( "fmt" "os" "strconv" "golang.org/x/xerrors" ) type Env struct { *MysqlEnv *WatchEnv Port string } type MysqlEnv struct { User xxxx Host xxxx Password xxxx Port xxxx } type WatchEnv struct { PollingInterval xxxx MountPath xxxx } // NewEnv 必ずEnv構造体は返る、POLLING_INTERVALに数字が入っていない場合にエラーが返る func NewEnv() (*Env, error) { watchEnv, err := NewWatchEnv() return &Env{ MysqlEnv: NewMysqlEnv(), WatchEnv: watchEnv, Port: GetEnv("PORT", "8080"), }, err } func NewMysqlEnv() *MysqlEnv { user := GetEnv("MYSQL_USER", "xxxx") host := GetEnv("MYSQL_HOST", "xxxx") pass := GetEnv("MYSQL_PASSWORD", "<PASSWORD>") port := GetEnv("MYSQL_PORT", "xxxx") return &MysqlEnv{ User: user, Host: host, Password: <PASSWORD>, Port: port, } } func NewWatchEnv() (*WatchEnv, error) { pollingInterval, err := strconv.Atoi(GetEnv("POLLING_INTERVAL", "1")) if err != nil { pollingInterval = 1 err = xerrors.Errorf("POLLING_INTERVAL should be int: %w", err) } return &WatchEnv{ PollingInterval: pollingInterval, MountPath: GetEnv("MOUNT_PATH", "/mnt/windows"), }, err } func (c *MysqlEnv) DSN() string { return fmt.Sprintf(`%v:%v@tcp(%v:%v)/%s?charset=utf8mb4&parseTime=True&loc=Local`, c.User, c.Password, c.Host, c.Port, "xxxxx") } func GetEnv(key, def string) string { value := os.Getenv(key) if value == "" { value = def } return value } <file_sep>/app/database/siteControl.go package database import ( "context" "database/sql" "fmt" scCsv "site-controller-data-update-to-mysql/app/csv" "site-controller-data-update-to-mysql/app/file" "site-controller-data-update-to-mysql/app/helper" "site-controller-data-update-to-mysql/app/models" "strings" "time" "github.com/volatiletech/null/v8" "github.com/volatiletech/sqlboiler/v4/boil" "github.com/volatiletech/sqlboiler/v4/queries/qm" "golang.org/x/xerrors" "github.com/latonaio/golang-logging-library/logger" ) type reservationGuest struct { ReservationID xxx GuestID xxx *scCsv.ReservationData } type ErrorStruct struct { CustomerName xxxx CustomerPhoneNumber xxxx ErrorMsg xxxx } var logging = logger.NewLogger() func (d *Database) TransactionReservationInfo(reservations []*scCsv.ReservationData, ctx context.Context) (map[int]ErrorStruct, error) { var reservationGuests []*reservationGuest errorMap := map[int]ErrorStruct{} for i, reservation := range reservations { tx, err := d.DB.BeginTx(ctx, nil) if err != nil { return nil, xerrors.Errorf("failed to begin transaction: %w", err) } switch reservation.Notice { case "予約": reservationGuest, err := d.addReservationInfoToDB(reservation, tx, ctx) if err != nil { errorMap[i] = ErrorStruct{ CustomerName: reservation.ReservationHolder, CustomerPhoneNumber: reservation.ReservationHolderPhoneNumber, ErrorMsg: fmt.Sprint(err), } if err := tx.Rollback(); err != nil { return nil, xerrors.Errorf("Rolleback is uncompleted: %w", err) } continue } if err := tx.Commit(); err != nil { return nil, xerrors.Errorf("Database Commit is uncompleted: %w", err) } reservationGuests = append(reservationGuests, reservationGuest) case "取消": err := deleteReservationInfoFromDB(reservation, reservationGuests, tx, ctx) if err != nil { errorMap[i] = ErrorStruct{ CustomerName: reservation.ReservationHolder, CustomerPhoneNumber: reservation.ReservationHolderPhoneNumber, ErrorMsg: fmt.Sprint(err), } if err := tx.Rollback(); err != nil { return nil, xerrors.Errorf("Rolleback is uncompleted: %w", err) } continue } if err := tx.Commit(); err != nil { return nil, xerrors.Errorf("Database Commit is uncompleted: %w", err) } default: errorMap[i] = ErrorStruct{ CustomerName: reservation.ReservationHolder, CustomerPhoneNumber: reservation.ReservationHolderPhoneNumber, ErrorMsg: fmt.Sprintf("unknown reservation type :%v", reservation.Notice), } } } if len(errorMap) != 0 { return errorMap, nil } return nil, nil } func (d *Database) GetCsvExecutionErrorsWithCsvUploadTransactionByStatus(ctx context.Context, status int) (models.CSVExecutionErrorSlice, error) { rows, err := models.CSVExecutionErrors( qm.Select("*"), models.CSVExecutionErrorWhere.Status.EQ(status), qm.Load(models.CSVExecutionErrorRels.CSV), ).All(ctx, d.DB) if err != nil { return nil, err } return rows, nil } func (d *Database) GetCsvUploadTransactionByTimeStamp(ctx context.Context, timestamp string) (models.CSVUploadTransactionSlice, error) { queries_csv_transaction := []qm.QueryMod{ qm.Where(models.CSVUploadTransactionColumns.Timestamp+"=?", timestamp), } csvTransaction, err := models.CSVUploadTransactions(queries_csv_transaction...).All(ctx, d.DB) if err != nil { return nil, err } return csvTransaction, nil } func (d *Database) GetCsvExecutionErrorsByStatus(ctx context.Context, status int) (models.CSVExecutionErrorSlice, error) { rows, err := models.CSVExecutionErrors( models.CSVExecutionErrorWhere.Status.EQ(status), ).All(ctx, d.DB) if err != nil { return nil, err } return rows, nil } func (d *Database) addReservationInfoToDB(reservation *scCsv.ReservationData, tx *sql.Tx, ctx context.Context) (*reservationGuest, error) { currentTime := time.Now() newReservationGuest := reservationGuest{ ReservationData: reservation, } stayDateFrom, err := checkInTime(reservation) if err != nil { logging.Error(fmt.Sprintf("failed to parse reservationDate: %v\n", err), nil) return &newReservationGuest, fmt.Errorf("チェックイン日が不正か入力されていません。") } stayDateTo, err := time.Parse("20060102", reservation.StayDateTo) if err != nil { logging.Error(fmt.Sprintf("failed to parse stayDateTo: %v\n", err), nil) return &newReservationGuest, fmt.Errorf("チェックアウト日が不正か入力されていません。") } reservationDate, err := time.Parse("20060102", reservation.ReservatioinDate) if err != nil { logging.Error(fmt.Sprintf("failed to parse reservationDate: %v\n", err), nil) return &newReservationGuest, fmt.Errorf("予約受信日が不正か入力されていません。") } reservationMethodId, err := checkReservationMethod(reservation, ctx, tx) if err != nil { logging.Error(fmt.Sprintf("invalid reservation method: %v", err), nil) return &newReservationGuest, fmt.Errorf("予約経路が不正か入力されていません。") } paymentMethodId, err := checkPaymentMethod(reservation.PaymentMethodName, ctx, tx) if err != nil { logging.Error(fmt.Sprintf("failed to insert payment method error: %v", err), nil) } planId := checkProductMaster(reservation.ProductCode, reservation.ProductName, ctx, tx) if Results := validateReservationData(reservation); Results != nil { logging.Error(fmt.Sprintf("validation reservation data error: %v", Results), nil) ResultsStr := fmt.Sprint(strings.Join(Results, ", ")) return &newReservationGuest, fmt.Errorf("必要な項目が入力されていません。: %v", ResultsStr) } guest := checkNewGuest(reservation, ctx, tx) // Insert reservationの準備 newReservation := models.Reservation{ ReservationHolder: null.StringFrom(reservation.ReservationHolder), ReservationHolderKana: null.StringFrom(reservation.ReservationHolderKana), StayDateFrom: null.TimeFrom(stayDateFrom), StayDateTo: null.TimeFrom(stayDateTo), StayDays: null.Int16From(reservation.StayDays), NumberOfRooms: null.Int16From(reservation.NumberOfRooms), NumberOfGuests: null.Int16From(reservation.NumberOfGuestsMale + reservation.NumberOfGuestsFemale), NumberOfGuestsMale: null.Int16From(reservation.NumberOfGuestsMale), NumberOfGuestsFemale: null.Int16From(reservation.NumberOfGuestsFemale), HasChild: null.Int8From(checkChild(reservation)), ProductID: null.StringFromPtr(planId), ReservationMethod: null.IntFrom(reservationMethodId), PaymentMethod: null.IntFrom(paymentMethodId), Coupon: null.IntFrom(0), //【要検討】0:未, 1:有, 2:無 // StatusCode: null.Int8From(0), // default:0が指定される Plan: null.StringFrom(reservation.ProductName), UpdateDate: null.TimeFrom(currentTime), // IsCheckin: null.Int8From(1), // defaultで0:未が指定される ReservationDate: null.TimeFrom(reservationDate), PaymentStatus: null.IntFrom(0), // defaultとして0:未を指定 // NewGuestFlag: null.Int8From(1), // defaultで0が指定される // DeleteFlag: null.IntFrom(1), // defaultで0が指定される } if guest == nil { logging.Info("新規顧客", nil) // Insert guest newGuests := models.Guest{ // GuestID: int Name: null.StringFrom(reservation.Name), NameKana: null.StringFrom(reservation.NameKana), Gender: null.IntFrom(1), // defaultとして1:女性を指定 // GenderByFace: null.StringFrom(), // AgeByFace: null.Float32From(), // BirthDate: null.TimeFrom(), // Age: null.IntFrom(30), // defaultとして30を指定? GuestEmail: null.StringFrom(reservation.Email), PhoneNumber: null.StringFrom(reservation.PhoneNumber), PostalCode: null.StringFrom(helper.PostalCodeFormat(reservation.PostalCode)), HomeAddress: null.StringFrom(reservation.HomeAddress), CreateDate: null.TimeFrom(currentTime), UpdateDate: null.TimeFrom(currentTime), // FaceIDAzure: null.StringFrom(), // FaceImagePath: null.StringFrom(), // DeleteFlag: null.Int8From(0), // default: 0 } if err := newGuests.Insert(ctx, tx, boil.Infer()); err != nil { logging.Error(fmt.Sprintf("failed to insert Guset record: %v", err), nil) return &newReservationGuest, fmt.Errorf("顧客情報の登録に失敗しました。") } // newReservation.GuestID = null.IntFrom(newGuests.GuestID) } else { logging.Info(fmt.Sprintf("既存顧客 guest_id: %d", guest.GuestID), nil) guest.GuestEmail = null.StringFrom(reservation.Email) guest.PhoneNumber = null.StringFrom(reservation.PhoneNumber) guest.PostalCode = null.StringFrom(helper.PostalCodeFormat(reservation.PostalCode)) guest.HomeAddress = null.StringFrom(reservation.HomeAddress) if _, err := guest.Update(ctx, tx, boil.Whitelist( models.GuestColumns.GuestEmail, models.GuestColumns.PhoneNumber, models.GuestColumns.PostalCode, models.GuestColumns.HomeAddress, )); err != nil { logging.Error(fmt.Sprintf("failed to update Guset record: %v", err), nil) return &newReservationGuest, fmt.Errorf("顧客情報の更新に失敗しました。") } newReservation.GuestID = null.IntFrom(guest.GuestID) newReservation.NewGuestFlag = null.Int8From(1) } if err := newReservation.Insert(ctx, tx, boil.Infer()); err != nil { logging.Error(fmt.Sprintf("failed to insert Reservation record: %v", err), nil) return &newReservationGuest, fmt.Errorf("予約情報の登録に失敗しました。") } logging.Info(fmt.Sprintf("add reservation ID: %v, Name: %v\n", newReservation.GuestID, newReservation.ReservationHolder), "csv") newReservationGuest = reservationGuest{ ReservationID: newReservation.ReservationID, ReservationData: reservation, } logging.Debug(fmt.Sprintf("reservation guest: %v", newReservationGuest), nil) return &newReservationGuest, nil } func deleteReservationInfoFromDB(reservation *scCsv.ReservationData, reservationGuests []*reservationGuest, tx *sql.Tx, ctx context.Context) error { updCols := map[string]interface{}{ models.ReservationColumns.DeleteFlag: 1, } targetID, err := selectDeleteReservationID(reservation, reservationGuests, tx, ctx) if err != nil || targetID == 0 { return err } query := qm.Where(models.ReservationColumns.ReservationID+"=?", targetID) _, err = models.Reservations(query).UpdateAll(ctx, tx, updCols) if err != nil { logging.Error(fmt.Sprintf("failed to update reservation delete flag: %v", err), nil) return fmt.Errorf("予約のキャンセルに失敗しました。") } return nil } func selectDeleteReservationID(reservation *scCsv.ReservationData, reservationGuests []*reservationGuest, tx *sql.Tx, ctx context.Context) (int, error) { if Results := validateDeleteReservationData(reservation); Results != nil { logging.Error(fmt.Sprintf("validation delete reservation data error: %v", Results), nil) ResultsStr := fmt.Sprint(strings.Join(Results, ", ")) return 0, fmt.Errorf("必要な項目が入力されていません。: %v", ResultsStr) } queries_guest := []qm.QueryMod{ //qm.Select("guest_id"), qm.Where(models.GuestColumns.Name+"=?", reservation.Name), qm.And(models.GuestColumns.NameKana+"=?", reservation.NameKana), qm.And(models.GuestColumns.PhoneNumber+"=?", reservation.PhoneNumber), // qm.And(models.GuestColumns.HomeAddress+"=?", reservation.PostalCode + reservation.HomeAddress), } guests, err := models.Guests(queries_guest...).All(ctx, tx) if err != nil { logging.Error(fmt.Sprintf("failed to get guest records: %v", err), nil) return 0, fmt.Errorf("キャンセルする顧客の取得に失敗しました。") } // WhereIn method needs to pass a slice of interface{} var guestIDs []interface{} for _, v := range guests { logging.Debug(fmt.Sprintf("guestID: %d", v.GuestID), nil) guestIDs = append(guestIDs, v.GuestID) } // guest_id, stayDateFrom, stayDateTo → reservationIdの特定 queries_reservation := []qm.QueryMod{ qm.WhereIn(models.ReservationColumns.GuestID+" IN ?", guestIDs), qm.And(models.ReservationColumns.StayDateTo+"=?", reservation.StayDateTo), qm.And(models.ReservationColumns.StayDays+"=?", reservation.StayDays), qm.And(models.ReservationColumns.NumberOfRooms+"=?", reservation.NumberOfRooms), qm.And(models.ReservationColumns.NumberOfGuests+"=?", reservation.NumberOfGuests), } counts, err := models.Reservations(queries_reservation...).Count(ctx, tx) if counts == 0 { logging.Debug("No reservation", nil) for _, reservationGuest := range reservationGuests { logging.Debug(fmt.Sprintf("reservationGuest: %v, %v, %v", reservationGuest.Name, reservationGuest.NameKana, reservationGuest.PhoneNumber), nil) if reservation.Name == reservationGuest.Name && reservation.NameKana == reservationGuest.NameKana && reservation.PhoneNumber == reservationGuest.PhoneNumber { return reservationGuest.ReservationID, nil } } logging.Error(fmt.Sprintf("no reservation, name: %s, phone number: %s", reservation.Name, reservation.PhoneNumber), nil) return 0, fmt.Errorf("キャンセルする予約が登録されていません。") } else if counts > 1 { logging.Error(fmt.Sprintf("multiple reservations exist, name: %v, phone number: %v", reservation.Name, reservation.PhoneNumber), nil) return 0, fmt.Errorf("キャンセルする同一予約が複数登録されています。") } else if err != nil { logging.Error(fmt.Sprintf("cannot detect delete reservationID: %v\n", err), nil) return 0, fmt.Errorf("キャンセルする予約を特定できませんでした。") } reservationId, err := models.Reservations(queries_reservation...).All(ctx, tx) if err != nil { logging.Error(fmt.Sprintf("failed to get reservation ID: %v", err), nil) // エラーメッセージ:reservationのgetエラー return 0, fmt.Errorf("キャンセルする予約の取得に失敗しました。") } logging.Info(fmt.Sprintf("delete ReservationID: %v, Name: %v\n", reservationId[0].ReservationID, reservationId[0].ReservationHolder), nil) return reservationId[0].ReservationID, nil } // TODO: websocket実装時に必要かも func (d *Database) SelectErrorCSVRowsWithIds(csvIds []int, ctx context.Context, tx *sql.Tx) (models.CSVExecutionErrorSlice, error) { // whereinに合わせて型を変換する var ids []interface{} for _, v := range csvIds { ids = append(ids, v) } // query := []qm.QueryMod{ // qm.Select("*"), // qm.From("csv_execution_errors"), // qm.InnerJoin("csv_upload_transaction on csv_upload_transaction.id = csv_execution_errors.csv_id"), // qm.WhereIn(models.CSVExecutionErrorColumns.ID+" IN ?", csvIds), // qm.WhereIn(fmt.Sprintf("%s in ?", models.CSVExecutionErrorColumns.ID), ids...), // } rows, err := models.CSVExecutionErrors(qm.InnerJoin("csv_upload_transaction on csv_upload_transaction.id = csv_execution_errors.csv_id")).All(ctx, tx) if err != nil { return nil, err } fmt.Printf("%v", *rows[0]) // rows, err := models.CSVExecutionErrors(query...).All(ctx, tx) // if err != nil { // return nil, err // } return rows, nil } func (d *Database) RegisterCSVDataToDB(ctx context.Context, file file.File, path string, id int, siteControllerName string) error { logging.Info(fmt.Sprintf("site ControllerName: %v ", siteControllerName), "controller_name") // トランザクション:insertReservation, insertGuest csvPath := fmt.Sprintf("%s/%s", path, file.Name) var reservations []*scCsv.ReservationData var err error switch siteControllerName { case "xxxx": reservations, err = scCsv.ImportFromLincoln(csvPath) case "xxxx": reservations, err = scCsv.ImportFromLincoln(csvPath) case "xxxx": reservations, err = scCsv.ImportFromLincoln(csvPath) default: return xerrors.Errorf("site controller name '%s' is not available", siteControllerName) } if err != nil { if err := d.updateCsvUploadTransactionStatusToError(id, ctx); err != nil { return xerrors.Errorf("failed to upload csv_upload_transaction status: %w", err) } return xerrors.Errorf("path: %s, failed to import csv: %w", csvPath, err) } errors, err := d.TransactionReservationInfo(reservations, ctx) // トランザクションOK...csvステータスをcompleteに変える if err == nil && errors == nil { if err := d.finishCsvUpload(id, ctx); err != nil { return fmt.Errorf("failed to upload csv_upload_transaction status: %v", err) } else { logging.Info("successful of csv uploading", nil) } } else { // トランザクションERROR...csvステータスをerrorに変える if err := d.updateCsvUploadTransactionStatusToError(id, ctx); err != nil { return fmt.Errorf("failed to upload csv_upload_transaction status: %v", err) } else { logging.Info("failed to upload csv", nil) } // csv_execution_errorにerror内容を入れる // TODO 戻り値のidsをチャネル使ってwebsocketに渡す ids := d.InsertCSVExecutionError(ctx, errors, id) logging.Debug(fmt.Sprintf("error ids: %v", ids), nil) } return nil } func (d *Database) CreateCsvUploadTransaction(ctx context.Context, fileName string, createdTime time.Time, timestamp string, path string) (*models.CSVUploadTransaction, error) { // mysqlにinsertするデータを作成 newCSVUploadTransaction := models.CSVUploadTransaction{ FileName: null.StringFrom(fileName), Status: null.StringFrom("before"), CreatedTimeInWindows: null.TimeFrom(createdTime), Timestamp: null.StringFrom(timestamp), Path: null.StringFrom(path), } // mysqlにinsertする if err := newCSVUploadTransaction.Insert(ctx, d.DB, boil.Infer()); err != nil { return nil, err } return &newCSVUploadTransaction, nil } func (d *Database) GetCSVUpdateTransaction(ctx context.Context) (models.CSVUploadTransactionSlice, error) { q := models.CSVUploadTransactions( qm.Select("id", "file_name", "created_time_in_windows"), qm.OrderBy("created_time_in_windows DESC"), ) rows, err := q.All(ctx, d.DB) if err != nil { return nil, fmt.Errorf("failed to get records of csv_upload_transaction records: %v", err) } return rows, nil } func (d *Database) updateCsvUploadTransactionStatusToError(id int, ctx context.Context) error { record := models.CSVUploadTransaction{ ID: id, Status: null.StringFrom("ERROR"), } err := record.Upsert(ctx, d.DB, boil.Whitelist(models.CSVUploadTransactionColumns.Status), boil.Infer()) if err != nil { return err } return nil } func (d *Database) finishCsvUpload(id int, ctx context.Context) error { record, err := models.CSVUploadTransactions( qm.Where(models.CSVUploadTransactionColumns.ID+" = ?", id), ).One(ctx, d.DB) if err != nil { return xerrors.Errorf("failed to get csv transaction data: %w", err) } if record.Status.String == "complete" { return xerrors.New("csv upload status is already complete") } record.Status = null.StringFrom("complete") _, err = record.Update(ctx, d.DB, boil.Infer()) if err != nil { return xerrors.Errorf("failed to get csv transaction data: %w", err) } return nil } func (d *Database) InsertCSVExecutionError(ctx context.Context, mapError map[int]ErrorStruct, csvId int) []int { var ids []int // mysqlにinsertするデータを生成 for i, errStruct := range mapError { newCSVExecutionError := models.CSVExecutionError{ //ID: null.IntFrom(), LineNumber: i + 1, CustomerName: null.StringFrom(errStruct.CustomerName), CustomerPhoneNumber: null.StringFrom(errStruct.CustomerPhoneNumber), ErrorMessage: errStruct.ErrorMsg, Status: 0, //未対応は0 CSVID: csvId, } if err := newCSVExecutionError.Insert(ctx, d.DB, boil.Infer()); err != nil { logging.Error(fmt.Sprintf("failed to insert new record to csv_execution_errors: line number: %d, error message: %v", i+1, err), nil) } // ID = 0はDB insertエラーを表します ids = append(ids, newCSVExecutionError.ID) } return ids } <file_sep>/go.mod module site-controller-data-update-to-mysql go 1.16 require ( github.com/latonaio/golang-logging-library v1.0.0 github.com/friendsofgo/errors v0.9.2 github.com/gin-contrib/cors v1.3.1 github.com/gin-gonic/gin v1.7.2 github.com/go-sql-driver/mysql v1.6.0 github.com/gocarina/gocsv v0.0.0-20210516172204-ca9e8a8ddea8 github.com/golang/glog v0.0.0-20210429001901-424d2337a529 github.com/gorilla/websocket v1.4.2 github.com/kat-co/vala v0.0.0-20170210184112-42e1d8b61f12 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd github.com/spf13/viper v1.8.1 github.com/volatiletech/null/v8 v8.1.2 github.com/volatiletech/randomize v0.0.1 github.com/volatiletech/sqlboiler/v4 v4.6.0 github.com/volatiletech/strmangle v0.0.1 golang.org/x/text v0.3.6 golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 ) <file_sep>/app/server/handlers/timestamp.go package handlers import ( "fmt" "net/http" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/models" "context" "github.com/gin-gonic/gin" "github.com/volatiletech/sqlboiler/v4/queries/qm" ) func GetLatestTimestamp(c *gin.Context, db *database.Database) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() row, err := models.CSVUploadTransactions( qm.Select("*"), qm.OrderBy("timestamp DESC"), ).One(ctx, db.DB) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_upload_transaction: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } logging.Debug(fmt.Sprintf("csv_upload_transaction record: %p", row), nil) if row == nil { logging.Info("no csv information", nil) c.JSON(http.StatusOK, gin.H{"timestamp": nil}) return } timestampStr := row.Timestamp.String timestampVal := fmt.Sprintf(`%s/%s/%s %s:%s:%s`, timestampStr[0:4], timestampStr[4:6], timestampStr[6:8], timestampStr[8:10], timestampStr[10:12], timestampStr[12:14]) logging.Info(fmt.Sprintf("latest timestamp: %s", timestampVal), nil) c.JSON(http.StatusOK, gin.H{"timestamp": timestampVal}) return } <file_sep>/mount.sh #!/bin/bash # jetson端末再起動時にwindowsサーバのフォルダーをマウントする find /mnt/windows -mindepth 1 -maxdepth 1 -type d | while read path; do rm -rf "$path" done smbnetfs /mnt/windows <file_sep>/app/file/file.go package file import ( "io/fs" "time" ) type File struct { Name string CreatedTime time.Time } type Files []*File func NewFile(file fs.FileInfo) *File { return &File{ Name: file.Name(), CreatedTime: file.ModTime(), } } <file_sep>/app/database/mysql.go package database import ( "database/sql" "site-controller-data-update-to-mysql/config" _ "github.com/go-sql-driver/mysql" "golang.org/x/xerrors" ) type Database struct { DB *sql.DB } func NewDatabase(mysqlEnv *config.MysqlEnv) (*Database, error) { db, err := sql.Open("mysql", mysqlEnv.DSN()) if err != nil { return nil, xerrors.Errorf(`database open error: %w`, err) } if err = db.Ping(); err != nil { return nil, xerrors.Errorf(`failed to connection database: %w`, err) } return &Database{ DB: db, }, nil } <file_sep>/app/server/response/authCSV.go package response type AuthCSV struct { Timestamp string `json:"timestamp"` Status string `json:"status"` Path string `json:"path"` } <file_sep>/app/server/server.go package server import ( "fmt" "site-controller-data-update-to-mysql/app/server/handlers" "time" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) type Server struct { gin *gin.Engine ws *websocket.Upgrader port string } func NewServer(port interface{}, handler *handlers.SCHandler) *Server { return &Server{ gin: gin.New(), ws: &websocket.Upgrader{ HandshakeTimeout: 5 * time.Second, ReadBufferSize: 0, WriteBufferSize: 0, WriteBufferPool: nil, Subprotocols: nil, Error: nil, CheckOrigin: nil, EnableCompression: false, }, port: fmt.Sprintf(`:%v`, port), } } <file_sep>/app/server/router/route.go package router import ( "fmt" "log" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/server/handlers" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "github.com/latonaio/golang-logging-library/logger" ) type Server struct { gin *gin.Engine ws *websocket.Upgrader port string db *database.Database log *logger.Logger } func NewServer(port string, db *database.Database, logging *logger.Logger) *Server { return &Server{ gin: gin.New(), ws: &websocket.Upgrader{ HandshakeTimeout: 5 * time.Second, ReadBufferSize: 0, WriteBufferSize: 0, WriteBufferPool: nil, Subprotocols: nil, Error: nil, CheckOrigin: nil, EnableCompression: false, }, port: fmt.Sprintf(`:%v`, port), db: db, log: logging, } } func (s *Server) Route() { handler := handlers.NewSCHandler(s.db, s.log) s.gin.Use(cors.New(cors.Config{ AllowOrigins: []string{ "*", }, AllowMethods: []string{ "POST", "GET", "PUT", "OPTIONS", "DELETE", }, AllowHeaders: []string{ "Accept", "Authorization", "Content-type", "X-CSRF-Token", }, ExposeHeaders: []string{ "Link", }, AllowCredentials: false, MaxAge: 300, })) // restAPI一覧 s.gin.GET("/api/auth/csv/:timestamp", handler.GetAuthCSV) baseGroup := s.gin.Group("/api/csv") // エラーハンドリング用エンドポイントその1 baseGroup.GET("/transaction/display/errors", handler.CSVError) // エラーテーブルにあるエラーを全て解決済みに更新する baseGroup.POST("/error/resolve", handler.UpdateErrorStatus) // csv手動登録用エンドポイント baseGroup.POST("/:timestamp", handler.CreateCSV) // 前回の手動連携日時を返すエンドポイント baseGroup.GET("/transaction/latest", handler.GetLatestTimestamp) //g.GET("/:timestamp") //g.POST("/:timestamp") // TODO エラーハンドリング用エンドポイントその2 s.gin.GET("/ws", func(c *gin.Context) { // handlers.GetCSVErrorHandler(c.Writer, c.Request) // handlers.WsConnect(c, s.db) // handlers.WsConnect(c, s.db, channel) }) } func (s *Server) Run() { // log.Println("run server") if err := s.gin.Run(s.port); err != nil { log.Printf("run server error :%v", err) } } <file_sep>/Makefile docker-build: bash builders/docker-build.sh docker-push: bash builders/docker-build.sh push delete-table: bash misc/delete-table.sh<file_sep>/app/main.go package main import ( "context" "fmt" "os" "os/signal" "site-controller-data-update-to-mysql/app/cmd/fileController" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/file" "site-controller-data-update-to-mysql/app/server/router" "site-controller-data-update-to-mysql/config" "github.com/latonaio/golang-logging-library/logger" ) func Server(port string, db *database.Database, logging *logger.Logger) { // Server構造体作成 s := router.NewServer(port, db, logging) // Route実行 s.Route() // Server実行 s.Run() } func main() { var logging = logger.NewLogger() ctx := context.Background() // // Watch内で、新しいファイルが生成されるまで待機させる。 listAuto := make(chan file.Files) // DB構造体作成 env, err := config.NewEnv() if err != nil { logging.Warn(fmt.Sprintf("NewEnv error: %+v", err), nil) } db, err := database.NewDatabase(env.MysqlEnv) if err != nil { logging.Error(fmt.Sprintf("failed to create database: %+v", err), nil) return } // mainを終了させるためのチャネル quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt) // mainが終了した時にgoルーチンも終了するためのチャネル done := make(chan bool, 1) siteControllerName := config.GetEnv("SITE_CONTROLLER_NAME", "Lincoln") // 自動でcsvファイルからデータをMySQLに入れるgoルーチン go fileController.Watch(ctx, listAuto, done, db, env.WatchEnv) // HTTPサーバを立てる go Server(env.Port, db, logging) for { select { // 自動登録 case newFileList := <-listAuto: for _, file := range newFileList { logging.Info(fmt.Sprintf("target fileName: %v\n", file.Name), nil) // csv登録...status=before model, err := db.CreateCsvUploadTransaction(ctx, file.Name, file.CreatedTime, "", "") if err != nil { logging.Error(fmt.Sprintf("failed to insert record to database: %v", err), nil) } if err := db.RegisterCSVDataToDB(ctx, *file, env.MountPath, model.ID, siteControllerName); err != nil { logging.Error(err, nil) } } case <-quit: goto END } } END: done <- true logging.Info("finish main function", nil) } <file_sep>/app/helper/format.go package helper import "strings" // PostalCodeFormat format the zip code; 1234567 to 123-4567 func PostalCodeFormat(postalCode string) string { if strings.Contains(postalCode, "-") { return postalCode } return postalCode[:3] + "-" + postalCode[3:] } <file_sep>/app/database/validation.go package database import ( "database/sql" "fmt" scCsv "site-controller-data-update-to-mysql/app/csv" "site-controller-data-update-to-mysql/app/helper" "site-controller-data-update-to-mysql/app/models" "time" "context" "github.com/volatiletech/null/v8" "github.com/volatiletech/sqlboiler/v4/boil" "github.com/volatiletech/sqlboiler/v4/queries/qm" ) func checkInTime(reservation *scCsv.ReservationData) (time.Time, error) { if len(reservation.CheckInTime) > 0 { stayDateFrom, err := time.Parse("20060102 15:04", reservation.StayDateFrom+" "+reservation.CheckInTime) if err != nil { return time.Time{}, fmt.Errorf("failed to parse checkInTime: %v\n", err) } return stayDateFrom, nil } else { stayDateFrom, err := time.Parse("20060102", reservation.StayDateFrom) if err != nil { return time.Time{}, fmt.Errorf("failed to parse checkInTime: %v\n", err) } return stayDateFrom, nil } } func checkChild(reservation *scCsv.ReservationData) int8 { numChild := reservation.NumberOfGuestsChildA + reservation.NumberOfGuestsChildB + reservation.NumberOfGuestsChildC + reservation.NumberOfGuestsChildD if numChild > 0 { return 1 //有 } else { return 0 } } func checkPaymentMethod(paymentMethodName string, ctx context.Context, tx *sql.Tx) (int, error) { if paymentMethodName != "" { id, err := getPaymentMethod(paymentMethodName, ctx, tx) if err != nil { logging.Info(fmt.Sprintf("failed to get payment method error: %v", err), nil) } if id == 0 { id, err = insertPaymentMethod(paymentMethodName, ctx, tx) if err != nil { return 0, err } return id, nil } return id, nil } id, err := getPaymentMethod("指定なし", ctx, tx) if err != nil { logging.Info(fmt.Sprintf("failed to get payment method id correspond to '指定なし' error: %v", err), nil) } return id, nil } func getPaymentMethod(paymentMethodName string, ctx context.Context, tx *sql.Tx) (int, error) { record, err := models.PaymentMethodMasters( qm.Where(models.PaymentMethodMasterColumns.PaymentMethodName+" = ?", paymentMethodName), ).One(ctx, tx) if err != nil { return 0, err } if record == nil { return 0, fmt.Errorf("%s not found", paymentMethodName) } return record.PaymentMethodID, nil } func insertPaymentMethod(paymentMethodName string, ctx context.Context, tx *sql.Tx) (int, error) { newPaymentMethodMaster := models.PaymentMethodMaster{ //ReservationMethodID: int, PaymentMethodName: null.StringFrom(paymentMethodName), } if err := newPaymentMethodMaster.Insert(ctx, tx, boil.Infer()); err != nil { return 0, err } return newPaymentMethodMaster.PaymentMethodID, nil } func checkReservationMethod(reservation *scCsv.ReservationData, ctx context.Context, tx *sql.Tx) (int, error) { if reservation.SalesAgentShopName != "" { id, err := getReservationMethod(reservation.SalesAgentShopName, ctx, tx) if err != nil { logging.Info(fmt.Sprintf("failed to get reservation method error: %v", err), nil) } if id == 0 { logging.Debug("start inserting reservation method master", nil) id, err = insertReservationMethod(reservation.SalesAgentShopName, ctx, tx) if err != nil { return 0, err } logging.Debug("finish inserting reservation method master", nil) return id, nil } return id, nil } return 0, fmt.Errorf("sales agent shop name is null") } func getReservationMethod(reservationMethod string, ctx context.Context, tx *sql.Tx) (int, error) { record, err := models.ReservationMethodMasters( qm.Where(models.ReservationMethodMasterColumns.ReservationMethodName+" = ?", reservationMethod), ).One(ctx, tx) if err != nil { return 0, err } if record == nil { return 0, fmt.Errorf("%s not found", reservationMethod) } return record.ReservationMethodID, nil } func insertReservationMethod(reservationMethod string, ctx context.Context, tx *sql.Tx) (int, error) { newReservationMethodMaster := models.ReservationMethodMaster{ //ReservationMethodID: int, ReservationMethodName: null.StringFrom(reservationMethod), } if err := newReservationMethodMaster.Insert(ctx, tx, boil.Infer()); err != nil { return 0, err } return newReservationMethodMaster.ReservationMethodID, nil } func checkProductMaster(productId, productName string, ctx context.Context, tx *sql.Tx) *string { // プランコード、プラン名がproduct_masterテーブルのproduct_id, product_nameに一致するかチェック if productId == "" || productName == "" { return nil } planId, err := getProductMaster(productId, productName, ctx, tx) if err != nil { logging.Info(fmt.Sprintf("failed to get product master error: %v", err), nil) } return planId } func getProductMaster(productId, productName string, ctx context.Context, tx *sql.Tx) (*string, error) { record, err := models.ProductMasters( qm.Where(models.ProductMasterColumns.ProductID+" = ?", productId), qm.And(models.ProductMasterColumns.ProductName+" = ?", productName), ).One(ctx, tx) if err != nil { return nil, err } if record == nil { return nil, fmt.Errorf("%s not found", productId) } return &record.ProductID, nil } func validateReservationData(reservation *scCsv.ReservationData) []string { var validationStr []string if reservation.Name == "" { validationStr = append(validationStr, "団体名または代表者氏名 漢字") } if reservation.NameKana == "" { validationStr = append(validationStr, "団体名または代表者氏名(半角)") } if reservation.PhoneNumber == "" { validationStr = append(validationStr, "団体または代表者番号") } if reservation.PostalCode == "" { validationStr = append(validationStr, "団体または代表者郵便番号") } if reservation.HomeAddress == "" { validationStr = append(validationStr, "団体または代表者住所") } if reservation.ReservationHolder == "" { validationStr = append(validationStr, "予約者・会員名漢字") } if reservation.ReservationHolderKana == "" { validationStr = append(validationStr, "予約者・会員名カタカナ") } if reservation.StayDays == 0 { validationStr = append(validationStr, "泊数") } if reservation.NumberOfRooms == 0 { validationStr = append(validationStr, "利用客室合計数") } if reservation.NumberOfGuests == 0 { validationStr = append(validationStr, "お客様総合計人数") } if reservation.ProductName == "" { validationStr = append(validationStr, "プラン名") } return validationStr } func checkNewGuest(reservation *scCsv.ReservationData, ctx context.Context, tx *sql.Tx) *models.Guest { guestRecord, err := models.Guests( qm.Select(models.GuestColumns.GuestID), qm.Where(models.GuestColumns.Name+" = ?", reservation.Name), qm.And(models.GuestColumns.NameKana+" = ?", reservation.NameKana), qm.And(models.GuestColumns.PhoneNumber+" = ? or "+models.GuestColumns.PostalCode+" = ?", reservation.PhoneNumber, helper.PostalCodeFormat(reservation.PostalCode)), ).One(ctx, tx) if err != nil { logging.Info(fmt.Sprintf("failed to check new guest error: %v", err), nil) } if guestRecord == nil { return nil } return guestRecord } func validateDeleteReservationData(reservation *scCsv.ReservationData) []string { var validationStr []string if reservation.Name == "" { validationStr = append(validationStr, "団体名または代表者氏名 漢字") } if reservation.NameKana == "" { validationStr = append(validationStr, "団体名または代表者氏名(半角)") } if reservation.PhoneNumber == "" { validationStr = append(validationStr, "団体または代表者番号") } return validationStr } <file_sep>/app/cmd/fileController/watch.go package fileController import ( "context" "fmt" "os" "os/signal" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/file" "site-controller-data-update-to-mysql/config" "syscall" "time" "github.com/latonaio/golang-logging-library/logger" ) var logging = logger.NewLogger() func Watch(ctx context.Context, list chan<- file.Files, done <-chan bool, db *database.Database, env *config.WatchEnv) { logging.Info("created watch go routine", nil) // DBから最新のファイルの作成情報を取得する rows, err := db.GetCSVUpdateTransaction(ctx) if err != nil { } var latestFileCreatedTime time.Time if len(rows) > 0 { createdTimeInWindows := rows[0].CreatedTimeInWindows if t, _ := createdTimeInWindows.Value(); t != nil { latestFileCreatedTime = t.(time.Time) } } tickTime := time.Duration(env.PollingInterval) * time.Minute ticker := time.NewTicker(tickTime) defer ticker.Stop() signalCh := make(chan os.Signal, 1) signal.Notify(signalCh, syscall.SIGTERM) for { select { case s := <-signalCh: logging.Info(fmt.Sprintf("received signal: %s", s.String()), nil) return case <-ticker.C: logging.Info(fmt.Sprintf("start watch %s ", env.MountPath), nil) logging.Info(fmt.Sprintf("latest file created time: %v", latestFileCreatedTime), nil) newFileList, err := file.GetFileList(&latestFileCreatedTime, env.MountPath) if err != nil { goto L } if len(newFileList) == 0 { goto L } // ファイル登録処理へ渡す list <- newFileList // 最新ファイルの更新 latestFileCreatedTime = newFileList[0].CreatedTime case <-done: goto END } L: logging.Info(fmt.Sprintf("finish watch %s", env.MountPath), nil) } END: logging.Info("finish Watch goroutine", nil) } <file_sep>/app/file/watch.go package file import ( "fmt" "io/fs" "path/filepath" "sort" "time" ) func GetFileList(latestFileCreatedTime *time.Time, watchDirPath string) (Files, error) { var fileList Files err := filepath.Walk(watchDirPath, func(path string, info fs.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { if latestFileCreatedTime.Before(info.ModTime()) { file := NewFile(info) fileList = append(fileList, file) } } return nil }) if err != nil { return nil, fmt.Errorf("cannot get file list in %v: %v", watchDirPath, err) } // 新しい順に並び替え sort.Slice(fileList, func(i, j int) bool { return fileList[i].CreatedTime.Unix() > fileList[j].CreatedTime.Unix() }) for _, file := range fileList { fmt.Printf("%s\n", file.Name) } return fileList, nil } <file_sep>/app/server/response/CsvExecutionError.go package response type Error struct { LineNumber int `json:"lineNumber"` CustomerName string `json:"customerName"` CustomerPhoneNumber string `json:"customerPhoneNumber"` } type CsvExectutionError struct { FileName string `json:"fileName"` Errors []Error `json:"errors"` } <file_sep>/app/csv/import.go package csv import ( "fmt" "os" "golang.org/x/xerrors" "github.com/gocarina/gocsv" ) type ReservationData struct { Notice string `csv:"xxxxxx"` sampleCode string `csv:"sample"` `...` } func ImportFromLincoln(csvPath string) ([]*ReservationData, error) { file, err := os.OpenFile(csvPath, os.O_RDWR|os.O_CREATE, os.ModePerm) if err != nil { return nil, xerrors.New("cannot open csv file") } defer file.Close() reservations := []*ReservationData{} if err := gocsv.UnmarshalFile(file, &reservations); err != nil { return nil, fmt.Errorf("cannot decode csv file to struct: %v\n", err) } return reservations, nil } <file_sep>/app/database/siteControl_test.go package database import ( "context" "fmt" scCsv "site-controller-data-update-to-mysql/app/csv" "site-controller-data-update-to-mysql/config" "testing" "time" "github.com/golang/glog" ) func TestAddReservationInfoToDB(t *testing.T) { SampleReservation := scCsv.ReservationData{ Notice: "", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "", NotificationNumber: 0, NameKana: "", Name: "", StayDateFrom: "", CheckInTime: "", StayDateTo: "", StayDays: 0, Transportation: "", PassengerCategory: "", NumberOfRooms: 0, NumberOfGuests: 0, NumberOfGuestsMale: 0, NumberOfGuestsFemale: 0, NumberOfGuestsChildA: 0, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "", Email: "", PostalCode: "", HomeAddress: "", NumberOfGuestsAdult: 0, ReservationHolder: "", ReservationHolderKana: "", ReservationHolderPhoneNumber: "", ReservationHolderEmail: "", ReservationHolderPostalCode: "", ReservationHolderHomeAddress: "", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, } env := &config.MysqlEnv{ User: "xxxx", Host: "xxxx", Password: "<PASSWORD>", Port: "xxxx", } db, err := NewDatabase(env) if err != nil { glog.Errorf("failed to create database: %v", err) return } ctx, cancel := context.WithCancel(context.Background()) defer cancel() tx, _ := db.DB.Begin() t.Run("test", func(t *testing.T) { if _, err := db.addReservationInfoToDB(&SampleReservation, tx, ctx); err != nil { t.Errorf("%v", err) } }) } func TestTransactionReservationInfo(t *testing.T) { SampleReservation1 := scCsv.ReservationData{ Notice: "予約", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "20060102", NotificationNumber: 0, NameKana: "テスト1", Name: "テスト1", StayDateFrom: "20210701", CheckInTime: "15:03", StayDateTo: "20210703", StayDays: 0, Transportation: "", PassengerCategory: "", NumberOfRooms: 0, NumberOfGuests: 0, NumberOfGuestsMale: 0, NumberOfGuestsFemale: 0, NumberOfGuestsChildA: 0, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "1111111", Email: "", PostalCode: "", HomeAddress: "", NumberOfGuestsAdult: 0, ReservationHolder: "", ReservationHolderKana: "", ReservationHolderPhoneNumber: "", ReservationHolderEmail: "", ReservationHolderPostalCode: "", ReservationHolderHomeAddress: "", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, } SampleReservation2 := scCsv.ReservationData{ Notice: "予約", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "20060102", NotificationNumber: 0, NameKana: "テスト2", Name: "テスト2", StayDateFrom: "20060102", CheckInTime: "15:04", StayDateTo: "20060103", StayDays: 0, Transportation: "", PassengerCategory: "", NumberOfRooms: 0, NumberOfGuests: 0, NumberOfGuestsMale: 0, NumberOfGuestsFemale: 0, NumberOfGuestsChildA: 0, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "2222222", Email: "", PostalCode: "", HomeAddress: "", NumberOfGuestsAdult: 0, ReservationHolder: "", ReservationHolderKana: "", ReservationHolderPhoneNumber: "", ReservationHolderEmail: "", ReservationHolderPostalCode: "", ReservationHolderHomeAddress: "", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, } SampleReservation3 := scCsv.ReservationData{ Notice: "取消", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "20060102", NotificationNumber: 0, NameKana: "テスト2", Name: "テスト2", StayDateFrom: "20060102", CheckInTime: "15:04", StayDateTo: "20060103", StayDays: 0, Transportation: "", PassengerCategory: "", NumberOfRooms: 0, NumberOfGuests: 0, NumberOfGuestsMale: 0, NumberOfGuestsFemale: 0, NumberOfGuestsChildA: 0, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "2222222", Email: "", PostalCode: "", HomeAddress: "", NumberOfGuestsAdult: 0, ReservationHolder: "", ReservationHolderKana: "", ReservationHolderPhoneNumber: "", ReservationHolderEmail: "", ReservationHolderPostalCode: "", ReservationHolderHomeAddress: "", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, } SampleReservations := []*scCsv.ReservationData{ &SampleReservation1, &SampleReservation2, &SampleReservation3, } env := &config.MysqlEnv{ User: "xxxx", Host: "xxxx", Password: "<PASSWORD>", Port: "xxxx", } db, err := NewDatabase(env) if err != nil { t.Errorf("failed to create database: %v", err) return } ctx, cancel := context.WithCancel(context.Background()) defer cancel() t.Run("test", func(t *testing.T) { errors, err := db.TransactionReservationInfo(SampleReservations, ctx) if err != nil { t.Errorf("failed to process transaction: %v", err) } if len(errors) != 0 { for i, err := range errors { t.Errorf("%dth row error: %v", i, err) } } }) } func TestTransaction(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() env := &config.MysqlEnv{ User: "xxxx", Host: "xxxx", Password: "<PASSWORD>", Port: "xxxx", } db, err := NewDatabase(env) if err != nil { t.Errorf("failed to create database: %v", err) return } var id int SampleReservationError1 := []*scCsv.ReservationData{ { Notice: "予約", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "テストトラベル", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "20060102", NotificationNumber: 0, NameKana: "テスト1", Name: "テスト1", StayDateFrom: "20210701", CheckInTime: "15:03", StayDateTo: "20210703", StayDays: 2, Transportation: "", PassengerCategory: "", NumberOfRooms: 1, NumberOfGuests: 3, NumberOfGuestsMale: 1, NumberOfGuestsFemale: 1, NumberOfGuestsChildA: 1, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "テストプラン1", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "1111111", Email: "", PostalCode: "111-2222", HomeAddress: "テスト都テスト区テスト111", NumberOfGuestsAdult: 0, ReservationHolder: "テスト1", ReservationHolderKana: "テスト1", ReservationHolderPhoneNumber: "00011112222", ReservationHolderEmail: "", ReservationHolderPostalCode: "111-2222", ReservationHolderHomeAddress: "テスト都テスト区テスト111", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, }, { Notice: "取消", SalesAgentCode: "", SalesAgentName: "", SalesAgentShopName: "テストトラベル", SalesAgentShopCode: 0, SalesAgentContactPerson: "", SalesAgentContactEmail: "", SalesAgentContactPhoneNumber: "", SalesAgentContactFax: "", SalesAgentPlace: "", ReservatioinNumber: "", ReservatioinDate: "20060102", NotificationNumber: 0, NameKana: "テスト2", Name: "テスト2", StayDateFrom: "20210701", CheckInTime: "15:03", StayDateTo: "20210703", StayDays: 2, Transportation: "", PassengerCategory: "", NumberOfRooms: 1, NumberOfGuests: 3, NumberOfGuestsMale: 1, NumberOfGuestsFemale: 1, NumberOfGuestsChildA: 1, NumberOfGuestsChildB: 0, NumberOfGuestsChildC: 0, NumberOfGuestsChildD: 0, NumberOfGuide: 0, ParticipationForm: "", ProductName: "テストプラン2", ProductCode: "", StayCondition: "", PricePerUnit: "", PriceType: "", TotalPrice: 0, TotalPriceOther: 0, PhoneNumber: "2222222222222", Email: "", PostalCode: "111-2222", HomeAddress: "テスト都テスト区テスト111", NumberOfGuestsAdult: 0, ReservationHolder: "テスト2", ReservationHolderKana: "テスト2", ReservationHolderPhoneNumber: "00011112222", ReservationHolderEmail: "", ReservationHolderPostalCode: "111-2222", ReservationHolderHomeAddress: "テスト都テスト区テスト111", ReservationHolderCompanyName: "", ReservationHolderCompanyDepartment: "", ReservationHolderMembershipNumber: "", PointsDiscount: 0, PointsAwarded: 0, PointsAllocated: 0, PaymentMethodName: "", UseOfDay1: 0, RoomType1: "", NumberOfRoom1: 0, RoomPrice1: 0, PriceOfMale1: 0, PriceOfFemale1: 0, PriceOfChildA1: 0, PriceOfChildB1: 0, PriceOfChildC1: 0, PriceOfChildD1: 0, UseOfDay2: 0, RoomType2: "", NumberOfRoom2: 0, RoomPrice2: 0, PriceOfMale2: 0, PriceOfFemale2: 0, PriceOfChildA2: 0, PriceOfChildB2: 0, PriceOfChildC2: 0, PriceOfChildD2: 0, UseOfDay3: 0, RoomType3: "", NumberOfRoom3: 0, RoomPrice3: 0, PriceOfMale3: 0, PriceOfFemale3: 0, PriceOfChildA3: 0, PriceOfChildB3: 0, PriceOfChildC3: 0, PriceOfChildD3: 0, UseOfDay4: 0, RoomType4: "", NumberOfRoom4: 0, RoomPrice4: 0, PriceOfMale4: 0, PriceOfFemale4: 0, PriceOfChildA4: 0, PriceOfChildB4: 0, PriceOfChildC4: 0, PriceOfChildD4: 0, UseOfDay5: 0, RoomType5: "", NumberOfRoom5: 0, RoomPrice5: 0, PriceOfMale5: 0, PriceOfFemale5: 0, PriceOfChildA5: 0, PriceOfChildB5: 0, PriceOfChildC5: 0, PriceOfChildD5: 0, UseOfDay6: 0, RoomType6: "", NumberOfRoom6: 0, RoomPrice6: 0, PriceOfMale6: 0, PriceOfFemale6: 0, PriceOfChildA6: 0, PriceOfChildB6: 0, PriceOfChildC6: 0, PriceOfChildD6: 0, UseOfDay7: 0, RoomType7: "", NumberOfRoom7: 0, RoomPrice7: 0, PriceOfMale7: 0, PriceOfFemale7: 0, PriceOfChildA7: 0, PriceOfChildB7: 0, PriceOfChildC7: 0, PriceOfChildD7: 0, UseOfDay8: 0, RoomType8: "", NumberOfRoom8: 0, RoomPrice8: 0, PriceOfMale8: 0, PriceOfFemale8: 0, PriceOfChildA8: 0, PriceOfChildB8: 0, PriceOfChildC8: 0, PriceOfChildD8: 0, UseOfDay9: 0, RoomType9: "", NumberOfRoom9: 0, RoomPrice9: 0, PriceOfMale9: 0, PriceOfFemale9: 0, PriceOfChildA9: 0, PriceOfChildB9: 0, PriceOfChildC9: 0, PriceOfChildD9: 0, UseOfDay10: 0, RoomType10: "", NumberOfRoom10: 0, RoomPrice10: 0, PriceOfMale10: 0, PriceOfFemale10: 0, PriceOfChildA10: 0, PriceOfChildB10: 0, PriceOfChildC10: 0, PriceOfChildD10: 0, UseOfDay11: 0, RoomType11: "", NumberOfRoom11: 0, RoomPrice11: 0, PriceOfMale11: 0, PriceOfFemale11: 0, PriceOfChildA11: 0, PriceOfChildB11: 0, PriceOfChildC11: 0, PriceOfChildD11: 0, UseOfDay12: 0, RoomType12: "", NumberOfRoom12: 0, RoomPrice12: 0, PriceOfMale12: 0, PriceOfFemale12: 0, PriceOfChildA12: 0, PriceOfChildB12: 0, PriceOfChildC12: 0, PriceOfChildD12: 0, OptionName1: "", OptionPrice1: 0, OptionName2: "", OptionPrice2: 0, NumberOfOptions2: 0, OptionName3: "", OptionPrice3: 0, NumberOfOptions3: 0, OptionName4: "", OptionPrice4: 0, NumberOfOptions4: 0, OptionName5: "", OptionPrice5: 0, NumberOfOptions5: 0, Notes: "", LincolnSalesAgentCode: 0, InitSalesAgentCode: 0, }, } tests := []struct { name string reservationData []*scCsv.ReservationData }{ { name: "正常系", reservationData: SampleReservationError1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { model, err := db.CreateCsvUploadTransaction(ctx, "test.csv", time.Now(), "", "") if err != nil { t.Errorf("failed to insert record to database: %v", err) } errors, err := db.TransactionReservationInfo(tt.reservationData, ctx) if err == nil && errors == nil { if err := db.finishCsvUpload(model.ID, ctx); err != nil { t.Errorf("failed to upload csv_upload_transaction status: %v", err) } else { logging.Info("successful of csv uploading", nil) } } else { if err := db.updateCsvUploadTransactionStatusToError(id, ctx); err != nil { t.Errorf("failed to upload csv_upload_transaction status: %v", err) } else { logging.Info("failed to upload csv", nil) } ids := db.InsertCSVExecutionError(ctx, errors, id) logging.Info(fmt.Sprintf("error ids: %v", ids), nil) } }) } } func TestSelectErrorCSVRows(t *testing.T) { env := &config.MysqlEnv{ User: "xxxx", Host: "xxxx", Password: "<PASSWORD>", Port: "xxxx", } db, err := NewDatabase(env) if err != nil { glog.Errorf("failed to create database: %v", err) return } ctx, cancel := context.WithCancel(context.Background()) defer cancel() t.Run("test", func(t *testing.T) { rows, err := db.GetCsvExecutionErrorsWithCsvUploadTransactionByStatus(ctx, 0) if err != nil { t.Errorf("%v", err) } fmt.Printf("%v", rows) }) } <file_sep>/app/server/handlers/siteControlHandler.go package handlers import ( "fmt" "io" "net/http" "net/http/httputil" "os" "site-controller-data-update-to-mysql/app/database" "site-controller-data-update-to-mysql/app/file" "site-controller-data-update-to-mysql/app/models" "strings" "time" "github.com/gin-gonic/gin" "github.com/latonaio/golang-logging-library/logger" "github.com/volatiletech/sqlboiler/v4/queries/qm" ) const ( CONSARVATION_PATH string = "/var/lib/aion/Data" ) type errors struct { LineNumber int `json:"line_number"` CustomerName string `json:"customer_name"` CustomerPhoneNumber string `json:"customer_phone_number"` } type SCHandler struct { db *database.Database log *logger.Logger } var logging = logger.NewLogger() func NewSCHandler(db *database.Database, logging *logger.Logger) *SCHandler { return &SCHandler{ db: db, log: logging, } } func (h *SCHandler) GetAuthCSV(c *gin.Context) { timestamp := c.Param("timestamp") rows, err := h.db.GetCsvUploadTransactionByTimeStamp(c.Request.Context(), timestamp) if err != nil { h.log.Error(fmt.Sprintf("database error: %+v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"status": "before"}) return } if len(rows) == 1 { row := rows[0] c.JSON(http.StatusOK, gin.H{"timestamp": row.Timestamp.String, "status": row.Status.String, "path": row.Path.String}) return } c.JSON(http.StatusInternalServerError, gin.H{"status": "before"}) return } func (h *SCHandler) CSVError(c *gin.Context) { // ステータスが未解決(0)のCSVエラー情報を取得する rows, err := h.db.GetCsvExecutionErrorsWithCsvUploadTransactionByStatus(c.Request.Context(), 0) if err != nil { logging.Error(fmt.Sprintf("cannot get csv error rows: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"error": []errors{}}) return } if len(rows) == 0 { c.JSON(http.StatusOK, gin.H{ "errors": []errors{}, }) return } row := rows[0] res := map[string]interface{}{ "file_name": row.R.CSV.FileName.String, "errors": []errors{ { LineNumber: row.LineNumber, CustomerName: row.CustomerName.String, CustomerPhoneNumber: row.CustomerPhoneNumber.String, }, }, } c.JSON(http.StatusOK, res) return } func (h *SCHandler) UpdateErrorStatus(c *gin.Context) { // ステータスが未解決(0)のレコードを取得する rows, err := h.db.GetCsvExecutionErrorsByStatus(c.Request.Context(), 0) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_excution_error: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } h.log.Debug(fmt.Sprintf("csv_excution_error record: %p", rows), nil) if len(rows) == 0 { h.log.Debug("no error csv", nil) c.JSON(http.StatusOK, gin.H{"timestamp": nil}) return } _, err = rows.UpdateAll(c, h.db.DB, models.M{"status": 1}) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_excution_error: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } c.JSON(http.StatusOK, gin.H{"timestamp": nil}) } func (h *SCHandler) CreateCSV(c *gin.Context) { timestamp := c.Param("timestamp") siteControllerName := c.Query("SC") if siteControllerName == "" { h.log.Error("failed to get site controller name", nil) c.String(http.StatusBadRequest, "BAD REQUEST") return } ctx := c.Request.Context() // リクエストの情報を出力 body, err := httputil.DumpRequest(c.Request, true) if err != nil { h.log.Error(fmt.Sprintf("failed to bind request body: %v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } h.log.Debug(fmt.Sprintf("req body: %v", body), nil) // "file"というフィールド名に一致するファイルが出力される formFile, _, err := c.Request.FormFile("file") if err != nil { h.log.Error(fmt.Sprintf("failed to get file: %v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } defer formFile.Close() // ファイル名をトリム defaultFileName := c.Request.FormValue("defaultFileName") trimmedDefaultFileName := strings.Trim(defaultFileName, ".csv") // csvファイルの情報を取得するために一度ファイルをローカル(コンテナ内)に保存する //データを保存するファイルを開く filePath := fmt.Sprintf("%v/%v_%v.csv", CONSARVATION_PATH, trimmedDefaultFileName, timestamp) saveFile, err := os.Create(filePath) if err != nil { h.log.Error(fmt.Sprintf("failed to save file: %v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } defer saveFile.Close() // ファイルにデータを書き込む _, err = io.Copy(saveFile, formFile) if err != nil { logging.Error(fmt.Sprintf("failed to copy file: %+v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } // ファイルのデータをDBに突っ込む fileInfo, err := saveFile.Stat() if err != nil { logging.Error(fmt.Sprintf("failed to get file info: %+v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } file := file.File{ Name: fileInfo.Name(), CreatedTime: fileInfo.ModTime(), } model, err := h.db.CreateCsvUploadTransaction(ctx, file.Name, time.Time{}, timestamp, filePath) if err != nil { logging.Error(fmt.Sprintf("failed to insert record to database: %+v", err), nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } if err := h.db.RegisterCSVDataToDB(ctx, file, CONSARVATION_PATH, model.ID, siteControllerName); err != nil { logging.Error(err, nil) c.String(http.StatusInternalServerError, "INTERNAL SERVER ERROR") return } c.String(http.StatusOK, "ok") } func (h *SCHandler) GetLatestTimestamp(c *gin.Context) { ctx := c.Request.Context() row, err := models.CSVUploadTransactions( qm.Select("*"), qm.OrderBy("timestamp DESC"), ).One(ctx, h.db.DB) if err != nil { logging.Error(fmt.Sprintf("failed to get csv_upload_transaction: %v", err), nil) c.JSON(http.StatusInternalServerError, gin.H{"timestamp": nil}) return } logging.Debug(fmt.Sprintf("csv_upload_transaction record: %p", row), nil) if row == nil { logging.Info("no csv information", nil) c.JSON(http.StatusOK, gin.H{"timestamp": nil}) return } timestampStr := row.Timestamp.String h.log.Info(timestampStr, nil) timestampVal := fmt.Sprintf(`%s/%s/%s %s:%s:%s`, timestampStr[0:4], timestampStr[4:6], timestampStr[6:8], timestampStr[8:10], timestampStr[10:12], timestampStr[12:14]) logging.Info(fmt.Sprintf("latest timestamp: %s", timestampVal), nil) c.JSON(http.StatusOK, gin.H{"timestamp": timestampVal}) return } <file_sep>/sqlboiler.toml pkgname="models" output="app/models" [mysql] dbname = xxxxxx host = xxx.xxx.xxx.xxx port = xxxxx user = xxxxx pass = <PASSWORD> sslmode= "false" blacklist = [ "audio_settings", "payment_detail", "payment_detail_transaction", "payment_transaction", "price_table", "room_maintenance" ] # sqlboiler mysql --output app/models <file_sep>/Dockerfile # syntax = docker/dockerfile:experimental FROM golang:1.16.2 as builder ENV GO111MODULE on ENV GOPRIVATE "bitbucket.org/xxxxxx" WORKDIR /go/src/bitbucket.org/xxxxxx COPY go.mod . RUN git config --global url."<EMAIL>:".insteadOf "https://bitbucket.org/" RUN mkdir /root/.ssh/ && touch /root/.ssh/known_hosts && ssh-keyscan -t rsa bitbucket.org >> /root/.ssh/known_hosts RUN --mount=type=secret,id=ssh,target=/root/.ssh/id_rsa go mod download COPY . . RUN go build -o site-controller-data-update-to-mysql site-controller-data-update-to-mysql/app/ # Runtime Container FROM alpine:3.12 RUN apk add --no-cache libc6-compat tzdata COPY --from=builder /go/src/bitbucket.org/latonaio/site-controller-data-update-to-mysql . CMD ["./site-controller-data-update-to-mysql"] <file_sep>/app/server/handlers/websocket.go package handlers import ( "encoding/json" "log" "site-controller-data-update-to-mysql/app/server/response" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) var wsupgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func (h *SCHandler) WsConnect(c *gin.Context, channel chan []int) { conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { log.Printf("Failed to set websocket upgrade: %v\n", err) return } tx, err := h.db.DB.Begin() //何か受け取ってそのまま返すパターン END: for { select { case errorRowIds := <-channel: rows, err := h.db.SelectErrorCSVRowsWithIds(errorRowIds, c.Request.Context(), tx) if err != nil { logging.Error("cannot get csv error rows", nil) break END } row := rows[0] responseStruct := response.CsvExectutionError{ FileName: row.R.CSV.FileName.String, Errors: []response.Error{ { LineNumber: row.LineNumber, CustomerName: row.CustomerName.String, CustomerPhoneNumber: row.CustomerPhoneNumber.String, }, }, } res, err := json.Marshal(responseStruct) if err != nil { logging.Error(err, nil) break END } conn.WriteMessage(websocket.BinaryMessage, res) } } } func sendError() { } func sendNoneError() { }
b60411bb1af1343b8c10d0c77cb59fc52c1c8327
[ "Markdown", "TOML", "Makefile", "Go", "Go Module", "Dockerfile", "Shell" ]
25
Markdown
latonaio/site-controller-data-update-to-mysql
60ed4c94c94a6906c2e6fd68b21ed112cf1d330d
9037fda47adcc355cee804ffa9828560166ae983
refs/heads/master
<repo_name>miker1423/proyecto_cripto<file_sep>/Proyecto1.ino #include <hydrogen.h> #include <AESLib.h> #define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b)))) #define QR(a, b, c, d)(\ b ^= ROTL(a + d, 7),\ c ^= ROTL(b + a, 9),\ d ^= ROTL(c + b, 13),\ a ^= ROTL(d + c, 18)) #define ROUNDS 20 uint32_t C[4] = { 0x4868, 0x57856, 0x165865, 0x456465}; uint32_t key[8] = { <KEY> 0x11684, 0x45786}; uint32_t iv[2] = { 0x46854, 0x16584}; uint32_t counter[2] = { 0x0, 0x0}; void chacha20_block(uint32_t const in[16], uint32_t out[16]) { int i = 0; uint32_t x[16]; memcpy(x, in, 16 * sizeof(uint32_t)); for (i = 0; i < ROUNDS; i += 2) { QR(x[ 0], x[ 4], x[ 8], x[12]); QR(x[ 1], x[ 5], x[ 9], x[13]); QR(x[ 2], x[ 6], x[10], x[14]); QR(x[ 3], x[ 7], x[11], x[15]); QR(x[ 0], x[ 5], x[10], x[15]); QR(x[ 1], x[ 6], x[11], x[12]); QR(x[ 2], x[ 7], x[ 8], x[13]); QR(x[ 3], x[ 4], x[ 9], x[14]); } for(i = 0; i < 16; ++i) out[i] = x[i] + in[i]; } void init_block_chacha(uint32_t C[8], uint32_t key[8], uint32_t counter[2], uint32_t iv[2], uint32_t stateBlock[16]) { memcpy(stateBlock, C, 4); memcpy(stateBlock + 4, key, 8); memcpy(stateBlock + 12, counter, 2); memcpy(stateBlock + 14, iv, 2); } void cypher_chachca20(uint32_t stateBlock[16], uint8_t const *bytes, uint8_t *output, size_t length) { uint32_t auxBlock[16]; uint8_t *auxStateBlock; for(int i = 0; i < length; i++){ chacha20_block(auxBlock, stateBlock); auxStateBlock = (uint8_t *)stateBlock; output[i] = bytes[i] ^ auxStateBlock[i]; } } // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); if(hydro_init() == 0) { Serial.write("TRUE"); Serial.println(); } const uint32_t size = 16; uint32_t* state = (uint32_t *)malloc(size * sizeof(uint32_t)); uint8_t* buffer = (uint8_t *)malloc(size * sizeof(uint8_t)); uint8_t* enc_buffer = (uint8_t *)malloc(size * sizeof(uint8_t)); uint8_t* dec_buffer = (uint8_t *)malloc(size * sizeof(uint8_t)); hydro_sign_keypair key_pair; hydro_sign_keygen(&key_pair); uint8_t signature[hydro_sign_BYTES]; init_block_chacha(C, key, counter, iv, state); uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}; char data[] = "0123456789012345"; hydro_sign_create(signature, data, 16, "EXAMPLE", key_pair.sk); Serial.print("signed\n"); if(hydro_sign_verify(signature, data, 16, "EXAMPLE", key_pair.sk)) { Serial.print("Ok sign"); } Serial.println(); aes256_enc_single(key, data); Serial.print("encrypted: "); for (int i=0; i<sizeof(data); i++) { Serial.print(data[i], HEX); Serial.print(" "); //separator } Serial.println(); cypher_chachca20(state, data, enc_buffer, size); Serial.print("encrypted chacha: "); for (int i=0; i<size; i++) { Serial.print(enc_buffer[i], HEX); Serial.print(" "); //separator } Serial.println(); cypher_chachca20(state, enc_buffer, data, size); Serial.print("decrypted chacha: "); for(int i=0; i<sizeof(data); i++){ Serial.print(data[i], HEX); Serial.print(" "); } Serial.println(); aes256_dec_single(key, data); Serial.print("decrypted:"); Serial.println(data); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
e6b601e63f676c7aa74054217cf29da1ebc5bb5c
[ "C++" ]
1
C++
miker1423/proyecto_cripto
73a8ba6185c69922d8220ddd5753bf17d0778681
ecb5b88d1a692957b6484367ce671264b89986a4
refs/heads/master
<repo_name>AjeaSmith/school_website_design<file_sep>/build/precache-manifest.6a646bc554bc1b9a3ba111f3e6967d03.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "72ff1e6ecb5c5d8173e1648e2516908f", "url": "/index.html" }, { "revision": "594e7914fdd1d0d32462", "url": "/static/css/main.c7329a12.chunk.css" }, { "revision": "1c24893cac447f417ee0", "url": "/static/js/2.efc3046c.chunk.js" }, { "revision": "594e7914fdd1d0d32462", "url": "/static/js/main.fe361456.chunk.js" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" }, { "revision": "974f1155e0836a20700c3dec56f99f9e", "url": "/static/media/boy2.974f1155.jpg" }, { "revision": "4af1ec7a7140de85f9a83c4d7c229754", "url": "/static/media/boy3.4af1ec7a.jpg" }, { "revision": "8bc6890dae5f3a09f3ddea764bced031", "url": "/static/media/girl1.8bc6890d.jpg" } ]);<file_sep>/src/components/Menu.js import React, { useEffect } from "react"; import { NavLink, Link } from "react-router-dom"; import "../styles/App.scss"; import M from "materialize-css"; const Menu = () => { useEffect(() => { // MORE dropdown const Dropdown = document.querySelectorAll(".dropdown-trigger"); M.Dropdown.init(Dropdown, { coverTrigger: false, hover: true }); // COUNSELING dropdown const Dropdown2 = document.querySelectorAll(".dropdown-trigger2"); M.Dropdown.init(Dropdown2, { coverTrigger: false, hover: true }); }); return ( <React.Fragment> <ul id="dropdown2" className="dropdown-content"> <li> <Link to="/Counseling">COUNSELING</Link> </li> </ul> <ul id="dropdown1" className="dropdown-content"> <li> <a href="https://www.weoc.info/"> Washtenaw Educational Options Consortium </a> </li> </ul> <nav className="nav_menu"> <div className="nav-wrapper"> <ul className="left"> <li> <Link to="/">HOME</Link> </li> <li> <NavLink to="/Admission">ADMISSION</NavLink> </li> <li> <NavLink to="/Calendar">CALENDAR</NavLink> </li> <li className="dropdown-trigger2" data-target="dropdown2"> <NavLink to="/Curriculum"> CURRICULUM <i className="material-icons right">arrow_drop_down</i> </NavLink> </li> <li> <NavLink to="/Student">STUDENT</NavLink> </li> <li className="dropdown-trigger" data-target="dropdown1"> <Link to="/"> MORE <i className="material-icons right">arrow_drop_down</i> </Link> </li> </ul> </div> </nav> </React.Fragment> ); }; export default Menu; <file_sep>/src/pages/Calendar.js import React, { useState } from "react"; const Calendar = () => { const [state] = useState({ dates: [ { id: 1, para: "The 2018-19 school calendar runs from September 4, 2018 - August 31, 2019." }, { id: 2, para: "Winter and spring breaks are determined by a county-wide calendar. These dates for 2018/19 will be:" }, { id: 3, heading: "Winter Break ", para: "School closes at the end of the day on Friday, December 21,2018 Classes resume on Tuesday, January 8, 2018" }, { id: 4, heading: "SpringBreak", para: "School closes at the end of the day on Friday, March 22, 2018 Classes resume on Tuesday, April 2, 2018" }, { id: 5, heading: "AADL Lab Schedule", para: "Tuesday 9:30AM-2:30PM Thursday 9:30AM-2:30PM" }, { id: 6, heading: "Ypsilanti Lab Schedule", para: "Tuesday 9AM-3PM Wednesday 9AM-3PM Thursday 9AM-3PM​ Friday 9AM-3PM" } ] }); return ( <React.Fragment> <section className="calendar_section"> <h2 className="center-align">Calendar</h2> <div className="calendar_wrapper"> <section className="calendar_dates"> <section className="dates"> {state.dates.map(date => { return ( <div className="date" key={date.id}> <h6>{date.heading}</h6> <p>{date.para}</p> </div> ); })} </section> </section> <section className="calendar"> <iframe title="calendar" src="https://calendar.google.com/calendar/embed?src=weocflex.org_u141hjg43dt61s1ob6hdtkalo4%40group.calendar.google.com&ctz=America%2FDetroit" style={{ border: 0 }} width="600" height="600" frameBorder="0" scrolling="no" /> </section> </div> </section> </React.Fragment> ); }; export default Calendar; <file_sep>/src/App.js import React from "react"; import Layout from "./components/Layout"; import Header from "./components/Header"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Home from "./pages/Home"; import Admission from "./pages/Admission"; import Calendar from "./pages/Calendar"; import Curriculum from "./pages/Curriculum"; import Student from "./pages/Student"; import Menu from "./components/Menu"; import "./styles/App.scss"; import Counseling from "./pages/Counseling"; function App() { return ( <Layout> <section className="wrapper"> <section className="header"> <Header /> </section> <section className="router"> <Router> <Menu /> <Switch> <Route path="/" exact component={Home} /> <Route path="/Admission" component={Admission} /> <Route path="/Calendar" component={Calendar} /> <Route path="/Curriculum" component={Curriculum} /> <Route path="/Student" component={Student} /> <Route path="/Counseling" component={Counseling} /> </Switch> </Router> </section> </section> </Layout> ); } export default App; <file_sep>/src/pages/Admission.js import React, { useState } from "react"; import "../styles/pages.scss"; const Admission = () => { const [state] = useState({ enroll: [ { id: 1, title: "Partner District Applications", content: "We have 420 total seats for Washtenaw County students residing in the school districts of Ann Arbor, Chelsea, Dexter, Lincoln, Manchester, Milan, Saline, Whitmore Lake, and Ypsilanti. The seats are proportionally distributed among the nine participating districts." }, { id: 2, title: "Out-of-County Applications", content: "Students must first enroll directly in a Washtenaw County School District prior to submitting an application to WAVE." }, { id: 3, title: "School of Choice Open Enrollment Dates", content: "To enroll as a School of Choice student, a student must apply during a district's open enrollment period. Once enrolled in a participating district, a student can then qualify for one of the district's slots in one of the programs operated by WEOC." } ], links: [ { id: 1, school: "Ann Arbor Public Schools", link: "https://www.a2schools.org/" }, { id: 2, school: "Chelsea Public Schools", link: "https://www.chelsea.k12.mi.us/education/district/district.php?sectionid=1" }, { id: 3, school: "Dexter Community Schools", link: "https://www.dexterschools.org/" }, { id: 4, school: "Lincoln Consolidated Schools", link: "https://www.lincolnk12.org/" }, { id: 5, school: "Manchester Community Schools", link: "http://www.mcs.k12.mi.us/education/district/district.php?sectionid=1" }, { id: 6, school: "Manchester Community Schools", link: "http://www.mcs.k12.mi.us/education/district/district.php?sectionid=1" }, { id: 7, school: "Milan Public Schools", link: "https://www.milanareaschools.org/" }, { id: 8, school: "Saline Area Schools", link: "https://www.salineschools.org/" }, { id: 9, school: "Washtenaw Intermediate School District", link: "https://washtenawisd.org/" }, { id: 10, school: "Whitmore Lake Public Schools", link: "https://www.wlps.net/" }, { id: 11, school: "Ypsilanti Community Schools ", link: "https://www.ycschools.us/" } ] }); return ( <React.Fragment> <section className="admission_wrapper"> <section className="admission_section row"> <div className="admission_title"> <h3 className="center-align">Admission Information</h3> <h6 className="center-align"> *Applications to the Washtenaw Alliance for Virtual Education are accepted on a rolling basis.* </h6> </div> <br /> <div className="admission_content blue-grey lighten-5"> <div className="admission_right"> {state.enroll.map(info => { return ( <div key={info.id}> <h5>{info.title}</h5> <p>{info.content}</p> </div> ); })} </div> <div className="divider hide-on-med-and-up" /> <div className="admission_left"> <h6> Washtenaw Alliance for Virtual Education <br /> is made possible by the following partnerships: </h6> {state.links.map(link => { return ( <div key={link.id}> <p> <a href={link.link}>{link.school}</a> </p> </div> ); })} </div> </div> </section> <section className="application_section row blue-grey lighten-4"> <div className="application_question"> <div className="question_box"> <h3>APPLICATION / INTEREST FORM</h3> <p> Please complete each field below with your student's information. Click Submit at the bottom of the form when complete. Office staff will call to discuss your interest in 5-7 business days. Admissions are on a rolling basis dependent upon the number of seats available in the program for each participating district. </p> <a href="mailto:<EMAIL>" className="btn grey black-text lighten-2" > Email for questions </a> </div> </div> <div className="question_button"> <a href="mailto:<EMAIL>" className="btn btn-small"> Email for questions </a> </div> <div className="application_form"> <iframe className="form" title="Wave Refferal" src="https://docs.google.com/forms/d/e/1FAIpQLSdpQiGJDTqMwEqZ14SSbMgH7YJDnRk_zSaqvJ8jgfi46U1sKg/viewform?embedded=true" width="640" height="1000" frameBorder="0" marginHeight="0" marginWidth="0" > Loading... </iframe> </div> </section> </section> </React.Fragment> ); }; export default Admission;
f3e13bf0822f52b57950536827e1d0105d21ec32
[ "JavaScript" ]
5
JavaScript
AjeaSmith/school_website_design
358c4f4ae8bcdbf8f990c32b4223e84a2d780603
1f712ab97e98f2699fad6eb194b36186c7add45b
refs/heads/master
<file_sep>namespace ReversePolishNotation { public class RpnCalculator { } }<file_sep>using System.Collections.Generic; namespace ReversePolishNotation { public class RpnUtils { private static readonly string[] OpStrings = { "*", "/", "+", "-" }; public static double Calculate(int[] numset, byte[] mask, byte[] opcodes) { var numStack = new Stack<double>(); var accum = 0; var flag = false; var codeId = 0; for (var i = 0; i < numset.Length; i++) { numStack.Push(numset[i]); if (i - 1 < 0) continue; for (var t = 0; t < mask[i - 1]; t++) { var num2 = numStack.Pop(); var num1 = numStack.Pop(); switch ((OpCode) opcodes[codeId]) { case OpCode.Mul: numStack.Push(num1 * num2); break; case OpCode.Div: if (num2 == 0) return -0; // /0 invalid operation returns != 100 numStack.Push(num1 / num2); break; case OpCode.Add: numStack.Push(num1 + num2); break; case OpCode.Sub: if (num2 == 0) return -0; // +-0 equal ops, returns != 100 numStack.Push(num1 - num2); break; } codeId++; } } var res = numStack.Pop(); return res; } public static string FromPolish(int[] numset, byte[] mask, byte[] opcodes) { var stack = new Stack<string>(); var codeId = 0; for (var i = 0; i < numset.Length; i++) { stack.Push(numset[i].ToString()); if (i - 1 < 0) continue; for (var t = 0; t < mask[i - 1]; t++) { var num2 = stack.Pop(); var num1 = stack.Pop(); stack.Push($"({num1}{OpStrings[opcodes[codeId]]}{num2})"); codeId++; } } return stack.Pop(); } public static bool IsPrime(byte[] mask, byte[] opcodes) { var codeId = 0; var lastPriority = -1; for (var i = 0; i < mask.Length; i++) if (mask[i] > 0) { if (lastPriority == opcodes[codeId] / 2) return false; lastPriority = opcodes[codeId + mask[i] - 1] / 2; codeId += mask[i]; } else { lastPriority = -1; } return true; } private enum OpCode { Mul = 0, Div = 1, Add = 2, Sub = 3 } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading; using LevelDB; namespace ReversePolishNotation { internal class Program { private static byte[][][] GenerateOpCodes() { var result = new byte[6][][]; for (var opCount = 0; opCount < 6; opCount++) { var chunk = new byte[(int) Math.Pow(4, opCount)][]; for (var i = 0; i < Math.Pow(4, opCount); i++) { var buf = new byte[opCount]; for (var pos = 0; pos < opCount; pos++) buf[pos] = (byte) (i / Math.Pow(4, pos) % 4); chunk[i] = buf; } result[opCount] = chunk; } return result; } private static int[][] GetNumsets(byte[] numset) { return new[] {numset.Select(x => (int) x).ToArray()}; } private static void TestNumber(byte[] x) { var opCodes = GenerateOpCodes(); var enumerator = new NumsetEnumerator(); var count = 0; var numsets = GetNumsets(x); for (var i = 0; i < numsets.Length; i++) { var l = numsets[i].Length - 1; for (var mask = 0; mask < enumerator.opcodeMask[l].Length; mask++) for (var codeId = 0; codeId < opCodes[l].Length; codeId++) try { if (RpnUtils.IsPrime(enumerator.opcodeMask[l][mask], opCodes[l][codeId])) if (Math.Abs(RpnUtils.Calculate(numsets[i], enumerator.opcodeMask[l][mask], opCodes[l][codeId]) - 100) < 0.0000000000001) { count++; Console.WriteLine(RpnUtils.FromPolish(numsets[i], enumerator.opcodeMask[l][mask], opCodes[l][codeId])); } } catch { } } } private static void Main(string[] args) { var opCodes = GenerateOpCodes(); var options = new Options {CreateIfMissing = true}; var db = new DB(options, @"result"); var enumerator = new NumsetEnumerator(); var data = new List<byte[]>(1000000); while (enumerator.MoveNext()) data.Add((byte[]) enumerator.Current.Clone()); var total = 0; data.AsParallel().ForAll(x => { var count = 0; var numsets = GetNumsets(x); for (var i = 0; i < numsets.Length; i++) { var l = numsets[i].Length - 1; for (var mask = 0; mask < enumerator.opcodeMask[l].Length; mask++) for (var codeId = 0; codeId < opCodes[l].Length; codeId++) try { if (RpnUtils.IsPrime(enumerator.opcodeMask[l][mask], opCodes[l][codeId])) if (Math.Abs(RpnUtils.Calculate(numsets[i], enumerator.opcodeMask[l][mask], opCodes[l][codeId]) - 100) < 0.0000000000001) count++; } catch { // ignored } } var num = Interlocked.Increment(ref total); if (num % 1000 == 0) Console.WriteLine(num); if (count > 0) db.Put(x, BitConverter.GetBytes(count)); }); } } }
b118b3a390d04af6ed2410eff59e65e2382acc91
[ "C#" ]
3
C#
SysUtils/GetOneHundred
6ffaf2c8c14e09beb9fde1d2ea4ef0a497f5bed5
cc815e908cd94cff056a3964c2abf3068512f9ae
refs/heads/master
<file_sep>import logging import datetime from datetime import timedelta import getpass import json import pymysql from fints.client import FinTS3PinTanClient from pymongo import MongoClient from pymongo import errors as PyMongoErrors from sqlalchemy.orm import sessionmaker from sqlalchemy import exc from sqlalchemy import text from sqlalchemy.sql import func from sqlalchemy import create_engine, Column, Table, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ( Integer, SmallInteger, String, Date, DateTime, Float, Boolean, Text, LargeBinary) DeclarativeBase = declarative_base() def create_table(engine): DeclarativeBase.metadata.create_all(engine) class Bank(DeclarativeBase): __tablename__ = 'tblbanks' bankId = Column(Integer(), primary_key=True) bankName = Column(String(100)) bankUrl = Column(String(2000)) def __repr__(self): return "<bank(bankName='%s', bankUrl='%s')>" % ( self.bankName, self.bankUrl) class User(DeclarativeBase): __tablename__ = 'tblusers' userId = Column(String(100), primary_key=True) userName = Column(String(100)) userCreatedAt = Column(Date()) def __repr__(self): return "<user(userId='%s', userName='%s')>" % ( self.userId, self.userName) class Account(DeclarativeBase): __tablename__ = 'tblaccounts' accountNumber = Column(String(100), primary_key=True) accountBlz = Column(String(100), primary_key=True) accountLogin = Column(String(100)) accountOwner = Column(String(100)) bankId = Column(Integer(), ForeignKey("tblbanks.bankId")) def __repr__(self): return "<Account(accountNumber='%s', accountBlz='%s', accountOwner='%s')>" % ( self.accountNumber, self.accountBlz, self.accountOwner) class Account_Transaction(DeclarativeBase): __tablename__ = 'tblacctransactions' accountNumber = Column(Integer(), primary_key=True) accountBlz = Column(Integer(), primary_key=True) transactionAmt = Column(Float(17, 2), primary_key=True) transactionCur = Column(String(3)) transactionType = Column(String(100)) transactionTitle = Column(String(250), primary_key=True) transactionApplicantName = Column(String(250)) transactionDate = Column(Date(), primary_key=True) transactionEntryDate = Column(Date()) withdrawDate = Column(Date()) localSysBankId = Column(Integer()) transactionOwnerId = Column(String(100), ForeignKey("tblusers.userId")) def __repr__(self): return "<account_transaction(accountNumber='%s', accountBlz='%s', transactionAmt='%s', transactionDate='%s')>" % ( self.accountNumber, self.accountBlz, self.transactionAmt, self.transactionDate) class Run: def __init__(self, mysql_conn_string, mongo_conn_string, args): if args["accountLogin"] is None: login = args["accountNumber"] else: login = args["accountLogin"] if args["accountKey"] is None or args["accountKey"] == "": key = getpass.getpass('PIN for {}:'.format(login)) else: key = args["accountKey"] fin_client = FinTS3PinTanClient( args["accountBlz"], login, key, args["bankUrl"] ) self.localSysBankId = args["bankId"] self.accountOwnerId = args["accountOwner"] self.fin_client = fin_client self.lastWithdrawn = args["maxWithdrawDate"] self.accounts = fin_client.get_sepa_accounts() self.balances = [] self.transactions = [] self.fetched = {} self.errors = [] self.duplicates = [] self.success = {} # MySQL engine = create_engine(mysql_conn_string) self.Session = sessionmaker(bind=engine) # MongoDB self.client = MongoClient(mongo_conn_string) db = self.client.fin71 self.tb_transactions = db.transactions def init_processing(self): session = self.Session() for acc in self.accounts: mongo_t_array, sql_t_array = self.process_transactions(acc) stored_mongo, stored_sql = self.store_transactions(mongo_t_array, sql_t_array) self.handle_success(acc, stored_sql) logging.info("For the account {}, {} transactions were retrieved, {} (mongo) and {} (sql) stored".format( acc.accountnumber, len(sql_t_array), stored_mongo, stored_sql)) self.complete_processing() def complete_processing(self): self.client.close() logging.info("Processing complete") for acc in self.accounts: logging.info("There were {} transactions fetched for the account {}, {} added to the database".format( self.get_fetched(acc.accountnumber), acc.accountnumber, self.get_success(acc.accountnumber))) def process_transactions(self, account): balance = self.fin_client.get_balance(account) self.balances.append(balance) start, end = self.get_starting_date() statements = self.fin_client.get_statement(account, start, end) # how many transactions have been fetched for the time periode total_num = len(statements) self.handle_statements_fetched(account, total_num) mongo_dict = [] sql_dict = [] for s in statements: # Cater for faulty entry_date parsing: # If dates vary for more than 50 days, then parsing of entry_date is faulty # Replace with normal date if abs(s.data["date"] - s.data["entry_date"]) > datetime.timedelta(days=50): s.data["entry_date"] = s.data["date"] # if booking date is at least today or before if s.data["entry_date"] <= datetime.datetime.now(): mongo_obj, sql_obj = self.make_transaction_dict(account, s.data) mongo_dict.append(mongo_obj) sql_dict.append(sql_obj) else: logging.info( "The following transaction is to be expected in the future {} at {}".format(s.data["entry_date"], s.data["purpose"])) return mongo_dict, sql_dict def handle_statements_fetched(self, account, total_num): self.fetched[account.accountnumber] = total_num def get_fetched(self, accountnumber): if accountnumber in self.fetched: return self.fetched[accountnumber] else: return 0 def get_success(self, accountnumber): if accountnumber in self.success: return self.success[accountnumber] else: return 0 def handle_success(self, account, num_items): self.success[account.accountnumber] = num_items def get_starting_date(self): if self.lastWithdrawn is None: start = datetime.datetime(2000, 1, 1) else: # if data has been withdrawn for this account, get one day previously and start from there start = self.lastWithdrawn + timedelta(-1) end = datetime.datetime.now() return start, end @staticmethod def sanitize_string(input_string): if input_string is None: return "#None#" if len(input_string) == 0: return "#None#" else: return input_string def get_transaction_item(self, account, data): return { "transactionOwnerId": self.accountOwnerId, "withdrawDate": datetime.datetime.now(), "accountNumber": account.accountnumber, "accountBlz": account.blz, "iban": account.iban, "bic": account.bic, "localSysBankId" : self.localSysBankId, "status": data.get("status", None), "funds_code": data.get("funds_code", None), "amount": data["amount"].amount.to_eng_string(), "id": data.get("id", None), "customer_reference": data.get("customer_reference", None), "bank_reference": data.get("bank_reference", None), "extra_details": data.get("extra_details", None), "currency": data.get("currency", None), "date": data["date"].isoformat(), "entry_date": data["entry_date"].isoformat(), "transaction_code": data.get("transaction_code", None), "posting_text": data.get("posting_text", ""), "prima_nota": data.get("prima_nota", None), "purpose": data.get("purpose", ""), "applicant_bin": data.get("applicant_bin", None), "applicant_iban": data.get("applicant_iban", None), "applicant_name": data.get("applicant_name", None), "return_debit_notes": data.get("return_debit_notes", None), "recipient_name": data.get("recipient_name", None), "additional_purpose": data.get("additional_purpose", None), "gvc_applicant_iban": data.get("gvc_applicant_iban", None), "gvc_applicant_bin": data.get("gvc_applicant_bin", None), "end_to_end_reference": data.get("end_to_end_reference", None), "additional_position_reference": data.get("additional_position_reference", None), "applicant_creditor_id": data.get("applicant_creditor_id", None), "purpose_code": data.get("purpose_code", None), "additional_position_date": data.get("additional_position_date", None), "deviate_applicant": data.get("deviate_applicant", None), "deviate_recipient": data.get("deviate_recipient", None), "FRST_ONE_OFF_RECC": data.get("FRST_ONE_OFF_RECC", None), "old_SEPA_CI": data.get("old_SEPA_CI", None), "old_SEPA_additional_position_reference": data.get("old_SEPA_additional_position_reference", None), "settlement_tag": data.get("settlement_tag", None), "debitor_identifier": data.get("debitor_identifier", None), "compensation_amount": data.get("compensation_amount", None), "original_amount": data.get("original_amount", None) } def make_transaction_dict(self, account, transaction_data): mongo_t_itm = self.get_transaction_item(account, transaction_data) sql_acc_trans_item = Account_Transaction( accountNumber=mongo_t_itm["accountNumber"], accountBlz=mongo_t_itm["accountBlz"], transactionAmt=mongo_t_itm["amount"], transactionCur=mongo_t_itm["currency"], transactionType=mongo_t_itm["posting_text"], transactionTitle=self.sanitize_string(mongo_t_itm["id"]) + "/" + self.sanitize_string( mongo_t_itm["purpose"]), transactionApplicantName=mongo_t_itm["applicant_name"], transactionDate=mongo_t_itm["date"], transactionEntryDate=mongo_t_itm["entry_date"], withdrawDate=mongo_t_itm["withdrawDate"], transactionOwnerId=mongo_t_itm["transactionOwnerId"], localSysBankId=self.localSysBankId ) return mongo_t_itm, sql_acc_trans_item def store_transactions(self, mongo_t_array, sql_t_array): def _store_sql_transaction(self, sql_item): try: session = self.Session() session.add(sql_item) session.commit() return True except exc.SQLAlchemyError as e: err_msg = e.args[0] session.rollback() logging.error(err_msg) if "1062," in err_msg: logging.warning("error MySQL, transaction with id {} already exists".format(sql_item)) else: self.errors.append(sql_item) logging.warning("unknown error adding transaction to mysql {}".format(sql_item)) return False except Exception as e: logging.warning("unknown error {}".format(e)) return False def _store_mongo_transaction(self, mongo_item): try: self.tb_transactions.insert_one(mongo_item) return True except PyMongoErrors.DuplicateKeyError as e: logging.warning("error MongoDB, transaction with id {} already exists".format(e)) return False except Exception as e: logging.warning("unknown error {}".format(e)) return False stored_mongo = 0 stored_sql = 0 for m in mongo_t_array: res = _store_mongo_transaction(self, m) if res: stored_mongo += 1 for t in sql_t_array: res = _store_sql_transaction(self, t) if res: stored_sql += 1 return stored_mongo, stored_sql <file_sep>import sys import argparse import logging import sys import os from sqlalchemy.orm import sessionmaker from sqlalchemy import text from sqlalchemy import create_engine from dotenv import load_dotenv from os.path import join, dirname dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path=dotenv_path) from BalanceStatement import Run parser = argparse.ArgumentParser(description='kDatacenter Kontoauszug') parser.add_argument("-u", "--user_ids", nargs='+', help="userIds to be used for withdrawing statements", metavar="STRINGS") logging.basicConfig(level=logging.INFO) def main(args=sys.argv[1:]): def _get_accounts(user_id): engine = create_engine(mysql_conn_string) Session = sessionmaker(bind=engine) sess = Session() sql_cmd = text('''SELECT acc.*, b.*, d.maxWithdrawDate FROM fin71.tblaccounts as acc left join fin71.tblbanks as b on acc.bankId = b.bankId left join ( select accountNumber, accountBlz, max(withdrawDate) as maxWithdrawDate FROM fin71.tblacctransactions GROUP BY accountNumber, accountBlz) as d on (acc.accountNumber = d.accountNumber And acc.accountBlz = d.accountBlz) where acc.accountOwner = :accountOwner''') options = { "accountOwner": user_id } accounts = [] for acc in sess.execute(sql_cmd, options): accounts.append(acc) return accounts args = parser.parse_args(args) mysql_conn_string = "{drivername}://{user}:{passwd}@{host}:{port}/{db_name}?charset=utf8".format( drivername="mysql+pymysql", user=os.environ.get("MYSQL_USER"), passwd=os.environ.get("MYSQL_PASS"), host=os.environ.get("MYSQL_HOST"), port=os.environ.get("MYSQL_PORT"), db_name=os.environ.get("MYSQL_DB") ) mongo_conn_string = "mongodb://{user}:{passwd}@{host}:{port}/{db_name}".format( user=os.environ.get("MONGO_USER"), passwd=os.environ.get("MONGO_PASS"), host=os.environ.get("MONGO_HOST"), port=os.environ.get("MONGO_PORT"), db_name=os.environ.get("MONGO_DB") ) user_ids = args.user_ids for u in user_ids: accounts = _get_accounts(u) print(u) for acc in accounts: r = Run(mysql_conn_string, mongo_conn_string, acc) r.init_processing() <file_sep>Run the application against database containing credentials {ENV_PYTHON}python3 {PATH_TO_THIS_PROG}/__main__.py -u {USERID}
f80e4f5af2e021b185406dfea167e956a7d9af7f
[ "Markdown", "Python" ]
3
Python
justusfowl/bankingstatement
abfa1f5c46816e7702ebaecccd5194bf060bc6bb
fb39a487f92c00677d66e35634fdd0cc6d6024f0
refs/heads/develop
<repo_name>Ruiru11/store-api-v1<file_sep>/v1/app/views/users_views.py from flask import Blueprint from flask_restful import reqparse # local imports from app.controllers.users_controllers import Users usr = Users() don_user = Blueprint('users', __name__, url_prefix="/api/v1") user_instance = Users() @don_user.route("/signup", methods=["POST"]) def create_user(): """ This function creates a new user. Parameters: username:Name to be used by user once account is created. email:Email to be used for verification. Password: To be used when signin to created account. role: This is the role of user can be attendant/admin Returns: Users:Creates a new user. """ parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument("username", type=str, required=True, help="field cannot be empty", location="json") parser.add_argument("email", type=str, required=True, help="field cannot be empty", location="json") parser.add_argument("password", type=str, required=True, help="field cannot be empty", location="json") parser.add_argument("role", type=str, required=True, help="fiels cannot be empty", location="json") data = parser.parse_args() return user_instance.create_user(data) @don_user.route("/signin", methods=["POST"]) def signin_user(): """ The function signsin a user. Parameters: email:Email used during regestration. password:<PASSWORD>. Returns: User: Signsin a user. """ parser = reqparse.RequestParser() parser.add_argument("email", type=str, required=True, help="cannot be empty", location="json") parser.add_argument("password", type=str, required=True, help="cannot be empty", location="json") data = parser.parse_args() return user_instance.signin_user(data) <file_sep>/v1/tests/test_users.py import unittest import json from app import create_app class TestOrders(unittest.TestCase): def setUp(self): self.app = create_app("test") self.client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() self.login_one = { "email": "<EMAIL>", "password": "<PASSWORD>" } self.login_two = { "email": "<EMAIL>", "password": "<PASSWORD>" } def teardown(self): self.app_context.pop() def test_create_user(self): data = { "username": "<NAME>", "password": "<PASSWORD>", "email": "<EMAIL>", "role": "attendant" } res = self.client.post( "api/v1/signup", data=json.dumps(data), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 201) # signin user def test_signin_user(self): login = { "email": "<EMAIL>", "password": "<PASSWORD>" } res = self.client.post( "api/v1/signin", data=json.dumps(login), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 404) # test for user who gives a wrong password def test_signin_user_with_wrong_pass(self): res = self.client.post( "api/v1/signin", data=json.dumps(self.login_two), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 404) # singin user who doesnt exist def test_signin_user_who_doesnt_exist(self): res = self.client.post( "api/v1/signin", data=json.dumps(self.login_one), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 404) if __name__ == "__main__": unittest.main() <file_sep>/v1/app/controllers/users_controllers.py from flask import jsonify, make_response, request import jwt import datetime from functools import wraps import re class Users(object): """This function deals with all user activities""" def __init__(self): """The constructor for users class""" # create empty list self.users = [] def validate_email(self, email): """The function validates the email""" match = re.match( r'(^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$)', email) if match is None: response_object = { "status": "fail", "message": "Please enter a valid email" } return(make_response(jsonify(response_object)), 403) elif len(email) == '': response_object = { "status": "fail", "message": " email cannot be empty" } return(make_response(jsonify(response_object))) else: return True def validate_password(self, password): """The function validates the password""" match = re.match(r'[a-z]{4,}', password) if match is None: response_object = { "status": "fail", "message": "password format wrong" } return(make_response(jsonify(response_object))) elif len(password) == '': response_object = { "status": "fail", "message": " password cannot be empty" } return(make_response(jsonify(response_object)), 403) else: return True def validate_username(self, username): """The function validates the username""" if len(username) < 4: response_object = { "status": "fail", "message": "username to short" } return(make_response(jsonify(response_object))) elif len(username) > 7: response_object = { "status": "fail", "message": "username too long" } return(make_response(jsonify(response_object))) else: return True def create_user(self, data): """ The function to create new users. Parameters: data:This are the arguments passed, they are defined in user_views file. Returns: Users:A new user with a uniqu id. """ username = self.validate_username(data['username']) email = self.validate_email(data['email']) password = self.validate_password(data['password']) if password and username and email is True: user_id = len(self.users) + 1 user = {"id": user_id, "username": data["username"], "email": data["email"], "password": data["password"], "role": data["role"]} self.users.append(user) response_object = { "message": "User created successfully", "status": "pass" } return(make_response(jsonify(response_object)), 201) elif password is not True: return password elif email is not True: return email elif username is not True: return username else: return email and password and username def signin_user(self, data): """ The function logs in a user. Parameters: data[email]:email used during signup. data[password]:password used during signup Returns: Users:Signs in a user and also generates a token. """ print('users', self.users) for user in self.users: if data["email"] in dict.values(user): if data["password"] == user["password"]: token = self.generate_token( user["id"], user["username"], user["role"]) response_object = { "message": "logged in successfully", "status": "pass", "token": token } return(make_response(jsonify(response_object))) else: response_object = { "message": "Wrong password please re-enter password", "status": "fail" } return(make_response(jsonify(response_object)), 409) else: if data["email"] not in dict.values(user): response_object = { "message": "user not found please register or contact admin", "status": "fail" } return(make_response(jsonify(response_object)), 404) def generate_token(self, id, username, role): """Generate authentication token for signin.""" payload = { 'exp': datetime.datetime.now() + datetime.timedelta(seconds=9000), 'iat': datetime.datetime.now(), 'sub': id, 'username': username, 'role': role } return jwt.encode( payload, 'newtothis', algorithm='HS256' ).decode("utf-8") def logged_in(self, func): @wraps(func) def decorator(*args, **kwargs): try: token = request.headers.get('Authorization') payload = jwt.decode(token, 'newtothis') user_id = payload['sub'] for user in self.users: if user_id in dict.values(payload): responseObject = { 'staus': 'sucess', 'message': 'user logged in' } new_kwargs = { 'res': responseObject, 'user_id': user[0] } kwargs.update(new_kwargs) else: responseObject = { 'status': 'fail', 'message': 'User not found' } return make_response(jsonify(responseObject)) except jwt.ExpiredSignatureError: responseObject = { 'status': 'Fail', 'message': 'Token expired please login' } return make_response(jsonify(responseObject), 401) except jwt.exceptions.DecodeError: responseObject = { 'status': 'Fail', 'message': 'No token passed or invalid token type' } return make_response(jsonify(responseObject), 500) return func(*args, **kwargs) return decorator def check_admin(self, func): @wraps(func) def decorator(*args, **kwargs): try: token = request.headers.get('Authorization') payload = jwt.decode(token, 'newtothis') user_role = payload['role'] if user_role == 'admin': new_kwargs = { 'user_role': user_role } kwargs.update(new_kwargs) else: responseObject = { 'status': 'fail', 'message': 'Un-authorized only admin allowed' } return make_response(jsonify(responseObject), 401) except jwt.ExpiredSignatureError: responseObject = { 'status': 'Fail', 'message': 'Token expired please login' } return make_response(jsonify(responseObject), 401) return func(*args, **kwargs) return decorator <file_sep>/v1/app/controllers/products_controllers.py from flask import jsonify, make_response class Products(object): """This is a class for handling all product activities.""" def __init__(self): """The constructor for products class. """ # creates an empty list self.items = [] def create_item(self, data): """ The function to create a new product. Parameter: data:This are the values to be passed, they are defined in product_views.py Returns: Products: A product with all data passed and a unique id """ item_id = len(self.items) + 1 item = {"id": item_id, "name": data['name'], "price": data['price'], "description": data['description'], "category": data['category']} self.items.append(item) response_object = { "status": "success", "message": "Product created successfully" } return(make_response(jsonify(response_object)), 201) def get_items(self): """ The function to get all products created. Returns: products: A list of all created products. """ return(jsonify(self.items)) def get_item(self, id): """ The function to get a specific product usiing its unique id.return. Parameters: id: This is the identiication number of product to be viewed. Returns: Products: A single product """ for i, item in enumerate(self.items): print(item['id'], id) if item['id'] == id: print(item) return(make_response(jsonify(item))) break response_object = { "message": "no item with that id", "status": "fail" } return(make_response(jsonify(response_object)), 404) <file_sep>/v1/tests/test_sales.py import unittest import json from app import create_app class TestOrders(unittest.TestCase): def setUp(self): self.app = create_app("test") self.client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() self.data = { "name": "<NAME>", "description": "['paint','wood','nails','T.cost=3000']" } self.admin = { "username": "<NAME>", "password": "<PASSWORD>", "email": "<EMAIL>", "role": "attendant" } self.admin_log = { "email": "<EMAIL>", "password": "<PASSWORD>" } def teardown(self): self.app_context.pop() # create a user admin def test_create_admin_user(self): res = self.client.post( "api/v1/signup", data=json.dumps(self.admin), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 201) # signin in the admin to get the token # without token def test_create_sale(self): res = self.client.post( "api/v1/sales", data=json.dumps(self.data), headers={"content-type": "application/json" } ) self.assertEqual(res.status_code, 500) # without token def test_get_sales(self): res = self.client.get( "api/v1/sales", headers={"content-type": "application/json" } ) self.assertEqual(res.status_code, 500) # without token def test_get_sales_by_id(self): res = self.client.get( "api/v1/sales", headers={"content-type": "application/json" } ) self.assertEqual(res.status_code, 500) if __name__ == "__main__": unittest.main() <file_sep>/v1/app/views/products_views.py from flask import Blueprint from flask_restful import reqparse # local import from app.controllers.products_controllers import Products from app.controllers.users_controllers import Users usr = Users() don_item = Blueprint('products', __name__, url_prefix="/api/v1") product_instance = Products() @don_item.route("/products", methods=["POST"]) @usr.logged_in @usr.check_admin def create_item(user_role=None): """ The function handles all arguments required for creating a new product. Parameter: name:Name of product and is of type str, the field must be included category:Category of product is of type str, the field must be included price:Price of product is of type str, the field must be included description:Description of product is of type str, the field must be included Returns: Arguments are passed to the create_item function in procucts_controllers to create the product """ parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument("name", type=str, required=True, help="name required", location="json") parser.add_argument("category", type=str, required=True, help="name required", location="json") parser.add_argument("price", type=str, required=True, help="name required", location="json") parser.add_argument("description", type=str, required=True, help="description required", location="json") data = parser.parse_args() return product_instance.create_item(data) @don_item.route("/products", methods=["GET"]) @usr.logged_in def get_items(): """The function is used to get all product created""" return product_instance.get_items() @don_item.route("/products/<int:id>", methods=["GET"]) @usr.logged_in def get_item(id): """The function returns a specific product using its unique id""" return product_instance.get_item(id) <file_sep>/v1/app/views/sales_views.py from flask import Blueprint from flask_restful import reqparse # local import from app.controllers.sales_controllers import Sales from app.controllers.users_controllers import Users usr = Users() don_sale = Blueprint('sales', __name__, url_prefix="/api/v1") sale_insatnce = Sales() @don_sale.route("/sales", methods=["POST"]) @usr.logged_in def create_sale(): """ The function helps handles all arguments required for creating, a sales record. Parameter: name:Name of employee creatin the sales order is of type str. item:this is a list, contains all the information realting to a sale. Return: Arguments are passed to the create_sale() function, from sales_controller to create a sale order """ parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument("description", action="append", type=str, help="must be given", location="json") parser.add_argument("name", type=str, required=True, help="this cannot be empty", location="json") data = parser.parse_args() return sale_insatnce.create_sale(data) @don_sale.route("/sales", methods=["GET"]) @usr.logged_in @usr.check_admin def get_sales(user_role=None): """The function is used to get all sales created""" return sale_insatnce.get_sales() @don_sale.route("/sales/<int:id>", methods=["GET"]) @usr.logged_in @usr.check_admin def get_sale(id,user_role=None): """The function gets a single order using its id""" return sale_insatnce.get_sale(id) <file_sep>/v1/app/__init__.py from flask import Flask from .config import Config_by_name from app.views.products_views import don_item from app.views.sales_views import don_sale from app.views.users_views import don_user def create_app(config_name): app = Flask(__name__) app.config.from_object(Config_by_name[config_name]) app.register_blueprint(don_item) app.register_blueprint(don_sale) app.register_blueprint(don_user) return app <file_sep>/v1/tests/test_products.py import unittest import json from app import create_app class TestOrders(unittest.TestCase): def setUp(self): self.app = create_app("test") self.client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() self.data = { "name": "steel", "id": 1, "price": "sh.825", "category": "construction", "description": "Y16-For Columns and Slab" } self.admin = { "username": "prod", "email": "<EMAIL>", "role": "admin", "password": "new" } self.admin_log = { "email": "<EMAIL>", "password": "new" } self.attendant = { "username": "theo", "email": "<EMAIL>", "role": "attendant", "password": "<PASSWORD>" } self.attendant_log = { "email": "<EMAIL>", "password": "<PASSWORD>" } def teardown(self): self.app_context.pop() # create a user admin def test_create_admin_user(self): res = self.client.post( "api/v1/signup", data=json.dumps(self.admin), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 201) # signin in the admin to get the token def get_user_token(self): res = self.client.post( "api/v1/signin", data=json.dumps(self.admin_log), headers={"content-type": "application/json"} ) response = json.loads(res.data.decode('utf-8'))['token'] print("token>>>>>>>>>>>>>>>>>>>>>", response) return response # creating a product needs admin access def test_create_product(self): token = self.get_user_token() res = self.client.post( "api/v1/products", data=json.dumps(self.data), headers={"content-type": "application/json", "Authorization": token } ) self.assertEqual(res.status_code, 201) # Trying to create product without a token def test_create_product3(self): res = self.client.post( "api/v1/products", data=json.dumps(self.data), headers={"content-type": "application/json" } ) self.assertEqual(res.status_code, 500) # getting all products can be done by both admin and attendant def test_get_all_products(self): token = self.get_user_token() res = self.client.get( "api/v1/products", headers={"content-type": "application/json", "Authorization": token } ) self.assertEqual(res.status_code, 200) # test to get single product both admin and attendant have the right def test_get_product_by_id(self): token = self.get_user_token() res = self.client.get( "api/v1/products/1", headers={"content-type": "application/json", "Authorization": token } ) self.assertEqual(res.status_code, 200) # getting a product that doesnot exist. def test_get_product_by_id1(self): token = self.get_user_token() res = self.client.get( "api/v1/products/2", headers={"content-type": "application/json", "Authorization": token } ) self.assertEqual(res.status_code, 404) # create a user attendant def test_create_attendant_user(self): res = self.client.post( "api/v1/signup", data=json.dumps(self.attendant), headers={"content-type": "application/json"} ) self.assertEqual(res.status_code, 201) if __name__ == "__main__": unittest.main() <file_sep>/v1/app/controllers/sales_controllers.py from flask import jsonify, make_response class Sales(object): """This is a class for handling all sales activities. """ def __init__(self): """The constructor for sales class.""" # creates an empty list self.sales = [] def create_sale(self, data): """ The function creates a new sale order. Parameter: data:This are values that are passed, they are defined and handled in sales_views.py Returns: Sales:A sale record """ # generating an id sale_id = len(self.sales) + 1 sale = {"id": sale_id, "name": data["name"], "description": data["description"]} # adding sale to sales list self.sales.append(sale) response_object = { "message": "sale record created", "status": "pass" } return(make_response(jsonify(response_object)), 201) def get_sales(self): """ The function to get all sales created. Returns: products: A list of all created sales. """ return(jsonify(self.sales)) def get_sale(self, id): """ The function to get a specific sale record. Parameter: id: This is the unique identification number of a sale order Returns: Sales:A single sale order """ for i, sale in enumerate(self.sales): if sale['id'] == id: return(make_response(jsonify(sale))) break response_object = { "message": "sale with that id does not exist", "status": "fail" } return(make_response(jsonify(response_object)), 404) <file_sep>/v1/run.py import os from app import create_app environment = os.getenv('ENV') print('environment', environment) app = create_app(environment) if __name__ == "__main__": app.run() <file_sep>/README.md # Store-api-v1 > An application programming interface. > To be used by Front End pages [![Build Status](https://travis-ci.org/Ruiru11/store-api-v1.svg?branch=develop)](https://travis-ci.org/Ruiru11/store-api-v1) [![Coverage Status](https://coveralls.io/repos/github/Ruiru11/store-api-v1/badge.svg?branch=develop)](https://coveralls.io/github/Ruiru11/store-api-v1?branch=develop) ## HELPS MANAGE CRUD OPERATIONS ## Installation: 1. Navigate to where you want to install the project 2. In your terminal: 3. git clone `https://github.com/Ruiru11/store-api-v1.git` 4. Navigate into into the created folder 5. git init #### create a virtualenv environment OS X & Linux: ```sh pip install -r requirements.txt ``` Windows: ```sh pip install -r requirements.txt ``` ## HOW TO USE THE APPLICATION . Available Endpoints > ```POST/api/v1/products``` . Used to create a new product for the store (Only accessible to admin) #### payload ``` { "name":"steel", "price":"sh.825", "category":"construction", "description":"Y16-For Columns and Slab" } ``` > ```POST/api/v1/sales``` . Used to create a new sale order (accessible by store attendants) #### payload ``` { "name": "<NAME>", "description": "['oil-paint','wood','nails','T.cost=3000']" } ``` > ```POST/api/v1/signup``` . Used to create users #### payload ``` { "username": "Kristine Camil", "password": "<PASSWORD>", "email": "<EMAIL>", "role": "attendant" } ``` #### The rest of the enpoints > ```POST/api/v1/signin``` . Used to signin a user > ```GET/api/v1/products``` . Used to get all products(accessible to admin and attendants) > ```GET/api/v1/products/<int:id>``` . Used to get a single product created (accessible to both admin and attendants) > ```GET/api/v1/sales``` . Used to get all sale orders (only accesible to admin) > ```GET/api/v1/sales/<int:id>``` . Used to get a single sale order (accessible only to admin and attendant who created the orders) ## How should this be manually tested? #### After cloning the repo locally run python run.py . Using postman to test the above endpoints using the below headers ##### key Content-Type →application/json ##### Key Authorization → Token ## Running the tests ``` pytest --cov=app tests ```<file_sep>/v1/requirements.txt alembic==1.0.0 aniso8601==3.0.2 astroid==2.0.4 attrs==17.4.0 autopep8==1.4 BareNecessities==0.2.8 bcrypt==3.1.4 blinker==1.4 cffi==1.11.5 Click==7.0 colorama==0.3.9 coverage==4.5.1 Flask==1.0.2 Flask-Bcrypt==0.7.1 Flask-Mail==0.9.1 Flask-Migrate==2.2.1 Flask-RESTful==0.3.5 Flask-Script==2.0.6 Flask-SQLAlchemy==2.3.2 Flask-WTF==0.14.2 future==0.16.0 gunicorn==19.9.0 isort==4.3.4 itsdangerous==0.24 Jinja2==2.10 lazy-object-proxy==1.3.1 Mail==2.1.0 Mako==1.0.7 MarkupSafe==1.0 mccabe==0.6.1 Pillow==5.2.0 pluggy==0.6.0 psycopg2==2.7.5 py==1.5.2 pycodestyle==2.4.0 pycparser==2.19 PyJWT==1.6.4 pylint==2.1.1 pytest==3.4.1 pytest-cov==2.6.0 python-dateutil==2.7.3 python-editor==1.0.3 pytz==2018.5 Sijax==0.3.2 simplejson==3.16.0 six==1.11.0 SQLAlchemy==1.2.3 typed-ast==1.1.0 virtualenv==15.1.0 Werkzeug==0.14.1 wrapt==1.10.11 wtf==0.1 WTForms==2.1
b6e5d3d680d76509288fa45732057c767a67f866
[ "Markdown", "Python", "Text" ]
13
Python
Ruiru11/store-api-v1
b5a43f565dd2b2a95be8102fdee310955e44962d
fa1e0eaa8a274c896af213a7ddf04bbae2e88c1e
refs/heads/master
<file_sep>xdebug.default_enable = on xdebug.remote_enable = on xdebug.remote_autostart = on xdebug.remote_connect_back = on xdebug.remote_port = 9000 xdebug.idekey = PHPSTORM xdebug.max_nesting_level = 500 xdebug.profiler_enable = off xdebug.remote_log = "php://stdout" xdebug.profiler_output_dir = "/var/www/dev/var/tmp" <file_sep><?php declare(strict_types=1); namespace App\Crawler\Page; use DateTime; use DateTimeZone; use Symfony\Component\DomCrawler\Crawler; class NewsArticlePage { /** * @var Crawler */ private $crawler; /** * @param Crawler $crawler */ public function __construct(Crawler $crawler) { $this->crawler = $crawler; } public function getTitle() : string { return $this->crawler->filter('div div#content article header h1')->text(); } public function getDescription() : string { return $this->crawler->filter('div div#content article header h2')->text(); } public function getContent() : string { return $this->crawler->filter('div div#content article div.contentBody')->html(); } public function getAuthor() : string { return $this->crawler->filter('div div#content article header div.noticias_media div.autor strong')->text(); } public function getPublishDate() : DateTime { $time = $this->crawler->filter('div div#content article header div.noticias_media time')->text(); return $this->getDateTime($time); } private function getDateTime(string $time) : DateTime { $timezone = new DateTimeZone('America/Sao_Paulo'); return DateTime::createFromFormat('Y-m-d H:i', $time, $timezone); } } <file_sep>ARG BASE_IMAGE FROM ${BASE_IMAGE} AS base MAINTAINER <NAME> <<EMAIL>> # Install Xdebug RUN yes | pecl install xdebug && \ docker-php-ext-enable xdebug <file_sep><?php declare(strict_types=1); namespace App\Command; use App\Crawler\Crawler\SymfonyCrawler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; class GetSymfonyReleasesCommand extends Command { protected static $defaultName = 'app:symfony:releases'; /** * @var SymfonyCrawler */ private $crawler; public function __construct(SymfonyCrawler $crawler) { $this->crawler = $crawler; parent::__construct(); } protected function configure() : void { $this ->setDescription('Get information about the Symfony releases.') ->setHelp('This command allows you to get information about the Symfony releases.'); } /** * @param InputInterface $input * @param OutputInterface $output * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ protected function execute(InputInterface $input, OutputInterface $output) : void { $releases = $this->crawler->getReleases(); if (!empty($releases)) { $output->writeln('========== Symfony Releases =========='); $output->writeln(sprintf('LTS: %s', $releases['symfony_versions']['lts'])); $output->writeln(sprintf('Stable: %s', $releases['symfony_versions']['stable'])); $output->writeln(sprintf('Next: %s', $releases['symfony_versions']['next'])); $output->writeln(sprintf('Latest Stable Version: %s', $releases['latest_stable_version'])); $output->writeln('Supported Versions:'); foreach ($releases['supported_versions'] as $version) { $output->writeln($version); } } } } <file_sep><?php declare(strict_types=1); namespace App\Command; use App\Crawler\Crawler\CityHallNewsCrawler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; class GetLatestCityHallNewsCommand extends Command { protected static $defaultName = 'app:news:latest'; /** * @var CityHallNewsCrawler */ private $crawler; public function __construct(CityHallNewsCrawler $crawler) { $this->crawler = $crawler; parent::__construct(); } protected function configure() : void { $this ->setDescription('Get the latest news from the São Paulo City Hall.') ->setHelp('This command allows you to get the latest news from the São Paulo City Hall.'); } /** * @param InputInterface $input * @param OutputInterface $output * @throws ClientExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ protected function execute(InputInterface $input, OutputInterface $output) : void { $searchPageUrl = 'http://www.capital.sp.gov.br/@@busca_atualizada?pt_toggle=%23&b_start:int=0&portal_type:list=News%20Item'; $searchPage = $this->crawler->getNewsArticleSearchPage($searchPageUrl); if ($searchPage->getNewsArticlesTotal() > 0) { $output->writeln('========== Latest News - São Paulo City Hall =========='); foreach ($searchPage->getNewsArticleLinks() as $link) { $output->writeln($link->getUri()); } } } } <file_sep><?php declare(strict_types=1); namespace App\Crawler\Crawler; use RuntimeException; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpFoundation\Response; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; class SymfonyCrawler { /** * @var HttpClientInterface */ private $httpClient; public function __construct(HttpClientInterface $httpClient) { $this->httpClient = $httpClient; } /** * @return array * @throws TransportExceptionInterface * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface */ public function getVersions() : array { $response = $this->httpClient->request('GET', 'https://symfony.com/versions.json'); if (Response::HTTP_OK === $response->getStatusCode()) { return $response->toArray(); } throw new RuntimeException('Could not retrieve the Symfony versions.'); } /** * @return array * @throws TransportExceptionInterface * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface */ public function getReleases() : array { $httpClient = HttpClient::create(); $response = $httpClient->request('GET', 'https://symfony.com/releases.json'); if (200 === $response->getStatusCode()) { return $response->toArray(); } throw new RuntimeException('Could not retrieve the Symfony releases.'); } } <file_sep><?php declare(strict_types=1); namespace App\Command; use App\Crawler\Crawler\CityHallNewsCrawler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; class GetCityHallNewsArticleCommand extends Command { protected static $defaultName = 'app:news:article'; /** * @var CityHallNewsCrawler */ private $crawler; public function __construct(CityHallNewsCrawler $crawler) { $this->crawler = $crawler; parent::__construct(); } protected function configure() : void { $this ->setDescription('Get the news article from URL.') ->setHelp('This command allows you to get the news article for the given URL.') ->addArgument('url', InputArgument::REQUIRED, 'News article URL'); } /** * @param InputInterface $input * @param OutputInterface $output * @throws ClientExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ protected function execute(InputInterface $input, OutputInterface $output) : void { $url = $input->getArgument('url'); $newsArticle = $this->crawler->getNewsArticle($url); $output->writeln('========== News Article - São Paulo City Hall =========='); $output->writeln($newsArticle->getTitle()); $output->writeln($newsArticle->getContent()); } } <file_sep><?php declare(strict_types=1); namespace App\Crawler\Page; use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\DomCrawler\Link; class NewsArticleSearchPage { /** * @var Crawler */ private $crawler; /** * @param Crawler $crawler */ public function __construct(Crawler $crawler) { $this->crawler = $crawler; } /** * @return int */ public function getNewsArticlesTotal() : int { return (int) $this->crawler->filter('#updated-search-results-number')->text(); } /** * @return Link[] */ public function getNewsArticleLinks() : array { return $this->crawler->filter( 'dl.searchResults div.contenttype-news-item a.state-published' )->links(); } /** * @return Link */ public function getNextSearchPageLink() : Link { return $this->crawler->filter('#search-results ul.paginacao.listingBar li a.proximo')->link(); } } <file_sep><?php declare(strict_types=1); namespace App\Command; use App\Crawler\Crawler\SymfonyCrawler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; class GetSymfonyVersionsCommand extends Command { protected static $defaultName = 'app:symfony:versions'; /** * @var SymfonyCrawler */ private $crawler; public function __construct(SymfonyCrawler $crawler) { $this->crawler = $crawler; parent::__construct(); } protected function configure() : void { $this ->setDescription('Get information about the Symfony versions.') ->setHelp('This command allows you to get information about the Symfony versions.'); } /** * @param InputInterface $input * @param OutputInterface $output * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ protected function execute(InputInterface $input, OutputInterface $output) : void { $versions = $this->crawler->getVersions(); if (!empty($versions)) { $output->writeln('========== Symfony Versions =========='); foreach ($versions as $key => $version) { // Skipping some keys because there are a lot of versions if ($key === 'non_installable' || $key === 'installable') { continue; } $output->writeln(sprintf('%s: %s', $key, $version)); } } } } <file_sep># Development ## Requirements 1. Install [Docker][docker-install] and [Docker Compose][compose-install], and add the binaries to the `PATH` environment variable. _Note: The following configurations are based on a Linux setup. Adjustments may be required to use Docker Compose in the Windows setup._ ## Installation ### Environment Variables 1. Access the `.deploy/local` directory, create an `.env` file from `.env.dist`, and set up the variables used on the containers: | Variable | Description | | --------------------- | --------------------------------------------------------------------- | | COMPOSE_FILE | The project docker-compose yaml file(s). | | COMPOSE_PROJECT_DIR | The project docker-compose directory for local config. | | COMPOSE_PROJECT_NAME | Project name used as prefix when creating containers. | | COMPOSER_MEMORY_LIMIT | Prevent memory limit errors as explained [here][memory-limit-errors]. | | DEV_COMPOSER_DIR | Your local composer directory, on your host machine, used for cache. | | DEV_DOCKER_IMAGE_PHP | Docker image used by the php service. | | DEV_HOST_PORT_HTTP | HTTP port used on the host machine. Default: 80. | | DEV_HOST_PORT_MYSQL | MySQL port used on host machine. Default: 3306. | | DEV_GID | The user group id, used to prevent permissions errors. | | DEV_UID | The user id, used to prevent permissions errors. | | MYSQL_DATABASE | Default database. | | MYSQL_PASSWORD | <PASSWORD> user password. | | MYSQL_ROOT_PASSWORD | MySQL root password. | | MYSQL_USER | MySQL user. | To get the `$GID` and `$UID` run the following commands: ``` id -u <user> id -g <group> ``` 2. Then you can execute the helper scripts from the `.deploy/local/bin` folder: ``` .deploy/local ├── bin │   ├── check-env.sh │   ├── install-env.sh │   └── set-aliases.sh ├── services │   ├── mysql │   ├── nginx │   └── php ├── docker-compose.yaml └── .env.dist .env ``` ### Docker 1. From the **project root folder**, run the following commands to create aliases for the development tools: ``` COMPOSE_PROJECT_DIR=${PWD}/.deploy/local . .deploy/local/bin/install-env.sh ``` 2. The following aliases will be created: * composer * console * dc * php 1. Build the docker images: ``` docker build -t ${DEV_DOCKER_IMAGE_PHP}:base .deploy/docker/base dc build --parallel ``` 1. Run the containers: ``` dc up -d ``` _Note: Make sure the host ports set up to the services on the `docker-compose.yaml` file are free. The `ports` directive maps ports on the host machine to ports on the containers and follows the format `<host-port>:<container-port>`. More info on the [Compose file reference][compose-ports]._ 1. To stop the containers, run: ``` dc down ``` ### Application 1. Access the root directory, create an `.env.local` file from `.env`, and set up the variables used on the application. 2. Then, run the following command: ``` composer install ``` [compose-install]: https://docs.docker.com/compose/install/ [compose-ports]: https://docs.docker.com/compose/compose-file/#ports [docker-install]: https://docs.docker.com/install/ [memory-limit-errors]: https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors <file_sep>#!/usr/bin/env bash alias composer="dc \ exec php composer $@" alias console="dc \ exec php bin/console $@" alias dc="docker-compose \ --project-directory ${COMPOSE_PROJECT_DIR} \ --file ${COMPOSE_PROJECT_DIR}/docker-compose.yaml \ $@" alias php="dc \ exec php php $@" <file_sep>FROM composer:latest AS composer FROM php:fpm-alpine AS php MAINTAINER <NAME> <<EMAIL>> # Install dependencies and tools RUN apk add --no-cache --update --virtual .build-deps \ autoconf \ g++ \ git \ libxml2-dev \ libzip-dev \ make \ openssl-dev \ zip # Build and install PHP extensions RUN docker-php-ext-configure \ opcache && \ docker-php-ext-install \ mysqli \ opcache \ pdo_mysql \ zip && \ pecl install \ mongodb && \ docker-php-ext-enable \ mongodb \ opcache # Remove dependencies RUN apk del --purge \ autoconf \ g++ \ libxml2-dev \ make \ openssl-dev && \ docker-php-source delete && \ rm -rf /tmp/* /var/cache/apk/* # Install Composer COPY --from=composer /usr/bin/composer /usr/bin/composer ENV COMPOSER_HOME /composer ENV PATH ${PATH}:/composer/vendor/bin ENV COMPOSER_ALLOW_SUPERUSER 0 <file_sep># SymfonyCon Amsterdam 2019 - Crawling the Web with the New Symfony Components ## Documentation [Symfony Documentation][doc-symfony] ## Requirements - MySQL 8.0 - PHP 7.3 - Symfony 4.3 ## Development * [Local][doc-local] [doc-symfony]: https://symfony.com/doc/current/index.html [doc-local]: .deploy/local/README.md <file_sep><?php declare(strict_types=1); namespace App\Crawler\Crawler; use App\Crawler\Page\NewsArticlePage; use App\Crawler\Page\NewsArticleSearchPage; use RuntimeException; use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\HttpFoundation\Response; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; class CityHallNewsCrawler { /** * @var HttpClientInterface */ private $httpClient; public function __construct(HttpClientInterface $httpClient) { $this->httpClient = $httpClient; } /** * @param string $url * @return NewsArticleSearchPage * @throws ClientExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ public function getNewsArticleSearchPage(string $url) : NewsArticleSearchPage { $response = $this->httpClient->request('GET', $url); if (Response::HTTP_OK === $response->getStatusCode()) { $content = $response->getContent(); $crawler = new Crawler($content); // Create an object to handle the target DOM elements return new NewsArticleSearchPage($crawler); } throw new RuntimeException('Could not retrieve the news articles.'); } /** * @param string $url * @return NewsArticlePage * @throws ClientExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface */ public function getNewsArticle(string $url) : NewsArticlePage { $response = $this->httpClient->request('GET', $url); if (Response::HTTP_OK === $response->getStatusCode()) { $content = $response->getContent(); $crawler = new Crawler($content); // Create an object to handle the target DOM elements return new NewsArticlePage($crawler); } throw new RuntimeException('Could not retrieve the news article.'); } }
bafc3b4f3a30efbd8f76d0e192ec8922525885fb
[ "Markdown", "INI", "PHP", "Dockerfile", "Shell" ]
14
INI
adielcristo/sfcon-amsterdam-2019-crawler
9a1ceea3b73eaa60886eb56955e58b11f63055cc
2159ae58d6233248074034a99f2bb7286fbeb29c
refs/heads/master
<file_sep>var slider = (function () { var slides = $('.slider__item'); return { scrollSlides: function (direction) { var slidesVisibleArr = []; $('.slider__item').each(function (indx) { if ($(this).hasClass('slider__item_visible')) { var elIndx = $(this).index(); slidesVisibleArr.push(elIndx); } }); $('.slider__item').removeClass('slider__item_visible'); for (var i = 1; i <= 4; i++) { $('.slider__item_visible-' + i).removeClass('slider__item_visible-' + i); }; for (var i = 0; i < 4; i++) { var visiblePosition = i + 1; $('.slider__item').eq(slidesVisibleArr[i] + direction) .addClass('slider__item_visible slider__item_visible-' + visiblePosition); } } } })(); $('.slider__arrow-next').on('click', function () { slider.scrollSlides(1); }); $('.slider__arrow-prev').on('click', function () { slider.scrollSlides(-1); });
3b4776306c64f2cd0deb6c9c0c2149930b2289bf
[ "JavaScript" ]
1
JavaScript
rvdvr/circle-slider
1e70eea5a63cc4a5db352f76599031f5da986694
dab1e11c5c63e2ffde81c3f66ac73c7790a62e4e
refs/heads/main
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaUsuario; import ec.edu.ups.controlador.ControladorUsuario; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.JOptionPane; /** * * @author dduta */ public class EditarUsuario extends javax.swing.JInternalFrame { private ControladorUsuario controladoUsuario; private Locale localizacion; private ResourceBundle mensajes; /** * Creates new form EditarUsuario */ public EditarUsuario(ControladorUsuario controladoUsuario) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladoUsuario = controladoUsuario; } public void limpiar() { contrasenia.setText(""); txtApellidoActualizarU.setText(""); txtCedulaU.setText(""); txtCorreoActualizarU.setText(""); txtNombreActualizarU.setText(""); txtTipoActualizarU.setText(""); txtcu.setText(""); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes = ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); lebelUsuarioEditar.setText(mensajes.getString("lebelUsuarioEditar")); ButtonBuscarU.setText(mensajes.getString("ButtonBuscarU")); Labesuariol.setText(mensajes.getString("Labesuariol")); tipo.setText(mensajes.getString("tipo")); nombre.setText(mensajes.getString("nombre")); apellido.setText(mensajes.getString("apellido")); correo.setText(mensajes.getString("correo")); contrasenia.setText(mensajes.getString("contrasenia")); ButtonActualizarU.setText(mensajes.getString("ButtonActualizarU")); jButton1.setText(mensajes.getString("jButton1")); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lebelUsuarioEditar = new javax.swing.JLabel(); Labesuariol = new javax.swing.JLabel(); tipo = new javax.swing.JLabel(); nombre = new javax.swing.JLabel(); apellido = new javax.swing.JLabel(); ButtonBuscarU = new javax.swing.JButton(); ButtonActualizarU = new javax.swing.JButton(); txtCedulaU = new javax.swing.JTextField(); correo = new javax.swing.JLabel(); txtTipoActualizarU = new javax.swing.JTextField(); txtApellidoActualizarU = new javax.swing.JTextField(); txtNombreActualizarU = new javax.swing.JTextField(); txtCorreoActualizarU = new javax.swing.JTextField(); contrasenia = new javax.swing.JLabel(); txtcu = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Editar Usuarios"); lebelUsuarioEditar.setText("Ingrese la Cedula del Usuario a Editar:"); Labesuariol.setText("Ingrese los nuevos Datos"); tipo.setText("Tipo:"); nombre.setText("Nombre:"); apellido.setText("Apellido:"); ButtonBuscarU.setText("Buscar"); ButtonBuscarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonBuscarUActionPerformed(evt); } }); ButtonActualizarU.setText("Actualizar"); ButtonActualizarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonActualizarUActionPerformed(evt); } }); correo.setText("Correo:"); txtTipoActualizarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtTipoActualizarUActionPerformed(evt); } }); contrasenia.setText("contraseña"); jButton1.setText("Cancelar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lebelUsuarioEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtCedulaU, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Labesuariol))) .addGroup(layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(ButtonBuscarU)) .addGroup(layout.createSequentialGroup() .addGap(84, 84, 84) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(nombre) .addComponent(tipo) .addComponent(apellido) .addComponent(correo)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtTipoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtApellidoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNombreActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCorreoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(contrasenia) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtcu)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(ButtonActualizarU) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(78, 78, 78))) .addContainerGap(48, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lebelUsuarioEditar) .addComponent(txtCedulaU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ButtonBuscarU) .addGap(14, 14, 14) .addComponent(Labesuariol) .addGap(14, 14, 14) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tipo) .addComponent(txtTipoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(nombre) .addComponent(txtNombreActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(apellido) .addComponent(txtApellidoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(correo) .addComponent(txtCorreoActualizarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(contrasenia) .addComponent(txtcu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonActualizarU) .addComponent(jButton1)) .addContainerGap(56, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtTipoActualizarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTipoActualizarUActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtTipoActualizarUActionPerformed private void ButtonActualizarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonActualizarUActionPerformed if (!txtApellidoActualizarU.getText().isEmpty() && !txtTipoActualizarU.getText().isEmpty() && !txtCorreoActualizarU.getText().isEmpty() && !txtNombreActualizarU.getText().isEmpty() && !txtcu.getText().isEmpty()) { controladoUsuario.update(txtTipoActualizarU.getText(), txtCedulaU.getText(), txtNombreActualizarU.getText(), txtApellidoActualizarU.getText(), txtCorreoActualizarU.getText(), txtcu.getText()); limpiar(); } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonActualizarUActionPerformed private void ButtonBuscarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonBuscarUActionPerformed if (!txtCedulaU.getText().isEmpty()) { if (controladoUsuario.read(txtCedulaU.getText()) != null) { txtTipoActualizarU.setText(controladoUsuario.read(txtCedulaU.getText()).getTipo()); txtNombreActualizarU.setText(controladoUsuario.read(txtCedulaU.getText()).getNombre()); txtApellidoActualizarU.setText(controladoUsuario.read(txtCedulaU.getText()).getApellido()); txtCorreoActualizarU.setText(controladoUsuario.read(txtCedulaU.getText()).getCorreo()); txtcu.setText(controladoUsuario.read(txtCedulaU.getText()).getContrasenia()); } else { JOptionPane.showMessageDialog(null, "No existe el Usuario"); limpiar(); } } else { JOptionPane.showMessageDialog(null, "Campo buscar Uusuario vacio"); } }//GEN-LAST:event_ButtonBuscarUActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonActualizarU; private javax.swing.JButton ButtonBuscarU; private javax.swing.JLabel Labesuariol; private javax.swing.JLabel apellido; private javax.swing.JLabel contrasenia; private javax.swing.JLabel correo; private javax.swing.JButton jButton1; private javax.swing.JLabel lebelUsuarioEditar; private javax.swing.JLabel nombre; private javax.swing.JLabel tipo; private javax.swing.JTextField txtApellidoActualizarU; private javax.swing.JTextField txtCedulaU; private javax.swing.JTextField txtCorreoActualizarU; private javax.swing.JTextField txtNombreActualizarU; private javax.swing.JTextField txtTipoActualizarU; private javax.swing.JPasswordField txtcu; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.dao; import ec.edu.ups.modelo.Usuario; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator; import ec.edu.ups.idao.IdaoUsuario; /** * * @author dduta */ public class DaoUsuario implements IdaoUsuario{ private Map<String, Usuario> diccionario; public DaoUsuario() { this.diccionario = new HashMap<String,Usuario>(); } @Override public void create(Usuario usuario) { diccionario.put(usuario.getId(), usuario ); } @Override public Usuario read(String id) { return diccionario.get(id); } @Override public void update(Usuario usuario) { diccionario.put(usuario.getId(), usuario); } @Override public void delete(Usuario usuario) { diccionario.remove(usuario.getId()); } @Override public Usuario validar(String correo, String contrasenia) { Collection <Usuario> usuarios=diccionario.values(); for (Usuario usuario : usuarios) { if (usuario.getCorreo().equals(correo) && usuario.getContrasenia().equals(contrasenia)) { return usuario; }else{ System.out.println("Usuario no existente"); } } return null; } @Override public Collection<Usuario> findAll() { Collection<Usuario> usuarios = diccionario.values(); return usuarios; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaUsuario; import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory; import ec.edu.ups.controlador.ControladorUsuario; import ec.edu.ups.modelo.Usuario; import java.util.Collection; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; /** * * @author dduta */ public class ListarUsuarios extends javax.swing.JInternalFrame { private ControladorUsuario controladorUsuario; private Locale localizacion; private ResourceBundle mensajes; private String cedula; private String nombre; private String apellido; private String correo; private String tipo; /** * Creates new form ListarUsuarios */ public ListarUsuarios(ControladorUsuario controladorUsuario) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladorUsuario = controladorUsuario; } public void actalizar(Collection<Usuario> usuarios) { DefaultTableModel modelo = (DefaultTableModel) TablaListarU.getModel(); modelo.setRowCount(0); for (Usuario usuario : usuarios) { Object[] fila = new Object[4]; fila[0] = usuario.getId(); fila[1] = usuario.getNombre(); fila[2] = usuario.getApellido(); fila[3] = usuario.getTipo(); } TablaListarU.setModel(modelo); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes = ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); ButtonListarU.setText(mensajes.getString("ButtonListarU")); ButtonCancelarU.setText(mensajes.getString("ButtonCancelarU")); this.cedula = mensajes.getString("cedula"); this.nombre = mensajes.getString("nombre"); this.apellido = mensajes.getString("apellido"); this.correo = mensajes.getString("correo"); this.tipo = mensajes.getString("tipo"); DefaultTableModel modelo = (DefaultTableModel) TablaListarU.getModel(); modelo.setColumnCount(0); modelo.setRowCount(0); modelo.addColumn(cedula); modelo.addColumn(nombre); modelo.addColumn(apellido); modelo.addColumn(correo); modelo.addColumn(tipo); this.TablaListarU.setModel(modelo); } public void limpiarTblLista() { TablaListarU.removeAll(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jInternalFrame1 = new javax.swing.JInternalFrame(); jScrollPane1 = new javax.swing.JScrollPane(); TablaListarU = new javax.swing.JTable(); ButtonListarU = new javax.swing.JButton(); ButtonCancelarU = new javax.swing.JButton(); jInternalFrame1.setVisible(true); javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane()); jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout); jInternalFrame1Layout.setHorizontalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jInternalFrame1Layout.setVerticalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Ventana Listar Usuario"); TablaListarU.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cedula", "Nombre", "Apellido", "Correo", "Tipo" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(TablaListarU); ButtonListarU.setText("Listar"); ButtonListarU.setToolTipText("Dale push para lista los USUARIOSr"); ButtonListarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonListarUActionPerformed(evt); } }); ButtonCancelarU.setText("Cancelar"); ButtonCancelarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonCancelarUActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 660, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(154, 154, 154) .addComponent(ButtonListarU, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49) .addComponent(ButtonCancelarU, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonListarU) .addComponent(ButtonCancelarU)) .addContainerGap(62, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void ButtonListarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonListarUActionPerformed Collection<Usuario> listaUsuarios = controladorUsuario.findAll(); DefaultTableModel modelo = (DefaultTableModel) TablaListarU.getModel(); modelo.setRowCount(0); for (Usuario usuario : listaUsuarios) { Object[] rowData = {usuario.getId(), usuario.getNombre(), usuario.getApellido(), usuario.getCorreo(), usuario.getTipo()}; modelo.addRow(rowData); } }//GEN-LAST:event_ButtonListarUActionPerformed private void ButtonCancelarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelarUActionPerformed limpiarTblLista(); this.setVisible(false); }//GEN-LAST:event_ButtonCancelarUActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonCancelarU; private javax.swing.JButton ButtonListarU; private javax.swing.JTable TablaListarU; private javax.swing.JInternalFrame jInternalFrame1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.idao; import ec.edu.ups.modelo.Usuario; import java.util.Collection; /** * * @author dduta */ public interface IdaoUsuario { public void create(Usuario usuario); public Usuario read(String cedula); public void update (Usuario usuario); public void delete (Usuario usuario); public Usuario validar(String correo, String contrasenia); public Collection<Usuario> findAll(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.idao; import ec.edu.ups.modelo.Carrito; import java.util.Collection; /** * * @author dduta */ public interface IdaoCarrito { public void create(Carrito carrito); public Carrito read(int codigo); public void update(Carrito carrito); public void delete(Carrito carrito); public Collection<Carrito> findAll(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.dao; import ec.edu.ups.modelo.Carrito; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import ec.edu.ups.idao.IdaoCarrito; /** * * @author dduta */ public class DaoCarrito implements IdaoCarrito{ private Map<Integer, Carrito> carritos; public DaoCarrito() { this.carritos= new HashMap<Integer,Carrito>(); } @Override public void create(Carrito carrito) { carritos.put(carrito.getNumeroCarrito(), carrito); } @Override public Carrito read(int codigo) { return carritos.get(codigo); } @Override public void update(Carrito carrito) { carritos.put(carrito.getNumeroCarrito(), carrito); } @Override public void delete(Carrito carrito) { carritos.remove(carrito.getNumeroCarrito()); } @Override public Collection<Carrito> findAll() { Collection<Carrito> carrito = carritos.values(); return carrito; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaUsuario; import com.sun.imageio.plugins.jpeg.JPEG; import ec.edu.ups.controlador.ControladorUsuario; import ec.edu.ups.ventanPrincipal.Principal; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.JOptionPane; /** * * @author dduta */ public class IngresarUsuario extends javax.swing.JInternalFrame { private Principal p; private Locale localizacion; private ResourceBundle mensajes; private ControladorUsuario controladorUsuario; public IngresarUsuario(ControladorUsuario controladorUsuario, Principal p) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladorUsuario = controladorUsuario; this.p = p; } public void limpiar() { txtContraseniaU.setText(""); txtCorreoU.setText(""); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes=ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); lebelCorreoU.setText(mensajes.getString("lebelCorreoU")); lebelContraseniaU.setText(mensajes.getString("lebelContraseniaU")); ButtonIngresarU.setText(mensajes.getString("ButtonIngresarU")); ButtonCancelarU.setText(mensajes.getString("ButtonCancelarU")); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jTextField2 = new javax.swing.JTextField(); ButtonCancelarU = new javax.swing.JButton(); lebelCorreoU = new javax.swing.JLabel(); lebelContraseniaU = new javax.swing.JLabel(); txtCorreoU = new javax.swing.JTextField(); txtContraseniaU = new javax.swing.JPasswordField(); ButtonIngresarU = new javax.swing.JButton(); jButton1.setText("Ingresar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Inicia Sesion"); ButtonCancelarU.setText("Cancelar"); ButtonCancelarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonCancelarUActionPerformed(evt); } }); lebelCorreoU.setText("Correo:"); lebelContraseniaU.setText("Contraseña"); txtCorreoU.setToolTipText("Ingresa el Usuario o Correo"); txtCorreoU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCorreoUActionPerformed(evt); } }); txtContraseniaU.setToolTipText("Ingresa la contraseña"); txtContraseniaU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtContraseniaUActionPerformed(evt); } }); ButtonIngresarU.setText("Ingresar"); ButtonIngresarU.setToolTipText("Dale push para Inicion Sesion"); ButtonIngresarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonIngresarUActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(lebelCorreoU) .addGap(23, 23, 23)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(lebelContraseniaU) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtCorreoU, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE) .addComponent(txtContraseniaU))) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(ButtonIngresarU) .addGap(18, 18, 18) .addComponent(ButtonCancelarU))) .addContainerGap(53, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCorreoU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lebelCorreoU)) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lebelContraseniaU) .addComponent(txtContraseniaU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonCancelarU) .addComponent(ButtonIngresarU)) .addContainerGap(30, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed }//GEN-LAST:event_jButton1ActionPerformed private void txtCorreoUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCorreoUActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtCorreoUActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void txtContraseniaUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtContraseniaUActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtContraseniaUActionPerformed private void ButtonIngresarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonIngresarUActionPerformed if (!txtContraseniaU.getText().isEmpty() && !txtCorreoU.getText().isEmpty()) { if (controladorUsuario.validar(String.valueOf(txtContraseniaU.getPassword()), txtCorreoU.getText()) != null) { JOptionPane.showMessageDialog(this, "A iniciado sesion correctamente"); p.getMenuBuscar().setVisible(true); p.getMenuBuscarP().setVisible(true); p.getMenuCrearC().setVisible(true); p.getMenuCrearP().setVisible(true); p.getMenuEditarU().setVisible(true); p.getMenuEliminarC().setVisible(true); p.getMenuListar().setVisible(true); p.getMenueliminarU().setVisible(true); p.getMenuAcutualizarP().setVisible(true); p.getMenuEliminarP().setVisible(true); p.getCerrarS().setVisible(true); p.getCrearU().setVisible(false); p.getMenuIniciar().setVisible(false); limpiar(); this.setVisible(false); } else { JOptionPane.showMessageDialog(null, "Contraseña o correo incorrectos"); limpiar(); this.setVisible(false); } } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonIngresarUActionPerformed private void ButtonCancelarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelarUActionPerformed limpiar(); this.setVisible(false); }//GEN-LAST:event_ButtonCancelarUActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonCancelarU; private javax.swing.JButton ButtonIngresarU; private javax.swing.JButton jButton1; private javax.swing.JTextField jTextField2; private javax.swing.JLabel lebelContraseniaU; private javax.swing.JLabel lebelCorreoU; private javax.swing.JPasswordField txtContraseniaU; private javax.swing.JTextField txtCorreoU; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaUsuario; import ec.edu.ups.controlador.ControladorUsuario; import ec.edu.ups.modelo.Usuario; import java.util.Collection; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author dduta */ public class BuscarUsuario extends javax.swing.JInternalFrame { private ControladorUsuario controladoUsuario; private Locale localizacion; private ResourceBundle mensajes; private String cedula; private String nombre; private String apellido; private String correo; private String tipo; /** * Creates new form BuscarUsuario */ public BuscarUsuario(ControladorUsuario controladoUsuario) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladoUsuario = controladoUsuario; } public void actalizar(Collection<Usuario> usuarios) { DefaultTableModel modelo = (DefaultTableModel) tableBuscarU.getModel(); modelo.setRowCount(0); for (Usuario usuario : usuarios) { Object[] fila = new Object[4]; fila[0] = usuario.getTipo(); fila[1] = usuario.getNombre(); fila[2] = usuario.getApellido(); fila[3] = usuario.getCorreo(); } tableBuscarU.setModel(modelo); } public void limpiar() { txtBuscarU.setText(""); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes = ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); dd.setText(mensajes.getString("dd")); ButtonBuscarU.setText(mensajes.getString("ButtonBuscarU")); ca.setText(mensajes.getString("ca")); this.cedula = mensajes.getString("cedula"); this.nombre = mensajes.getString("nombre"); this.apellido = mensajes.getString("apellido"); this.correo = mensajes.getString("correo"); this.tipo = mensajes.getString("tipo"); DefaultTableModel modelo = (DefaultTableModel) tableBuscarU.getModel(); modelo.setColumnCount(0); modelo.setRowCount(0); modelo.addColumn(cedula); modelo.addColumn(tipo); modelo.addColumn(nombre); modelo.addColumn(apellido); modelo.addColumn(correo); this.tableBuscarU.setModel(modelo); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dd = new javax.swing.JLabel(); txtBuscarU = new javax.swing.JTextField(); ButtonBuscarU = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tableBuscarU = new javax.swing.JTable(); ca = new javax.swing.JButton(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Buscar Usuario"); dd.setText("Ingrese el Codigo de la persona a Buscar:"); txtBuscarU.setToolTipText("Inserta el codigo para listar el Usuario"); txtBuscarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtBuscarUActionPerformed(evt); } }); ButtonBuscarU.setText("Buscar"); ButtonBuscarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonBuscarUActionPerformed(evt); } }); tableBuscarU.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cedula", "Tipo", "Nombre", "Apellido", "Correo" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tableBuscarU); ca.setText("Cancelar"); ca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { caActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(dd) .addGap(18, 18, 18) .addComponent(txtBuscarU, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(ButtonBuscarU)) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(253, 253, 253) .addComponent(ca))) .addContainerGap(24, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtBuscarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(dd) .addComponent(ButtonBuscarU)) .addGap(37, 37, 37) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(ca) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtBuscarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBuscarUActionPerformed }//GEN-LAST:event_txtBuscarUActionPerformed private void ButtonBuscarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonBuscarUActionPerformed if (!txtBuscarU.getText().isEmpty()) { if (controladoUsuario.read(txtBuscarU.getText()) != null) { DefaultTableModel modelo = (DefaultTableModel) tableBuscarU.getModel(); modelo.setRowCount(0); Object[] rowData = {controladoUsuario.read(txtBuscarU.getText()).getId(), controladoUsuario.read(txtBuscarU.getText()).getTipo(), controladoUsuario.read(txtBuscarU.getText()).getNombre(), controladoUsuario.read(txtBuscarU.getText()).getApellido(), controladoUsuario.read(txtBuscarU.getText()).getCorreo()}; modelo.addRow(rowData); limpiar(); } else { JOptionPane.showMessageDialog(null, "el Usuario no existe"); limpiar(); } } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonBuscarUActionPerformed private void caActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_caActionPerformed this.setVisible(false); }//GEN-LAST:event_caActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonBuscarU; private javax.swing.JButton ca; private javax.swing.JLabel dd; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tableBuscarU; private javax.swing.JTextField txtBuscarU; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.controlador; import ec.edu.ups.modelo.Producto; import java.util.Collection; import ec.edu.ups.idao.IdaoProducto; /** * * @author dduta */ public class ControladorProducto { private IdaoProducto idaoP; private Producto producto; public ControladorProducto(IdaoProducto IDAOProducto) { idaoP=IDAOProducto; } public void create(int codigo,String descripcion,double precio){ producto= new Producto(codigo, descripcion, precio); idaoP.create(producto); } public Producto read(int codigo){ producto=idaoP.read(codigo); if(producto!=null){ return producto; }else{ System.out.println("El producto no existente"); } return null; } public void update(int codigo,String descripcion,double precio){ producto= new Producto(codigo, descripcion, precio); idaoP.update(producto); } public void delete(int codigo){ producto=new Producto(codigo, null, 0); idaoP.delete(producto); } public Collection<Producto> findAll() { return idaoP.findAll(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaProducto; import ec.edu.ups.controlador.ControladorProducto; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.JOptionPane; /** * * @author dduta */ public class ModificarProducto extends javax.swing.JInternalFrame { private ControladorProducto controladorProducto; private Locale localizacion; private ResourceBundle mensajes; /** * Creates new form VentanaModificar */ public ModificarProducto(ControladorProducto controladorProducto) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladorProducto = controladorProducto; } public void limpiar() { txtCodigoP.setText(""); txtDescrpcionActualizarP.setText(""); txtPrecioActualizarP.setText(""); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes = ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); ingreseproducto.setText(mensajes.getString("ingreseproducto")); ButtonBuscarP.setText(mensajes.getString("ButtonBuscarP")); ingreselosdatos.setText(mensajes.getString("ingreselosdatos")); jj.setText(mensajes.getString("jj")); PrecioP.setText(mensajes.getString("PrecioP")); ButtonActualizarP.setText(mensajes.getString("ButtonActualizarP")); ButtonCancelarA.setText(mensajes.getString("ButtonCancelarA")); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { ingreseproducto = new javax.swing.JLabel(); ButtonBuscarP = new javax.swing.JButton(); txtCodigoP = new javax.swing.JTextField(); ingreselosdatos = new javax.swing.JLabel(); ButtonActualizarP = new javax.swing.JButton(); jj = new javax.swing.JLabel(); txtDescrpcionActualizarP = new javax.swing.JTextField(); PrecioP = new javax.swing.JLabel(); txtPrecioActualizarP = new javax.swing.JTextField(); ButtonCancelarA = new javax.swing.JButton(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Modificar Producto"); ingreseproducto.setText("Ingrese el codigo del producto a Modificar:"); ButtonBuscarP.setText("Buscar"); ButtonBuscarP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonBuscarPActionPerformed(evt); } }); ingreselosdatos.setText("Ingrese los nuevos datos del Producto"); ButtonActualizarP.setText("Actualizar"); ButtonActualizarP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonActualizarPActionPerformed(evt); } }); jj.setText("Descripcion:"); txtDescrpcionActualizarP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtDescrpcionActualizarPActionPerformed(evt); } }); PrecioP.setText("Precio:"); ButtonCancelarA.setText("Cancelar"); ButtonCancelarA.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonCancelarAActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(97, 97, 97) .addComponent(jj)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(PrecioP))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtDescrpcionActualizarP, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(txtPrecioActualizarP, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ingreselosdatos) .addGroup(layout.createSequentialGroup() .addComponent(ingreseproducto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtCodigoP, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGap(63, 63, 63) .addComponent(ButtonActualizarP) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ButtonCancelarA))) .addGap(18, 18, 18) .addComponent(ButtonBuscarP))) .addContainerGap(24, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonBuscarP) .addComponent(ingreseproducto) .addComponent(txtCodigoP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(ingreselosdatos) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jj) .addComponent(txtDescrpcionActualizarP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PrecioP) .addComponent(txtPrecioActualizarP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonActualizarP) .addComponent(ButtonCancelarA)) .addContainerGap(36, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtDescrpcionActualizarPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDescrpcionActualizarPActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtDescrpcionActualizarPActionPerformed private void ButtonBuscarPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonBuscarPActionPerformed if (!txtCodigoP.getText().isEmpty()) { if (controladorProducto.read(Integer.valueOf(txtCodigoP.getText())) != null) { txtDescrpcionActualizarP.setText(controladorProducto.read(Integer.valueOf(txtCodigoP.getText())).getDescripcion()); double total = controladorProducto.read(Integer.parseInt(txtCodigoP.getText())).getPrecio(); txtPrecioActualizarP.setText(String.valueOf(total)); } else { JOptionPane.showMessageDialog(null, "No existe el Usuario"); limpiar(); } } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonBuscarPActionPerformed private void ButtonActualizarPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonActualizarPActionPerformed if (!txtDescrpcionActualizarP.getText().isEmpty() && !txtPrecioActualizarP.getText().isEmpty()) { controladorProducto.update(Integer.parseInt(txtCodigoP.getText()), txtDescrpcionActualizarP.getText(), Double.valueOf(txtPrecioActualizarP.getText())); JOptionPane.showMessageDialog(null, "Producto Actualizado"); limpiar(); this.setVisible(false); } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonActualizarPActionPerformed private void ButtonCancelarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelarAActionPerformed limpiar(); this.setVisible(false); }//GEN-LAST:event_ButtonCancelarAActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonActualizarP; private javax.swing.JButton ButtonBuscarP; private javax.swing.JButton ButtonCancelarA; private javax.swing.JLabel PrecioP; private javax.swing.JLabel ingreselosdatos; private javax.swing.JLabel ingreseproducto; private javax.swing.JLabel jj; private javax.swing.JTextField txtCodigoP; private javax.swing.JTextField txtDescrpcionActualizarP; private javax.swing.JTextField txtPrecioActualizarP; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.ventanaUsuario; import ec.edu.ups.controlador.ControladorUsuario; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.JOptionPane; /** * * @author dduta */ public class EliminarUsuario extends javax.swing.JInternalFrame { private ControladorUsuario controladoUsuario; private Locale localizacion; private ResourceBundle mensajes; /** * Creates new form EliminarUsuario */ public EliminarUsuario(ControladorUsuario controladoUsuario) { initComponents(); this.mensajes = mensajes; cambiarIdioma(mensajes); this.controladoUsuario = controladoUsuario; } public void limpiar() { txtEliminarU.setText(""); } public void cambiarIdioma(ResourceBundle mensajes) { mensajes = ResourceBundle.getBundle("ec.edu.ups.Idiomas.mensajes", Locale.getDefault()); lebelEliminarU.setText(mensajes.getString("lebelEliminarU")); ButtonEliminarU.setText(mensajes.getString("ButtonEliminarU")); labelCancelarU.setText(mensajes.getString("labelCancelarU")); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lebelEliminarU = new javax.swing.JLabel(); txtEliminarU = new javax.swing.JTextField(); ButtonEliminarU = new javax.swing.JButton(); labelCancelarU = new javax.swing.JButton(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Eliminar un Usuario"); lebelEliminarU.setText("Ingrese la Cedula del Usuario a Eliminar:"); txtEliminarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtEliminarUActionPerformed(evt); } }); ButtonEliminarU.setText("Eliminar"); ButtonEliminarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonEliminarUActionPerformed(evt); } }); labelCancelarU.setText("Cancelar"); labelCancelarU.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { labelCancelarUActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(lebelEliminarU) .addGap(26, 26, 26) .addComponent(txtEliminarU, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(100, 100, 100) .addComponent(ButtonEliminarU) .addGap(18, 18, 18) .addComponent(labelCancelarU) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtEliminarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lebelEliminarU)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonEliminarU) .addComponent(labelCancelarU)) .addContainerGap(39, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtEliminarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEliminarUActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtEliminarUActionPerformed private void ButtonEliminarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonEliminarUActionPerformed if (!txtEliminarU.getText().isEmpty()) { if (controladoUsuario.read(txtEliminarU.getText()) != null) { controladoUsuario.delete(txtEliminarU.getText()); JOptionPane.showMessageDialog(null, "Eliminado Con Exito"); limpiar(); } else { JOptionPane.showMessageDialog(null, "usuario no existe"); limpiar(); this.setVisible(false); } } else { JOptionPane.showMessageDialog(null, "Llena todos los Campos"); } }//GEN-LAST:event_ButtonEliminarUActionPerformed private void labelCancelarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelCancelarUActionPerformed this.setVisible(false); }//GEN-LAST:event_labelCancelarUActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonEliminarU; private javax.swing.JButton labelCancelarU; private javax.swing.JLabel lebelEliminarU; private javax.swing.JTextField txtEliminarU; // End of variables declaration//GEN-END:variables }
9c9f38e93b5196c57db7db1df4cd176091e19d66
[ "Java" ]
11
Java
DavidDutan/practica_04
abde67275b785b0afdd9641b0049e2ffc04a5d72
715831c0cf8f888b1e4e05545eaa102f9bdb9edd
refs/heads/master
<repo_name>lyakyb/BlockBreaker<file_sep>/Assets/Scripts/Paddle.cs using UnityEngine; using System.Collections; public class Paddle : MonoBehaviour { float mousePositionInBlocks; // Use this for initialization void Start () { } // Update is called once per frame void Update () { mousePositionInBlocks = Input.mousePosition.x / Screen.width * 16; var paddlePosition = new Vector3 (0.5f, this.transform.position.y, 0f); paddlePosition.x = Mathf.Clamp (mousePositionInBlocks, 0.5f, 15.5f); this.transform.position = paddlePosition; } }
0c26da79e19151351fc3faccbe103e7df01ba154
[ "C#" ]
1
C#
lyakyb/BlockBreaker
8a4ab39642583b631c28dac955245118bbd4ac6d
c24c76ae84a28cbd4115e4f4e4ceafe62e13370d
refs/heads/master
<file_sep><?php session_start(); include 'header.php'; include 'functions.php'; $email=$password=$name=$lastname=""; if (isset($_SESSION['useremail'])) destorySession(); if (isset($_POST['email'])&&isset($_POST['password'])&&isset($_POST['name'])&&isset($_POST['lastname'])) { $conn=dbConnect(); $email=sanitizeString($conn,$_POST['email']); $password=sanitizeString($conn,$_POST['password']); $name=sanitizeString($conn,$_POST['name']); $lastname=sanitizeString($conn,$_POST['lastname']); if ($email==""||$password=="") { echo "<script>alert(\"** Must input all fields.**\");</script>"; mysqli_close($conn); }else { if (filter_var($email,FILTER_VALIDATE_EMAIL)) { mysqli_autocommit($conn, false); $query="SELECT * FROM user WHERE Email='$email' for update"; $ris=mysqli_query($conn, $query); if (!$ris) { die('Query Failed\n'); } if (mysqli_fetch_array($ris)==NULL) { $shaPassword=md5($password); $time=time(); $sql = "INSERT INTO `dbtorino`.`user`(`Email`,`Password`,`Name`,`Lastname`,`Time`, `THR`) VALUES ('". $email."', '".$shaPassword."','".$name."','".$lastname."', '".$time."', ' ')"; if (!@mysqli_query($conn, $sql)) { mysqli_rollback($conn); die("Query error:".$sql."<br>".mysqli_error($conn)); } mysqli_commit($conn); mysqli_close($conn); $_SESSION['useremail']=$email; $_SESSION['password']=$<PASSWORD>; $_SESSION['lasttime']=$time; header('location:login.php'); exit; }else{ echo "<script>alert(\" Duplicated Register\");</script>"; mysqli_close($conn); } }else{ echo "<script>alert(\" Incorrect email format!\");</script>"; mysqli_close($conn); } } } ?> <!DOCTYPE HTML> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/style.css"/> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/> <title>Torino_Register</title> </head> <body> <div class="wrap"> <div class="header"> <img src="img/wrapper.JPG" width="100%" height="250px" alt="headerphoto" class="no-border"> </div> <div class="navbar"> <a class="active" href="home.php">Home</a> <a id="login "href="login.php">Login</a> <a id="register" href="register.php">SignUp</a> <a id="about" style="float:right" href="about.php">About</a> </div> <div class="main"> <noscript> <p style="color:red">Unfortunately your browser <strong>does not support Javascript</strong> and some functionality are not available!<br> For a better browsing experience we recommend you to remedy. <a href="http://www.enable-javascript.com/" target="_blank">Here </a> are the instructions how to enable JavaScript in your web browser.</p> </noscript> <h1>User Register</h1> <div class="userlogin"> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <p >* Required, email format: <EMAIL></p> <p>Name:</p> <p><input id="a" type="text" name="name" title="Name" placeholder="Name" value=<?php echo $name;?>><span class="error" >* </span></p> <p>Lastname:</p> <p><input id="a" type="text" name="lastname" placeholder="Last Name" title="Last Name" value=<?php echo $lastname;?>><span class="error" >* </span></p> <p>Email:</p> <p><input id="a" type="text" name="email" placeholder="Email Adress" title="example: <EMAIL>" value=<?php echo $email;?>><span class="error">* </span></p> <p>Password:</p> <p><input id="a" type="password" name="password" placeholder="<PASSWORD>" title="password"><span class="error">* </span></p> <p style="text-align: center"><input type="submit" name="commit" value="Register"></p> </form> </div> </div> <div class="footer"> <p>&copy;2018 <strong>Created</strong> All rights deserved. contact: <NAME> <EMAIL></p> </div> </div> </body> </html><file_sep><?php session_start(); include "header.php"; include "functions.php"; if(!isset($_SESSION['useremail'])){ header('location:login.php'); } ?> <!DOCTYPE HTML> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/style.css"/> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/> <title>Torino_Homepage</title> </head> <body> <div class="wrap"> <div class="header"> <img src="img/wrapper.JPG" width="100%" height="250px" alt="headerphoto" class="no-border"> </div> <div class="navbar"> <a class="active" href="home.php">Home</a> <a id="login" href="login.php">Login</a> <a id="register" href="register.php">SignUp</a> <a id="about" style="float:right" href="about.php">About</a> </div> <div class="main"> <noscript> <p style="color:red">Unfortunately your browser <strong>does not support Javascript</strong> and some functionality are not available!<br> For a better browsing experience we recommend you to remedy. <a href="http://www.enable-javascript.com/" target="_blank">Here </a> are the instructions how to enable JavaScript in your web browser.</p> </noscript> </div> <div class="footer"> <p>&copy;2018 <strong>Created</strong> All rights deserved. contact: YAXUE DU <EMAIL></p> </div> </div> </body> </html><file_sep># text php program---trying hard folder img:The needed images folder css:The css style about.php functions.php header.php home.php login.php logout.php main.php register.php <description: In this project,I learned how to write php code to do the user register and user login> <file_sep><?php //sanitize input string function sanitizeString($conn,$var) { $var = trim($var); $var = htmlentities($var); $var = stripcslashes($var); $var = mysqli_real_escape_string($conn,$var); return $var; } $servername = 'localhost'; $username = 'root'; $password = ''; $database = 'dbtorino'; // connect to the DB // return connection handle function dbConnect() { //a variable declared within a function with the global qualifier has the global scope global $servername; global $username; global $password; global $database; $conn = @mysqli_connect( $servername, $username, $password, $database); if(mysqli_connect_error()) die("Database connection failed:" .mysqli_connect_errno()."-----".mysqli_connect_error()); if(!@mysqli_select_db($conn,$database)) die("Database selection error: ".mysqli_error($conn)); return $conn; } //store the user register function storeRegister($email,$password,$name,$lastname) { $conn = dbConnect(); $sql = "INSERT INTO `dbtorino`.`user`(`Email`,`Password`,`Name`,`Lastname`,'Time','THR') VALUES ('".$email."', '".$shaPassword ."','".$name."','".$lastname."','".$time."','.$thr.')"; if (!@mysqli_query($conn, $sql)) { die("Query error: ". $sql. "<br>". mysqli_error($conn)); } mysqli_close($conn); } //normal mysqli_query function normalQuery($conn, $query) { $result = mysqli_query($conn, $query); if (!$result){ mysqli_close($conn); die('Normal SQL fail.'); } return $result; } // check given username and password // return true if user exists with given username and password function validUser($user, $password) { $conn = dbConnect(); $sql = "SELECT Password FROM user WHERE Email ='". $user . "'"; $resp = @mysqli_query($conn,$sql); if(!$resp) die("Error in query: ".$sql."<br>".mysqli_error($conn)); if (mysqli_num_rows($resp) == 0){ return FALSE; } $row = mysqli_fetch_array($resp); $res = ($password == $row[0]); mysqli_close($conn); return ($res); //return true; } ?><file_sep><?php session_start(); include 'header.php'; include 'functions.php'; $useremail=$password=''; if($_SERVER["REQUEST_METHOD"] == "POST"){ if(isset($_POST['useremail'])&&isset($_POST['password'])) { $connect = dbConnect(); $useremail = sanitizeString($connect,$_POST['useremail']); $password = sanitizeString($connect,$_POST['password']); if (empty($useremail||empty($password))){ echo "<script>alert(\" **Must input all fields.**\");</script>"; mysqli_close($connect); }else{ $sql = "SELECT * FROM user WHERE Email ='$useremail'"; $result = normalQuery($connect, $sql); $arr = mysqli_fetch_array($result); $row = mysqli_num_rows($result); if($row==0){ echo "<script>alert(\"Username does not exist!\");</script>"; mysqli_close($connect); }elseif(strcmp($arr['Password'], md5($password))!=0){ echo "<script>alert(\"Password is error!\");</script>"; mysqli_close($connect); } else { $_SESSION['useremail'] = $useremail; $_SESSION['password'] = $<PASSWORD>; $_SESSION['lasttime'] = time(); //echo "<script>alert(\"You have logged in!\");</script>"; header('location:main.php'); exit; } } } } session_unset(); ?> <!DOCTYPE HTML> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/style.css"/> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/> <title>Torino_Login</title> </head> <body> <div class="wrap"> <div class="header"> <img src="img/wrapper.JPG" width="100%" height="250px" alt="headerphoto" class="no-border"> </div> <div class="navbar"> <a class="active" href="home.php">Home</a> <a id="login "href="login.php">Login</a> <a id="register" href="register.php">SignUp</a> <a id="about" style="float:right" href="about.php">About</a> </div> <div class="main"> <noscript> <p style="color:red">Unfortunately your browser <strong>does not support Javascript</strong> and some functionality are not available!<br> For a better browsing experience we recommend you to remedy. <a href="http://www.enable-javascript.com/" target="_blank">Here </a> are the instructions how to enable JavaScript in your web browser.</p> </noscript> <h1>User Login</h1> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <div class="userlogin"> <p>User Name</p> <p><input type="text" id="a" name="useremail" placeholder="Email Address" value=<?php echo $useremail;?>><span class="error" >* </span></p> <p>Password</p> <p><input type="<PASSWORD>" id="a" name="password" placeholder="<PASSWORD>"><span class="error" >*</span></p> <p style="text-align: center"><input type="submit" name="commit" value="Login"/></p> </div> </form> </div> <div class="footer"> <p>&copy;2018 <strong>Created</strong> All rights deserved. contact: <NAME> <EMAIL></p> </div> </div> </body> </html><file_sep><?php /*if(empty($_SERVER['HTTPS'])||$_SERVER['HTTPS']!='on'){ header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],TRUE,301); die(); } */ if(isset($_SESSION['lasttime'])){ if(time()-$_SESSION['lasttime']>120){ unset($_SESSION['lasttime']); session_destroy(); header('Location: logout.php?msg=SessionTimeOut'); exit; } else { $_SESSION['lasttime']=time(); /* update time */ } } ?> <file_sep><?php session_start(); include 'header.php'; include 'functions.php'; ?> <!DOCTYPE HTML> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/style.css"/> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/> <title>Torino_Homepage</title> </head> <body> <div class="wrap"> <div class="header"> <img src="img/wrapper.JPG" width="100%" height="250px" alt="headerphoto" class="no-border"> </div> <div class="navbar"> <a class="active" href="home.php">Home</a> <a id="login" href="login.php">Login</a> <a id="register" href="register.php">SignUp</a> <a id="about" style="float:right" href="about.php">About</a> </div> <div class="main"> <noscript> <p style="color:red">Unfortunately your browser <strong>does not support Javascript</strong> and some functionality are not available!<br> For a better browsing experience we recommend you to remedy. <a href="http://www.enable-javascript.com/" target="_blank">Here </a> are the instructions how to enable JavaScript in your web browser.</p> </noscript> <div style="float: left;clear:both"> <img id=1_0 width="997" height="600" src="img/p1.jpg" alt="Iphone 7" style='float:left'> <br><br><br><br><br><br><br><br><br> <ul style='float: left' class="menu"> <li id=1_1 class="current"><a>pic1</a></li> <li id=2_2><a>pic2</a></li> <li id=3_3><a>pic3</a></li> <li id=4_4><a>pic4</a></li> <li id=5_5><a>pic5</a></li> <li id=6_6><a>pic6</a></li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#1_1").mouseover(function(){ $("#1_0").attr("src", "img/p1.jpg"); }); $("#2_2").mouseover(function(){ $("#1_0").attr("src", "img/p2.jpg"); }); $("#3_3").mouseover(function(){ $("#1_0").attr("src", "img/p3.jpg"); }); $("#4_4").mouseover(function(){ $("#1_0").attr("src", "img/p4.jpg"); }); $("#5_5").mouseover(function(){ $("#1_0").attr("src", "img/p5.jpg"); }); $("#6_6").mouseover(function(){ $("#1_0").attr("src", "img/p6.jpg"); }); }); </script> <!-- <ul class="slide-pic"> <li class="current"><img width="997" height="600" src="img/p1.jpg" /></li> <li><img width="997" height="600" src="img/p2.jpg" /></li> <li><img width="997" height="600" src="img/p3.jpg" /></li> <li><img width="997" height="600" src="img/p4.jpg" /></li> <li><img width="997" height="600" src="img/p5.jpg" /></li> </ul> <ul class="slide-li op"> <li class="current"></li> <li></li> <li></li> <li></li> <li></li> </ul> <ul class="slide-li"> <li class="current"><a>pic1</a></li> <li><a>pic2</a></li> <li><a>pic3</a></li> <li><a>pic4</a></li> <li><a>pic5</a></li> </ul> --> </div> <div class="footer"> <p>&copy;2018 <strong>Created</strong> All rights deserved. contact: <NAME> <EMAIL></p> </div> </div> </body> </html>
5984d174db2d3beaf0f693188a70d352c105dc79
[ "Markdown", "PHP" ]
7
PHP
elissa231696/text
17a01c1cc998d2ae62ce6c479854b71469701e1e
56e74651dbb5d3f25095e894fa62780eb029b7a9
refs/heads/master
<file_sep>// Set Date var countDownDate = new Date("oct 1, 2021 21:00:00").getTime(); // CountDown Action var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); var output = "", minutesResult, hoursResult, daysResult; if (days >= 0) { daysResult = days; } if (hours >= 0) { hoursResult = hours; } if (minutes >= 0) { minutesResult = minutes; } document.getElementsByClassName("days")[0].innerHTML = daysResult; document.getElementsByClassName("hours")[0].innerHTML = hoursResult; document.getElementsByClassName("minutes")[0].innerHTML = minutesResult; document.getElementsByClassName("seconds")[0].innerHTML = seconds; if (distance < 0) { clearInterval(x); document.getElementsByClassName('finalText')[0].innerHTML = "It's time to Buy"; } }, 100);
05a2ece4e85262dd499c19292caf26fc01d8c260
[ "JavaScript" ]
1
JavaScript
KrakenMetaverse/Kraken-Metaverse
bdbfe4b09927fd9719b7bf377fdfcbae7ffa0164
07a159c6165c77906ce5191e8fdcb40137898394
refs/heads/master
<file_sep>package com.rachman_warehouse.ui.produk; import android.os.Parcel; import android.os.Parcelable; public class DataProduk implements Parcelable { String idbarang,idsuplier,namasuplier,idlogin,namaadmin,barang,stok,hargabeli,hargajual; public DataProduk(String idbarang, String idsuplier,String namasuplier, String idjenis ,String jenisproduk, String idlogin, String namaadmin, String baranag, String stok, String hargabeli, String hargajual){ this.idbarang = idbarang; this.idsuplier = idsuplier; this.namasuplier = namasuplier; this.idlogin = idlogin; this.namaadmin =namaadmin; this.barang = baranag; this.stok = stok; this.hargabeli = hargabeli; this.hargajual = hargajual; } public DataProduk(){ } protected DataProduk(Parcel in) { idbarang = in.readString(); idsuplier = in.readString(); namasuplier = in.readString(); idlogin = in.readString(); namaadmin = in.readString(); barang = in.readString(); stok = in.readString(); hargabeli = in.readString(); hargajual = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(idbarang); dest.writeString(idsuplier); dest.writeString(namasuplier); dest.writeString(idlogin); dest.writeString(namaadmin); dest.writeString(barang); dest.writeString(stok); dest.writeString(hargabeli); dest.writeString(hargajual); } @Override public int describeContents() { return 0; } public static final Creator<DataProduk> CREATOR = new Creator<DataProduk>() { @Override public DataProduk createFromParcel(Parcel in) { return new DataProduk(in); } @Override public DataProduk[] newArray(int size) { return new DataProduk[size]; } }; public String getIdbarang() { return idbarang; } public String getIdsuplier() { return idsuplier; } public String getNamasuplier() { return namasuplier; } public String getIdlogin() { return idlogin; } public String getNamaadmin() { return namaadmin; } public String getBarang() { return barang; } public String getStok() { return stok; } public String getHargabeli() { return hargabeli; } public String getHargajual() { return hargajual; } public void setIdbaranag(String idbarang) { this.idbarang = idbarang; } public void setIdsuplier(String idsuplier) { this.idsuplier = idsuplier; } public void setNamasuplier(String namasuplier) { this.namasuplier = namasuplier; } public void setIdlogin(String idlogin) { this.idlogin = idlogin; } public void setNamaadmin(String namaadmin) { this.namaadmin = namaadmin; } public void setBarang(String barang) { this.barang = barang; } public void setStok(String stok) { this.stok = stok; } public void setHargabeli(String hargabeli) { this.hargabeli = hargabeli; } public void setHargajual(String hargajual) { this.hargajual = hargajual; } } <file_sep>package com.rachman_warehouse.connect; public class Server { // public static final String URL = "http://192.168.43.150/rachman_warehouse/"; public static final String URL = "http://192.168.1.10/rachman_warehouse/"; } <file_sep>package com.rachman_warehouse.ui.transaksi; import android.os.Parcel; import android.os.Parcelable; public class DataPemesanan implements Parcelable { String idpenjualan, idadmin, pembeli, tgljual; public DataPemesanan(String idpenjualan, String idadmin, String pembeli, String tgljual){ this.idpenjualan = idpenjualan; this.idadmin = idadmin; this.pembeli = pembeli; this.tgljual = tgljual; } public DataPemesanan(){ } protected DataPemesanan(Parcel in) { idpenjualan = in.readString(); idadmin = in.readString(); pembeli = in.readString(); tgljual = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(idpenjualan); dest.writeString(idadmin); dest.writeString(pembeli); dest.writeString(tgljual); } @Override public int describeContents() { return 0; } public static final Creator<DataPemesanan> CREATOR = new Creator<DataPemesanan>() { @Override public DataPemesanan createFromParcel(Parcel in) { return new DataPemesanan(in); } @Override public DataPemesanan[] newArray(int size) { return new DataPemesanan[size]; } }; public String getIdpenjualan() { return idpenjualan; } public String getIdadmin() { return idadmin; } public String getPembeli() { return pembeli; } public String getTgljual() { return tgljual; } public void setIdpenjualan(String idpenjualan) { this.idpenjualan = idpenjualan; } public void setIdadmin(String idadmin) { this.idadmin = idadmin; } public void setPembeli(String pembeli) { this.pembeli = pembeli; } public void setTgljual(String tgljual) { this.tgljual = tgljual; } } <file_sep>package com.rachman_warehouse.ui.transaksi; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.rachman_warehouse.R; import java.util.List; public class AdapterPemesanan extends ArrayAdapter<DataPemesanan> { private List<DataPemesanan> dataPemesananList; private Context context; public AdapterPemesanan(List<DataPemesanan> dataPemesananList, Context context){ super(context, R.layout.pemesanan_fragment,dataPemesananList); this.dataPemesananList = dataPemesananList; this.context = context; } public int getCount(){ return dataPemesananList.size(); } @Override public DataPemesanan getItem(int location){ return dataPemesananList.get(location); } @Override public long getItemId(int position){ return position; } @Override public View getView(final int position, View convertView, ViewGroup parent){ LayoutInflater inflater = LayoutInflater.from(context); View listViewItem = inflater.inflate(R.layout.pemesanan_list,null,false); TextView ViewPembeli = listViewItem.findViewById(R.id.txt_pembeli); TextView ViewTGL = listViewItem.findViewById(R.id.txt_tgl); final DataPemesanan dataPemesanan = dataPemesananList.get(position); ViewPembeli.setText(dataPemesanan.getPembeli()); ViewTGL.setText("Tgl : "+dataPemesanan.getTgljual()); return listViewItem; } } <file_sep>package com.rachman_warehouse.ui.suplier; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.rachman_warehouse.Login; import com.rachman_warehouse.R; import com.rachman_warehouse.connect.AppController; import com.rachman_warehouse.connect.Server; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class SuplierFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { public static SuplierFragment newInstance() { return new SuplierFragment(); } private static final String TAG = Login.class.getSimpleName(); public static final String url = Server.URL + "data_suplier/data_suplier.php"; public static final String url_insert = Server.URL + "data_suplier/tambah_suplier.php"; public static final String url_update = Server.URL + "data_suplier/edit_suplier.php"; public static final String url_delete = Server.URL + "data_suplier/del_suplier.php"; public static final String url_by_id = Server.URL + "data_suplier/by_id_suplier.php"; public final static String TAG_ID = "id"; public static final String TAG_USERNAME = "username"; private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; public static final String session_status = "session_status"; String tag_json_obj = "json_obj_req"; List<DataSuplier> dataSuplierList = new ArrayList<>(); SharedPreferences sharedpreferences; ConnectivityManager conMgr; ProgressDialog pDialog; String id,username; Boolean session = false; SwipeRefreshLayout swipe; FloatingActionButton fab; AdapterSuplier adapter; AlertDialog.Builder dialog; LayoutInflater inflater; int success; View dialogView; String id_suplier,suplier,saless,kontakk,jeniss; EditText edit_idsuplier,edit_perusahaan,edit_sales,edit_kontak,edit_jenis; TextView txt_idsuplier,txt_perusahaan,txt_sales,txt_kontak,txt_jenis; ListView listView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.suplier_fragment, container, false); conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); { if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) { } else { Toast.makeText(getContext(), "No Internet Connection", Toast.LENGTH_LONG).show(); } } fab = (FloatingActionButton) root.findViewById(R.id.fabSuplier); swipe = (SwipeRefreshLayout) root.findViewById(R.id.swipeRefreshAll); listView = (ListView) root.findViewById(R.id.listViewAll); Collections.sort(dataSuplierList, new SuplierComparator()); adapter = new AdapterSuplier(dataSuplierList,getContext()); listView.setAdapter(adapter); swipe.setOnRefreshListener(this); swipe.post(new Runnable() { @Override public void run() { swipe.setRefreshing(true); dataSuplierList.clear(); adapter.notifyDataSetChanged(); loadDataSuplier(); } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DialogSuplier("","","","","","SIMPAN"); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view,final int position, long id) { final String idsuplier = dataSuplierList.get(position).getIdsuplier(); final CharSequence[] dialogitem = {"Detail","Delete"}; dialog = new AlertDialog.Builder(getContext()); dialog.setCancelable(true); dialog.setItems(dialogitem, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i){ case 0: detailSuplier(idsuplier); break; case 1: deleteSuplier(idsuplier); break; } } }).show(); return false; } }); return root; } @Override public void onRefresh() { dataSuplierList.clear(); adapter.notifyDataSetChanged(); loadDataSuplier(); } private void kosong(){ edit_idsuplier.setText(null); edit_perusahaan.setText(null); edit_sales.setText(null); edit_kontak.setText(null); edit_jenis.setText(null); } private void kosong2(){ txt_idsuplier.setText(null); txt_perusahaan.setText(null); txt_sales.setText(null); txt_kontak.setText(null); txt_jenis.setText(null); } private void DialogSuplier(final String idSuplier, String namaPerusahaan, String sls, String knt, String keterangan, String button){ dialog = new AlertDialog.Builder(getContext()); inflater = getLayoutInflater(); dialogView = inflater.inflate(R.layout.suplier_edit,null); dialog.setView(dialogView); dialog.setCancelable(true); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("Form Suplier"); edit_idsuplier = (EditText) dialogView.findViewById(R.id.edit_Id_Suplier); edit_perusahaan = (EditText) dialogView.findViewById(R.id.suplier1); edit_sales = (EditText) dialogView.findViewById(R.id.suplierSales); edit_kontak = (EditText) dialogView.findViewById(R.id.suplierKontak); edit_jenis = (EditText) dialogView.findViewById(R.id.suplierjenis); if(!idSuplier.isEmpty()){ edit_idsuplier.setText(idSuplier); edit_perusahaan.setText(namaPerusahaan); edit_sales.setText(sls); edit_kontak.setText(knt); edit_jenis.setText(keterangan); }else { kosong(); } dialog.setPositiveButton(button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { id_suplier = edit_idsuplier.getText().toString(); suplier = edit_perusahaan.getText().toString(); saless = edit_sales.getText().toString(); kontakk = edit_kontak.getText().toString(); jeniss = edit_jenis.getText().toString(); simpan_update(); detailSuplier(idSuplier); dialog.dismiss(); } }); dialog.setNegativeButton("BATAL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { detailSuplier(idSuplier); dialog.dismiss(); kosong(); } }); dialog.show(); } private void DetailDialogSuplier(String idSuplier, String namaPerusahaan, String sls,String knt,String keterangan,String button){ dialog = new AlertDialog.Builder(getContext()); inflater = getLayoutInflater(); dialogView = inflater.inflate(R.layout.suplier_detail,null); dialog.setView(dialogView); dialog.setCancelable(true); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("Detail Suplier"); txt_idsuplier = (TextView) dialogView.findViewById(R.id.txtId_Suplier); txt_perusahaan = (TextView) dialogView.findViewById(R.id.txtsuplier1); txt_sales = (TextView) dialogView.findViewById(R.id.txtsuplierSales); txt_kontak = (TextView) dialogView.findViewById(R.id.txtsuplierKontak); txt_jenis = (TextView) dialogView.findViewById(R.id.txtsuplierjenis); if(!idSuplier.isEmpty()){ txt_idsuplier.setText(idSuplier); txt_perusahaan.setText("Perusahaan : "+namaPerusahaan); txt_sales.setText("Sales : "+sls); txt_kontak.setText("Kontak : "+knt); txt_jenis.setText("Jenis Produk :"+keterangan); }else { kosong2(); } dialog.setPositiveButton(button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { id_suplier = txt_idsuplier.getText().toString(); editSuplier(id_suplier); dialog.dismiss(); } }); dialog.setNegativeButton("BATAL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); kosong2(); } }); dialog.show(); } private void loadDataSuplier(){ dataSuplierList.clear(); adapter.notifyDataSetChanged(); swipe.setRefreshing(true); pDialog = new ProgressDialog(getContext()); pDialog.setCancelable(false); pDialog.setMessage("Loading..."); showDialog(); RequestQueue requestQueue = Volley.newRequestQueue(getContext()); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); JSONArray JKArray = obj.getJSONArray("result"); for (int i = 0; i < JKArray.length(); i++) { JSONObject JKObject = JKArray.getJSONObject(i); // DataSuplier dataSuplier = new DataSuplier(); dataSuplier.setIdsuplier(JKObject.getString("idsuplier")); dataSuplier.setPerusahaan(JKObject.getString("perusahaan")); dataSuplier.setSales(JKObject.getString("sales")); dataSuplier.setNo(JKObject.getString("kontak")); dataSuplier.setJenisP(JKObject.getString("jenis")); dataSuplierList.add(dataSuplier); } Collections.sort(dataSuplierList, new SuplierComparator()); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); swipe.setRefreshing(false); } catch (JSONException e) { e.printStackTrace(); } hideDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.e(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); } }); requestQueue.add(stringRequest); } private void simpan_update(){ String url; if(id_suplier.isEmpty()){ url = url_insert; }else { url = url_update; } StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Response: " + response.toString()); try { JSONObject jObj = new JSONObject(response); success = jObj.getInt(TAG_SUCCESS); // Cek error node pada json if (success == 1) { Log.d("Add/update", jObj.toString()); loadDataSuplier(); kosong(); Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); adapter.notifyDataSetChanged(); } else { Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters ke post url Map<String, String> params = new HashMap<String, String>(); // jika id kosong maka simpan, jika id ada nilainya maka update if (id_suplier.isEmpty()){ params.put("perusahaan", suplier); params.put("sales", saless); params.put("kontak", kontakk); params.put("jenis", jeniss); } else { params.put("id", id_suplier); params.put("perusahaan", suplier); params.put("sales", saless); params.put("kontak", kontakk); params.put("jenis", jeniss); } return params; } }; AppController.getInstance().addToRequestQueue(strReq, tag_json_obj); } private void detailSuplier(final String idsuplier){ StringRequest strReq = new StringRequest(Request.Method.POST, url_by_id, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Response: " + response.toString()); try { JSONObject jObj = new JSONObject(response); success = jObj.getInt(TAG_SUCCESS); // Cek error node pada json if (success == 1) { Log.d("get edit data", jObj.toString()); String idSuplier = jObj.getString("idsuplier"); String namaPerusahaan = jObj.getString("perusahaan"); String ssales = jObj.getString("sales"); String kkontak = jObj.getString("kontak"); String ket = jObj.getString("jenis"); DetailDialogSuplier(idSuplier,namaPerusahaan,ssales,kkontak,ket, "EDIT"); adapter.notifyDataSetChanged(); } else { Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters ke post url Map<String, String> params = new HashMap<String, String>(); params.put("id", idsuplier); return params; } }; AppController.getInstance().addToRequestQueue(strReq, tag_json_obj); } private void editSuplier(final String idsuplier){ StringRequest strReq = new StringRequest(Request.Method.POST, url_by_id, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Response: " + response.toString()); try { JSONObject jObj = new JSONObject(response); success = jObj.getInt(TAG_SUCCESS); // Cek error node pada json if (success == 1) { Log.d("get edit data", jObj.toString()); String idSuplier = jObj.getString("idsuplier"); String namaPerusahaan = jObj.getString("perusahaan"); String ssales = jObj.getString("sales"); String kkontak = jObj.getString("kontak"); String ket = jObj.getString("jenis"); DialogSuplier(idSuplier,namaPerusahaan,ssales,kkontak,ket, "UPDATE"); adapter.notifyDataSetChanged(); } else { Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters ke post url Map<String, String> params = new HashMap<String, String>(); params.put("id", idsuplier); return params; } }; AppController.getInstance().addToRequestQueue(strReq, tag_json_obj); } private void deleteSuplier(final String idsuplier){ StringRequest strReq = new StringRequest(Request.Method.POST, url_delete, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Response: " + response.toString()); try { JSONObject jObj = new JSONObject(response); success = jObj.getInt(TAG_SUCCESS); // Cek error node pada json if (success == 1) { Log.d("delete", jObj.toString()); loadDataSuplier(); Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); adapter.notifyDataSetChanged(); } else { Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters ke post url Map<String, String> params = new HashMap<String, String>(); params.put("id", idsuplier); return params; } }; AppController.getInstance().addToRequestQueue(strReq, tag_json_obj); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }<file_sep>package com.rachman_warehouse.ui.suplier; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.rachman_warehouse.R; import java.util.List; public class AdapterSuplier extends ArrayAdapter<DataSuplier> { private List<DataSuplier> dataSuplierList; private Context context; public AdapterSuplier(List<DataSuplier> dataSuplierList, Context context){ super(context, R.layout.suplier_fragment,dataSuplierList); this.dataSuplierList = dataSuplierList; this.context = context; } @Override public int getCount(){ return dataSuplierList.size(); } @Override public DataSuplier getItem(int location){ return dataSuplierList.get(location); } @Override public long getItemId(int position){ return position; } @Override public View getView(final int position, View convertView, ViewGroup parent){ LayoutInflater inflater = LayoutInflater.from(context); View listViewItem = inflater.inflate(R.layout.suplier_list,null,false); TextView ViewSuplier = listViewItem.findViewById(R.id.txtSuplier); TextView ViewSales = listViewItem.findViewById(R.id.txtSales); TextView ViewKontak = listViewItem.findViewById(R.id.txtKontak); final DataSuplier dataSuplier = dataSuplierList.get(position); ViewSuplier.setText("Perusahaan : "+dataSuplier.getPerusahaan()); ViewSales.setText("Sales : "+dataSuplier.getSales()); ViewKontak.setText("Kontak : "+dataSuplier.getNo()); return listViewItem; } } <file_sep>package com.rachman_warehouse.ui.suplier; import android.os.Parcel; import android.os.Parcelable; public class DataSuplier implements Parcelable { String idsuplier,perusahaan,sales,no,jenisP; public DataSuplier(String idsuplier,String perusahaan,String sales,String no,String jenisP){ this.idsuplier = idsuplier; this.perusahaan = perusahaan; this.sales = sales; this.no = no; this.jenisP = jenisP; } protected DataSuplier(Parcel in) { idsuplier = in.readString(); perusahaan = in.readString(); sales = in.readString(); no = in.readString(); jenisP = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(idsuplier); dest.writeString(perusahaan); dest.writeString(sales); dest.writeString(no); dest.writeString(jenisP); } @Override public int describeContents() { return 0; } public static final Creator<DataSuplier> CREATOR = new Creator<DataSuplier>() { @Override public DataSuplier createFromParcel(Parcel in) { return new DataSuplier(in); } @Override public DataSuplier[] newArray(int size) { return new DataSuplier[size]; } }; public DataSuplier(){ } public String getIdsuplier() { return idsuplier; } public String getPerusahaan() { return perusahaan; } public String getSales() { return sales; } public String getNo() { return no; } public String getJenisP() { return jenisP; } public void setIdsuplier(String idsuplier) { this.idsuplier = idsuplier; } public void setPerusahaan(String perusahaan) { this.perusahaan = perusahaan; } public void setSales(String sales) { this.sales = sales; } public void setNo(String no) { this.no = no; } public void setJenisP(String jenisP) { this.jenisP = jenisP; } } <file_sep>package com.rachman_warehouse.ui.suplier; import java.util.Comparator; public class SuplierComparator implements Comparator<DataSuplier> { @Override public int compare(DataSuplier ds1, DataSuplier ds2) { return ds1.getPerusahaan().compareTo(ds2.getPerusahaan()); } } <file_sep>include ':app' rootProject.name = "RachmanWarehouse"<file_sep>package com.rachman_warehouse.ui.laporan; import android.os.Parcel; import android.os.Parcelable; public class DataLaporan implements Parcelable { String idlaporan,idlogin,lapor,totl,jenislap; public DataLaporan(String idlaporan,String idlogin,String lapor,String totl,String jenislap){ this.idlaporan = idlaporan; this.idlogin = idlogin; this.lapor = lapor; this.totl = totl; this.jenislap = jenislap; } public DataLaporan(){ } protected DataLaporan(Parcel in) { idlaporan = in.readString(); idlogin = in.readString(); lapor = in.readString(); totl = in.readString(); jenislap = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(idlaporan); dest.writeString(idlogin); dest.writeString(lapor); dest.writeString(totl); dest.writeString(jenislap); } @Override public int describeContents() { return 0; } public static final Creator<DataLaporan> CREATOR = new Creator<DataLaporan>() { @Override public DataLaporan createFromParcel(Parcel in) { return new DataLaporan(in); } @Override public DataLaporan[] newArray(int size) { return new DataLaporan[size]; } }; public String getIdlaporan() { return idlaporan; } public String getIdlogin() { return idlogin; } public String getLapor() { return lapor; } public String getTotl() { return totl; } public String getJenislap() { return jenislap; } public void setIdlaporan(String idlaporan) { this.idlaporan = idlaporan; } public void setIdlogin(String idlogin) { this.idlogin = idlogin; } public void setLapor(String lapor) { this.lapor = lapor; } public void setTotl(String totl) { this.totl = totl; } public void setJenislap(String jenislap) { this.jenislap = jenislap; } } <file_sep>package com.rachman_warehouse.ui.produk; import com.rachman_warehouse.ui.produk.DataProduk; import java.util.Comparator; //Comparator untuk list produk public class ProdukComparator implements Comparator<DataProduk> { @Override public int compare(DataProduk dp1, DataProduk dp2) { return dp1.getBarang().compareTo(dp2.getBarang()); } }
841a74f4d7c4c804b489e8240c634765ef90daff
[ "Java", "Gradle" ]
11
Java
TAX015/RachmanWarehouse
2d2c17259aac207170194821aecf1ca197290b9f
88a1375f4a8bdeb58b7a2da543824a872d16c164
refs/heads/master
<repo_name>nganba/Statistical_Data_Preprocessing<file_sep>/main.py import numpy as np import pandas as pd def is_type(df, baseType): test = [issubclass(np.dtype(d).type, baseType) for d in df.dtypes] return pd.DataFrame(data=test, index=df.columns, columns=["test"]) def is_float(df): return is_type(df, np.float) def is_number(df): return is_type(df, np.number) def is_integer(df): return is_type(df, np.integer) def calc_entropy(df, var, wgt=None): tmpdf = df.copy()
8f04e8f0296b5b598f0802c92fa7a0637d04b4d7
[ "Python" ]
1
Python
nganba/Statistical_Data_Preprocessing
44d31f8dd94f722e293ac33067d1a2c1eec9d6f9
9f459102a1ae66c7dbd25a3eb10f92175b832bbe
refs/heads/master
<file_sep>package edu.illinois.cs.cs125.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Zodiac10 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_zodiac10); } }
6af9e1793717ea41cd8da9577295ab676bd846fb
[ "Java" ]
1
Java
NierYoRHa/ZodiacTrivia
145e6db8c21f16b5c3c3aa7c6e30b7afb65c6fc6
ea3a0d7f3d88a1e0c51ddd23d8916c617191e15f
refs/heads/master
<file_sep>GEDI - Game Engine DIstribuído ============================== __Gedi__ é um motor de jogos que usa técnicas de computação distribuída para conversar o núcleo com os módulos. Módulos podem usar computação distribuída dentro de si também, mas não é necessário. Mais infos ---------- Leia os documentos de ideias e afins da pasta [ideias](ideias/index.md) <file_sep>#include "Module.hpp" #include "GameObject.hpp" #include "Exception.hpp" #include <unordered_map> #include <utility> #include <cstdint> #include <SFML/Graphics.hpp> using namespace std; using namespace zmq; struct Ispraite { sf::Drawable *drawable; sf::Shader *shader {nullptr}; Ispraite (sf::Drawable *d) : drawable (d) {} ~Ispraite () { delete drawable; } void draw (sf::RenderTarget & target) { target.draw (*drawable, shader ? shader : sf::RenderStates::Default); } }; using ObjMap = unordered_map<ID, Ispraite *>; using TextureMap = unordered_map<string, sf::Texture>; using ShaderMap = unordered_map<string, sf::Shader *>; extern "C" void abre (context_t * ctx, const char * endereco); int main () { context_t ctx; abre (&ctx, "ipc://teste"); return 0; } extern "C" void abre (context_t * ctx, const char * endereco) { // módulo do gráfico Module M (*ctx, endereco); ObjMap objetos; TextureMap texturas; ShaderMap shaders; sf::RenderWindow window; //-- Sai da janela --// M.on ("quit", [&] (Arguments & args) { window.close (); M.close (); }); M.on ("open", [&] (Arguments & args) { M.sync (); }); //-- Criação/instanciação --// M.on ("window", [&] (Arguments & args) { int width = args.as<int> (0); int height = args.as<int> (1); string title = args.asDefault<string> (2, "Teste"); window.create (sf::VideoMode (width, height), title); window.display (); }); M.on ("texture", [&] (Arguments & args) { auto nome = args.as<string> (0); auto arquivo = args.as<string> (1); sf::Texture tex; if (!tex.loadFromFile (arquivo)){ throw runtime_error ("[grafico::texture] Erro ao carregar textura \"" + arquivo + "\""); } texturas.insert (make_pair (move (nome), move (tex))); }); //-- Criação de objetos, com ID --// M.on ("sprite", [&] (Arguments & args) { auto id = args.as<ID> (0); auto nomeTextura = args.as<string> (1); const auto & tex = texturas.at (nomeTextura); auto sprite = new sf::Sprite (tex); objetos.emplace (id, new Ispraite (sprite)); }); //-- Transformables --// M.on ("setOrigin", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { int x = args.as<int> (1); int y = args.as<int> (2); obj->setOrigin (x, y); } }); M.on ("setPosition", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double x = args.as<double> (1); double y = args.as<double> (2); obj->setPosition (x, y); } }); M.on ("setRotation", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double angulo = args.as<double> (1); obj->setRotation (angulo); } }); M.on ("setScale", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double sx = args.as<double> (1); double sy = args.as<double> (2); obj->setScale (sx, sy); } }); M.on ("move", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double x = args.as<double> (1); double y = args.as<double> (2); obj->move (x, y); } }); M.on ("rotate", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double angulo = args.as<double> (1); obj->rotate (angulo); } }); M.on ("scale", [&] (Arguments & args) { auto id = args.as<ID> (0); if (auto * obj = dynamic_cast<sf::Transformable *> (objetos.at (id)->drawable)) { double sx = args.as<double> (1); double sy = args.as<double> (2); obj->scale (sx, sy); } }); //-- Shaders --// M.on ("shader", [&] (Arguments & args) { auto nome = args.as<string> (0); auto arquivo1 = args.as<string> (1); auto arquivo2 = args.as<string> (2); auto *shader = new sf::Shader; if (arquivo2 == "vertex") { shader->loadFromFile (arquivo1, sf::Shader::Type::Vertex); } else if (arquivo2 == "fragment") { shader->loadFromFile (arquivo1, sf::Shader::Type::Fragment); } else if (arquivo2 == "geometry") { shader->loadFromFile (arquivo1, sf::Shader::Type::Geometry); } else if (args.size () > 3) { shader->loadFromFile (arquivo1, arquivo2, args.as<string> (3)); } else { shader->loadFromFile (arquivo1, arquivo2); } shaders.emplace (move (nome), shader); }); M.on ("attach", [&] (Arguments & args) { auto id = args.as<ID> (0); auto shader = args.as<string> (1); objetos.at (id)->shader = shaders.at (shader); }); M.on ("unattach", [&] (Arguments & args) { auto id = args.as<ID> (0); objetos.at (id)->shader = nullptr; }); //-- Controle --// M.on ("draw", [&] (Arguments & args) { window.clear (); for (auto & it : objetos) { it.second->draw (window); } window.display (); }); bool didClose = false; // bool que conta se fechou janela, pega no 'input' e checa no 'didClose' M.on ("input", [&] (Arguments & args) { static sf::Event ev; while (window.pollEvent (ev)) { switch (ev.type) { case sf::Event::Closed: didClose = true; break; default: break; } } }); M.on ("didClose", [&] (Arguments & args) { M.respond (didClose); }); while (M.isOpen ()) { M.handle (); } // limpa os rolê for (auto & it : objetos) { delete it.second; } for (auto & it : shaders) { delete it.second; } } <file_sep>#!/usr/bin/env lua soma = 0 n = 0 for l in io.lines () do local inc = tonumber (l) if inc then soma = soma + inc n = n + 1 else print (l) end end print ('FPS médio:', n / soma) <file_sep>/// Teste de um ModuleManager, que conecta com os módulos e talz #pragma once #include "ModuleConnection.hpp" #include "ModuleHandle.hpp" #include <iostream> #include <utility> #include <cstring> #include <unordered_map> #include <zmq.hpp> #include <yaml-cpp/yaml.h> using namespace zmq; using namespace std; class ModuleManager { public: /// Ctor ModuleManager () {} /// Dtor ~ModuleManager () { ModuleHandle h; for (auto & it : modulos) { h.set (it.second); cout << "Mandando quit pro \"" << it.first << '"' << endl; h ("quit").resp (); delete it.second; } } void readConfig (const string & fname) { auto config = YAML::LoadFile (fname); for (auto mod : config) { auto nome = mod.first.as<string> (); cout << "Achei módulo: " << nome << endl; auto opts = mod.second; auto endereco = opts["endereco"].as<string> (); // Tenta ler arquivo de config específico do módulo, que é melhor né try { ostringstream os; if (const char *prefix = getenv ("GEDI_MODULE_PATH")) { os << prefix << '/'; } os << nome << '/' << nome << ".yml"; opts = YAML::LoadFile (os.str ()); cout << "\tUsando config específica do módulo" << endl; } catch (...) {} // e conecta ModuleHandle h; if (strncmp (endereco.data (), "inproc", 6) == 0 && opts["thread"]) { cout << "\tCriando novo thread pro módulo" << endl; auto no = opts["thread"]; h = threadedConnection (nome, endereco, no["lib"].as<string> () , no["open"].as<string> ()); } else if (strncmp (endereco.data (), "ipc", 3) == 0 || opts["spawn"]) { cout << "\tRodando comando do módulo" << endl; h = spawnConnection (nome, endereco, opts["spawn"].as<string> ()); } else { cout << "\tAguardando conexão" << endl; h = addConnection (nome, endereco); } // sincroniza com o novo módulo h ("open").sync (); } } /// Adiciona uma conexão com módulo ModuleHandle addConnection (const string & nome, const string & conexao) { auto it = modulos.emplace (nome, new ModuleConnection (ctx, conexao)).first; return move (ModuleHandle (it->second)); } /// Spawna uma conexão com módulo ModuleHandle spawnConnection (const string & nome, const string & conexao , const string & comando) { auto it = modulos.emplace (nome, new ModuleConnectionProcess (ctx, conexao, comando)).first; return move (ModuleHandle (it->second)); } ModuleHandle threadedConnection (const string & nome, const string & conexao , const string & nomeLib, const string & simbolo) { auto it = modulos.emplace (nome, new ModuleConnectionThread (ctx, conexao, nomeLib, simbolo)).first; return move (ModuleHandle (it->second)); } /// Pega módulo referente ao nome dado, nullptr se não existir ModuleHandle get (const string & nome) { auto it = modulos.find (nome); if (it == modulos.end ()) { throw GEDI_API_EXCEPTION ("ModuleManager", "Não achei módulo de nome \"" + nome + "\" =/"); } return move (ModuleHandle (it->second)); } private: /// Context context_t ctx; /// Mapa dos módulos unordered_map<string, ModuleConnection *> modulos; }; <file_sep>#pragma once #include <iostream> using namespace std; /// Vetor 2d =] struct Vec2 { float x, y; /// Ctor, com parâmetros Vec2 (float x = 0, float y = 0) : x (x), y (y) {} /// Operações básicas Vec2 operator+ (const Vec2 & outro) const { return Vec2 (x + outro.x, y + outro.y); } Vec2 operator- (const Vec2 & outro) const { return Vec2 (x - outro.x, y - outro.y); } Vec2 & operator+= (const Vec2 & outro) { x += outro.x; y += outro.y; return *this; } Vec2 & operator-= (const Vec2 & outro) { x -= outro.x; y -= outro.y; return *this; } }; ostream& operator<< (ostream& os, const Vec2 & v) { os << '(' << v.x << ',' << v.y << ')'; return os; } <file_sep>#include "Module.hpp" #include "Exception.hpp" #include <unordered_map> #include <SFML/Audio.hpp> using namespace std; using namespace zmq; using MusicMap = unordered_map<string, sf::Music *>; using SoundMap = unordered_map<string, sf::Sound>; using BufferMap = unordered_map<string, sf::SoundBuffer>; extern "C" void abre (context_t * ctx, const char * endereco); int main () { context_t ctx; abre (&ctx, "ipc://gedi_audio"); return 0; } extern "C" void abre (context_t * ctx, const char * endereco) { // módulo do audio Module M (*ctx, endereco); MusicMap musicas; SoundMap sons; BufferMap buffers; M.on ("open", [&] (Arguments & args) { M.sync (); }); M.on ("quit", [&] (Arguments & args) { M.close (); }); //-- Música --// M.on ("music", [&] (Arguments & args) { auto nome = args.as<string> (0); auto arquivo = args.as<string> (1); auto novaMusica = new sf::Music; novaMusica->openFromFile (arquivo); musicas.emplace (move (nome), novaMusica); }); M.on ("mplay", [&] (Arguments & args) { auto nome = args.as<string> (0); musicas.at (nome)->play (); }); M.on ("mstop", [&] (Arguments & args) { auto nome = args.as<string> (0); musicas.at (nome)->stop (); }); M.on ("mpause", [&] (Arguments & args) { auto nome = args.as<string> (0); musicas.at (nome)->pause (); }); M.on ("setLoop", [&] (Arguments & args) { auto nome = args.as<string> (0); auto loop = args.as<bool> (1); musicas.at (nome)->setLoop (loop); }); //-- Buffer pros sonzinhos --// M.on ("buffer", [&] (Arguments & args) { auto nome = args.as<string> (0); auto arquivo = args.as<string> (1); sf::SoundBuffer novoBuffer; novoBuffer.loadFromFile (arquivo); buffers.emplace (move (nome), novoBuffer); }); //-- Sonzinhos --// M.on ("sound", [&] (Arguments & args) { auto nome = args.as<string> (0); auto buffer = args.as<string> (1); sf::Sound novoSom; novoSom.setBuffer (buffers.at (buffer)); sons.emplace (move (nome), novoSom); }); M.on ("splay", [&] (Arguments & args) { auto nome = args.as<string> (0); sons.at (nome).play (); }); M.on ("sstop", [&] (Arguments & args) { auto nome = args.as<string> (0); sons.at (nome).stop (); }); M.on ("spause", [&] (Arguments & args) { auto nome = args.as<string> (0); sons.at (nome).pause (); }); while (M.isOpen ()) { M.handle (); } // apaga os rolê for (auto & it : musicas) { delete it.second; } } <file_sep>Game Engine DIstribuído - GEDI ============================== O quê? ------ Um motor de jogos que usa técnicas de computação distribuída para conversar o núcleo com os módulos. Módulos podem usar computação distribuída dentro de si também, mas não é necessário. Por quê? -------- Flexibilidade. A comunicação entre o núcleo e os módulos feita via _sockets_ abstrai o modo como as coisas são implementadas, forçando somente especificação de protocolo de chamada. Desse modo, módulos (ou mesmo o núcleo) podem ser implementados em qualquer linguagem de programação, podem diferir entre plataformas (SO, processador), podem usar quaisquer tecnologias que convier, podem residir em diferentes máquinas, etc... Além disso, módulos podem ser facilmente ligados ou desligados ao núcleo, diminuindo as dependências de cada jogo e facilitando a criação, compartilhamento e testes de diferentes módulos, ou mesmo diferentes versões de um mesmo módulo. Um sistema gerenciador de pacotes para módulos pode/será feito, para facilitar a instalação de módulos e não precisar de várias cópias do mesmo módulo no mesmo ambiente. Pesquisa -------- A flexibilidade proporcionada pela arquitetura distribuída possibilita uma facilidade na pesquisa de algoritmos novos ou implementações diferentes de tais algoritmos. Performance ----------- Chamadas de procedimento remoto (RPC) são mais demoradas e imprevisíveis. Pra que o __Gedi__ funcione, algum paranauê vai ter que rolar pra não ficar muito lento, talvez assincronia e talz. Segurança --------- Comunicação por sockets podem ser interceptadas e talz. Criar segurança nisso talvez deixe as coisas muito lentas, o que é ruim pra jogos. Como a maioria das comunicações serão locais, ou provavelmente LANs, acho que é de boa não fazer. API --- Leia sobre a até então pensada [API](api.md) <file_sep>#pragma once #include <sstream> #include <exception> using namespace std; class Exception : public exception { public: Exception (const string & what_arg) : what_arg (what_arg) {} Exception (const char * what_arg) : what_arg (what_arg) {} const char * what () const noexcept override { return what_arg.c_str (); } private: string what_arg; }; #define GEDI_API_EXCEPTION(funcName, what) \ [&] () -> Exception { \ ostringstream os; \ os << "[gedi::" << funcName << " @ " << __FILE__ << ':' << __LINE__ \ << "] " << what; \ return move (Exception (move (os.str ()))); \ } () <file_sep>#include "ModuleHandle.hpp" #include "ModuleManager.hpp" #include "GameObject.hpp" #include <iostream> #include <chrono> using namespace std; constexpr double largura = 800; constexpr double altura = 600; int main () { // conta os tempo dos frames chrono::time_point<chrono::system_clock> inicio, fim; ModuleManager mgr; mgr.readConfig ("gedimods.yml"); auto audio = mgr.get ("audio"); audio ("music", "fundo", "musica.ogg"); audio ("setLoop", "fundo", true); audio ("mplay", "fundo"); audio ("buffer", "shot", "shotgun.ogg"); audio ("sound", "shot", "shot"); audio ("splay", "shot"); auto gfx = mgr.get ("grafico"); gfx ("window", (int) largura, (int) altura, "Minha janela pocoto"); // primeiro círculo GameObject primeiro; gfx ("texture", "flango", "flango.png"); gfx ("sprite", primeiro, "flango"); // gfx ("shader", "meuShader", "f.glsl", "fragment"); // gfx ("attach", primeiro, "meuShader"); gfx ("move", primeiro, largura / 2, altura / 2); gfx ("setOrigin", primeiro, 71, 105); bool fechou = false; chrono::duration<double> timeDiff; double ang = 0, delta = 0; while (!fechou) { inicio = chrono::system_clock::now (); gfx ("input"); double sc = 1.5 + sin (ang) / 2; ang += 0.001; gfx ("setScale", primeiro, sc, sc); gfx ("rotate", primeiro, 10 * delta); gfx ("draw"); fechou = gfx ("didClose").resp ().as<bool> (0); // verifica o tempo fim = chrono::system_clock::now (); timeDiff = fim - inicio; delta = timeDiff.count (); cout << delta << endl; } return 0; } <file_sep>#include <SFML/Graphics.hpp> #include <cmath> #include <iostream> #include <chrono> using namespace std; constexpr int largura = 800; constexpr int altura = 600; int main () { // conta os tempo de tudo! chrono::time_point<chrono::system_clock> inicio, fim; sf::RenderWindow window (sf::VideoMode (largura, altura), "Minha janela pocoto"); sf::Texture tex; tex.loadFromFile ("flango.png"); sf::Sprite objeto (tex); objeto.move (largura / 2, altura / 2); objeto.setOrigin (71, 105); chrono::duration<double> timeDiff; double ang = 0; while (window.isOpen ()) { inicio = chrono::system_clock::now (); double sc = 1.5 + sin (ang) / 2; ang += 0.001; objeto.rotate (0.01); objeto.setScale (sc, sc); sf::Event ev; while (window.pollEvent (ev)) { switch (ev.type) { case sf::Event::Closed: window.close (); break; default: break; } } window.clear (); window.draw (objeto); window.display (); fim = chrono::system_clock::now (); timeDiff = fim - inicio; cout << timeDiff.count () << endl; } } <file_sep>#pragma once #include "Vec2.hpp" #include "Connection.hpp" using ID = uintptr_t; /// GameObject: o objeto na sua main que tem as infos gerais necessárias, diga-se // um ID e seu transform struct GameObject { Vec2 position; Vec2 rotation; const ID id { reinterpret_cast<ID> (this) }; }; BuffNSize getBuffer (const GameObject & x) { return getBuffer (x.id); } <file_sep>#!/usr/bin/env python import sdl2 as sdl import sdl2.ext as sdlx import zmq import time class Conexao: def __init__ (self, título, tamanho): self.título = título self.win = sdlx.Window (título, tamanho) self.win.show () self.time = time.perf_counter () self.tempoTotal = 0 self.i = 0 def update (self): último = self.time self.time = time.perf_counter () # desenha cinza sdlx.fill (self.win.get_surface (), sdlx.string_to_color ('#555')) sdl.SDL_UpdateWindowSurface (self.win.window) # e soma o tempo total self.tempoTotal += self.time - último self.i += 1 def getFps (self): return self.i / self.tempoTotal class ConnectionManager: """Um gerenciador de conexões pra esse módulo =P""" def __init__ (self): self.conexões = {} self.ctx = zmq.Context () self.skt = self.ctx.socket (zmq.ROUTER) self.skt.bind ('tcp://*:5555') def create (self, id, nome = b'MeuModuloTeste', largura = 640, altura = 480): # se alguém pedir pra abrir uma janela nova, mata if self.conexões.get (id): del self.conexões[id] self.conexões[id] = Conexao (nome.decode ('utf-8'), (int (largura), int (altura))) print (id, 'conectou') def loop (self, id): # processa eventos events = sdlx.get_events () for ev in events: if ev.type == sdl.SDL_QUIT: self.close (id) return # atualiza os fps e tela self.conexões[id].update () def close (self, id): self.skt.send_multipart ([id, b'flws']) print (id, 'quitou. Média de FPS:', self.conexões[id].getFps ()) del self.conexões[id] def main (): cabou = False clientes = ConnectionManager () while not cabou: msgs = clientes.skt.recv_multipart () if msgs[1] == b'quit': cabou = True elif msgs[1] == b'create': clientes.create (msgs[0], *msgs[2:]) elif clientes.conexões.get (msgs[0]): getattr (clientes, msgs[1].decode ('utf-8')) (msgs[0], *msgs[2:]) sdlx.quit () if __name__ == '__main__': main () <file_sep>/// Conexão com módulos, tenha um só por módulo pliz #pragma once #include "Exception.hpp" #include "Connection.hpp" #include "Arguments.hpp" #include <iostream> #include <tuple> #include <thread> #include <zmq.hpp> #include <cstdlib> #include <cstring> #include <glib.h> #include <gmodule.h> using namespace std; using namespace zmq; /// Conexão com o módulo de fato, sendo extendida para inicialização automática e talz class ModuleConnection { public: /// Ctor, com contexto zmq, endereço de conexão ModuleConnection (context_t & ctx, const string & endereco) : conn (ctx, ZMQ_DEALER) { conn.skt.connect (endereco); } virtual ~ModuleConnection () {} /// Chamar operação sem argumentos void call (const string & func) { conn.send (func); } /// Chamar operação com argumentos, transformando-os usando `getBuffer` template<typename ...Args> void call (const string & func, const Args & ... args) { conn.send (func, args...); } void fillResponse (Arguments & args) { args.recebeMensagens (conn.skt); } private: /// O socket pra comunicar, sempre DEALER Connection conn; }; /// Conexão com módulo que spawna o processo class ModuleConnectionProcess : public ModuleConnection { public: ModuleConnectionProcess (context_t & ctx, const string & endereco , const string & comando) : ModuleConnection (ctx, endereco) { GError * err = NULL; gchar * cmd = strdup (comando.data ()); gchar * argv[] = { cmd, NULL }; if (!g_spawn_async (NULL, argv, NULL, G_SPAWN_DEFAULT , NULL, NULL, &pid, &err)) { throw GEDI_API_EXCEPTION ("ModuleConnectionProcess", err->message); } free (cmd); } virtual ~ModuleConnectionProcess () { g_spawn_close_pid (pid); } private: /// PID do processo, usado pra fechá-lo depois GPid pid; }; /// Conexão com módulo que spawna um thread class ModuleConnectionThread : public ModuleConnection { using gediopenFunc = void (*) (context_t *, const char *); public: ModuleConnectionThread (context_t & ctx, const string & endereco , const string & nomeLib, const string & simbolo) : ModuleConnection (ctx, endereco) { lib = g_module_open (nomeLib.c_str (), G_MODULE_BIND_LAZY); // tenta pegar a função lá gediopenFunc openFunc; if (!g_module_symbol (lib, simbolo.c_str (), (gpointer *) &openFunc)) { auto ex = GEDI_API_EXCEPTION ("ModuleConnectionThread", g_module_error ()); g_module_close (lib); throw ex; } T = thread (openFunc, &ctx, endereco.c_str ()); } virtual ~ModuleConnectionThread () { const char * nomeLib = g_module_name (lib); cout << "Esperando módulo \"" << nomeLib << "\" terminar" << endl; T.join (); if (!g_module_close (lib)) { g_warning ("%s: %s\n", nomeLib, g_module_error ()); } } private: /// Módulo do glib da lib dinâmica GModule * lib; /// Thread onde tá rodando thread T; }; <file_sep>#pragma once #include <iostream> #include <tuple> #include <zmq.hpp> using namespace zmq; struct Vazio {}; const Vazio VAZIO; using BuffNSize = pair<void *, size_t>; BuffNSize getBuffer (const Vazio & v) { return make_pair (nullptr, 0); } BuffNSize getBuffer (const bool & b) { return make_pair ((void *) &b, 1); } BuffNSize getBuffer (const char * const & str) { return make_pair ((void *) str, strlen (str)); } BuffNSize getBuffer (const string & str) { return make_pair ((void *) str.data (), str.size ()); } BuffNSize getBuffer (const double & x) { return make_pair ((void *) &x, sizeof (double)); } BuffNSize getBuffer (const int & x) { return make_pair ((void *) &x, sizeof (int)); } BuffNSize getBuffer (const uintptr_t & x) { return make_pair ((void *) &x, sizeof (uintptr_t)); } template<typename T> BuffNSize getBuffer (const pair<size_t, T *> & P) { return make_pair (P.second, P.first * sizeof (T)); } /// Wrapper pros sockets zmq, pra mandar/receber coisas mais fácil class Connection { public: /// Ctor, com contexto e tipo do socket ZMQ Connection (context_t & ctx, int type) : skt (ctx, type) {} ~Connection () { skt.close (); } /// Caso base, mandando último argumento, sem mandar ZMQ_SNDMORE, fechando // mensagem template<class T> void send (const T & arg) { size_t size; void * buf; tie (buf, size) = getBuffer (arg); skt.send (buf, size); } /// Manda argumentos para o módulo, usando `getBuffer` pra mandar argumentos // direitim template<typename T, typename...Args> void send (const T & head, const Args & ... tail) { size_t size; void * buf; tie (buf, size) = getBuffer (head); skt.send (buf, size, ZMQ_SNDMORE); send (tail...); } socket_t skt; }; <file_sep>/// Argumentos, pra pegar no Module #pragma once #include <string> #include <vector> #include <cstdint> #include <zmq.hpp> using namespace std; using namespace zmq; template<typename T> T fromMessage (message_t & msg); template<> string fromMessage (message_t & msg) { return move (string (msg.data<char> (), msg.size ())); } template<> double fromMessage (message_t & msg) { return (double) *msg.data<double> (); } template<> int fromMessage (message_t & msg) { return (int) *msg.data<int> (); } template<> uintptr_t fromMessage (message_t & msg) { return (uintptr_t) *msg.data<uintptr_t> (); } template<> bool fromMessage (message_t & msg) { return (bool) *msg.data<bool> (); } class Arguments { public: /// Ctor Arguments () {} /// Lê mensagens void recebeComando (socket_t & skt) { args.clear (); skt.recv (&id); skt.recv (&comando); while (skt.getsockopt<int> (ZMQ_RCVMORE)) { message_t msg; skt.recv (&msg); args.push_back (move (msg)); } } void recebeMensagens (socket_t & skt) { args.clear (); do { message_t msg; skt.recv (&msg); args.push_back (move (msg)); } while (skt.getsockopt<int> (ZMQ_RCVMORE)); } /// Pega o comando string getComando () { return fromMessage<string> (comando); } /// Pega o ID de quem mandou, como string mesmo string getId () { return fromMessage<string> (id); } /// Pega mensagem idx como um T template<typename T> T as (int idx) { auto & msg = args.at (idx); return fromMessage<T> (msg); } /// Pega a mensagem idx como um T. Se não tiver, torna o padrão template<typename T> T asDefault (int idx, const T & dflt) { try { return as<T> (idx); } catch (...) { return dflt; } } size_t size () { return args.size (); } private: message_t comando; message_t id; vector<message_t> args; }; <file_sep>#!/usr/bin/env python import sdl2 as sdl import sdl2.ext as sdlx import time win = sdlx.Window ('Direto', (800, 600)) win.show () tempo = time.perf_counter () done = False tempoTotal = 0 i = 0 while not done: events = sdlx.get_events () for ev in events: if ev.type == sdl.SDL_QUIT: done = True break; # desenha =P sdlx.fill (win.get_surface (), sdlx.string_to_color ('#555')) sdl.SDL_UpdateWindowSurface (win.window) último = tempo tempo = time.perf_counter () tempoTotal += tempo - último i += 1 print ('Média de FPS:', 1 / (tempoTotal / i)) <file_sep>#!/usr/bin/env python import zmq def main (): ctx = zmq.Context () skt = ctx.socket (zmq.DEALER) skt.connect ('tcp://127.0.0.1:5555') skt.send_string ('create', zmq.SNDMORE) skt.send_string ('ZMQ', zmq.SNDMORE) skt.send_string ('800', zmq.SNDMORE) skt.send_string ('600') while skt.getsockopt (zmq.EVENTS) & zmq.POLLIN == 0: skt.send_string ('loop') print (skt.recv_string ()) skt.send_string ('quit') if __name__ == '__main__': main () <file_sep>/// Teste do módulo, um dos jeitos de implementar a bagaça #pragma once #include "Arguments.hpp" #include "Connection.hpp" #include <unordered_map> #include <functional> #include <iostream> #include <zmq.hpp> using namespace std; using namespace zmq; using comando = function<void (Arguments &)>; using mapaComando = unordered_map<string, comando>; class Module { public: /// Ctor Module (context_t & ctx, const string & endereco) : conn (ctx, ZMQ_ROUTER) , endereco (endereco), taberto (true) { conn.skt.bind (endereco); } /// Dtor, manda mensagem confirmando que acabou sussa ~Module () { sync (); } /// Fecha módulo void close () { taberto = false; } /// Módulo tá aberto? bool isOpen () { return taberto; } void on (const string & nome, comando cmd) { comandosConhecidos[nome] = cmd; } void handle () { args.recebeComando (conn.skt); auto cmd = args.getComando (); auto it = comandosConhecidos.find (cmd); if (it == comandosConhecidos.end ()) { throw runtime_error ("[" + endereco + "] Comando \"" + cmd + "\" desconhecido!"); } it->second (args); } /// Manda mensagem vazia, pra sincronização void sync () { conn.send (args.getId (), VAZIO); } template<typename...Args> void respond (Args... arguments) { conn.send (args.getId (), arguments...); } private: /// O socket pra comunicar, sempre ROUTER Connection conn; string endereco; /// Tá aberto o módulo? bool taberto; /// Nossos argumentos =] Arguments args; /// E o mapa de comandos, pra chamar hora que receber um comando mapaComando comandosConhecidos; }; <file_sep>Projeto de API ============== Quais funcionalidades podem ser proporcionadas para facilitar criação e uso de módulos? ModuleManager ------------- Uma classe que gerencia a conexão com os módulos, contendo info sobre os módulos conectados. Uma instância é suficiente por jogo, talvez compense fazer singleton. Métodos: - __construtor__: inicializa podendo ler o arquivo de configuração, e conectando com os módulos. Pode usar `argc` e `argv` pra sacar umas coisa, incluindo caminho da configuração. - __Module connect (string nome, string endereço)__: conecta com o módulo baseado no endereço `endereço`, salvando-o com o nome especificado. Note que esse método só realiza a conexão, então trate de já ter o módulo ligado e pronto (ao ler do arquivo de configuração, criação do processo do módulo vai ser feita automaticamente pelo __Gedi__, talvez métodos específicos como "connectIpc", ou "connectInproc") - __Module get (string)__: pega uma instância de módulo baseado em seu nome, o mesmo usado no arquivo de configuração. <file_sep>/// Teste de um Module, que conversa com o módulo e recebe resposta (se precisar) #pragma once #include "ModuleConnection.hpp" #include "Arguments.hpp" #include <iostream> using namespace std; /// Handler de módulos, pra podermos usar polimorfismo =] class ModuleHandle { public: ModuleHandle () : ModuleHandle (nullptr) {} ModuleHandle (ModuleConnection * con) : connection (con) {} /// Setter da conexão, pra poder iterar sobre conexões reutilizando o handle void set (ModuleConnection * con) { connection = con; } template<typename ...Args> ModuleHandle & operator() (const Args & ... args) { connection->call (args...); return *this; } void sync () { connection->fillResponse (respostas); } Arguments & resp () { connection->fillResponse (respostas); return respostas; } private: ModuleConnection * connection; Arguments respostas; };
57d46905e34ccb711bac47f029f6b34ac7093586
[ "Markdown", "Python", "C++", "Lua" ]
20
Markdown
FellowshipOfTheGame/gedi
c39b1325be6cee9ee9849a95da2a8779010a84b2
76bc161391e3e9c91127e389b373a6fd9e1cf599
refs/heads/master
<file_sep>import threading import pyperclip class ClipboardWatcher(threading.Thread): urls = set() def __is_youtube_url(self,url): if 'https://www.youtube.com/watch?v=' in url: return True return False def __init__(self): super(ClipboardWatcher, self).__init__() self._stopping = False def run(self): recent_value = "" pyperclip.copy('') while not self._stopping: tmp_value = pyperclip.paste() if tmp_value != recent_value and self.__is_youtube_url(tmp_value): recent_value = tmp_value if recent_value not in self.urls: self.urls.add(recent_value) print(recent_value) def stop(self): self._stopping = True def get_urls(self): return self.urls<file_sep>from dlmanager import manager from clipboard import ClipboardWatcher import time def main(): watcher = ClipboardWatcher() watcher.start() while True: try: # print "Waiting for changed clipboard..." time.sleep(1) except KeyboardInterrupt: watcher.stop() mgr=manager() mgr.start(watcher.get_urls()) break if __name__ == "__main__": main()<file_sep>import youtube_dl import json class manager(): links=None def __init__(self): super().__init__() def __putque(self,links): lista=list() for i in links: lista.append({"link":i,"finished":False}) with open('lista.json','a') as f: json.dump(lista,f,indent=2) def start(self,links): self.links=links ydl_opts = { 'format': '137+140', 'writesubtitles': True, 'postprocessors': [{ 'key': 'FFmpegSubtitlesConvertor', 'format': 'srt' }] } self.__putque(links) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(self.links)
1cb6f82f0d25eedcb623ea368a489b066ec4f7e0
[ "Python" ]
3
Python
pgrtiragg/py-downloader
574d6553103f423dee2dcd784d9812cf5f53c2e6
ad145b9a0e66738956bef9b86f7ae23a75f30cfc
refs/heads/main
<file_sep>package br.com.alura.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder @Configuration @EnableWebSecurity class SecurityConfiguration( private val userDetailsService: UserDetailsService ) : WebSecurityConfigurerAdapter() { @Throws(Exception::class) override fun configure(auth: AuthenticationManagerBuilder) { auth.userDetailsService(this.userDetailsService) .passwordEncoder(bCryptPasswordEncoder()) } override fun configure(http: HttpSecurity) { http .authorizeRequests() .antMatchers("/topics").hasAnyAuthority("WRITER_READER") .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .formLogin().disable() .httpBasic() } @Bean fun bCryptPasswordEncoder(): BCryptPasswordEncoder { return BCryptPasswordEncoder() } }<file_sep>package br.com.alura.controller import br.com.alura.dto.NewTopicForm import br.com.alura.dto.TopicByCategoryDto import br.com.alura.dto.TopicView import br.com.alura.dto.UpdateTopicForm import br.com.alura.model.Topic import br.com.alura.service.TopicService import org.springframework.cache.annotation.CacheEvict import org.springframework.cache.annotation.Cacheable import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.util.UriComponentsBuilder import javax.transaction.Transactional import javax.validation.Valid @RestController @RequestMapping("topics") class TopicController( val service: TopicService ) { @GetMapping @Cacheable("topics") fun list(page: Pageable): Page<TopicView> { return service.getList(page) } @GetMapping("/report") fun report(): List<TopicByCategoryDto> { return service.report() } @GetMapping("/{id}") fun getById(@PathVariable id: Long): TopicView { return service.getById(id) } @PostMapping @Transactional @CacheEvict(value = ["topics"], allEntries = true) fun create(@RequestBody @Valid form: NewTopicForm, uriBuilder: UriComponentsBuilder): ResponseEntity<TopicView> { val topicView = service.save(form) val uri = uriBuilder.path("topics/${topicView.id}").build().toUri() return ResponseEntity.created(uri).body(topicView) } @PutMapping @Transactional @CacheEvict(value = ["topics"], allEntries = true) fun update(@RequestBody @Valid form: UpdateTopicForm): TopicView { return service.update(form) } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional @CacheEvict(value = ["topics"], allEntries = true) fun delete(@PathVariable id: Long) { service.delete(id) } } <file_sep>package br.com.alura.repository import br.com.alura.model.User import org.springframework.data.jpa.repository.JpaRepository interface UserRepository: JpaRepository<User, Long> { fun findByEmail(email: String): User? }<file_sep>create table role ( id bigint not null auto_increment, name varchar(50) not null, primary key (id) ); insert into role(id, name) values (1, 'WRITER_READER'); <file_sep>create table topic ( id bigint not null auto_increment, title varchar(50) not null, message varchar(300) not null, created_at datetime not null, status varchar(20) not null, course_id bigint not null, author_id bigint not null, primary key (id), foreign key (course_id) references course (id), foreign key (author_id) references user (id) ); <file_sep>package br.com.alura.model import java.time.LocalDateTime import javax.persistence.* @Entity data class TopicResponse( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, val message: String, val createdAt: LocalDateTime = LocalDateTime.now(), @ManyToOne val author: User, @ManyToOne val topic: Topic, val solution: Boolean ) <file_sep>create table course ( id bigint not null auto_increment, name varchar(50) not null, category varchar(50) not null, primary key (id) ); insert into course(id, name, category) values (1, 'kotlin', 'programing'); insert into course(id, name, category) values (2, 'react', 'front-end');<file_sep>update user set password='<PASSWORD>' where id=1; update user set password='<PASSWORD>' where id=2;<file_sep>package br.com.alura.model import java.time.LocalDateTime import javax.persistence.* @Entity data class Topic( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, val title: String, val message: String, val createdAt: LocalDateTime = LocalDateTime.now(), @ManyToOne val course: Course, @ManyToOne val author: User, @Enumerated(value = EnumType.STRING) val status: TopicStatus = TopicStatus.NO_ANSWERED, @OneToMany(mappedBy = "topic") val responses: List<TopicResponse> = ArrayList() ) <file_sep>package br.com.alura.model import javax.persistence.* @Entity @Table(name = "course") data class Course( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, val name: String, val category: String ) <file_sep>package br.com.alura.repository import br.com.alura.dto.TopicByCategoryDto import br.com.alura.model.Topic import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query interface TopicRepository: JpaRepository<Topic, Long> { @Query("SELECT new br.com.alura.dto.TopicByCategoryDto(t.course.category, count(t)) from Topic t JOIN t.course GROUP BY t.course.category") fun report(): List<TopicByCategoryDto> }<file_sep>package br.com.alura.repository import br.com.alura.model.Course import org.springframework.data.jpa.repository.JpaRepository interface CourseRepository: JpaRepository<Course, Long> { }<file_sep>package br.com.alura.service import br.com.alura.model.User import org.springframework.security.core.userdetails.UserDetails class UserDetail(private val user: User) : UserDetails { override fun getAuthorities() = user.role override fun getPassword() = <PASSWORD> override fun getUsername() = user.email override fun isAccountNonExpired() = true override fun isAccountNonLocked() = true override fun isCredentialsNonExpired() = true override fun isEnabled() = true }<file_sep>create table topic_response ( id bigint not null auto_increment, message varchar(300) not null, created_at datetime not null, status varchar(20) not null, topic_id bigint not null, author_id bigint not null, solution bigint not null, primary key (id), foreign key (topic_id) references topic (id), foreign key (author_id) references user (id) ); <file_sep>create table user_role ( id bigint not null auto_increment, user_id bigint not null, role_id bigint not null, primary key (id), foreign key (user_id) references user(id), foreign key (role_id) references role(id) ); insert into user_role(id, user_id, role_id) values (1, 1, 1); <file_sep>package br.com.alura.service import br.com.alura.model.User import br.com.alura.repository.UserRepository import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service import java.lang.RuntimeException @Service class UserService(private val repository: UserRepository) : UserDetailsService { fun getById(id: Long): User = repository.getById(id) override fun loadUserByUsername(email: String): UserDetails { val user = repository.findByEmail(email) ?: throw RuntimeException("user not found") return UserDetail(user) } } <file_sep>package br.com.alura.model enum class TopicStatus { NO_ANSWERED, NO_SOLVED, SOLVED, CLOSED } <file_sep>package br.com.alura.mapper import br.com.alura.dto.NewTopicForm import br.com.alura.model.Topic import br.com.alura.service.CourseService import br.com.alura.service.UserService import org.springframework.stereotype.Component @Component class TopicFormMapper( private val courseService: CourseService, private val userService: UserService, ) : Mapper<NewTopicForm, Topic> { override fun map(t: NewTopicForm): Topic = Topic( title = t.title, message = t.message, course = courseService.getById(t.courseId), author = userService.getById(t.authorId) ) } <file_sep>package br.com.alura.dto import javax.validation.constraints.* class NewTopicForm( @field:NotBlank @field:Size(min = 5, max = 100) val title: String, @field:NotBlank val message: String, @field:Positive val courseId: Long, // not null not working here @field:Positive val authorId: Long ) <file_sep>package br.com.alura.service import br.com.alura.model.Course import br.com.alura.repository.CourseRepository import org.springframework.stereotype.Service import java.util.* @Service class CourseService(private val repository: CourseRepository) { fun getById(id: Long): Course = repository.getById(id) } <file_sep>package br.com.alura.exception import br.com.alura.dto.ErrorView import org.springframework.http.HttpStatus import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestControllerAdvice import javax.servlet.http.HttpServletRequest @RestControllerAdvice class ExceptionHandler { @ExceptionHandler(NotFoundException::class) @ResponseStatus(HttpStatus.NOT_FOUND) fun handleNotFound(exp: NotFoundException, request: HttpServletRequest): ErrorView { return ErrorView( status = HttpStatus.NOT_FOUND.value(), error = HttpStatus.NOT_FOUND.name, message = exp.message, path = request.servletPath ) } @ExceptionHandler(MethodArgumentNotValidException::class) @ResponseStatus(HttpStatus.BAD_REQUEST) fun handleValidationError(exp: MethodArgumentNotValidException, request: HttpServletRequest): ErrorView { val errorMessage = HashMap<String, String?>() exp.bindingResult.fieldErrors.forEach { e -> errorMessage[e.field] = e.defaultMessage } return ErrorView( status = HttpStatus.BAD_REQUEST.value(), error = HttpStatus.BAD_REQUEST.name, message = errorMessage.toString(), path = request.servletPath ) } @ExceptionHandler(Exception::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) fun handleServerError(exp: Exception, request: HttpServletRequest): ErrorView { return ErrorView( status = HttpStatus.INTERNAL_SERVER_ERROR.value(), error = HttpStatus.INTERNAL_SERVER_ERROR.name, message = exp.message, path = request.servletPath ) } } <file_sep>package br.com.alura.mapper import br.com.alura.dto.TopicView import br.com.alura.model.Topic import org.springframework.stereotype.Component @Component class TopicViewMapper : Mapper<Topic, TopicView> { override fun map(t: Topic): TopicView { return TopicView( id = t.id, title = t.title, message = t.message, status = t.status, createdAt = t.createdAt ) } } <file_sep>package br.com.alura.model import com.fasterxml.jackson.annotation.JsonIgnore import javax.persistence.* @Entity @Table(name = "user") class User( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, val name: String, val email: String, val password: String, @JsonIgnore @ManyToMany(fetch = FetchType.EAGER) @JoinColumn(name = "user_role") val role: List<Role> = mutableListOf() ) <file_sep>alter table user add column password text;<file_sep>package br.com.alura.service import br.com.alura.dto.NewTopicForm import br.com.alura.dto.TopicByCategoryDto import br.com.alura.dto.TopicView import br.com.alura.dto.UpdateTopicForm import br.com.alura.exception.NotFoundException import br.com.alura.mapper.TopicFormMapper import br.com.alura.mapper.TopicViewMapper import br.com.alura.model.Topic import br.com.alura.repository.TopicRepository import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.http.ResponseEntity import org.springframework.stereotype.Service @Service class TopicService( private val repository: TopicRepository, private val topicViewMapper: TopicViewMapper, private val topicFormMapper: TopicFormMapper ) { private val notFoundExceptionMessage = "Topic not found" fun getList(page: Pageable): Page<TopicView> { return repository.findAll(page).map { topicViewMapper.map(it) } } fun getById(id: Long): TopicView { val topic = repository.findById(id).orElseThrow { NotFoundException(notFoundExceptionMessage) } return topicViewMapper.map(topic) } fun save(form: NewTopicForm): TopicView { val newTopic = topicFormMapper.map(form) repository.save(newTopic) return topicViewMapper.map(newTopic) } fun update(form: UpdateTopicForm): TopicView { val topic = repository.findById(form.id).orElseThrow { NotFoundException(notFoundExceptionMessage) } val updatedTopic = topic.copy(title = form.title, message = form.message) repository.save(updatedTopic) return topicViewMapper.map(updatedTopic) } fun delete(id: Long) { repository.deleteById(id) } fun report(): List<TopicByCategoryDto> { return repository.report() } } <file_sep>create table user ( id bigint not null auto_increment, name varchar(50) not null, email varchar(50) not null, primary key (id) ); insert into user(id, name, email) values (1, '<NAME>', '<EMAIL>'); insert into user(id, name, email) values (2, '<NAME>', '<EMAIL>'); <file_sep>package br.com.alura.exception class NotFoundException(message: String? = null) : RuntimeException(message) { } <file_sep>package br.com.alura.model import org.springframework.security.core.GrantedAuthority import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id @Entity data class Role( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private val id: Long, private val name: String ) : GrantedAuthority { override fun getAuthority(): String = name }<file_sep># API-kotlin-spring # Topics Web - Implemtação de GET, POST, PUT e DELETE - DTOs para representar as informações de input/output da API - Classes Mappers para conversão de DTOs - Validações utilizando o Bean Validation - Princípios do modelo REST - Tratamento de exceptions na API usando global handler Data - Spring Data JPA - Flyway como ferramenta de migrations - Paginação e ordenação nas consultas - Cache - Queries personalizadas nas interfaces repository # Requirements - java 11 - maven ^3.8.1 # Technologies - kotlin - spring 2.5.5 - starter-web - starter-validation - starter-devtools - starter-test - starter-data-jpa - starter-cache - h2 - flyway # RUN ``` ./mvnw clean install -DskipTests ./mvnw clean spring-boot: run ``` <file_sep>package br.com.alura.dto import javax.validation.constraints.NotBlank import javax.validation.constraints.Positive import javax.validation.constraints.Size class UpdateTopicForm( @field:Positive val id: Long, @field:NotBlank @field:Size(min = 5, max = 100) val title: String, @field:NotBlank val message: String ) <file_sep>package br.com.alura.dto data class TopicByCategoryDto( val category: String, val qnt: Long )
75683dab29caddc1d8dbd92c702d8409320bb358
[ "Markdown", "SQL", "Kotlin" ]
31
Kotlin
Gilmardealcantara/forum-kotlin-spring
196358b3a11b7dab7492d4215856b5feac7f9d8e
8c4a7ccc9926ddb9c5c5beedb9794003ee76432e
refs/heads/master
<repo_name>Kaczmarczyk-M/messenger<file_sep>/script.js var tresc_diva = []; function refresh() { var calyChat = ""; for(var i = 0; i < tresc_diva.length; i++) { calyChat += tresc_diva[i]; } document.getElementById("chat").innerHTML = tresc_diva.join(''); } function submit() { tresc_diva.unshift('<div class="log">' + document.getElementById("message").value + '</div>'); tresc_diva.unshift('<div style="clear: both;"></div>'); document.getElementById("message").value = ""; // document.getElementById("chat").innerHTML = document.getElementById("message").value refresh(); console.log(tresc_diva); }
59ec4eab6d218597d4f80fcf35b5f8a23dd032f5
[ "JavaScript" ]
1
JavaScript
Kaczmarczyk-M/messenger
f98cc646a46c08c2a820cd7d38cf80834133f35b
86d8b2f68359cedab7defd5debf95f928edfb4cc
refs/heads/master
<repo_name>jackrack/vault712<file_sep>/vault712.sh #!/bin/bash ##Download on https://github.com/jackrack/Vault712 ##Config setup ##GrinLog=/root/mw/grin/server/grin.log ##Rust installer function rust_installer() { sudo apt-get update -y sudo apt-get install build-essential cmake -y curl https://sh.rustup.rs -sSf | sh source $HOME/.cargo/env } ##Clang installer function clang_installer() { sudo apt-get update sudo apt-get install clang-3.8 } ##Libncurses & zlib1g installer function not yet activated dependencies_installer() { sudo apt-get install libncurses5-dev libncursesw5-dev sudo apt-get install zlib1g-dev } ##Grin installer function main_installer() { while true; do read -p "Do you wish to install Grin? " yn case $yn in [Yy]* ) break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done cd $HOME mkdir mw/ cd mw git clone https://github.com/mimblewimble/grin.git cd grin cargo build --verbose main_menu } #Reinstall Grin reinstall_grin() { rm -rf $HOME/mw cd $HOME mkdir mw/ cd mw git clone https://github.com/mimblewimble/grin.git cd grin cargo build --verbose main_menu } ##Start node function my_node() { cd $HOME/mw/grin/ export PATH=$HOME/mw/grin/target/debug:$PATH grin } ##Start spend balance function my_spendbalance() { cd $HOME/mw/grin/ export PATH=/$HOME/mw/grin/target/debug/:$PATH grin wallet info echo "Press ENTER To Return" read continues } ##Start output function my_outputs() { cd $HOME/mw/grin export PATH=$HOME/mw/grin/target/debug/:$PATH grin wallet outputs echo "Press ENTER To Return" read continue } ##Start output function in detail my_outputs_detailed() { cd $HOME/mw/grin cat wallet.dat echo "Press ENTER To Return" read continue } ##Function to send Grin to an ip address sendgrinto_ip() { echo This option will send Grins to an IP address cd $HOME/mw/grin/ export PATH=$HOME/mw/grin/target/debug:$PATH read -p 'Please enter the ip address of recipient to send: ' sendipvar read -p 'Please enter the amount of Grins to send: ' sendamountvar grin wallet send -d http$sendipvar:13415 $sendamountvar echo You have sent $sendamountvar Grins to $sendipvar echo Press any key to return read } ##Start the main part of the application menu if Grin and prerequisites are installed main_menu() { while : do clear echo " " echo -e "Grin has been succesfully installed, please choose one of the options below\n" echo "MAIN OPTIONS" echo "1) Start Grin" echo "2) Shutdown all Grin Nodes & Servers" echo "" echo "GRIN DEBUG OPTIONS" echo "3) View Confirmed & Spendable Balance " echo "4) Show Individual Outputs" echo "5) Show Detailed Individual Outputs" echo "" echo "GRIN SEND & RECEIVE OPTIONS" echo "6) Send Grin to an IP" echo "" echo "OPTIONS" echo "7) Reinstall Grin (Latest Available)" echo "8) Exit" echo "=====================================" read m_menu case "$m_menu" in 1) option_1;; 2) option_2;; 3) option_3;; 4) option_4;; 5) option_5;; 6) option_6;; 7) option_7;; 8) exit 0;; *) echo "Error, invalid input, press ENTER to go back"; read;; esac done } option_1() { ##export function, run a new shell starting Grin export -f my_node $(gnome-terminal --tab -e "bash -c 'my_node'") } option_2() { ##shutdown any Grin process killall -9 grin main_menu } option_3() { ##export function, run a new shell export -f my_spendbalance $(gnome-terminal --tab -e "bash -c 'my_spendbalance'") } option_4() { ##export function, run a new shell export -f my_outputs $(gnome-terminal --tab -e "bash -c 'my_outputs'") } option_5() { ##export function, run a new shell export -f my_outputs_detailed $(gnome-terminal --tab -e "bash -c 'my_outputs_detailed'") } option_6() { ##export function, run a new shell export -f sendgrinto_ip $(gnome-terminal --tab -e "bash -c 'sendgrinto_ip'") } option_7() { export -f reinstall_grin $(gnome-terminal --tab -e "bash -c 'reinstall_grin'") } option_wait() { echo This option will send Grins to Termbin and can be claimed by anyone that knows the url export PATH=$HOME/mw/grin/target/debug:$PATH read -p 'Please enter amount to send: ' amountvar grin wallet send -d $amountvar termbinvar="$(echo $amountvar | nc termbin.com 9999)" echo Share this url to allow someone to claim the output: "$termbinvar" echo Press any key to return read } ##Check if Clang is installed if [ "type -p clang-3.8" ]; then : else clang_installer fi ##Check if Rust is installed if [ "type -p rustc" ]; then : else rust_installer fi ##Check if Grin is installed if [ -d "$HOME/mw/grin/" ]; then main_menu else main_installer fi <file_sep>/README.md # Vault 712 Vault 712 is a Grin installer for the MimbleWimble protocol. It will install Grin and all prerequisites on your linux computer. Vault 712 is also an interactive shell that allows you to run the Grin server for mining and the Grin wallet and sending/receiving the cryptocurrency Grin. ## Getting Started 1) Run the command below to download the script ``` wget https://raw.githubusercontent.com/jackrack/Vault712/master/vault712.sh ``` 2) Run the main shell script by executing ```./vault712``` on the command line interface 3) Run ```chmod +x on vault712.sh``` to make sure you have permissions to run it on the command line interface 4) Follow the instructions in the terminal prompt to proceed with the installation ![alt text](https://user-images.githubusercontent.com/32465294/34165766-18ca3724-e4d5-11e7-9077-427a79e215d2.png) **This script has been updated and is now compatible with Testnet 3** This script is mainly used for testing and fast deployment of the latest Grin as well as testing features in the latest Grin build. The installation script works independently of starting a node and server, and can be closed and opened independently to run different optional commands for Grin. ### Requirements * Linux - Primary platform (x86 only, at present) * Ubuntu 16.04 or later * zlib1g-dev, libncurses5-dev and libncursesw5-dev currently need to be manually installed ### What will be installed - Clang 3.6 - Latest Rust, if not already installed (NOTE! If you run older than Rust 1.26, Grin might not work, and you will manually have to update before running this script) - The latest Grin with wallet and server. (NOTE! Grin is constantly updated and this script does not autoupdate. You need to delete the folder mw in $HOME to install the latest Grin with this script - An interactive shell wallet to send the cryptocurrency Grin ## Information * More about Grin: https://github.com/mimblewimble/grin * More about Grin compared to Bitcoin: https://github.com/mimblewimble/grin/blob/master/doc/grin4bitcoiners.md * More information about Grin: http://grin-tech.org/ * More information about MimbleWimble & Grin development: https://lists.launchpad.net/mimblewimble/ * Grin forum: https://www.grin-forum.org
76fa05007105c7fb34b99a8b63d57fe09c19138b
[ "Markdown", "Shell" ]
2
Shell
jackrack/vault712
356eb699d1d82a5962ae066b545e47074143da71
42792e3b16e7f61abd833c7ae1b72b3b14847650
refs/heads/main
<file_sep>window.onload = function(){ function geoFindMe() { const status = document.querySelector('#status'); const lon = document.querySelector("#lon") const lat = document.querySelector("#lat") function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textContent = ''; if(lon.value == '' || lat.value == ''){ lon.value = longitude; lat.value = latitude; } $.ajax({url: "https://api.openweathermap.org/data/2.5/weather?lat="+lat.value+"&lon="+lon.value+"&appid=809d866831ecf5cf6a3105f32a0754b0&units=metric", success: function(res){ console.log(res); w = res.weather[0]['main']; s = res.wind['speed']; if((w == 'Clear' || w=='Clouds') && s < 10.7){ document.getElementById("road_condition").value = 1; document.getElementById("weather_condition").value = 1; } else if((w == 'Clear' || w=='Clouds') && s > 10.7){ document.getElementById("road_condition").value = 1; document.getElementById("weather_condition").value = 4; } else if(w == 'Rain' && s < 10.7){ document.getElementById("road_condition").value = 2; document.getElementById("weather_condition").value = 2; } else if(w == 'Rain' && s > 10.7){ document.getElementById("road_condition").value = 2; document.getElementById("weather_condition").value = 5; } else if(w == 'Snow' && s < 10.7){ document.getElementById("road_condition").value = 3; document.getElementById("weather_condition").value = 3; } else if(w == 'Snow' && s > 10.7 ){ document.getElementById("road_condition").value = 3; document.getElementById("weather_condition").value =6; } else if(w == 'Fog' || w == 'Mist'){ document.getElementById("road_condition").value = 2; document.getElementById("weather_condition").value = 7; } else{ document.getElementById("road_condition").value = 1; document.getElementById("weather_condition").value = 1; } const date = new Date(); const hour = date.getHours(); if(hour <= 6 || hour >= 19){ document.getElementById("light").value = 4; } else{ document.getElementById("light").value = 1; } const day = date.getDay(); document.getElementById("day_of_the_week").value = day+1; }}); } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating…'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); }
1aa3f4be1bfa9f7ffe6ece2428864b6a8bd65966
[ "JavaScript" ]
1
JavaScript
manojmsr2000/ML-Accident-Analysis-Project
b285cd1a88d979e42a74dd61500484f43e3fae5c
41c16fb1195465a045900f9d3231eb7075c27766
refs/heads/master
<repo_name>MorganDark21798/Pass-Manager-python-script<file_sep>/Pass.py def askUser(): username = input("Enter your username: ") password = input("Enter your password: ") checkPass(username, password) def checkPass(use, pwd): if use == ("ID8") and pwd == ("<PASSWORD>"): login(use) else: print ("Your username and/or password was incorrect") askUser() def login(use): print ("Welcome " + use) print ("You have successfully logged in!") askCom() def askCom(): command = input("Enter your command: ") if command == ("log off") or command == ("quit"): username = ("") password = ("") print ("You have logged off") askUser() if command == ("what is this code?") : username = ("") password = ("") print ("Python 3") askUser() else: print ("Unknown command") askCom() askUser()
1f9e7165dfa2e43e0de3985997de1121f411712d
[ "Python" ]
1
Python
MorganDark21798/Pass-Manager-python-script
910d2ae9f9b7f0b401b6eaf14eb71829ac4f0cc9
b2b7e296f7807dabfb7d41681bed4c2a4be6e837
refs/heads/master
<file_sep>#!/usr/bin/env sh if [ "true" != "${XDEBUG_ENABLED}" ]; then rm /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini fi COMMAND="composer install --prefer-dist --no-progress --no-suggest --no-interaction" if [[ "prod" = "${APP_ENV}" ]]; then COMMAND="${COMMAND} --no-dev --optimize-autoloader --classmap-authoritative" fi su \ -c "${COMMAND}" \ -s /bin/sh \ -m \ www-data chown -R www-data: var/ php-fpm<file_sep>version: '3.2' services: php: build: context: . dockerfile: docker/php/Dockerfile.dev args: - HOST_UID=${HOST_UID} - HOST_GUID=${HOST_GUID} volumes: - .:/var/www/html - ${HOST_COMPOSER_HOME}:/var/www/html/var/.composer environment: - COMPOSER_HOME=/var/www/html/var/.composer - XDEBUG_ENABLED - XDEBUG_CONFIG - PHP_IDE_CONFIG db: image: postgres:12-alpine volumes: - db:/var/lib/postgresql/data environment: - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_PORT ports: - "${EXTERNAL_POSTGRES_PORT}:${POSTGRES_PORT}" nginx: build: context: . dockerfile: docker/nginx/Dockerfile.dev args: - HOST_UID=${HOST_UID} - HOST_GUID=${HOST_GUID} depends_on: - php ports: - ${EXTERNAL_HTTP_PORT}:80 volumes: - .:/var/www/html - ./var/log:/var/log/nginx environment: - UPSTREAM=php:9000 volumes: db:<file_sep># TODO List API Server ## Dev Requirements - Docker - Docker Compose >= 1.26 ## Setup 1. Create `.env` file with the contents of the `.env.dist` file 2. Modify variables for your needs 3. Run `docker-compose up -d` 4. Open http://localhost:<${EXTERNAL_HTTP_PORT}> (by default just http://localhost)
63226d552ae0fddc893e995d613ea0502813118b
[ "Markdown", "YAML", "Shell" ]
3
Shell
artem328/test-179e1bab-bb8d-4f3a-89a8-3e85e4921292
138db810ca5b9bf790b36f8efe04110a1ac218dd
51a0eda136513d7b2f79f310b862797e52559e78
refs/heads/master
<file_sep>package com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.impl; import com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.FlyBehavior; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/5/2 20:28 * @Description 什么事都不做,不会飞! */ public class FlyNoWay implements FlyBehavior { @Override public void fly() { //TODO 什么都不做,不会飞 System.out.println("I can't fly"); } } <file_sep>package com.thinkgem.jeesite.common.enumdemo; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/8/31 15:45 */ public class CommonExceptions { public enum UserCommonException{ CUST_NOT_REGISTER(new CommonException(1000,"用户尚未注册")), CUST_NOT_FOUND(new CommonException( 1001,"用户不存在")), CUST_PASS_WRONG(new CommonException(1002,"用户名或密码错误")), CUST_VERIFY_WRONG(new CommonException(1003,"验证码错误,请重新尝试")), CUST_USER_NOT_AUTH(new CommonException(1004,"用户没有登录此平台的权限")), CUST_USER_EXITST(new CommonException(1005,"用户登录名已经存在")), CUST_USER_NOT_CHECKED(new CommonException(1006,"注册用户尚未审核通过,暂时不允许登录")), TOKEN_NOT_REQUEST(new CommonException(1007,"未传入isCheckToken参数")), TOKEN_NOT_FOUNT(new CommonException(1008,"token失效")), LOGIN_NOT_EXIST(new CommonException(1009,"您未登录")), OLDPWD_WRONG(new CommonException(1010,"原密码错误")), PHONE_PASSWORD_NOT_RECEIVE(new CommonException(1012,"手机号或密码不能为空")), CUST_VERIFY_NOT_NULL(new CommonException(1013,"验证码不能为空")), USER_ID_NOT_NULL(new CommonException(1014,"用户userid不能为空")), VERIFY_CODE_SEND_ERROR(new CommonException(1015,"短信发送失败")), PHONE_VERIFYCODE_NOT_RECEIVE(new CommonException(1016,"手机号或验证码不能为空")), OLD_AND_NEW_PASSWORD_NOT_NULL(new CommonException(1017,"旧密码或新密码不能为空")), CUSTOMER_AVATAR_NOT_RECEIVE(new CommonException(1018,"未传入用户头像")), ID_CARD_VERIFY_NOT_FULL(new CommonException(1019,"实名认证信息不完整")), CUSTOMER_PASSWORD_NOT_FOUND(new CommonException(1020,"用户密码不存在")), USERNAME_PASSWORD_EQUAL(new CommonException(1021,"用户名和密码不能相同")), USER_STATE_WRONG(new CommonException(1027,"用户已冻结或已注销")), USER_CENTER_CONNECT_FAIL(new CommonException(1028,"连接注册中心失败")), USER_CENTER_REGISTE_FAIL(new CommonException(1029,"用户中心注册失败")), PHONENO_INPUT_ERROR(new CommonException(2030,"手机号不符合规则")), USER_CENTER_UPDATE_FAIL(new CommonException(2031,"注册中心修改用户信息失败")), PARAM_NOT_COMPLETE(new CommonException(2032,"传入参数不完整")), USER_CENTER_SERVER_FAIL(new CommonException(2033,"注册中心暂不提供服务")), USER_CENTER_VALIDATE_FAIL(new CommonException(2034,"用户中心登陆验证失败,用户名或密码不正确")), USER_CENTER_MERGE_FAIL(new CommonException(2035,"合并失败(无主用户信息或登录名重复)")), USER_CENTER_EXIST_PHONE(new CommonException(2040,"合并失败,该登录名的手机或邮箱存在多条数据,请更换手机或邮箱合并")), USER_CENTER_PWD_WRONG(new CommonException(2036,"注册中心同步修改密码出错:-->用户名或原密码不正确")), USER_CENTER_PWD_EQUALS(new CommonException(2037,"注册中心同步修改密码出错:-->原密码不能与新密码相同")), USER_CENTER_RESETPWD_FAIL(new CommonException(2038,"注册中心重置密码失败")), CUSCORP_NOT_EXIS(new CommonException(2039,"查找的企业不存在")), CUSCORP_NOT_FOUND(new CommonException(2039,"此企业未查询到")), USER_CENTER_RESULT_FAIL(new CommonException(2041,"注册中心查询结果无数据或查询异常")), USER_CENTER_NOT_RETURN_PHONE(new CommonException(2047,"注册中心未返回手机号")), SERVICE_UNAVAILABLE(new CommonException(2042,"服务不可用 (此异常是控制用户注册和修改密码开关异常)")), ACCESS_CHANNEL_ERROR(new CommonException(2043,"访问渠道不正确")), USER_CARD_STATE_ERROR(new CommonException(2044,"输入的卡状态有误")), ALLOW_PAY_MODEL_ERROR(new CommonException(2045,"输入信息有误")), PAY_MODEL_NOT_EXIST(new CommonException(2046,"此卡业务设置信息不存在")), ID_TYPE_NOT_NULL (new CommonException( 2045,"证件类型不为空")), ID_NO_FORMAT_ERROR (new CommonException( 2055,"用户身份证格式不正确")), OLD_EQUAL_NEW(new CommonException(3042,"输入的新密码等于旧密码")), PWD_NOT_NULL(new CommonException(3043,"用户名或密码错误")), NEW_NOTEQUAL_CONFIRM(new CommonException(3041,"两次输入的密码不相同")), PWD_NOTEQUAL_THIRD(new CommonException(3044,"输入的新密码不能与最近三次密码相同")); private CommonException commonException; UserCommonException(CommonException commonException){ this.commonException = commonException; } public CommonException getCommonException() { return commonException; } public void setCommonException(CommonException commonException) { this.commonException = commonException; } public static void show(){ for(UserCommonException u : UserCommonException.values()){ System.out.println(u + ": UserCommonException =" + u.getCommonException()); } } } }<file_sep>-- 秒杀执行存储过程 DELIMITER $$ -- console; 转换为 $$ -- 定义存储过程 -- 参数:in 输入参数;out 输出参数 -- row_count()返回上一条修改类型sql(delete、insert、update)的影响行数 -- row_count():0未修改数据 >0表示修改的行数 <0sql错误或者未执行sql CREATE PROCEDURE `jeesite`.`execute_seckill`( IN v_seckill_id BIGINT , IN v_phone BIGINT , IN v_kill_time TIMESTAMP , OUT r_result INT ) BEGIN DECLARE insert_count int DEFAULT 0 ; START TRANSACTION ; INSERT IGNORE INTO success_killed(seckill_id ,user_phone ,create_time) VALUES(v_seckill_id ,v_phone ,v_kill_time); SELECT ROW_COUNT() INTO insert_count; IF(insert_count = 0) THEN ROLLBACK; SET r_result = 0; ELSEIF(insert_count < 0) THEN ROLLBACK; SET r_result = -1; ELSE UPDATE seckill SET number = number -1 WHERE seckill_id = v_seckill_id AND (v_kill_time BETWEEN start_time AND end_time) AND number > 0; SELECT ROW_COUNT() INTO insert_count ; IF(insert_count = 0) THEN ROLLBACK; SET r_result = 0; ELSEIF(insert_count < 0) THEN ROLLBACK; SET r_result = -1; ELSE COMMIT; SET r_result = 1; END IF; END IF; END $$ -- 储存过程结束 show create procedure execute_seckill DELIMITER ; set @r_result=-3; call execute_seckill(1001,13502178891,now(),@r_result); SELECT @r_result; --储存过程优化:事务行级锁持有的时间<file_sep>package com.thinkgem.jeesite.common.pattern.singleton; /** * 懒汉单例模式 * 写法简单,适合简单、小的对象创建; * 当创建一个非常复杂、非常大I/O操作、非常耗内存的对象时,不宜采用; * @Author duhongming * @Email <EMAIL> * @Date 2018/6/28 16:56 */ public class LazySingletonPattern { //方法1 声明为常量 private static final LazySingletonPattern instance = new LazySingletonPattern(); //方法2 静态代码块 /*private static LazySingletonPattern instance = null; static{ instance = new LazySingletonPattern(); }*/ //构造方法私有 private LazySingletonPattern(){} public static LazySingletonPattern getInstance() { return instance; } }<file_sep>package com.thinkgem.jeesite.common.security.shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.subject.Subject; import org.junit.Test; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/4/14 15:59 * 认证 */ public class IniRealmTest { private static final IniRealm iniRealm = new IniRealm("classpath:user.ini"); @Test public void testAuthentication() { //1. 构建SecurityManager环境 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); defaultSecurityManager.setRealm(iniRealm); //2. 主体提交认证请求 SecurityUtils.setSecurityManager(defaultSecurityManager); Subject subject = SecurityUtils.getSubject(); //3. 登录 UsernamePasswordToken token = new UsernamePasswordToken("Mark","<PASSWORD>"); subject.login(token); System.out.println("isAuthenticated : " + subject.isAuthenticated()); //4. 授权 subject.checkRole("admin"); subject.checkPermissions("user:delete","user:update"); } } <file_sep>package com.thinkgem.jeesite.common.pattern.pattern2; import lombok.ToString; /** * @Author duhongming * @Email <EMAIL> * @Date 2019-04-24 21:04 */ @ToString public class StatisticsDisplay implements Observer,DisplayElement{ private float temperature; private float humidity; private float pressure; private WeatherData weatherData; public StatisticsDisplay(Subject weatherData){ weatherData.registerObserver(this); } @Override public void update(float temperature,float humidity,float pressure){ this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; display(); } @Override public void update(Subject subject){ if(subject instanceof WeatherData){ weatherData = (WeatherData)subject; } this.temperature = weatherData.getTemperature(); this.humidity = weatherData.getHumidity(); this.pressure = weatherData.getPressure(); display(); } @Override public void display() { System.out.println("StatisticsDisplay = " + toString()); } } <file_sep>package com.thinkgem.jeesite.common.security.encrypt.util; import com.thinkgem.jeesite.common.security.encrypt.enums.EnumAuthCodeAlgorithm; import com.thinkgem.jeesite.common.utils.NumberUtil; import lombok.extern.slf4j.Slf4j; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/8/16 9:30 */ @Slf4j public class MessageAuthCodeUtil { public static byte[] encode(EnumAuthCodeAlgorithm authCodeAlgorithm,byte[] byteData, byte[] keyData) throws NoSuchAlgorithmException, InvalidKeyException { Mac mac = Mac.getInstance(authCodeAlgorithm.name()); SecretKey secretKey = new SecretKeySpec(keyData, authCodeAlgorithm.name()); mac.init(secretKey); return mac.doFinal(byteData); } public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException { String dataString = "ZGL"; for (EnumAuthCodeAlgorithm authCodeAlgorithm : EnumAuthCodeAlgorithm.values()){ log.info(authCodeAlgorithm.getValue()); SecretKey secretKey = KeyUtil.generateKey(authCodeAlgorithm); log.info("消息验证码的密钥: {}", NumberUtil.bytesToStrHex(secretKey.getEncoded())); byte[] mac = encode(authCodeAlgorithm,dataString.getBytes(),secretKey.getEncoded()); log.info("消息验证码后数据: {}", NumberUtil.bytesToStrHex(mac)); } log.info("前后台通用HmacMD5消息验证码: {}",NumberUtil.bytesToStrHex(encode(EnumAuthCodeAlgorithm.HmacMD5, "消息摘要".getBytes(),"HmacMD5".getBytes()))); log.info("前后台通用HmacSHA256消息验证码: {}",NumberUtil.bytesToStrHex(encode(EnumAuthCodeAlgorithm.HmacSHA256, "消息摘要".getBytes(),"HmacSHA256".getBytes()))); } }<file_sep>package com.thinkgem.jeesite.common.pattern.strategy_plus.behavior; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/5/2 20:27 * @Description 封装飞行行为接口 */ public interface FlyBehavior { /** * 飞行行为 */ void fly(); } <file_sep>package com.thinkgem.jeesite.common.security.shiro; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.Md5Hash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/4/14 16:45 */ public class CustomRealm extends AuthorizingRealm { //用户 public static final Map<String,String> USERS = new HashMap<>(); //角色 public static final Set<String> ROLES = new HashSet<>(); //权限 public static final Set<String> PERMISSIONS = new HashSet<>(); { USERS.put("Mark","283538989cef48f3d7d8a1c1bdf2008f"); ROLES.add("admin"); PERMISSIONS.add("user:delete"); PERMISSIONS.add("user:update"); } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName = (String)token.getPrincipal(); if(USERS.get(userName) == null){ return null; } SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName,USERS.get(userName),"customRealm"); simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("Mark")); return simpleAuthenticationInfo; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String userName = (String)principals.getPrimaryPrincipal(); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); simpleAuthorizationInfo.setRoles(ROLES); simpleAuthorizationInfo.setStringPermissions(PERMISSIONS); return simpleAuthorizationInfo; } public static void main(String[] args) { Md5Hash md5Hash = new Md5Hash("123456"); System.out.println("md5Hash = " + md5Hash); md5Hash = new Md5Hash("123456","Mark"); System.out.println("md5Hash salt = " + md5Hash); } } <file_sep>package com.thinkgem.jeesite.common.pattern.chain; import static org.junit.Assert.*; public class HandlerProcessorTest { public static void main(String[] args) { HandlerProcessor handlerProcessor = new HandlerProcessor(); handlerProcessor.addHandler(new ComplainHandler()) .addHandler(new FanHandler()) .addHandler(new NewLocHandler()) .addHandler(new SpamHandler()).handleRequest(" email test"); } }<file_sep>package com.thinkgem.jeesite.common.enumdemo; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/8/31 15:50 */ public class CommonExceptionsTest { public static void main(String[] args) { CommonExceptions.UserCommonException.show(); throw CommonExceptions.UserCommonException.CUST_NOT_REGISTER.getCommonException(); } }<file_sep>package com.thinkgem.jeesite.common.security.encrypt.util; import com.thinkgem.jeesite.common.security.encrypt.enums.EnumSignatureAlgorithm; import com.thinkgem.jeesite.common.utils.NumberUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * 数字证书工具类 * @author ZGL * */ public class DigitalSignatureUtil { /** * 私钥签名 * @param signatureAlgorithm 签名算法 * @param strHexPrivateKey 16进制字符串私钥 * @param byteData * @return * @throws Exception */ public static byte[] sign(EnumSignatureAlgorithm signatureAlgorithm, String strHexPrivateKey, byte[] byteData) throws Exception{ return sign(signatureAlgorithm, NumberUtil.strHexToBytes(strHexPrivateKey), byteData); } /** * 私钥签名 * @param signatureAlgorithm 签名算法 * @param bytePrivateKey 二进制私钥 * @param byteData 待签名数据 * @return * @throws Exception */ public static byte[] sign(EnumSignatureAlgorithm signatureAlgorithm,byte[] bytePrivateKey,byte[] byteData) throws Exception{ Security.addProvider(new BouncyCastleProvider()); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(bytePrivateKey); KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgorithm.getKeyAlgorithm().name()); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); return sign(signatureAlgorithm, privateKey, byteData); } /** * 私钥签名 * @param signatureAlgorithm 签名算法 * @param privateKey 私钥 * @param byteData 待签名数据 * @return * @throws Exception */ public static byte[] sign(EnumSignatureAlgorithm signatureAlgorithm,PrivateKey privateKey,byte[] byteData) throws Exception{ Security.addProvider(new BouncyCastleProvider()); Signature signature = Signature.getInstance(signatureAlgorithm.name()); signature.initSign(privateKey); signature.update(byteData); return signature.sign(); } /** * 公钥校验签名 * @param signatureAlgorithm * @param strHexPublicKey 16进制字符串公钥 * @param byteData 源数据 * @param byteSign 签名 * @return * @throws Exception */ public static boolean verify(EnumSignatureAlgorithm signatureAlgorithm,String strHexPublicKey,byte[] byteData,byte[] byteSign) throws Exception { return verify(signatureAlgorithm, NumberUtil.strHexToBytes(strHexPublicKey), byteData, byteSign); } /** * 公钥校验签名 * @param signatureAlgorithm 签名算法 * @param bytePublicKey 二进制公钥 * @param byteData 源数据 * @param byteSign 签名 * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static boolean verify(EnumSignatureAlgorithm signatureAlgorithm,byte[] bytePublicKey,byte[] byteData,byte[] byteSign) throws Exception { Security.addProvider(new BouncyCastleProvider()); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytePublicKey); KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgorithm.getKeyAlgorithm().name()); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); return verify(signatureAlgorithm, publicKey, byteData, byteSign); } /** * 公钥校验签名 * @param signatureAlgorithm 签名算法 * @param publicKey 公钥 * @param byteData 源数据 * @param byteSign 签名 * @return * @throws Exception */ public static boolean verify(EnumSignatureAlgorithm signatureAlgorithm,PublicKey publicKey,byte[] byteData,byte[] byteSign) throws Exception { Security.addProvider(new BouncyCastleProvider()); Signature signature = Signature.getInstance(signatureAlgorithm.name()); signature.initVerify(publicKey); signature.update(byteData); return signature.verify(byteSign); } public static void main(String[] args) throws Exception { String dataString = "ZGL"; for (EnumSignatureAlgorithm signatureAlgorithm : EnumSignatureAlgorithm.values()) { System.out.println(signatureAlgorithm.name()); KeyPair keyPair = KeyUtil.generateKeyPair(signatureAlgorithm.getKeyAlgorithm(), null); byte[] byteSign = sign(signatureAlgorithm, NumberUtil.bytesToStrHex(keyPair.getPrivate().getEncoded()), dataString.getBytes()); System.out.println("签名: " + NumberUtil.bytesToStrHex(byteSign)); System.out.println("校验结果: "+verify(signatureAlgorithm, keyPair.getPublic().getEncoded(), dataString.getBytes(), byteSign)); System.out.print("\n"); } } } <file_sep># Immutable模式>>>想破坏也破坏不了 ## 标准类库中用到的Immutable模式 ``` 表示字符串的java.lang.String类 表示大数字的java.math.BigInteger类 表示正则表达式模式的java.util.regex.Pattern类 基本类型的包装类(wrapper class)、java.lang.Void ```<file_sep>package com.thinkgem.jeesite.common.pattern.strategy; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/7/25 10:39 */ public class ExecutorRouteLFU implements ExecutorRouteStrategy{ private static ConcurrentHashMap<String,Integer> lfuItemMap = new ConcurrentHashMap<>(); @Override public String selectRouteRun(List<String> addressList) { for(String address:addressList){ if(!lfuItemMap.containsKey(address)){ lfuItemMap.put(address,0); } } List<Map.Entry<String,Integer>> itemList = new ArrayList<>(lfuItemMap.entrySet()); Collections.sort(itemList, Comparator.comparing(Map.Entry::getValue)); Map.Entry<String, Integer> itemMap = itemList.get(0); itemMap.setValue(itemMap.getValue()+1); return itemMap.getKey(); } }<file_sep>package com.thinkgem.jeesite.common.pattern.chain; import java.util.ArrayList; import java.util.List; /** * @author duhongming * @version 1.0 * @description TODO * @date 2019-10-05 13:10 */ public class HandlerProcessor{ private List<Handler> handlers = new ArrayList<>(); public HandlerProcessor addHandler(Handler handler){ handlers.add(handler); return this; } public void handleRequest(String email) { for (Handler handler : handlers) { if(handler.preHandler(email)) { handler.handleRequest(email); } handler.afterHandler(email); } } } <file_sep>package com.thinkgem.jeesite.common.security.encrypt.util; import com.thinkgem.jeesite.common.security.encrypt.enums.EnumDigestAlgorithm; import com.thinkgem.jeesite.common.utils.Exceptions; import com.thinkgem.jeesite.common.utils.NumberUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.io.*; import java.security.*; /** * 消息摘要工具类 * @author ZGL * */ @Slf4j public class MessageDigestUtil { private static SecureRandom random = new SecureRandom(); public static byte[] encode(EnumDigestAlgorithm digestAlgorithm, byte[] byteData) throws NoSuchAlgorithmException{ Security.addProvider(new BouncyCastleProvider()); return MessageDigest.getInstance(digestAlgorithm.name()).digest(byteData); } public static byte[] encodeWithSalt(EnumDigestAlgorithm digestAlgorithm, byte[] byteData, byte[] salt) throws NoSuchAlgorithmException{ Security.addProvider(new BouncyCastleProvider()); return MessageDigest.getInstance(digestAlgorithm.name()).digest(byteData); } public static byte[] encodeWithSaltIterations(EnumDigestAlgorithm digestAlgorithm, byte[] byteData, byte[] salt, int iterations){ try{ Security.addProvider(new BouncyCastleProvider()); MessageDigest digest = MessageDigest.getInstance(digestAlgorithm.name()); if (salt != null) { digest.update(salt); } byte[] result = digest.digest(byteData); for (int i = 1; i < iterations; i++) { digest.reset(); result = digest.digest(result); } return result; } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 生成随机的Byte[]作为salt. * * @param numBytes byte数组的大小 */ public static byte[] generateSalt(int numBytes) { Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes); byte[] bytes = new byte[numBytes]; random.nextBytes(bytes); return bytes; } public static void main(String[] args) throws NoSuchAlgorithmException, IOException { String dataString = "ZGL"; /** * * MD是消息摘要(Message Digest),它们都不安全了。 * SHA-1已经不安全了,SHA-2还尚未被攻破。 */ for (EnumDigestAlgorithm digestAlgorithm : EnumDigestAlgorithm.values()) { byte[] md = encode(digestAlgorithm, dataString.getBytes()); log.info("{},文本摘要信息: {}", digestAlgorithm.getValue(), NumberUtil.bytesToStrHex(md)); } log.info("前后台通用MD5摘要信息: {}",NumberUtil.bytesToStrHex(encode(EnumDigestAlgorithm.MD5, "消息摘要".getBytes()))); log.info("前后台通用SHA256摘要信息: {}",NumberUtil.bytesToStrHex(encode(EnumDigestAlgorithm.SHA256, "消息摘要".getBytes()))); byte[] bytes = new MessageDigestUtil().inputStream2ByteArray("E:\\personal-software-auto\\Hadoop\\1.Hadoop\\hadoop-3.1.1.tar.gz"); //文件指纹,参见文件hadoop-3.1.1.tar.gz.mds.txt for (EnumDigestAlgorithm digestAlgorithm : EnumDigestAlgorithm.values()) { byte[] md = encode(digestAlgorithm,bytes); log.info("{},文件摘要信息: {}", digestAlgorithm.getValue(),NumberUtil.bytesToStrHex(md)); } } private byte[] inputStream2ByteArray(String filePath) throws IOException { InputStream in = new FileInputStream(filePath); byte[] data = toByteArray(in); in.close(); return data; } private byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n = 0; while ((n = in.read(buffer)) != -1) { out.write(buffer, 0, n); } return out.toByteArray(); } } <file_sep>[users] Mark=123456,admin [roles] admin=user:delete,user:update<file_sep>package com.thinkgem.jeesite.common.pattern.pattern2; /** * @Author duhongming * @Email <EMAIL> * @Date 2019-04-24 21:43 */ public interface DisplayElement { void display(); } <file_sep>package com.thinkgem.jeesite.common.security.encrypt.util; import com.thinkgem.jeesite.common.security.encrypt.enums.EnumCipherAlgorithm; import com.thinkgem.jeesite.common.security.encrypt.enums.EnumKeyAlgorithm; import com.thinkgem.jeesite.common.utils.NumberUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * 加解密工具类 * * @author ZGL * */ @Slf4j public class CipherUtil { /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrypt(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return encrypt(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrypt(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case DSA: case ElGamal: { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e) { try { // 尝试获取私钥 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return encrypt(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteData 待解密数据 * @param key 钥匙 * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws Exception */ public static byte[] encrypt(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return decrypt(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case DSA: case ElGamal: { try { // 尝试获取私钥 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e) { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return decrypt(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param key 钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(byteData); } /** * JS、JAVA通用:DES加密 * @param key * @param plaintext * @return */ public static String encodeDES(String key,String plaintext){ try{ SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.DES.name()); //现在,获取数据并加密 byte[] e = encrypt(EnumCipherAlgorithm.DES_ECB_PKCS5Padding,keyspec.getEncoded(),plaintext.getBytes()); //现在,获取数据并编码 byte[] temp = Base64.encodeBase64(e); return IOUtils.toString(temp,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * JS、JAVA通用:DESede加密 * @param key * @param plaintext * @return */ public static String encodeDESede(String key,String plaintext){ try{ SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.DESede.name()); //现在,获取数据并加密 byte[] e = encrypt(EnumCipherAlgorithm.DESede_ECB_PKCS5Padding,keyspec.getEncoded(),plaintext.getBytes()); //现在,获取数据并编码 byte[] temp = Base64.encodeBase64(e); return IOUtils.toString(temp,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * JS、JAVA通用:AES加密 * @param key * @param plaintext * @return */ public static String encodeAES(String key,String plaintext){ try{ SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.AES.name()); //现在,获取数据并加密 byte[] e = encrypt(EnumCipherAlgorithm.AES_ECB_PKCS5Padding,keyspec.getEncoded(),plaintext.getBytes()); //现在,获取数据并编码 byte[] temp = Base64.encodeBase64(e); return IOUtils.toString(temp,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * JS、JAVA通用:DES解密 * @param key * @param ciphertext * @return * @throws Exception */ public static String decodeDES(String key,String ciphertext) { try { SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.DES.name()); // 真正开始解码操作 byte[] temp = Base64.decodeBase64(ciphertext); // 真正开始解密操作 byte[] e = decrypt(EnumCipherAlgorithm.DES_ECB_PKCS5Padding,keyspec.getEncoded(),temp); return IOUtils.toString(e,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * JS、JAVA通用:DESede解密 * @param key * @param ciphertext * @return * @throws Exception */ public static String decodeDESede(String key,String ciphertext) { try { SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.DESede.name()); // 真正开始解码操作 byte[] temp = Base64.decodeBase64(ciphertext); // 真正开始解密操作 byte[] e = decrypt(EnumCipherAlgorithm.DESede_ECB_PKCS5Padding,keyspec.getEncoded(),temp); return IOUtils.toString(e,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * JS、JAVA通用:AES解密 * @param key * @param ciphertext * @return * @throws Exception */ public static String decodeAES(String key,String ciphertext) { try { SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), EnumKeyAlgorithm.AES.name()); // 真正开始解码操作 byte[] temp = Base64.decodeBase64(ciphertext); // 真正开始解密操作 byte[] e = decrypt(EnumCipherAlgorithm.AES_ECB_PKCS5Padding,keyspec.getEncoded(),temp); return IOUtils.toString(e,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { try { String dataString = "ZGL"; for (EnumCipherAlgorithm cipherAlgorithm : EnumCipherAlgorithm.values()) { log.info(cipherAlgorithm.getValue()); if(EnumKeyAlgorithm.getSymmetric().contains(cipherAlgorithm.getKeyAlgorithm())){ /** * 对称密码(共享密钥密码)- 用相同的密钥进行加密和解密 * DES(data encryption standard)- 淘汰 * 3DES(triple DES)- 目前被银行机构使用 * AES(advanced encryption standard)- 方向 * IDEA用于邮件加密,避开美国法律限制 – 国产 */ SecretKey secretKey = KeyUtil.generateKey(cipherAlgorithm.getKeyAlgorithm(), null); log.info("对称加密的密钥: {}", NumberUtil.bytesToStrHex(secretKey.getEncoded())); byte[] e = encrypt(cipherAlgorithm,NumberUtil.bytesToStrHex(secretKey.getEncoded()), dataString.getBytes()); log.info("对称加密后数据: {}", NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, secretKey.getEncoded(), e); log.info("对称解密后数据: {}", new String(d)); }else{ /** * 公钥密码(非对称密码) - 用公钥加密,用私钥解密 * RSA */ KeyPair keyPair = KeyUtil.generateKeyPair(cipherAlgorithm.getKeyAlgorithm(), null); log.info("非对称加密的公钥: {}\n非对称加密的私钥: {}", NumberUtil.bytesToStrHex(keyPair.getPublic().getEncoded()), NumberUtil.bytesToStrHex(keyPair.getPrivate().getEncoded())); byte[] e = encrypt(cipherAlgorithm, keyPair.getPublic().getEncoded(),dataString.getBytes()); log.info("非对称加密后数据: {}", NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, keyPair.getPrivate().getEncoded(), e); log.info("非对称解密后数据: {}", new String(d)); } } } catch (Exception e) { e.printStackTrace(); } //DES的key长度为8位的字符串,否则会报错 log.info("前后台通用DES对称加密:{}",encodeDES("des@enc@","我有一个消息")); log.info("前后台通用DES对称解密:{}",decodeDES("des@enc@","06tpmY+9V9mPI6AaHXO+IgeLDlDkWUbN")); //DESede的key长度为16位的字符串,否则会报错 log.info("前后台通用DESede对称加密:{}",encodeDESede("@desede@encrypt@","我有一个消息")); log.info("前后台通用DESede对称解密:{}",decodeDESede("@desede@encrypt@","iYLomPjfeaoRdolL3kVdVM8I0zZuZyHk")); //AES的key长度为16位的字符串,否则会报错 log.info("前后台通用AES对称加密:{}",encodeAES("aes@encrypt@key@","我有一个消息")); log.info("前后台通用AES对称解密:{}",decodeAES("aes@encrypt@key@","<KEY>)); //RSA每次加密后的数据都不一样 String e = encryptRSA("我有一个消息"); log.info("前后台通用RSA非对称加密: {}", e); String d = decryptRSA(e); log.info("前后台通用RSA非对称解密: {}", d); } /** * 从字符串中加载公钥 * @return * @throws Exception 加载公钥时产生的异常 */ private static RSAPublicKey loadPublicKeyByStr() throws Exception { String publicKey = "<KEY>"; try { KeyFactory keyFactory = KeyFactory.getInstance(EnumCipherAlgorithm.RSA_ECB_PKCS1Padding.getKeyAlgorithm().name()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey)); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("无此算法"); } catch (InvalidKeySpecException e) { throw new Exception("公钥非法"); } catch (NullPointerException e) { throw new Exception("公钥数据为空"); } } /** * 从字符串中加载私钥 * @return * @throws Exception */ public static RSAPrivateKey loadPrivateKeyByStr() throws Exception { String privateKey = "<KEY>"; try { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey.getBytes())); KeyFactory keyFactory = KeyFactory.getInstance(EnumCipherAlgorithm.RSA_ECB_PKCS1Padding.getKeyAlgorithm().name()); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("无此算法"); } catch (InvalidKeySpecException e) { throw new Exception("私钥非法"); } catch (NullPointerException e) { throw new Exception("私钥数据为空"); } } /** * 公钥加密过程 * @param plainTextData 明文数据 * @return * @throws Exception 加密过程中的异常信息 */ public static String encryptRSA(String plainTextData) throws Exception { Cipher cipher = null; try { // 使用默认RSA cipher = Cipher.getInstance(EnumCipherAlgorithm.RSA_ECB_PKCS1Padding.getKeyAlgorithm().name()); // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, loadPublicKeyByStr()); byte[] byteContent = plainTextData.getBytes("utf-8"); byte[] output = cipher.doFinal(byteContent); return new String(Base64.encodeBase64(output)); } catch (NoSuchAlgorithmException e) { throw new Exception("无此加密算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("加密公钥非法,请检查"); } catch (IllegalBlockSizeException e) { throw new Exception("明文长度非法"); } catch (BadPaddingException e) { throw new Exception("明文数据已损坏"); } } /** * 私钥解密过程 * @param cipherData 密文数据 * @return 明文 * @throws Exception 解密过程中的异常信息 */ public static String decryptRSA(String cipherData) throws Exception { Cipher cipher = null; try { // 使用默认RSA cipher = Cipher.getInstance(EnumCipherAlgorithm.RSA_ECB_PKCS1Padding.getKeyAlgorithm().name()); cipher.init(Cipher.DECRYPT_MODE, loadPrivateKeyByStr()); byte[] byteContent = Base64.decodeBase64(cipherData.getBytes()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteContent.length; i += 128) { byte[] subarray = ArrayUtils.subarray(byteContent, i, i + 128); byte[] doFinal = cipher.doFinal(subarray); sb.append(new String(doFinal, "utf-8")); } // byte[] output = cipher.doFinal(byteContent); String strDate = sb.toString(); return strDate; } catch (NoSuchAlgorithmException e) { throw new Exception("无此解密算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("解密私钥非法,请检查"); } catch (IllegalBlockSizeException e) { e.printStackTrace(); throw new Exception("密文长度非法"); } catch (BadPaddingException e) { throw new Exception("密文数据已损坏"); } } } <file_sep>package com.thinkgem.jeesite.common.security.encrypt.enums; public enum EnumDigestAlgorithm { MD2("MD2"), MD4("MD4"), MD5("MD5"), SHA1("SHA-1"), SHA224("SHA-224"), SHA256("SHA-256"), SHA384("SHA-384"), SHA512("SHA-512"),; private String value; public String getValue() { return value; } EnumDigestAlgorithm(String value){ this.value = value; } } <file_sep>package com.thinkgem.jeesite.common.enumdemo; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/8/31 15:16 */ public class CommonException extends RuntimeException { protected int errorCode; protected String errorInfo; public CommonException(int errorCode,String errorInfo){ this.errorCode=errorCode; this.errorInfo=errorInfo; } @Override public String toString() { return "CommonException{" + "errorCode=" + errorCode + ", errorInfo='" + errorInfo + '\'' + '}'; } }<file_sep>package com.thinkgem.jeesite.common.enumdemo; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/7/19 15:37 */ public class OrganizationType { /** * 组织机构类型 */ public enum TYPE{ TYPE_QY(1,"企业"), TYPE_DW(2,"单位"), TYPE_BM(3,"部门"); private Integer key; private String value; TYPE(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(TYPE v : TYPE.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } /** * 根节点标识 */ public enum ROOT_OU{ ROOT_OU_ELECCAR(1,"电动汽车"), ROOT_OU_CORPUSER(2,"企业用户"), ROOT_OU_ELEC_MERCHANT(3,"国网商户"), ROOT_OU_COMMON_MERCHANT(4,"社会商户"), ROOT_OU_PER_MERCHANT(5,"个人商户"); private Integer key; private String value; ROOT_OU(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(ROOT_OU v : ROOT_OU.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } /** * 注册渠道 */ public enum ZQ{ ZQ_XT(1,"系统"), ZQ_YYT(2,"营业厅"), ZQ_WZ(3,"网站"), ZQ_SJAPP(4,"手机app"), ZQ_WX(5,"微信"); private Integer key; private String value; ZQ(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(ZQ v : ZQ.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } /** * 机构状态 */ public enum STATE{ STATE_ZC(1,"正常"), STATE_DJ(2,"冻结"), STATE_XH(3,"销户"), STATE_LJSC(4,"逻辑删除"); private Integer key; private String value; STATE(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(STATE v : STATE.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } /** * 机构性质 */ public enum OU_PROP{ OU_PROP_DDGS_ZB(12,"电动汽车公司总部"), OU_PROP_DDGS_SGS(13,"电动汽车省公司"), OU_PROP_DDGS_DS(14,"电动汽车地市公司"), OU_PROP_DDGS_YYT(15,"电动汽车公司营业厅"), OU_PROP_QY(21,"企业"), OU_PROP_QY_XS(22,"企业下属单位"), OU_PROP_DW_ZB(31,"国家电网公司"), OU_PROP_DW_SGS(32,"省电网公司"), OU_PROP_DW_DS(33,"地市电力公司"), OU_PROP_DW_XGS(34,"区县电力公司"), OU_PROP_DW_GDS(35,"供电所"), OU_PROP_SHQY(41,"社会商户"), OU_PROP_SHQY_XS(42,"社会商户下属单位"), OU_PROP_GR(50,"个人商户"); private Integer key; private String value; OU_PROP(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(OU_PROP v : OU_PROP.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } /** * 叶子节点 */ public enum OU_IS_LEAF{ OU_IS_LEAF_TRUE(1,"叶子节点"), OU_IS_LEAF_FALSE(0,"不是叶子节点"); private Integer key; private String value; OU_IS_LEAF(Integer key, String value) { this.key = key; this.value = value; } public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void show(){ for(OU_IS_LEAF v : OU_IS_LEAF.values()){ System.out.println(v + ": key=" + v.getKey() + " value=" + v.getValue()); } } } }<file_sep>package com.thinkgem.jeesite.common.pattern.strategy; import com.thinkgem.jeesite.common.utils.StringUtils; import org.apache.commons.collections.CollectionUtils; import java.util.List; import java.util.Random; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/7/26 23:52 */ public class ExecutorRouteRandom implements ExecutorRouteStrategy { private Random random = new Random(); @Override public String selectRouteRun(List<String> addressList) { if(CollectionUtils.isNotEmpty(addressList)){ return addressList.get(random.nextInt(addressList.size())); } return StringUtils.EMPTY; } }<file_sep>package com.thinkgem.jeesite.common.security.encrypt.enums; public enum EnumKeyStoreType { JKS("JKS"),PKCS12("PKCS12"); private String value; public String getValue() { return value; } private EnumKeyStoreType(String value){ this.value = value; } } <file_sep>#Single Threaded Execution模式>>>能通过这座桥的只有一个人 ## 标准类库中用到的Single Threaded Execution模式 ``` import java.util.Collections; Collections.synchronizedCollection(); Collections.synchronizedList(); Collections.synchronizedMap(); Collections.synchronizedSet(); Collections.synchronizedSortedMap(); Collections.synchronizedSortedSet(); ``` ## Before/After模式 ``` private final Mutex mutex = new Mutex(); mutex.lock(); try{ unsafeMethod(); }finally { mutex.unlock(); } ```<file_sep>package com.thinkgem.jeesite.common.pattern.strategy; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.List; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/7/25 10:36 * 总是执行最后一个 */ public class ExecutorRouteLast implements ExecutorRouteStrategy { @Override public String selectRouteRun(List<String> addressList) { if(CollectionUtils.isNotEmpty(addressList)){ return addressList.get(addressList.size()-1); } return StringUtils.EMPTY; } }<file_sep>package com.thinkgem.jeesite.common.pattern.chain; /** * @author duhongming * @version 1.0 * @description TODO * @date 2019-10-05 13:07 */ public class SpamHandler implements Handler { @Override public boolean preHandler(String email) { return false; } @Override public void handleRequest(String email) { System.out.println("SpamHandler" + email); } @Override public void afterHandler(String email) { } } <file_sep>package com.thinkgem.jeesite.common.pattern.prototype; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/6/19 10:03 */ public class PrototypeSerializableObject extends SerializableObject{ private String aaa; private int bbb; private double ccc; public PrototypeSerializableObject(String aaa, int bbb, double ccc) { this.aaa = aaa; this.bbb = bbb; this.ccc = ccc; } public String getAaa() { return aaa; } public void setAaa(String aaa) { this.aaa = aaa; } public int getBbb() { return bbb; } public void setBbb(int bbb) { this.bbb = bbb; } public double getCcc() { return ccc; } public void setCcc(double ccc) { this.ccc = ccc; } }<file_sep>package com.thinkgem.jeesite.multithread.guarded_suspension; /** * @Author duhongming * @Email <EMAIL> * @Date 2019-05-12 15:56 */ public class Main { public static void main(String[] args) { RequestQueue requestQueue = new RequestQueue(); new ClientThread(3141592L,requestQueue, "Alice").start(); new ServerThread(6535897L, requestQueue, "Bobby").start(); } } <file_sep># Guarded Suspension模式>>>等我准备好哦 ## 阻塞队列 ``` //非线程安全的队列 private final Queue<Request> queue = new LinkedList<>(); //线程安全的队列 private final BlockingDeque<Request> queue = new LinkedBlockingDeque<>(); ```<file_sep>package com.thinkgem.jeesite.common.pattern.chain; /** * @author duhongming * @version 1.0 * @description TODO * @date 2019-10-05 13:09 */ public class ComplainHandler implements Handler { @Override public boolean preHandler(String email) { return true; } @Override public void handleRequest(String email) { System.out.println("ComplainHandler" + email); } @Override public void afterHandler(String email) { } } <file_sep>package com.thinkgem.jeesite.common.pattern.prototype; import java.io.*; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/6/19 10:00 * * 抽象类:InputStream/OutputStream * 文件流类:FileInputStream/FileOutputStream * 字节数字流类:ByteArrayInputStream/ByteArrayOutputStream * 对象流类:ObjectInputStream/ObjectOutputStream * 管道流类:PipedInputStream/PipedOutputStream */ public class PrototypePattern implements Cloneable,Serializable { private static final long serialVersionUID = 1L; private String string; private SerializableObject obj; /* 浅复制 */ public PrototypePattern clone() throws CloneNotSupportedException { return (PrototypePattern) super.clone(); } /* 深复制 */ public PrototypePattern deepClone(){ PrototypePattern prototype = null; //使用try-resource的方式来自动关闭资源,没有必要再手动调用一次close /* 写入当前对象的二进制流 */ try( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream) ) { objectOutputStream.writeObject(this); /* 读出二进制流产生的新对象 */ try( ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream) ){ return (PrototypePattern) objectInputStream.readObject(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return prototype; } /* 文件复制 */ public PrototypePattern fileClone(){ PrototypePattern prototype = null; //使用try-resource的方式来自动关闭资源,没有必要再手动调用一次close try( FileOutputStream fileOutputStream = new FileOutputStream("PrototypePattern.dat"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream) ){ objectOutputStream.writeObject(this); try( FileInputStream fileInputStream = new FileInputStream("PrototypePattern.dat"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream) ){ prototype = (PrototypePattern)objectInputStream.readObject(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return prototype; } /** * 管道复制 * * PipedInputStream,管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。 * 通常,数据由某个线程从PipedInputStream 对象读取, 并由其他线程将其写入到相应的 PipedOutputStream。 * 不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的 范 围内将读操作和写操作分离开。 * 如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。 * * PipedOutputStream,可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。 * 通常,数据由某个线程写入PipedOutputStream 对象,并由 其他线程从连接的PipedInputStream 读取。 * 不建议对这两个对象尝试使用单个线程,因为这样可能会造成该线程死锁。 * 如果某个线程正从连接的管道输入流中读取数据字节,但该线程不再处于活动状态,则该管道被视为处于毁坏状态。 * * 通过官方API的两段解释,大概能摸到这种实现方式的设计思路了:PipedOutputStream(生产者)生产数据,PipedInputStream(消费者)读取数据,二者同步进行。 * 但谁也不能先挂掉,一旦挂掉,管道便处于损坏状态。 * * @return */ public PrototypePattern pipeClone(){ final PrototypePattern[] prototype = {null}; try { PipedOutputStream pipedOutputStream = new PipedOutputStream(); PipedInputStream pipedInputStream = new PipedInputStream(); //将管道输出流连接到管道输入流来创建通信管道 pipedOutputStream.connect(pipedInputStream); //创建生产者线程来为管道输出流写入数据. new Thread(() -> { try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream); objectOutputStream.writeObject(this); } catch (IOException e) { e.printStackTrace(); } }).start(); //创建消费者线程来从 PipedInputStream对象读取数据 Thread consumer = new Thread(()->{ try { ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream); prototype[0] = (PrototypePattern)objectInputStream.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }); consumer.start(); //勿必等所有数据读完才继续后面的操作,否则可能造成数据仍未读完便GameOver了. consumer.join(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return prototype[0]; } public String getString() { return string; } public void setString(String string) { this.string = string; } public SerializableObject getObj() { return obj; } public void setObj(SerializableObject obj) { this.obj = obj; } } class SerializableObject implements Serializable { private static final long serialVersionUID = 1L; }<file_sep>package com.thinkgem.jeesite.common.pattern.strategy; /** * @Author duhongming * @Email <EMAIL> * @Date 2018/7/26 18:18 */ public enum ExecutorRouteStrategyEnum { FIRST("第一个",new ExecutorRouteFirst()), LAST("最后一个",new ExecutorRouteLast()), LFU("最不经常使用",new ExecutorRouteLFU()), LRU("最近最久未使用",new ExecutorRouteLRU()), RANDOM("随机",new ExecutorRouteRandom()), ROUND("轮询",new ExecutorRouteRound()), BUSYOVER("繁忙转移",new ExecutorRouteBusyover()), FAILOVER("故障转移",new ExecutorRouteFailover()); private String title; private ExecutorRouteStrategy routeStrategy; ExecutorRouteStrategyEnum(String title,ExecutorRouteStrategy routeStrategy){ this.title = title; this.routeStrategy = routeStrategy; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public ExecutorRouteStrategy getRouteStrategy() { return routeStrategy; } public void setRouteStrategy(ExecutorRouteStrategy routeStrategy) { this.routeStrategy = routeStrategy; } }<file_sep>package com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.impl; import com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.FlyBehavior; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/5/2 20:29 * @Description 用翅膀飞 */ public class FlyWithWings implements FlyBehavior { @Override public void fly() { //TODO 实现鸭子飞行 System.out.println("I'm flying!!"); } } <file_sep>package com.thinkgem.jeesite.multithread.single_threaded_execution; /** * @Author duhongming * @Email <EMAIL> * @Date 2019-05-12 14:41 */ public class Main { public static void main(String[] args) { System.out.println("Testing Gate, hit CTRL+C to exit."); Gate gate = new Gate(); new UserThread(gate, "Alice", "Alaska").start(); new UserThread(gate, "Bobby", "Brazil").start(); new UserThread(gate, "Chris", "Canad").start(); } } <file_sep>package com.thinkgem.jeesite.common.pattern.strategy_plus; import com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.impl.FlyWithWings; import com.thinkgem.jeesite.common.pattern.strategy_plus.behavior.impl.Quack; /** * @Author duhongming * @Email <EMAIL> * @Date 2019/5/2 20:33 * @Description 绿头鸭 */ public class MallardDuck extends Duck { public MallardDuck() { super(); super.setFlyBehavior(new FlyWithWings()); super.setQuackBehavior(new Quack()); } @Override public void display() { System.out.println("外观是绿头"); } public static void main(String[] args) { Duck mallardDuck = new MallardDuck(); mallardDuck.performAll(); } }
7db77bc5562d4117f015503a2ef62e3fdaf6e196
[ "Markdown", "Java", "SQL", "INI" ]
36
Java
duhongming1990/jeesite
e4a95079ce18a1ee5b8c187deb2091e665484f6a
3bd05d85e2e518db190baf3e4cd7a2804bcb7202
refs/heads/master
<repo_name>Sakuto/TabsPOC<file_sep>/src/app/tabs/shared/tabs.service.ts import { Injectable } from '@angular/core'; @Injectable() export class TabsService { public myObject; public search(): void { this.myObject = { dea: 'Valeur DEA', iis: 'Valeur IIS', other: 'Autre valeur' }; } } <file_sep>/src/app/tabs/tabs.module.ts import { TabsService } from './shared/tabs.service'; import { TabsRoutingModule } from './tabs-routing.module'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TabsComponent } from './tabs/tabs.component'; import { TabsDeaComponent } from './tabs-dea/tabs-dea.component'; import { TabsIisComponent } from './tabs-iis/tabs-iis.component'; import { TabsOtherComponent } from './tabs-other/tabs-other.component'; @NgModule({ imports: [ CommonModule, TabsRoutingModule ], declarations: [TabsComponent, TabsDeaComponent, TabsIisComponent, TabsOtherComponent], providers: [TabsService] }) export class TabsModule { } <file_sep>/e2e/app.e2e-spec.ts import { PoCAdiilPage } from './app.po'; describe('po-cadiil App', function() { let page: PoCAdiilPage; beforeEach(() => { page = new PoCAdiilPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); }); <file_sep>/src/app/tabs/tabs-other/tabs-other.component.ts import { Component, OnInit } from '@angular/core'; @Component({ templateUrl: './tabs-other.component.html', }) export class TabsOtherComponent { } <file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { TabsService } from './tabs/shared/tabs.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { public constructor(private tabsService: TabsService) {} public search() { this.tabsService.search(); } } <file_sep>/src/app/tabs/tabs-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { TabsComponent } from './tabs/tabs.component'; import { TabsOtherComponent } from './tabs-other/tabs-other.component'; import { TabsIisComponent } from './tabs-iis/tabs-iis.component'; import { TabsDeaComponent } from './tabs-dea/tabs-dea.component'; const appRoutes: Routes = [ { path: 'tabs', component: TabsComponent, pathMatch: 'full' }, { path: 'tabsdea', component: TabsDeaComponent, outlet: 'tabs' }, { path: 'tabsiis', component: TabsIisComponent, outlet: 'tabs' }, { path: 'tabsother', component: TabsOtherComponent, outlet: 'tabs' } ]; /** * Module de routing de l'application * * @export ExampleRoutingModule * @class ExampleRoutingModule */ @NgModule({ exports: [ RouterModule, ], imports: [ RouterModule.forRoot(appRoutes), ], }) export class TabsRoutingModule {}
fffb95f9a384dd1ffb3b5d61be294989130f6cde
[ "TypeScript" ]
6
TypeScript
Sakuto/TabsPOC
c4813cb6a610566eb22562ee55e44914fbb81e15
c9874f97cc0a7c872f6be6403a303eaf461a5802
refs/heads/master
<repo_name>mfountoulakis/hoopify<file_sep>/components/Button.js import React from 'react'; import styled from 'styled-components'; import { space, color } from 'styled-system'; const StyledButton = styled.button(color, space, { fontFamily: 'sans-serif', fontSize: '24px', backgroundColor: 'inherit', }); const Button = props => <StyledButton {...props} />; Button.defaultProps = { color: 'blue', px: [2, 3], }; export default Button; <file_sep>/next.config.js const withOffline = moduleExists('next-offline') ? require('next-offline') : {}; const withManifest = moduleExists('next-manifest') ? require('next-manifest') : {}; const withPlugins = moduleExists('next-compose-plugins') ? require('next-compose-plugins') : {}; const nextConfig = { publicRuntimeConfig: { BASEURL: process.env.BASEURL, }, webpack: (config, { dev }) => { if (dev) { config.module.rules.push({ test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader', options: { // eslint options (if necessary) }, }); } return config; }, }; module.exports = moduleExists('next-offline') && moduleExists('next-compose-plugins') ? withPlugins( [ [ withOffline, { workboxOpts: { swDest: 'static/service-worker.js', runtimeCaching: [ { urlPattern: /^https?.*/, handler: 'networkFirst', options: { cacheName: 'https-calls', networkTimeoutSeconds: 15, expiration: { maxEntries: 150, maxAgeSeconds: 30 * 24 * 60 * 60, // 1 month }, backgroundSync: { name: 'hoopify-sync-queue', options: { maxRetentionTime: 24 * 60, // Retry for max of 24 Hours }, }, cacheableResponse: { statuses: [0, 200], }, }, }, ], }, }, ], ], nextConfig, ) : nextConfig; function moduleExists(name) { try { return require.resolve(name); } catch (error) { return false; } } <file_sep>/lib/theme.js export default { colors: { black: '#000', white: '#fff', gray: '#777', orange: '#FA823F', }, fonts: { pilat: `'Pilat Bold', sans-serif`, pilatExtended: `'Pilat Extended Bold', sans-serif`, }, fontSizes: [10, 13, 18, 32], }; <file_sep>/components/ActiveScore.js import React from 'react'; import PropTypes from 'prop-types'; import { Flex } from '@rebass/grid'; import Text from './Text'; class ActiveScore extends React.Component { render() { const { activeGame = {} } = this.props; return ( <Flex justifyContent="space-between"> <Flex flexDirection={'column'} alignItems={'center'}> <Text fontSize={4}>{activeGame.hTeam.score}</Text> <Text color={'gray'} fontSize={0}> {activeGame.hTeam.triCode} {activeGame.hTeam.record} </Text> </Flex> <Flex flexDirection={'column'} alignItems={'center'}> <Text fontSize={4}>{activeGame.vTeam.score}</Text> <Text color={'gray'} fontSize={0}> {activeGame.vTeam.triCode} {activeGame.vTeam.record} </Text> </Flex> </Flex> ); } } ActiveScore.propTypes = { activeGame: PropTypes.object.isRequired, }; export default ActiveScore; <file_sep>/pages/_app.js import React from 'react'; import App, { Container } from 'next/app'; import { ThemeProvider } from 'styled-components'; import getConfig from 'next/config'; import fetch from 'isomorphic-unfetch'; import { compose, filter, map, prop } from 'lodash/fp'; import GameContext from '../context/GameContext'; import theme from '../lib/theme'; import { View } from '../components/Layout'; export default class MyApp extends App { constructor(props) { super(props); this.state = { favTeam: '', loading: true, }; } static async getInitialProps({ Component, ctx }) { let pageProps = {}; const { publicRuntimeConfig } = getConfig(); const url = `${publicRuntimeConfig.BASEURL}`; const result = await fetch(`${url}/api/today`); const json = await result.json(); if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx); } return { pageProps, games: json.games }; } setFavTeam = favTeam => { return Promise.resolve(localStorage.setItem('favTeam', favTeam)); }; getFavTeam = () => { return Promise.resolve(localStorage.getItem('favTeam')); }; componentDidMount() { const { router } = this.props; if (window.localStorage) { this.getFavTeam().then(favTeam => { !!favTeam && favTeam.length ? this.filterFavorite() : router.push('/teams'); this.setState({ favTeam, loading: false }); }); } if ('serviceWorker' in navigator) { window.addEventListener('beforeinstallprompt', e => { e.preventDefault(); // Prevents prompt display initially this.setState({ promptEvent: e }); }); } } filterFavorite = () => { const { favTeam } = this.state; const { games, router } = this.props; const mapGame = xs => xs.map(xs => { return { id: xs.gameId, matchup: [xs.hTeam.triCode, xs.vTeam.triCode], }; }); const teamPlayingToday = compose( map(prop('id')), filter({ matchup: [favTeam] }), mapGame, ); teamPlayingToday(games).length ? router.push(`/game/${teamPlayingToday(games)}`) : null; }; render() { const { Component, pageProps } = this.props; return ( <Container> <ThemeProvider theme={theme}> <GameContext.Provider value={this.state.favTeam}> <View filterFavorite={this.filterFavorite}> <Component {...pageProps} {...this.props} {...this.state} filterFavorite={this.filterFavorite} setFavTeam={v => this.setState({ favTeam: v }, () => { this.setFavTeam(this.state.favTeam); }) } /> </View> </GameContext.Provider> </ThemeProvider> </Container> ); } } <file_sep>/components/Layout/index.js import React from 'react'; import PropTypes from 'prop-types'; import { Box, Flex } from '@rebass/grid'; import Navigation from '../Navigation'; export const MaxBound = props => <Box px={2} mx={'auto'} {...props} />; const bottomCss = { bottom: '0', flexDirection: 'column', height: '140px', marginTop: '100%', postion: 'fixed', width: '100%', }; export const View = props => { return ( <Box> <MaxBound pt={6}>{props.children}</MaxBound> {props.bottom ? ( <Flex css={bottomCss}>{props.bottom}</Flex> ) : ( <Navigation filterFavorite={props.filterFavorite} /> )} </Box> ); }; View.propTypes = { filterFavorite: PropTypes.func.isRequired, children: PropTypes.node.isRequired, bottom: PropTypes.node, }; <file_sep>/components/ActionButton.js import React from 'react'; import styled from 'styled-components'; import { color, space, fontSize } from 'styled-system'; const StyledActionButton = styled.button(space, fontSize, color, { alignItems: 'center', border: 'none', bottom: '0', display: 'flex', flexDirection: 'column', fontFamily: 'Pilat Extended Bold', height: '140px', position: 'fixed', width: '100%', letterSpacing: '0.05em', }); const ActionButton = props => <StyledActionButton {...props} />; ActionButton.defaultProps = { bg: 'orange', color: 'white', fontSize: 2, pt: 3, }; export default ActionButton; <file_sep>/components/Scoreboard.js import React from 'react'; import PropTypes from 'prop-types'; import { Flex } from '@rebass/grid'; import Text from './Text'; import ActivityIndicator from './ActivityIndicator'; import Logo from './Logo'; /** * TODO: Make the activity indicator smarter, as in, different state * for timeouts and stuff **/ class Scoreboard extends React.Component { render() { const { game } = this.props; return ( <Flex flex={1} justifyContent="space-between"> <Flex alignItems="center"> <Logo mr={3} src={`../static/images/teams/${ game.basicGameData.hTeam.triCode }.svg`} /> <Flex flexDirection="column" alignItems="center"> <Text fontSize={3}>{game.basicGameData.hTeam.score}</Text> <Text caps fontSize={0}> {game.basicGameData.hTeam.triCode} </Text> </Flex> </Flex> <Flex flexDirection="column" alignItems="center"> <Text>{game.basicGameData.time}</Text> <Text caps fontSize={0}>{`Q${ game.basicGameData.period.current }`}</Text> <Text caps fontSize={3}> {game.basicGameData.clock} </Text> <Flex my={2}> <ActivityIndicator gameOn={game.basicGameData.isGameActivated} /> </Flex> </Flex> <Flex alignItems="center"> <Flex flexDirection="column" alignItems="center"> <Text fontSize={3}>{game.basicGameData.vTeam.score}</Text> <Text caps fontSize={0}> {game.basicGameData.vTeam.triCode} </Text> </Flex> <Logo ml={3} src={`../static/images/teams/${ game.basicGameData.vTeam.triCode }.svg`} /> </Flex> </Flex> ); } } Scoreboard.propTypes = { game: PropTypes.object.isRequired, }; export default Scoreboard; <file_sep>/components/Select.js import React from 'react'; import styled from 'styled-components'; import { space } from 'styled-system'; const StyledSelect = styled.select(space, { appearance: 'none', backgroundColor: 'black', backgroundImage: `url("/static/icons/chevron.svg")`, backgroundPosition: 'right 32px top 50%', backgroundRepeat: 'no-repeat', backgroundSize: '14px 8px', border: '2px solid white', color: 'white', display: 'block', fontFamily: 'Pilat Extended Bold', fontSize: '12px', height: '72px', textTransform: 'uppercase', width: '100%', letterSpacing: '0.05em', }); const Select = props => <StyledSelect {...props} />; Select.defaultProps = { px: 3, mb: 3, }; export default Select; <file_sep>/components/Logo.js import React from 'react'; import { Flex } from '@rebass/grid'; const Logo = props => ( <Flex flex="1" css={{ maxWidth: '64px', height: '64px' }} {...props}> <img style={{ objectFit: 'contain' }} src={props.src} /> </Flex> ); export default Logo; <file_sep>/components/Navigation.js import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'next/router'; import styled from 'styled-components'; import { Flex } from '@rebass/grid'; import { Heart, Activity, Settings } from 'react-feather'; import ActionButton from './ActionButton'; import Text from './Text'; import t from '../lib/theme'; const navCSS = { backdropFilter: 'saturate(80%) blur(20px)', background: 'rgba(0, 0, 0, 0.8)', borderTop: '1px solid rgba(255, 255, 255, 0.1)', bottom: '0', height: '122px', position: 'fixed', width: '100%', }; const Tabs = styled(Flex)({ justifyContent: 'space-between', width: '100%', }); const Tab = styled(Flex)({ alignItems: 'center', flexDirection: 'column', fontFamily: 'sans-serif', height: '48px', justifyContent: 'space-between', width: '48px', color: '#fff', }); class Navigation extends React.Component { handleClick = e => { this.props.filterFavorite(); e.preventDefault(); }; render() { const { router, filterFavorite } = this.props; return ( <React.Fragment> {router.pathname === '/teams' ? ( <ActionButton onClick={filterFavorite}>GO</ActionButton> ) : ( <Flex as="nav" px={4} pt={3} css={navCSS}> <Tabs> <a href="/" style={{ textDecoration: 'none' }}> <Tab> <Activity size={24} color={ router.pathname === '/' ? `${t.colors.orange}` : '#fff' } /> <Text fontSize={0}>Today</Text> </Tab> </a> <a href="/game" style={{ textDecoration: 'none' }} onClick={e => this.handleClick(e)} > <Tab> <Heart size={24} color={ router.pathname === '/game' ? `${t.colors.orange}` : '#fff' } /> <Text fontSize={0}>My Team</Text> </Tab> </a> <a href="/settings" style={{ textDecoration: 'none' }}> <Tab> <Settings size={24} color={ router.pathname === '/settings' ? `${t.colors.orange}` : '#fff' } /> <Text fontSize={0}>Settings</Text> </Tab> </a> </Tabs> </Flex> )} </React.Fragment> ); } } Navigation.propTypes = { filterFavorite: PropTypes.func.isRequired, router: PropTypes.object.isRequired, }; export default withRouter(Navigation); <file_sep>/pages/teams.js import React, { Component } from 'react'; import fetch from 'isomorphic-unfetch'; import PropTypes from 'prop-types'; import getConfig from 'next/config'; import Text from '../components/Text'; import Select from '../components/Select'; class Teams extends Component { static async getInitialProps() { const { publicRuntimeConfig } = getConfig(); const url = `${publicRuntimeConfig.BASEURL}`; const result = await fetch(`${url}/api/teams`); const json = await result.json(); return { teams: json, }; } handleChange = event => this.props.setFavTeam(event.target.value); render() { const { teams: { league: { standard }, }, } = this.props; const Nba = standardTeams => standardTeams.filter(team => team.isNBAFranchise === true); const standardTeams = Nba(standard); return ( <React.Fragment> <Text fontSize={3} mb={4} as={'label'} htmlFor={'team-picker'}> Choose your favorite NBA team to start: </Text> <Select htmlName={'team-picker'} onChange={e => this.handleChange(e)}> {standardTeams.map(team => ( <option value={team.tricode} key={team.teamId}> {team.fullName} </option> ))} </Select> <Text color={'gray'}> Free agent fan? Don’t stress it, you can choose a different team later in the settings. </Text> </React.Fragment> ); } } Teams.propTypes = { filterFavorite: PropTypes.func.isRequired, teams: PropTypes.object.isRequired, setFavTeam: PropTypes.func.isRequired, }; export default Teams; <file_sep>/components/ActivityIndicator.js import React from 'react'; import PropTypes from 'prop-types'; import posed from 'react-pose'; import styled from 'styled-components'; import { Flex } from '@rebass/grid'; const IndicatorBackground = styled(Flex)({ height: 2, width: 40, }); const IndicatorInner = styled(Flex)({ backgroundColor: '#00FA9A', height: '100%', width: 20, borderRadius: 2, }); const AnimatedIndicator = posed(IndicatorInner)({ left: { x: '0%', transition: { type: 'spring', ease: 'easeOut', }, }, right: { x: '100%', transition: { type: 'spring', ease: 'easeOut', }, }, }); class ActivityIndicator extends React.Component { constructor() { super(); this.props = { gameOn: false, }; this.state = { isActive: true, sliderOn: false, }; } static propTypes = { gameOn: PropTypes.bool.isRequired, }; componentDidMount() { if (this.props.gameOn) { this.interval = setInterval(this.slide, 300); } } componentWillUnmount() { clearInterval(this.interval); } slide = () => this.setState({ sliderOn: !this.state.sliderOn, }); render() { const { sliderOn } = this.state; return ( <IndicatorBackground> <AnimatedIndicator pose={sliderOn ? 'left' : 'right'} /> </IndicatorBackground> ); } } export default ActivityIndicator; <file_sep>/components/Text.js import PropTypes from 'prop-types'; import styled from 'styled-components'; import { space, color, fontSize } from 'styled-system'; const caps = props => (props.caps ? { textTransform: 'uppercase' } : null); const Text = styled.p(space, color, fontSize, caps, { letterSpacing: '0.02em', }); Text.displayName = 'Text'; Text.propTypes = { ...space.propTypes, ...color.propTypes, ...fontSize.propTypes, caps: PropTypes.bool, }; Text.defaultProps = { fontSize: 1, }; export default Text; <file_sep>/lib/teamNames.js export default { ATL: 'Atlanta Hawks', BOS: 'Boston Celtics', CHA: 'Charlotte Hornets', CHI: 'Chicago Bulls', CLE: 'Cleveland Cavaliers', DAL: 'Dallas Mavericks', DEN: '<NAME>', DET: 'Detroit Pistons', GSW: 'Golden State Warriors', HOU: 'Houston Rockets', IND: 'Indiana Pacers', LAC: 'LA Clippers', LAL: 'LA Lakers', MEM: 'Memphis Grizzlies', MIA: 'Miami Heat', MIL: 'Milwaukee Bucks', MIN: 'Minnesota Timberwolves', BKN: 'Brooklyn Nets', NOP: 'New Orleans Pelicans', NYK: 'New York Knicks', OKC: 'Oklahoma City Thunder', ORL: 'Orlando Magic', PHI: 'Philadelphia 76ers', PHX: 'Phoenix Suns', POR: 'Portland Trail Blazers', SAS: 'San Antonio Spurs', SAC: 'Sacramento Kings', TOR: 'Toronto Raptors', UTA: 'Utah Jazz', WAS: 'Washington Wizards', }; <file_sep>/components/GameTime.js import React from 'react'; import PropTypes from 'prop-types'; import { Flex } from '@rebass/grid'; import Text from './Text'; const GameTime = ({ time }) => ( <Flex justifyContent={'center'}> <Text fontSize={2}>{time}</Text> </Flex> ); GameTime.propTypes = { time: PropTypes.string.isRequired, }; export default GameTime;
5fc4863e78ed19ca3152d34506d2a9a50896dac9
[ "JavaScript" ]
16
JavaScript
mfountoulakis/hoopify
34771bb71d8acdbb954f007266a33f3601f56b6b
fea4c49bcd9a7055d73a8eb87018073611e118ca
refs/heads/master
<repo_name>rytrose/Voice-Remixer<file_sep>/client/js/dependencies/vowelworm.game.js /** * @param {Object=} options Configuration options * @param {VowelWorm.instance|Array.<VowelWorm.instance>} options.worms Any * VowelWorm instances to begin with * @param {number=} [options.width=700] The width of the game board * @param {number=} [options.height=500] The height of the game board * @param {number=} [options.background=0xFFFFFF] The background color of the game * @param {HTMLElement=} [options.element=document.body] What to append the graph to * @constructor * @name VowelWorm.Game */ window.maxHeight = 0; window.maxBackness = 0; window.VowelWorm.Game = function (p5) { "use strict"; var game = this; window.game = this; game.p5 = p5; game.margin = 50; game.x1 = 0; game.x2 = 4.0; game.y1 = 0; game.y2 = 3.0; game.minHz = 0; game.maxHz = 8000; game.numTrail = 10; /** * Represents the threshold in dB that VowelWorm's audio should be at in * order to to plot anything. * @see {@link isSilent} * @memberof VowelWorm.Game * @name silence * @type number */ game.silence = -70; /** * Specify here which vowel mapping algorithm to use * @see {@link VowelWorm._MAPPING_METHODS} * @memberof VowelWorm.Game * @name map */ game.map = window.VowelWorm._MAPPING_METHODS.linearRegression; // game.map = window.VowelWorm._MAPPING_METHODS.mfccFormants; // game.map = window.VowelWorm._MAPPING_METHODS.cepstrumFormants; /** * Indicates whether to normalize the MFCC vector before prediction * @memberof VowelWorm.Game * @name normalizeMFCCs * @type boolean */ game.normalizeMFCCs = true; /** * Indicates whether to save time domain and frequency domain data for experimentation. * @memberof VowelWorm.Game * @name saveData * @type boolean */ game.saveData = false; /** * The number of past positions to keep when computing the simple moving average (SMA) * @memberof VowelWorm.Game * @name smoothingConstant * @type number */ game.smoothingConstant = 5; /** * Contains all instances of worms for this game * @type Array.<Object> * @private */ game.worms = []; var stopped = false; /** * You can change this with game.ipa = true/false * @type boolean * @memberof VowelWorm.Game * @name ipa */ // var ipaEnabled = true; // var ipaChart = new PIXI.DisplayObjectContainer(); /** * Begins animation of worms * @memberof VowelWorm.Game * @name play */ game.draw = function () { game.drawWorm(game.p5); }; /** * Inserts a worm into the ever-increasing frenzy of VowelWorm. * @param {window.VowelWorm.instance} worm * @memberof VowelWorm.Game * @name addWorm */ game.addWorm = function (worm, stream) { var container = {}; container.worm = worm; container.circles = []; container.stream = stream; game.p5.imageMode(game.p5.CENTER); // If stream is a MediaStream if (typeof stream === 'object' && stream['constructor']['name'] === 'MediaStream') { // Remove audio for animation var audiolessStream = stream.clone(); audiolessStream.removeTrack(audiolessStream.getAudioTracks()[0]); var cap = game.p5.createCaptureFromStream(audiolessStream); cap.hide(); container.video = cap; container.recording = false; game.worms.push(container); } // If stream is a video URL else { var video = game.p5.createVideo(stream); video.volume(0.0); video.loop(); video.hide(); container.video = video; container.recording = true; game.worms.push(container); } }; /** * @private */ game.drawWorm = function (p5) { var current_color = "#00FF00"; game.worms.forEach(function (container) { var worm = container.worm, circles = container.circles; var coords = getCoords(container); if (coords !== null) { var doRender = true; var x = coords.x; var y = coords.y; var circle = {}; circle.position = {}; circle.position.x = x; circle.position.y = y; circle.tint = current_color; circles.unshift(circle); } current_color = getNextColor(current_color); }); game.worms.forEach(function (container) { var circles = container.circles; // Calaculate fading alphas and maintain numTrail circles for (var i = 0; i < circles.length; i++) { var obj = circles[i]; obj.alpha = 255 - p5.ceil(i * (255 / (game.numTrail - 1))); if (i >= game.numTrail) { circles.splice(i, 1); i--; } } // Draw circles for (var i = 0; i < circles.length; i++) { var circle = circles[i]; p5.stroke(255); var color = p5.color(circle.tint); color.setAlpha(circle.alpha); p5.fill(color); p5.ellipse(circle.position.x, circle.position.y, 200); } // Draw video container.video.mask(maskImage); if (circles.length > 0) p5.image(container.video, circles[0].position.x, circles[0].position.y, 200, 200); }); }; var getCoords = function (container) { var buffer = container.worm.getFFT(); if (isSilent(buffer)) { container.circles.pop(); container.worm.resetPosition(); return null; } // Get the position from the worm var position = container.worm.getPosition(); // Transform (backness, height) to (x, y) canvas coordinates if (position.length) { var coords = transformToXAndY(position[0], position[1]); return coords; } return null; }; /** * Transforms from vowel space (backness, height) to canvas space (x, y) * @param {number} backness * @param {number} height * @name transformToXAndY */ var transformToXAndY = function (backness, height) { var xStart = game.x1; var xEnd = game.x2; // 4 var yStart = game.y1; var yEnd = game.y2; // 3 var source_x1 = 0.51; var source_y1 = 1.8; var source_x2 = 1.3; var source_y2 = 1.6; var source_x3 = 1.4 //1.3; var source_y3 = 0.8; var source_x4 = 1.45; var source_y4 = 1.0; var dest_x1 = 0; var dest_y1 = 1; var dest_x2 = 1; var dest_y2 = 1; var dest_x3 = 0; var dest_y3 = 0; var dest_x4 = 1; var dest_y4 = 0; // https://math.stackexchange.com/questions/296794/finding-the-transform-matrix-from-4-projected-points-with-javascript var source_a = math.matrix([[source_x1, source_x2, source_x3], [source_y1, source_y2, source_y3], [1, 1, 1]]); var source_b = math.matrix([[source_x4], [source_y4], [1]]); var source_aPrime = math.inv(source_a); var source_coeffs = math.multiply(source_aPrime, source_b); var source_coeffIdentity = math.matrix([[source_coeffs.subset(math.index(0, 0)), 0, 0], [0, source_coeffs.subset(math.index(1, 0)), 0], [0, 0, source_coeffs.subset(math.index(2, 0))]]); var source_a = math.multiply(source_a, source_coeffIdentity); var dest_a = math.matrix([[dest_x1, dest_x2, dest_x3], [dest_y1, dest_y2, dest_y3], [1, 1, 1]]); var dest_b = math.matrix([[dest_x4], [dest_y4], [1]]); var dest_aPrime = math.inv(dest_a); var dest_coeffs = math.multiply(dest_aPrime, dest_b); var dest_coeffIdentity = math.matrix([[dest_coeffs.subset(math.index(0, 0)), 0, 0], [0, dest_coeffs.subset(math.index(1, 0)), 0], [0, 0, dest_coeffs.subset(math.index(2, 0))]]); var dest_a = math.multiply(dest_a, dest_coeffIdentity); var c = math.multiply(dest_a, math.inv(source_a)); var orig = math.matrix([[backness], [height], [1]]); var transformed = math.multiply(c, orig); var x_prime = transformed.subset(math.index(0, 0)); var y_prime = transformed.subset(math.index(1, 0)); var z_prime = transformed.subset(math.index(2, 0)); var newCoords = {x: (x_prime / z_prime) * game.p5.width, y: game.p5.height - (y_prime / z_prime) * game.p5.height}; return newCoords; // console.log(newCoords); // // // var xDist = game.p5.width; / (xEnd - xStart); // // var yDist = game.p5.height / (yEnd - yStart); // // // // var adjustedX = (backness - xStart) * xDist + game.margin; // // var adjustedY = game.p5.height - (height - yStart) * yDist + game.margin; // if(backness > maxBackness) window.maxBackness = backness; // if(height > maxHeight) window.maxHeight = height; // var adjustedX = backness * game.p5.width; // var adjustedY = height * game.p5.height; // // var coords = document.getElementById('coords'); // coords.innerHTML = "(" + backness + ", " + height + ")"; // // return {x: adjustedX, y: adjustedY}; }; /** * Determines whether, for plotting purposes, the audio data is silent or not * Compares against the threshold given for {@link game.silence}. * @param {Array.<number>|Float32Array} data - An array containing dB values * @return {boolean} Whether or not the data is essentially 'silent' */ var isSilent = function (data) { for (var i = 0; i < data.length; i++) { if (data[i] > game.silence) { return false; } } return true; }; //Color Functions //Converts an integer representing a color to an integer representing a color 45 degrees away var getNextColor = function (old_color) { if (typeof old_color == 'number') { old_color = old_color.toString(16); //Pad with 0's if necessary while (old_color.length < 6) { old_color = "0" + old_color; } } old_color = new tinycolor(old_color); var new_color = old_color.spin(45).toHexString(); return new_color; }; // /** // * Fills the IPA Chart. A constructor helper method. // */ // var drawVowels = function() { // if(!ipaChart.children.length) { // var letters = [ // ["e",221.28871891963863,252.35519027188354], // ["i",169.01833799969594,171.97765003235634], // ["a",317.6219414250667,337.00896411883406], // ["o",384.5714404194302,284.96641792056766], // ["u",412.17314090483404,231.94657762575406] // ]; // var chart = new PIXI.Sprite.fromImage("plot2.png"); // chart.position.x = 0 + game.margin; // chart.position.y = 0 + game.margin; // ipaChart.addChild(chart); // // for(var i=0; i<letters.length; i++){ // // var letter = new PIXI.Text(letters[i][0],{font: "35px sans-serif", fill: "black", align: "center"}); // // letter.position.x = letters[i][1]; // // letter.position.y = letters[i][2]; // // ipaChart.addChild(letter); // // } // } // }; }; <file_sep>/client/js/master/webrtc_master.js var localStream; var recorder; var mixedStream; var peerConnections = {}; var uuid; var serverConnection; var numPeers = 0; var peerConnectionConfig = { 'iceServers': [ {'urls': 'stun:stun.services.mozilla.com'}, {'urls': 'stun:stun.l.google.com:19302'}, ] }; function loadWebRTC() { uuid = createUUID(); document.getElementById('masterId').innerHTML = uuid; serverConnection = new WebSocket('wss://' + window.location.hostname + ':8443'); serverConnection.onmessage = gotMessageFromServer; // Tell server what UUID this client is serverConnection.onopen = () => serverConnection.send(JSON.stringify({'identify': true, 'uuid': uuid})); var constraints = { video: true, audio: true, }; if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia(constraints).then(getUserMediaSuccess).catch(errorHandler); } else { alert('Your browser does not support getUserMedia API'); } } function getUserMediaSuccess(stream) { localStream = stream.clone(); // Create new recorder from local stream recorder = new MediaRecorder(localStream); recorder.ondataavailable = function (e) { recordingChunks.push(e.data); } // Set recorder callback recorder.onstop = function () { var newRecordingWorm = document.createElement('video'); var newRecordingMixer = document.createElement('video'); var blob = new Blob(recordingChunks, {'type': 'video/mp4'}); recordingChunks = []; var videoURL = URL.createObjectURL(blob); newRecordingWorm.src = videoURL; newRecordingMixer.src = videoURL; newRecordingWorm.loop = true; newRecordingMixer.loop = true; newRecordingWorm.play(); newRecordingMixer.play(); // Needs two separate recordings for two separate Web Audio graphs // 1. the Vowel Worm, 2. the Mixer // Create a new worm from the audio var worm = new window.VowelWorm.instance(newRecordingWorm); window.vw.addWorm(worm, videoURL); // Add recording to mixer mixer.addSource(newRecordingMixer); } mixedStream = stream; // Add stream to mixer mixer.addSource(mixedStream); // Get the mixed audio stream from mixer var streamFromMixer = mixer.getOutputStream(); // Remove the original audio track from local stream mixedStream.removeTrack(mixedStream.getAudioTracks()[0]); // Add the mixer audio track to mixed stream mixedStream.addTrack(streamFromMixer.getAudioTracks()[0]); // Add localStream to VowelWorm var worm = new window.VowelWorm.instance(localStream); window.vw.addWorm(worm, localStream); // Add to Tonejs var toneStream = new Tone.UserMedia(); toneStream.openMediaStream(streamFromMixer); toneStream.toMaster(); } function start(signal) { var peerConnection = new RTCPeerConnection(peerConnectionConfig); peerConnection.onicecandidate = gotIceCandidate; peerConnection.ontrack = gotRemoteStream; peerConnection.addStream(mixedStream); peerConnections[signal.uuid] = peerConnection; } function gotMessageFromServer(message) { var signal = JSON.parse(message.data); // Ignore messages from ourself if (signal.uuid == uuid) return; if (signal.sdp) { start(signal); var peerConnection = peerConnections[signal.uuid]; peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function () { // Only create answers in response to offers if (signal.sdp.type == 'offer') { if (numPeers < MAX_CONNECTIONS) { peerConnection.createAnswer().then( function (description) { console.log('got description'); peerConnection.setLocalDescription(description).then(function () { serverConnection.send(JSON.stringify({ 'sdp': peerConnection.localDescription, 'uuid': uuid })); }).catch(errorHandler); }).catch(errorHandler); } else { alert("Only " + MAX_CONNECTIONS + " connections are allowed.") } } }).catch(errorHandler); } else if (signal.ice) { var peerConnection = peerConnections[signal.uuid]; peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler); } } function gotIceCandidate(event) { if (event.candidate != null) { serverConnection.send(JSON.stringify({'ice': event.candidate, 'uuid': uuid})); } } var remoteStream = null; function gotRemoteStream(event) { console.log('got remote stream'); // First track event if (!remoteStream) { remoteStream = new MediaStream([event.track]); if (event.track.kind == "audio") { mixer.addSource(event.streams[0]); } } // Second track event else { remoteStream.addTrack(event.track); if (event.track.kind == "audio") mixer.addSource(event.streams[0]); var worm = new window.VowelWorm.instance(remoteStream); window.vw.addWorm(worm, remoteStream); remoteStream = null; numPeers++; } } function errorHandler(error) { console.log(error); } // Taken from http://stackoverflow.com/a/105074/515584 // Strictly speaking, it's not a real UUID, but it gets the job done here function createUUID() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ) } <file_sep>/README.md # Voice Remixer <file_sep>/server.js const HTTPS_PORT = 8443; const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const WebSocketServer = WebSocket.Server; const express = require('express'); const url_shortener_api_key = "<KEY>"; // Yes, TLS is required const serverConfig = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem'), }; // ---------------------------------------------------------------------------------------- var app = express(); var path = require('path'); var httpsServer = https.createServer(serverConfig, app).listen(HTTPS_PORT, "0.0.0.0"); var redis = require("redis"); var redis_client = redis.createClient(); redis_client.on('error', function (err) { console.log('Error ' + err) }) process.on('SIGTERM', function() { redis_client.quit(); process.exit(); }); process.on('SIGINT', function() { redis_client.quit(); process.exit(); }); app.use(express.static( __dirname + '/client')); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'client/views', 'index.html')); }); app.get('/master', function (req, res) { res.sendFile(path.join(__dirname, 'client/views', 'master.html')); }); app.get('/slave', function (req, res) { res.sendFile(path.join(__dirname, 'client/views', 'slave.html')); }); // ---------------------------------------------------------------------------------------- const wss = new WebSocketServer({server: httpsServer, clientTracking: true}); var networks = {}; wss.on('connection', function(ws) { ws.on('error', (e) => { if(e.code != 'ECONNRESET') console.log(e); }); ws.uuid = -99; ws.on('message', function(message) { var signal = JSON.parse(message); if(signal.identify) { ws.uuid = signal.uuid; return; } console.log("MESSAGE: " + signal); console.log("Master in message: " + signal.master); // this message is from a slave if(signal.master){ // if this is not the first message to the master if(signal.master in networks) { console.log("NOT the first message from slave."); var slaves = networks[signal.master]; // if this is a new slave if(slaves.indexOf(signal.uuid) == -1) networks[signal.master].push(signal.uuid); } // this is the first message from the slave, establish master<-->slave link else { console.log("First message from slave."); networks[signal.master] = [signal.uuid]; } console.log(networks); // forward the message to the master var client_array = Array.from(wss.clients); console.log("Clients: " + client_array); client_array.forEach(cl => console.log(cl.uuid)); var master = Array.from(wss.clients).filter(client => client.uuid == signal.master)[0]; console.log("Master: " + master); if(master && master.readyState === WebSocket.OPEN) master.send(message); else console.log("Master not found!"); } // this message is from a master else { // forward the message to all slaves console.log("Master uuid: " + signal.uuid); console.log("networks: " + networks); networks[signal.uuid].forEach(function each(slave) { var slave_ws = Array.from(wss.clients).filter(client => client.uuid == slave)[0]; console.log(slave_ws); if(slave_ws && slave_ws.readyState === WebSocket.OPEN) slave_ws.send(message); else console.log("Slave not found!"); }); } }); }); wss.broadcast = function(data) { this.clients.forEach(function(client) { if(client.readyState === WebSocket.OPEN) { client.send(data); } }); }; // ------------------------------------------------- // Ensures that there are no hanging ws connections function noop() {} function heartbeat() { this.isAlive = true; } wss.on('connection', function connection(ws) { ws.isAlive = true; ws.on('pong', heartbeat); }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); // ------------------------------------------------- console.log('Server running. Visit https://localhost:' + HTTPS_PORT + ' in Firefox/Chrome.\n\n\ Some important notes:\n\ * Note the HTTPS; there is no HTTP -> HTTPS redirect.\n\ * You\'ll also need to accept the invalid TLS certificate.\n\ * Some browsers or OSs may not allow the webcam to be used by multiple pages at once. You may need to use two different browsers or machines.\n' ); <file_sep>/client/js/dependencies/vowelworm.js (function (numeric) { "use strict"; /** * @namespace * @const * @ignore */ var VowelWorm = {}; /** * @namespace * @name VowelWorm */ window.VowelWorm = VowelWorm; /** * @const */ var CONTEXT = new window.AudioContext(); /** * A collection of all vowel worm instances. Used for attaching modules. * @see {@link VowelWorm.module} * @type {Array.<window.VowelWorm.instance>} */ var instances = []; /** * A collection of modules to add to instances, whenever they are created * @type {Object.<string, Function>} */ var modules = {}; /** * The sample rate used when one cannot be found. */ var DEFAULT_SAMPLE_RATE = 44100; /** * The window size to use for each analysis frame * From both Wikipedia (http://en.wikipedia.org/wiki/Formant; retrieved 23 Jun. * 2014, 2:52 PM UTC) and <NAME>'s chart (personal email) * * These indicate the minimum values in Hz in which we should find our formants * * TODO get better documentation (wikipedia's not the most reliable of sources, and I don't know if anyone who's still here has access to the email with <NAME>son's chart.) */ /** * @const * @type number */ var F1_MIN = 100; /** * @const * @type number */ var WINDOW_SIZE = 0.046; /** * The number of filter banks to use when computing MFCCs. * @const * @type number */ var NUM_FILTER_BANKS = 40; /** * The first MFCC to use in the mapping algorithms. * @const * @type number */ var FIRST_MFCC = 2; /** * The last MFCC to use in the mapping algorithms. * @const * @type number */ var LAST_MFCC = 25; /** <<<<<<< HEAD * The minimum backness value. Used for transforming between formants to backness. ======= * Represent the minimum differences between formants, to ensure they are * properly spaced * * * I'm not sure if this is possible. Sometimes the formants, especially the * second and third formants, merge together for a little bit. (TODO Find source.) * * If it's possible/reasonable, we might want to look at the beginning and end of * the vowelss to see if it's one or two formants. * >>>>>>> ae5b061f1d0660bdb59dd980c7dd801ac5f31fb2 * @const * @type number */ var BACKNESS_MIN = 0; /** * The maximum backness value. Used for transforming between formants and backness. * @const * @type number */ var BACKNESS_MAX = 4; /** * The minimum height value. Used for transforming between formants and height. * @const * @type number */ var HEIGHT_MIN = 0; /** * The maximum height value. Used for transforming between formants and height. * @const * @type number */ var HEIGHT_MAX = 3; /** * Transposed MFCC weight matrices for prediction. * Numeric keys represent the number of filter MFFCs used as regressors (features). * These are transposed from the matrices given in the VowelWorm MATLAB code * @constant */ /** * @license * VowelWorm concept and VowelWorm._MFCC_WEIGHTS from <NAME>, Andreas * Arzt, and <NAME> at the Department of Computational Perception * Johannes Kepler University, Linz, Austria. * http://www.cp.jku.at/projects/realtime/vowelworm.html * */ VowelWorm._MFCC_WEIGHTS = { 25: { height: new Float32Array([ 1.104270, 0.120389, 0.271996, 0.246571, 0.029848, -0.489273, -0.734283, -0.796145, -0.441830, -0.033330, 0.415667, 0.341943, 0.380445, 0.260451, 0.092989, -0.161122, -0.173544, -0.015523, 0.251668, 0.022534, 0.054093, 0.005430, -0.035820, -0.057551, 0.161558 ]), backness: new Float32Array([ 0.995437, 0.540693, 0.121922, -0.585859, -0.443847, 0.170546, 0.188879, -0.306358, -0.308599, -0.212987, 0.012301, 0.574838, 0.681862, 0.229355, -0.222245, -0.222203, -0.129962, 0.329717, 0.142439, -0.132018, 0.103092, 0.052337, -0.034299, -0.041558, 0.141547 ]) } }; /** * Loads the regression weights from the server * @param boolean normalizeMFCCs indicates whether to use weights for normalized or * non-normalized MFCCs */ VowelWorm.loadRegressionWeights = function (normalizeMFCCs) { var weightsReq = new XMLHttpRequest(); weightsReq.addEventListener("load", function () { // Parse the backness and height weights var xmlDoc = weightsReq.responseXML; var backWeightsElements = xmlDoc.getElementsByTagName("backness")[0] .getElementsByTagName("weight"); var heightWeightsElements = xmlDoc.getElementsByTagName("height")[0] .getElementsByTagName("weight"); var backWeights = []; var heightWeights = []; for (var i = 0; i < backWeightsElements.length; i++) { backWeights.push(backWeightsElements[i].childNodes[0].nodeValue); heightWeights.push(heightWeightsElements[i].childNodes[0].nodeValue); } VowelWorm._MFCC_WEIGHTS[25].backness = new Float32Array(backWeights); VowelWorm._MFCC_WEIGHTS[25].height = new Float32Array(heightWeights); }) if (normalizeMFCCs) { weightsReq.open("GET", "training/weights_norm_mfcc.xml", true); } else { weightsReq.open("GET", "training/weights.xml", true); } weightsReq.send(); } /** * Given an array of fft data, returns backness and height coordinates * in the vowel space. * @param {Array.<number>} fftData The fftData to map * @return {Array.<number>} an array formatted thusly: [x,y]. May be empty * @nosideeffects */ VowelWorm._MAPPING_METHODS = { linearRegression: function (fftData, options) { // Get the mfccs to use as features var mfccs = window.AudioProcessor.getMFCCs({ fft: fftData, fftSize: options.fftSize, minFreq: options.minHz, maxFreq: options.maxHz, filterBanks: NUM_FILTER_BANKS, sampleRate: options.sampleRate, }); // Predict the backness and height using multiple linear regression if (mfccs.length) { // Get the specified MFCCs to use as regressors (features) // Also makes a copy of mfccs (since they are changing with the streaming audio) var features = mfccs.slice(FIRST_MFCC - 1, LAST_MFCC); // Normalize the MFCC vector if (window.game.normalizeMFCCs) { var normSquared = 0; for (var i = 0; i < features.length; i++) { normSquared += features[i] * features[i]; } for (var i = 0; i < features.length; i++) { features[i] /= Math.sqrt(normSquared); } } // Insert DC coefficient for regression features.splice(0, 0, 1); // Check for corresponding weights if (VowelWorm._MFCC_WEIGHTS[features.length] === undefined) { throw new Error("No weights found for mfccs of length " + mfccs.length + ". If you are using getMFCCs, make sure the " + "amount of filter banks you are looking for corresponds to one of " + "the keys found in VowelWorm._MFCC_WEIGHTS."); } // Do the prediction var backness = window.MathUtils.predict(features, VowelWorm._MFCC_WEIGHTS[features.length].backness); var height = window.MathUtils.predict(features, VowelWorm._MFCC_WEIGHTS[features.length].height); return [backness, height]; } return []; }, mfccFormants: function (fftData, options) { var mfccs = window.AudioProcessor.getMFCCs({ fft: fftData, fftSize: options.fftSize, minFreq: options.minHz, maxFreq: options.maxHz, filterBanks: options.numFilterBanks, sampleRate: options.sampleRate }); if (mfccs.length) { // Convert the mfccs to formants var formants = window.AudioProcessor.getFormantsFromMfccs(mfccs); var backness; var height; if (formants.length > 0) { var pos = mapFormantsToIPA(formants[0], formants[1]); } return [backness, height]; } return []; }, cepstrumFormants: function (fftData, options) { var cepstrum = window.AudioProcessor.getCepstrum(fftData, {}); if (cepstrum.length) { // Convert the cepstrum to formants var formants = window.AudioProcessor.getFormantsFromCepstrum(cepstrum, { numFormants: 2, sampleRate: options.sampleRate, fftSize: options.fftSize, cutoff: 200 }); if (formants.length > 0) { var pos = mapFormantsToIPA(formants[0], formants[1]); return pos; } else { return []; } } return []; } }; /** * Maps first and second formants to the IPA vowel space. */ var mapFormantsToIPA = function (f1, f2) { // var backness = window.MathUtils.mapToScale(f2 - f1, // window.AudioProcessor.F2_MAX - window.AudioProcessor.F1_MAX, // window.AudioProcessor.F2_MIN - window.AudioProcessor.F1_MIN, BACKNESS_MIN, BACKNESS_MAX); var backness = window.MathUtils.mapToScale(f2, window.AudioProcessor.F2_MAX, window.AudioProcessor.F2_MIN, BACKNESS_MIN, BACKNESS_MAX); var height = window.MathUtils.mapToScale(f1, window.AudioProcessor.F1_MAX, window.AudioProcessor.F1_MIN, HEIGHT_MIN, HEIGHT_MAX); return [backness, height]; } /** * Representative of the current mode VowelWorm is in. * In this case, an audio element * @const * @memberof VowelWorm */ VowelWorm.AUDIO = 1; /** * Representative of the current mode VowelWorm is in. * In this case, a video element * @const * @memberof VowelWorm */ VowelWorm.VIDEO = 2; /** * Representative of the current mode VowelWorm is in. * In this case, a media stream * @const * @memberof VowelWorm */ VowelWorm.STREAM = 3; /** * Representative of the current mode VowelWorm is in. * In this case, a remote URL turned into a source node * @const * @memberof VowelWorm */ VowelWorm.REMOTE_URL = 4; /** * Contains methods used in the analysis of vowel audio data * @param {*} stream The audio stream to analyze OR a string representing the URL for an audio file * @constructor * //@struct (attaching modules breaks this as a struct; is there a better way?) * @final * @name VowelWorm.instance * @memberof VowelWorm */ window.VowelWorm.instance = function (stream) { var that = this; this._context = CONTEXT; this._analyzer = this._context.createAnalyser(); this._sourceNode = null; // for analysis with files rather than mic input this._analyzer.fftSize = window.MathUtils.nextPow2(this._context.sampleRate * WINDOW_SIZE); this._buffer = new Float32Array(this._analyzer.frequencyBinCount); this._audioBuffer = null; // comes from downloading an audio file // Attach an processor node to analyze data from every buffer. // Note: this is deprecated but the replacement has not been implemented in any browers yet. // See https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode/onaudioprocess this._processorNode = this._context.createScriptProcessor(this._analyzer.fftSize, 1, 1); this._processorNode.onaudioprocess = function (e) { that.computePosition(window.game.map, window.game.smoothingConstant); if (window.game.saveData) { // Save the timestamp for this frame this.timestamps.push(this._analyzer.currentTime); // Save the time domain data var timeDomainBuffer = new Float32Array(this.getFFTSize()); this._analyzer.getFloatTimeDomainData(timeDomainBuffer); var timeDomainData = new Float32Array(this.fftSize); for (var i = 0; i < timeDomainBuffer.length; i++) { timeDomainData[i] = timeDomainBuffer[i]; } this.timeDomainData.push(timeDomainData[i]); // Save the FFT data var fftBuffer = this.getFFT(); var fftData = new Float32Array(fftBuffer.length); for (var i = 0; i < fftBuffer.length; i++) { fftData[i] = fftBuffer[i]; } this.ffts.push(fftBuffer[i]); } } this._processorNode.connect(this._context.destination); if (stream) { this.setStream(stream); } for (var name in modules) { if (modules.hasOwnProperty(name)) { attachModuleToInstance(name, that); } } instances.push(this); }; VowelWorm.instance = window.VowelWorm.instance; VowelWorm.instance.prototype = Object.create(VowelWorm); VowelWorm.instance.constructor = VowelWorm.instance; var proto = VowelWorm.instance.prototype; /** * Attaches a module to the given instance, with the given name * @param {string} name The name of the module to attach. Should be present in * {@link modules} to work * @param {window.VowelWorm.instance} instance The instance to affix a module to */ function attachModuleToInstance(name, instance) { instance[name] = {}; modules[name].call(instance[name], instance); }; /** * Callback used by {@link VowelWorm.module} * @callback VowelWorm~createModule * @param {window.VowelWorm.instance} instance */ /** * Adds a module to instances of {@link VowelWorm.instance}, as called by * `new VowelWorm.instance(...);` * @param {string} name the name of module to add * @param {VowelWorm~createModule} callback - Called if successful. * `this` references the module, so you can add properties to it. The * instance itself is passed as the only argument, for easy access to core * functions. * @throws An Error when trying to create a module with a pre-existing * property name * * @see {@link attachModuleToInstance} * @see {@link modules} * @see {@link instances} * @memberof VowelWorm */ VowelWorm.module = function (name, callback) { if (proto[name] !== undefined || modules[name] !== undefined) { throw new Error("Cannot define a VowelWorm module with the name \"" + name + "\": a property with that name already exists. May I suggest \"" + name + "_kewl_sk8brdr_98\" instead?"); } if (typeof callback !== 'function') { throw new Error("No callback function submitted."); } modules[name] = callback; instances.forEach(function (instance) { attachModuleToInstance(name, instance); }); }; /** * Removes a module from all current and future VowelWorm instances. Used * primarily for testing purposes. * @param {string} name - The name of the module to remove * @memberof VowelWorm */ VowelWorm.removeModule = function (name) { if (modules[name] === undefined) { return; } delete modules[name]; instances.forEach(function (instance) { delete instance[name]; }); }; /** * Callback used by {@link VowelWorm.module} * @callback VowelWorm~createModule * @param {VowelWorm.instance.prototype} prototype */ /** * The current mode the vowel worm is in (e.g., stream, audio element, etc.) * @type {?number} * * @see VowelWorm.AUDIO * @see VowelWorm.VIDEO * @see VowelWorm.STREAM * @see VowelWorm.REMOTE_URL * @member * @memberof VowelWorm.instance */ VowelWorm.instance.prototype.mode = null; /** * Removes reference to this particular worm instance as well as * all properties of it. * @memberof VowelWorm.instance */ VowelWorm.instance.prototype.destroy = function () { var index = instances.indexOf(this); if (index !== -1) { instances.splice(index, 1); } for (var i in this) { if (this.hasOwnProperty(i)) { delete this[i]; } } }; /** * The sample rate of the attached audio source * @return {number} * @memberof VowelWorm.instance * @nosideeffects */ VowelWorm.instance.prototype.getSampleRate = function () { switch (this.mode) { case this.REMOTE_URL: return this._sourceNode.buffer.sampleRate; break; case this.AUDIO: case this.VIDEO: return DEFAULT_SAMPLE_RATE; // this cannot be retrieved from the element break; case this.STREAM: return this._context.sampleRate; break; default: throw new Error("Current mode has no method for sample rate"); } }; /** * The size of the FFT. This is twice the number of bins. * @return {number} * @memberof VowelWorm.instance * @nosideeffects */ VowelWorm.instance.prototype.getFFTSize = function () { return this._analyzer.fftSize; }; /** * Retrieves the current FFT data of the audio source. NOTE: this returns a * reference to the internal buffer used to store this information. It WILL * change. If you need to store it, iterate through it and make a copy. * * The reason this doesn't return a new Float32Array is because Google Chrome * (as of v. 36) does not adequately garbage collect new Float32Arrays. Best * to keep them to a minimum. * * @return Float32Array * @memberof VowelWorm.instance * @example * var w = new VowelWorm.instance(audioelement), * fft = w.getFFT(); * * // store a copy for later * var saved_data = []; * for(var i = 0; i<fft.length; i++) { * saved_data[i] = fft[i]; * } */ VowelWorm.instance.prototype.getFFT = function () { this._analyzer.getFloatFrequencyData(this._buffer); return this._buffer; }; /** * Stores all timestamps for future use. */ VowelWorm.instance.prototype.timestamps = []; /** * Stores all fft buffers for future use. */ VowelWorm.instance.prototype.ffts = []; /** * Stores all time domain buffers for future use. */ VowelWorm.instance.prototype.timeDomainData = []; /** * Stores the previous positions for smoothing */ VowelWorm.instance.prototype.positions = []; /** * Stores the current simple moving average for smoothing. */ VowelWorm.instance.prototype.positionSMA = []; /** * Computes the (backness, height) coordinates of this worm for the current time frame * The position is smoothed over time with a simple moving average. * See https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average */ VowelWorm.instance.prototype.computePosition = function (mappingMethod, smoothingConstant) { var buffer = this.getFFT(); // Copy the fft data since it will change as audio streams in var fft = []; for (var i = 0; i < buffer.length; i++) { fft.push(buffer[i]); } // Map the fft data to (backness, height) coordinates in the vowel space var position = mappingMethod(fft, { fftSize: this.getFFTSize(), minHz: window.game.minHz, maxHz: window.game.maxHz, sampleRate: this.getSampleRate() }); // Smooth the position over time if (this.positions.length == 0) { this.positionSMA = position; } else if (this.positions.length < smoothingConstant) { // Compute each coordinate separately for (var i = 0; i < this.positionSMA.length; i++) { // Until we have enough previous data, this is the same as the cumulative moving average this.positionSMA[i] = (position[i] + this.positions.length * this.positionSMA[i]) / (this.positions.length + 1) } } else { var oldPosition = this.positions[0]; for (var i = 0; i < this.positionSMA.length; i++) { this.positionSMA[i] += (position[i] - oldPosition[i]) / this.positions.length; } this.positions = this.positions.slice(1); } // Make sure to store this position for next time this.positions.push(position); } /** * Gets the current (backness, height) coordinates of this worm. */ VowelWorm.instance.prototype.getPosition = function () { return this.positionSMA; } VowelWorm.instance.prototype.resetPosition = function () { this.positions = []; this.positionSMA = []; } /** * @license * * VowelWorm.instance.prototype.setStream helper functions borrow heavily from * <NAME>'s pitch detector, under the MIT license. * See https://github.com/cwilso/pitchdetect * */ /** * Specifies the audio source for the instance. Can be a video or audio element, * a URL, or a MediaStream * @memberof VowelWorm.instance * @param {MediaStream|string|HTMLAudioElement|HTMLVideoElement} stream The audio stream to analyze OR a string representing the URL for an audio file OR an Audio file * @throws An error if stream is neither a Mediastream, Audio or Video Element, or a string */ VowelWorm.instance.prototype.setStream = function (stream) { if (typeof stream === 'string') { this._loadFromURL(stream); } else if (typeof stream === 'object' && stream['constructor']['name'] === 'MediaStream') { this._loadFromStream(stream); } else if (stream && (stream instanceof window.Audio || stream.tagName === 'AUDIO')) { this._loadFromAudio(stream); } else if (stream && stream.tagName === 'VIDEO') { this._loadFromVideo(stream); } else { throw new Error("VowelWorm.instance.setStream only accepts URL strings, " + "instances of MediaStream (as from getUserMedia), or " + "<audio> elements"); } }; /** * @param {string} url Where to fetch the audio data from * @throws An error when the server returns an error status code * @throws An error when the audio file cannot be decoded * @private * @memberof VowelWorm.instance */ VowelWorm.instance.prototype._loadFromURL = function loadFromURL(url) { var that = this, request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; request.onerror = function error() { throw new Error("Tried to load audio file at '" + url + "', but a " + "netowrk error occurred: " + request.statusText); }; function decodeSuccess(buffer) { that.mode = this.REMOTE_URL; that._audioBuffer = buffer; that._resetSourceNode(); // TODO - enable playback through speakers, looping, etc. }; function decodeError() { throw new Error("Could not parse audio data. Make sure the file " + "(" + url + ") you are passing to " + "setStream or VowelWorm.instance is a valid audio " + "file."); }; request.onload = function () { if (request.status !== 200) { throw new Error("Tried to load audio file at '" + url + "', but the " + "server returned " + request.status + " " + request.statusText + ". Make sure the URL you are " + "passing to setStream or VowelWorm.instance is " + "correct"); } that._context.decodeAudioData(this.response, decodeSuccess, decodeError); }; request.send(); }; /** * Creates (or resets) a source node, as long as an available audioBuffer * exists * @private * @memberof VowelWorm.instance */ VowelWorm.instance.prototype._resetSourceNode = function resetSourceNode() { this._sourceNode = this._context.createBufferSource(); this._sourceNode.buffer = this._audioBuffer; this._sourceNode.connect(this._analyzer); this._sourceNode.connect(this._processorNode); }; /** * @param {MediaStream} stream * @memberof VowelWorm.instance * @private */ VowelWorm.instance.prototype._loadFromStream = function (stream) { this.mode = this.STREAM; this._sourceNode = this._context.createMediaStreamSource(stream); this._sourceNode.connect(this._analyzer); this._sourceNode.connect(this._processorNode); }; /** * Loads an audio element as the data to be processed * @param {HTMLAudioElement} audio * @private * @memberof VowelWorm.instance */ VowelWorm.instance.prototype._loadFromAudio = function loadFromAudio(audio) { this.mode = this.AUDIO; this._sourceNode = this._context.createMediaElementSource(audio); this._sourceNode.connect(this._analyzer); // this._analyzer.connect(this._context.destination); this._sourceNode.connect(this._processorNode); }; /** * Loads a video element as the data to be processed * @param {HTMLVideoElement} video * @private * @memberof VowelWorm.instance */ VowelWorm.instance.prototype._loadFromVideo = function loadFromVideo(video) { this.mode = this.VIDEO; this._sourceNode = this._context.createMediaElementSource(video); this._sourceNode.connect(this._analyzer); // this._analyzer.connect(this._context.destination); this._sourceNode.connect(this._processorNode); }; }(window.numeric));
afd4236a0dd1a327abd6d3f74c201c3e0f8a5bbf
[ "JavaScript", "Markdown" ]
5
JavaScript
rytrose/Voice-Remixer
070a535e9748773a886b7d29e6cbed07dfae3b78
7d94a472aafe71a17e8ad523620f9046e3e38e5f
refs/heads/master
<file_sep>#Placeholder for a model class Article < ActiveRecord::Base end
facd03724ab493cabf9d9106ec38bfcf53e1e5ec
[ "Ruby" ]
1
Ruby
Umnums/sinatra-ar-crud-lab-online-web-sp-000
8d765cba65df186175434038e10556deaffc7114
81e5b2adf4c43b814ffb026f6ed321ad2572755c
refs/heads/master
<file_sep>package com.bawei.caolina20190513.net; import android.annotation.SuppressLint; import android.os.AsyncTask; import com.google.common.io.CharStreams; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /* *@Auther:cln *@Date: 时间 *@Description:功能 * */ public class HttpUtil { private static final HttpUtil ourInstance = new HttpUtil(); public static HttpUtil getInstance() { return ourInstance; } private HttpUtil() { } @SuppressLint("StaticFieldLeak") public void doHttpGet(String surl, final CallBackPost post) { new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); if (connection.getResponseCode() == 200) { return CharStreams.toString(new InputStreamReader(connection.getInputStream())); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); post.onSuccess(s); } }.execute(surl); } } <file_sep>package com.bawei.caolina20190513.bean; /* *@Auther:cln *@Date: 时间 *@Description:功能 * */ public class Bean { private String title; private String image; public Bean() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } } <file_sep>package com.bawei.caolina20190513.mvp; import com.bawei.caolina20190513.net.CallBackPost; import com.bawei.caolina20190513.net.HttpUtil; /* *@Auther:cln *@Date: 时间 *@Description:功能 * */ public class HomeModelImpl implements HomeContanct.IHomeModel { private final HttpUtil httpUtil; public HomeModelImpl() { httpUtil = HttpUtil.getInstance(); } @Override public void ListModel(String title, String image, CallBackPost post) { String str ="https://code.aliyun.com/598254259/FristProject/raw/master/bw_list.txt\n"; httpUtil.doHttpGet(str, new CallBackPost() { @Override public void onSuccess(String result) { } @Override public void onFail(String msg) { } }); } }
580d395c800d2189aa4a06047e433faf49fdebfe
[ "Java" ]
3
Java
Nina2265462/Caolina20190513
3413c7c5f57aa1cfad6d01509274b017362be854
3b09020899e908126390d9aaf00376e1304b5fe4
refs/heads/master
<file_sep>import React from 'react'; import styled from 'styled-components'; import Img from 'gatsby-image'; import { Link, useStaticQuery, graphql } from 'gatsby'; const LogoWrap = styled.div` ${(props) => (props.footer === 'true' ? '' : 'margin: auto 0')}; ${(props) => (props.footer === 'true' ? '' : 'flex: 0 0 207px')}; @media (max-width: 860px) { flex: 0 0 150px; } `; export default function Logo({ footer }) { const data = useStaticQuery(graphql` query { file(name: { eq: "logo" }, extension: { eq: "png" }) { childImageSharp { fluid(quality: 100, maxWidth: 207) { ...GatsbyImageSharpFluid } } } } `); return ( <LogoWrap as={Link} to="/" footer={footer}> <Img fluid={data.file.childImageSharp.fluid} alt="logo" /> </LogoWrap> ); } <file_sep>import { createGlobalStyle } from 'styled-components'; import latoBlackwoff2 from '../assets/fonts/lato-black-webfont.woff2'; import latoBlackwoff from '../assets/fonts/lato-black-webfont.woff'; import latoBoldwoff2 from '../assets/fonts/lato-bold-webfont.woff2'; import latoBoldwoff from '../assets/fonts/lato-bold-webfont.woff'; import latoLightwoff2 from '../assets/fonts/lato-light-webfont.woff2'; import latoLightwoff from '../assets/fonts/lato-light-webfont.woff'; import latoRegularwoff2 from '../assets/fonts/lato-regular-webfont.woff2'; import latoRegularwoff from '../assets/fonts/lato-regular-webfont.woff'; const Typography = createGlobalStyle` @font-face { font-family: 'latoblack'; src: url(${latoBlackwoff2}) format('woff2'), url(${latoBlackwoff}) format('woff'); font-weight: normal; font-style: normal; } @font-face { font-family: 'latobold'; src: url(${latoBoldwoff2}) format('woff2'), url(${latoBoldwoff}) format('woff'); font-weight: normal; font-style: normal; } @font-face { font-family: 'latolight'; src: url(${latoLightwoff2}) format('woff2'), url(${latoLightwoff}) format('woff'); font-weight: normal; font-style: normal; } @font-face { font-family: 'latoregular'; src: url(${latoRegularwoff2}) format('woff2'), url(${latoRegularwoff}) format('woff'); font-weight: normal; font-style: normal; } html { font-family: 'latolight'; color: var(--blue-vogue); font-size: 62.5% } h1,h2,h3,h4,h5,h6 { font-weight: normal; margin: 0; } `; export default Typography; <file_sep>import React from 'react'; import styled from 'styled-components'; import { Link } from 'gatsby'; const NavItem = styled(Link)` font-family: 'latobold'; text-decoration: none; color: var(--blue-vogue); display: inline-block; white-space: nowrap; margin: 1vw 1vw; transition: all 200ms ease-in; position: relative; --scaleX: 1; :after { position: absolute; bottom: 0; left: 0; right: 0; width: 0%; content: '.'; color: transparent; background: var(--burnt-sienna); height: 2px; transition: all 0.4s ease-in; transform: skew(-20deg) rotate(1.64deg) scaleX(var(--scaleX)); } :hover { color: var(--burnt-sienna); ::after { width: 100%; } } @media (max-width: 768px) { padding: 1vw 0; z-index: 6; } `; export default function NavbarLinks({ onChange }) { function handleClick() { // Here, we invoke the callback with the new value onChange(); } return ( <> <NavItem to="/" onClick={handleClick} activeClassName="link-active"> Inicio </NavItem> <NavItem to="/servicios/" onClick={handleClick} activeClassName="link-active" > Servicios </NavItem> <NavItem to="/acerca-de/" onClick={handleClick} activeClassName="link-active" > Acerca De </NavItem> <NavItem to="/contacto/" onClick={handleClick} activeClassName="link-active" > Contacto </NavItem> </> ); } <file_sep>import React from 'react'; import S from '@sanity/desk-tool/structure-builder'; import { GiCctvCamera } from 'react-icons/gi'; export default function Sidebar() { return S.list() .title(`Seguridad Electrónica Integral`) .items([ S.listItem() .title('Inicio') .icon(() => <GiCctvCamera />) .child(S.editor().schemaType('siteSettings').documentId('central')), ...S.documentTypeListItems().filter( (item) => item.getId() !== 'siteSettings' ), ]); } <file_sep>import React, { useState, useEffect } from 'react'; import Nav from './Nav'; import GlobalStyles from '../styles/GlobalStyles'; import Typography from '../styles/Typography'; import Footer from './Footer'; export default function Layout({ children }) { // determined if page has scrolled and if the view is on mobile const [scrolled, setScrolled] = useState(false); // change state on scroll useEffect(() => { const handleScroll = () => { const isScrolled = window.scrollY > 100; if (isScrolled) { setScrolled(true); } else { setScrolled(false); } }; document.addEventListener('scroll', handleScroll, { passive: true }); return () => { // clean up the event handler when the component unmounts document.removeEventListener('scroll', handleScroll); }; }, [scrolled]); return ( <> <GlobalStyles /> <Typography /> <Nav scrolled={scrolled} /> {children} <Footer /> </> ); } <file_sep>import { graphql, useStaticQuery } from 'gatsby'; import Img from 'gatsby-image'; import React from 'react'; import styled from 'styled-components'; import { ButtonStyles } from '../styles/Button'; const TechnologyStyles = styled.section` height: 100%; width: 100%; min-height: 100vh; display: grid; --columns: 2; grid-template-columns: repeat(var(--columns), 1fr); font-family: 'latoblack'; background-color: var(--titan-white); @media (max-width: 720px) { --columns: 1; } `; const TextSideStyles = styled.div` padding: 12rem 5vw 5rem; color: var(--blue-vogue); display: flex; flex-direction: column; justify-content: center; font-size: clamp(1.2rem, 3vw, 1.8rem); @media (max-width: 720px) { order: 2; padding: 0px 5vw 5rem; } h2 { font-size: clamp(1.2rem, 3vw, 1.8rem); margin-bottom: 1rem; } h3 { font-size: clamp(2.5rem, 5vw, 5rem); margin-bottom: 2rem; a { text-decoration: underline; } } `; const SideImageStyles = styled.div` display: flex; flex-direction: column; justify-content: center; padding-top: 10rem; padding-bottom: 10rem; @media (max-width: 720px) { padding: 10rem 5vw 0; } `; export default function Technology() { const { image } = useStaticQuery(graphql` query { image: file(relativePath: { eq: "cameras.png" }) { sharp: childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } } `); return ( <TechnologyStyles> <TextSideStyles> <h2>TECNOLOGÍA</h2> <h3> DISTRIBUIDORES AUTORIZADOS DE{' '} <a href="https://www.hikvision.com/" title="Hikvision" target="_blank" rel="noopener noreferrer" > HIKVISION </a>{' '} Y{' '} <a href="https://www.epcom.net/" title="Epcom" target="_blank" rel="noopener noreferrer" > EPCOM </a> , MARCAS LÍDERES EN EL MERCADO DE SEGURIDAD. </h3> <ButtonStyles>CONTACTANOS</ButtonStyles> </TextSideStyles> <SideImageStyles> <Img fluid={image.sharp.fluid} /> </SideImageStyles> </TechnologyStyles> ); } <file_sep>import { AiFillProject as icon } from 'react-icons/ai'; export default { name: 'project', title: 'Proyecto', type: 'document', icon, fields: [ { name: 'title', title: 'Título', type: 'string', }, { name: 'slug', title: 'Slug', type: 'slug', options: { source: 'title', maxLength: 96, }, }, { name: 'subtitle', title: 'Introducción', type: 'text', }, { name: 'mainImage', title: 'Imagen Principal', type: 'image', options: { hotspot: true, }, }, { name: 'categories', title: 'Categorías', type: 'array', of: [{ type: 'reference', to: { type: 'category' } }], }, { name: 'publishedAt', title: 'Fecha de Publicación', type: 'datetime', }, { name: 'body', title: 'Contenido', type: 'blockContent', }, ], preview: { select: { title: 'title', media: 'mainImage', subtitle: 'publishedAt', }, }, }; <file_sep>import React from 'react'; import { LayoutStyles } from '../styles/LayoutStyles'; export default function Services() { return ( <LayoutStyles> <span>Servicios</span> </LayoutStyles> ); } <file_sep>import React from 'react'; import styled from 'styled-components'; const ProjectStyles = styled.article` height: 460px; background-color: var(--titan-white); border-radius: 20px; padding: 2rem; box-shadow: 0 5px 10px rgba(154, 160, 185, 0.05), 0 15px 40px rgba(166, 173, 201, 0.2); `; export default function Project() { return <ProjectStyles>Project</ProjectStyles>; } <file_sep>import * as React from 'react'; import { Link } from 'gatsby'; import styled from 'styled-components'; const PageStyles = styled.main` padding: 8rem 10rem 5rem 10rem; height: 100%; min-height: 100vh; display: flex; flex-direction: column; align-items: center; background-position: center; background-repeat: no-repeat; background-size: cover; .container { background-color: var(--cape-cod-70); color: var(--white); padding: 2rem; } @media (max-width: 48rem) { padding: 8rem 1rem 5rem 1rem; } `; // markup const NotFoundPage = () => ( <PageStyles> <div className="container"> <title>No Encontrada</title> <h1>Pagina no encontrada</h1> <p> Lo Siento{' '} <span role="img" aria-label="Pensive emoji"> 😔 </span>{' '} No pudimos encontrar la página que buscabas. <br /> <strong> <Link to="/">ir a Inicio.</Link> </strong> . </p> </div> </PageStyles> ); export default NotFoundPage; <file_sep>import React from 'react'; import styled from 'styled-components'; import { ButtonStyles } from '../styles/Button'; import Project from './Project'; const ProjectsStyles = styled.section` padding: 12rem 5vw 5rem; min-height: 100vh; height: 100%; width: 100%; font-family: 'latoblack'; h2 { font-size: clamp(1.2rem, 3vw, 1.8rem); margin-bottom: 1rem; } h3 { font-size: clamp(2.5rem, 5vw, 5rem); } .button-container { width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; } `; const ProjectsGrid = styled.div` display: grid; --columns: 3; grid-template-columns: repeat(var(--columns), 1fr); margin-top: 2rem; margin-bottom: 4rem; gap: 2rem; @media (max-width: 720px) { --columns: 1; } `; export default function Projects() { return ( <ProjectsStyles> <h2>PROYECTOS</h2> <h3>Un proyecto de seguridad adaptado a tus necesidades</h3> <ProjectsGrid> {[1, 2, 3].map((_, i) => ( <Project key={i} /> ))} </ProjectsGrid> <div className="button-container"> <ButtonStyles>CONTACTANOS</ButtonStyles> </div> </ProjectsStyles> ); } <file_sep>import { IoMdSettings as icon } from 'react-icons/io'; export default { name: 'siteSettings', type: 'document', title: 'Ajustes del Sitio', icon, fields: [ { name: 'title', type: 'string', title: 'Título', }, { name: 'description', type: 'text', title: 'Descripción', description: 'Describe tu sitio para busquedas en google y redes sociales.', }, { name: 'phone', type: 'string', title: 'Teléfono', description: 'Teléfono de contacto que será usado en el pié de página', }, { name: 'email', type: 'string', title: 'E-mail', description: 'mail de contacto que será usado en el pié de página', }, { name: 'facebook', type: 'string', title: 'Facebook', description: 'Facebook que será usado en el pié de página', }, { name: 'whatsapp', type: 'string', title: 'Whatsapp', description: 'Whatsapp que será usado en el pié de página', }, { name: 'address', type: 'string', title: 'Dirección', description: 'Dirección que será usada en el pié de página', }, { name: 'addressUrl', type: 'string', title: 'Url Dirección', description: 'Url para Google Maps que será usada en el pié de página', }, { name: 'projects', title: 'Proyectos a Mostrar', type: 'array', of: [{ type: 'reference', to: [{ type: 'project' }] }], validation: (Rule) => Rule.max(3), }, ], }; <file_sep>import React from 'react'; import { LayoutStyles } from '../styles/LayoutStyles'; export default function Contact() { return ( <LayoutStyles> <span>Contacto</span> </LayoutStyles> ); } <file_sep>import { graphql, useStaticQuery } from 'gatsby'; import BackgroundImage from 'gatsby-background-image'; import React from 'react'; import styled from 'styled-components'; import { ButtonStyles } from '../styles/Button'; const DescriptionStyles = styled.section` margin-top: -1px; height: 100%; width: 100%; min-height: 100vh; display: grid; grid-template-columns: repeat(2, 1fr); font-family: 'latoblack'; position: relative; @media (max-width: 720px) { display: block; } `; const SideImageStyles = styled(BackgroundImage)` background-position: center; background-repeat: no-repeat; background-size: cover; @media (max-width: 720px) { height: 100vh; } `; const TextSideStyles = styled.div` padding: 12rem 5vw 5rem; background-color: var(--texas-rose); color: var(--blue-vogue); display: flex; flex-direction: column; justify-content: center; font-size: clamp(1.2rem, 3vw, 1.8rem); @media (max-width: 720px) { position: absolute; top: 0; bottom: 0; background: linear-gradient( 80deg, var(--texas-rose-70) 75%, transparent 100% ); } h2 { font-size: clamp(1.2rem, 3vw, 1.8rem); margin-bottom: 1rem; } h3 { font-size: clamp(2.5rem, 5vw, 5rem); } p { font-size: clamp(1.2rem, 3vw, 1.8rem); margin-bottom: 3rem; } `; export default function Description() { const { image } = useStaticQuery(graphql` query { image: file(relativePath: { eq: "side-camera.jpg" }) { sharp: childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } } `); return ( <DescriptionStyles> <SideImageStyles Tag="div" fluid={image.sharp.fluid} /> <TextSideStyles> <h2>PROYECTOS PERSONALIZADOS</h2> <h3>COTIZAMOS, DISEÑAMOS E IMPLEMENTAMOS TU PROYECTO</h3> <p> Todos nuestros productos trabajan juntos para proveer máxima eficacia y así asegurar la entera satisfacción de nuestros clientes. </p> <ButtonStyles>CONTACTANOS</ButtonStyles> </TextSideStyles> </DescriptionStyles> ); } <file_sep>import React from 'react'; import styled from 'styled-components'; import { LayoutStyles } from '../styles/LayoutStyles'; const AboutStyles = styled(LayoutStyles)` padding: 15rem 12vw 5rem; --scaleX: 1; .title { position: relative; font-family: 'latoblack'; font-size: clamp(2.5rem, 5vw, 5rem); &::before { height: 5px; content: ''; position: absolute; width: 100%; background: var(--burnt-sienna); bottom: -2px; z-index: -1; transition: transform 0.1s ease 0s; transform: skew(-20deg) rotate(1.64deg) scaleX(var(--scaleX)); } } `; export default function About() { return ( <AboutStyles> <div className="container"> <h2 className="title">QUIENES SOMOS</h2> </div> </AboutStyles> ); } <file_sep>import styled from 'styled-components'; export const ButtonStyles = styled.button` font-family: 'latobold'; border-radius: 25px; height: 50px; width: 16rem; padding: 0.5rem; cursor: pointer; background-color: var(--burnt-sienna); border: none; color: var(--blue-vogue); box-shadow: 2px 3px 6px 0 rgba(0, 0, 0, 0.5); font-size: 1.2rem; transition: 0.6s; @media (max-width: 768px) { width: 14rem; } @media (max-width: 368px) { width: 12rem; font-size: 1rem; } &:focus { outline: none; } &:disabled { background-color: #aaa; color: grey !important; border: 1px solid grey; pointer-events: none; } &:hover { background-color: var(--blue-vogue); color: var(--white); transition: 0.6s; } `;
15f671e4fb0839d41a139dee388f7e33a615077c
[ "JavaScript" ]
16
JavaScript
luishcastroc/seguridad-electronica
62ade79d4c1a33bf44106fa9639bccc5e1935528
a2316409508f06e0bbd0d85f2a4fdc50ce1c755a
refs/heads/master
<repo_name>mohibkhan-nedian/Student-Management-System-RESTful-Webservice<file_sep>/src/main/java/com/springapp/mvc/dao/Studentdaoimpl.java package com.springapp.mvc.dao; import com.springapp.mvc.domain.Student; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * Created by mohib on 10/27/2015. */ @Repository public class Studentdaoimpl implements Studentdao { @Autowired private SessionFactory sessionFactory; @Override public void insert(Student student) { sessionFactory.getCurrentSession().saveOrUpdate(student); } @Override public void delete(int id) { Student student =(Student)sessionFactory.getCurrentSession().get(Student.class,id); sessionFactory.getCurrentSession().delete(student); } @Override public Student getStudentById(int id){ Student student =(Student)sessionFactory.getCurrentSession().get(Student.class,id); return student; } @Override public Student update(int id,String name){ Student student =(Student)sessionFactory.getCurrentSession().get(Student.class,id); student.setName(name); sessionFactory.getCurrentSession().saveOrUpdate(student); return student; } @Override public Student update(int id, int age, String name){ Student student =(Student)sessionFactory.getCurrentSession().get(Student.class,id); student.setName(name); student.setAge(age); sessionFactory.getCurrentSession().saveOrUpdate(student); return student; } } <file_sep>/README.md # Student-Management-System-RESTful-Webservice A RESTful web service for managing student records developed using Java, Spring Framework, JSP and Hibernate with MySQL. <file_sep>/src/main/java/com/springapp/mvc/service/StudentServiceImpl.java package com.springapp.mvc.service; import com.springapp.mvc.dao.Studentdao; import com.springapp.mvc.dao.Studentdaoimpl; import com.springapp.mvc.domain.Student; import com.springapp.mvc.dto.StudentDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Created by mohib on 10/27/2015. */ @Service public class StudentServiceImpl implements StudentService { @Autowired private Studentdao studentdao; // actually object of studentdaoimpl is created, see mvc-dispatcher-servlet.xml @Override @Transactional public void insert(Student student) { studentdao.insert(student); } @Override @Transactional public void delete(int id ){ studentdao.delete(id); } @Override @Transactional public Student update( int id, String name ){ Student student = studentdao.update( id, name); return student; } @Override @Transactional public Student update(int id, int age, String name ){ Student student = studentdao.update( id, age, name); return student; } @Override @Transactional public Student getStudentById(int id) { Student student = (Student)studentdao.getStudentById(id); return student; } } <file_sep>/src/main/java/com/springapp/mvc/service/StudentService.java package com.springapp.mvc.service; import com.springapp.mvc.dao.Studentdao; import com.springapp.mvc.domain.Student; /** * Created by mohib on 10/27/2015. */ // although dao and service interfaces are usually same...following is wrong, studentservice shouldnt extend dao public interface StudentService extends Studentdao{ // made another interface for studentservice to add some special behavior if required other than defined in dao }
334e6607c901a207aecd37bc3df1aa8bb21dd905
[ "Markdown", "Java" ]
4
Java
mohibkhan-nedian/Student-Management-System-RESTful-Webservice
241152e8c44af004d789e4fc46dc311253866b66
a1a92586c690f5140603887fe93ea6e0f90719d5
refs/heads/master
<repo_name>zyrjdtyrj/casino<file_sep>/app/Http/Controllers/Casino/Game/SlotController.php <?php namespace App\Http\Controllers\Casino\Game; use App\Models\Prize; use App\Services\Casino; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\App; class SlotController extends Controller { public function show() { /** * @var $casinoService Casino */ $casinoService = App::make('CasinoService'); $gambler = $casinoService->getGambler(); $prizes = Prize::getPrizesOfGambler($gambler); //dd($prizes); return view('casino.slot', ['message' => null]); } public function play() { /** * @var Casino $casino */ $casino = App::make('CasinoService'); $prize = $casino->generatePrize(); return view('casino.slot', ['message' => $prize->getPrizeName()]); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', [\App\Http\Controllers\HomeController::class, 'welcome'])->name('welcome'); Route::get('/casino/bank', [\App\Http\Controllers\Casino\Game\CasinoController::class, 'bank']) ->name('casino.bank'); Route::get('/casino/slot', [\App\Http\Controllers\Casino\Game\SlotController::class, 'show']) ->middleware('auth') ->name('casino'); Route::post('/casino/slot', [\App\Http\Controllers\Casino\Game\SlotController::class, 'play']) ->middleware('auth'); Route::get('/casino/prizes', [\App\Http\Controllers\Casino\Game\PrizesController::class, 'prizes']) ->middleware('auth') ->name('casino.prizes'); Route::post('/casino/prizes', [\App\Http\Controllers\Casino\Game\PrizesController::class, 'prizeCancel']) ->middleware('auth'); // TODO: make authentication for admins Route::get('/casino/admin', [\App\Http\Controllers\Casino\Admin\AdminController::class, 'prizesShow']) ->name('casino.admin'); Route::post('/casino/admin', [\App\Http\Controllers\Casino\Admin\AdminController::class, 'prizeAction']); Auth::routes(); <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Models\Gambler; use Illuminate\Support\Facades\Auth; class HomeController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function welcome() { if (Auth::user()) { return redirect()->route('casino'); } else { $users = Gambler::all(); return view('home', ['users' => $users]); } } } <file_sep>/database/factories/CasinoGiftFactory.php <?php namespace Database\Factories; use App\Models\CasinoGift; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class CasinoGiftFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = CasinoGift::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => self::getRandomName(), 'amount' => mt_rand(1,10) ]; } private function getRandomName () { static $names = [ 'POC Obex BC SPIN', '1More Stylish', 'Fellow Carter Mug, 16 oz.', 'Tern HSD S8i', 'Tile Sticker', 'ZSA Planck EZ', 'One Eleven SWII Solar Three-Hand rPet Watch', 'Cybex e-Priam', 'Fujifilm Instax Mini LiPlay', 'Timbuk2 Tech Tote', 'IK Multimedia Uno Drum', 'Industry West 1L Carafe', 'Anden Cameo Mirror', 'Roku Smart Soundbar', 'Civil Doppio 65', 'Giant Microbes Waterbear', 'Razer Blade 15', 'Tecnica Plasma S GTX', 'Frank DePaula FrankOne Coffee Maker', 'Form Leather Laptop Case', 'Nintendo Switch Lite', 'Sonos Move', 'DJI Robomaster S1', 'Denon DP-450USB', 'Am I Overthinking This?', 'Sphero Mini Activity Kit', 'Onewheel Pint', 'Garmin Fenix 6S Pro', 'BioLite Headlamp 330', 'JBL L100 Classic', 'Master &amp; Dynamic MW65', 'Sensel Morph With Buchla Thunder Overlay', 'Craighill Venn Puzzle', 'Leica Q2', 'BedJet 3', 'Yubico YubiKey 5Ci', 'Vizio P-Series Quantum 4K 65-Inch', 'Yuki Otoko “Snow Yeti” Sake, 24 oz.', 'SmartWool Women\'s Smartloft-X 60 Hoodie Full Zip', 'Gantri Buddy Light', 'Google Nest Hub Max', 'Sandworm', 'SteelSeries Arctis 1 Wireless', 'Breville Super Q', 'OnePlus 7T', 'Form Swim Goggles (With Display)', 'Stellar Factory Peek & Push', 'Raspberry Pi 4', 'Amazon Kindle', 'R<NAME>', 'Black &amp; Decker Furbuster' ]; static $index = 0; if (!$index) shuffle($names); if (++$index >= count($names)) return Str::random(20); return $names[$index]; } } <file_sep>/tests/Unit/PrizeMoneyServiceTest.php <?php namespace Tests\Unit; use App\Services\PrizeFactory; use PHPUnit\Framework\TestCase; use App\Services\Prize\PrizeMoneyService; use Mockery as M; class PrizeMoneyServiceTest extends TestCase { /** * @dataProvider dataForConvertMoneyToBonus */ public function testConvertMoneyToBonus($rate, $moneyAmount, $bonusAmount) { $prizeFactory = M::mock(PrizeFactory::class); $config = [ 'generatePrize' => [ 'amountMin' => 1, 'amountMax' => 10, ], 'rateConvertToBonus' => $rate ]; $prizeMoneyService = new PrizeMoneyService($prizeFactory, $config); $this->assertEquals($bonusAmount, $prizeMoneyService->convertMoneyToBonus($moneyAmount)); } public function dataForConvertMoneyToBonus() { // rate, money, bonus return [ [1, 1, 1], [2, 1, 2], [1.5, 10, 15], [1.3, 3, 4] ]; } } <file_sep>/database/migrations/2020_15_12_102436_create_prizes_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePrizesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('prizes', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('gambler_id'); $table->enum('type', ['Gift','Bonus','Money']); $table->enum('state', ['wait', 'canceled', 'received', 'converted']); $table->longText('prize'); $table->timestamps(); $table->foreign('gambler_id') ->references('id') ->on('gamblers') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('prizes'); } } <file_sep>/app/Services/Prize/PrizeMoneyService.php <?php namespace App\Services\Prize; use App\Models\Gambler; use App\Models\Prize; use App\Models\PrizeMoney; use App\Services; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\App; class PrizeMoneyService extends AbstractPrizeService { /** * @var int */ protected $amountPrizeMin; /** * @var int */ protected $amountPrizeMax; /** * @var float */ protected $rateConvertToBonus; /** * PrizeMoneyService constructor. * @param Services\PrizeFactory $prizeFactory * @param null|array $config */ public function __construct(Services\PrizeFactory $prizeFactory, $config = null) { parent::__construct($prizeFactory); $this->amountPrizeMin = isset($config['generatePrize']['amountMin']) ? $config['generatePrize']['amountMin'] : config('casino.prizeServices.' . static::class . '.generatePrize.amountMin'); $this->amountPrizeMax = isset($config['generatePrize']['amountMax']) ? $config['generatePrize']['amountMax'] : config('casino.prizeServices.' . static::class . '.generatePrize.amountMax'); $this->rateConvertToBonus = isset($config['rateConvertToBonus']) ? $config['rateConvertToBonus'] : config('casino.prizeServices.' . static::class . '.rateConvertToBonus'); } public function allowedPrizeGenerate() { $casinoService = $this->getCasinoService(); if ($casinoService->moneyGetAvailable() > 0) { return true; } return false; } /** * @param Gambler $gambler * @return PrizeMoney */ public function generatePrize($gambler = null) { $moneyAvailable = $this->getCasinoService()->moneyGetAvailable(); // Profitable solution for Gambler $amountBonus = mt_rand($this->amountPrizeMin, $this->amountPrizeMax); $amountBonus = min($amountBonus, $moneyAvailable); // // Profitable solution for Casino // $amountBonus = mt_rand($this->amountPrizeMin, min($moneyAvailable, $this->amountPrizeMax)); $prize = $this->prizeFactory->create('Money', ['amount' => $amountBonus], $gambler); return $prize; } /** * @param int $limit * @return Collection */ public function getPrizesForCrediting($limit = 10) { return PrizeMoney::where('state', 'wait')->orderBy('id')->limit($limit)->get(); } /** Prize events on created * @param PrizeMoney $prize */ public function eventPrizeStateWait(Prize $prize) { $this->getCasinoService()->moneyReserved($prize->getAmount()); } /** Prize events before change state to Canceled * @param PrizeMoney $prize */ public function eventPrizeStateCanceled(Prize $prize) { $this->getCasinoService()->moneyUnreserved($prize->getAmount()); } /** Prize events before change state to Received * @param PrizeMoney $prize */ public function eventPrizeStateReceived(Prize $prize) { /** * @var $bankService Services\BankService */ $bankService = App::make('CasinoBankService'); $bankService->sendOrderToBank([ 'recipient' => $prize->getGambler()->name, 'amount' => $prize->getAmount() ]); } /** Prize events before change state to Converted * @param PrizeMoney $prize */ public function eventPrizeStateConverted(PrizeMoney $prize) { $bonusPlus = $this->convertMoneyToBonus($prize->getAmount()); $casinoService = $this->getCasinoService(); $casinoService->bonusGamblerPlus($prize->getGambler(), $bonusPlus); $casinoService->moneyUnreserved($prize->getAmount()); $prize->setBonusAmount($bonusPlus); } public function convertMoneyToBonus($amountMoney) { return round($this->rateConvertToBonus * $amountMoney, 0); } } <file_sep>/app/Http/Controllers/Casino/Game/CasinoController.php <?php namespace App\Http\Controllers\Casino\Game; use App\Services\Casino; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\App; class CasinoController extends Controller { public function bank(Request $request) { /** * @var $casino Casino */ $casino = App::make('CasinoService'); $gifts = $casino->giftGetAvailable(); $moneyBank = $casino->moneyGetAvailable(); return view('casino.bank', ['moneyBank' => $moneyBank, 'gifts' => $gifts]); } } <file_sep>/app/Services/Prize/AbstractPrizeService.php <?php namespace App\Services\Prize; use App\Models\Gambler; use App\Models\Prize; use App\Services\Casino; use App\Services\PrizeFactory; use Illuminate\Support\Facades\App; abstract class AbstractPrizeService { /** * @var PrizeFactory */ protected $prizeFactory; /** * PrizeService constructor. * @param PrizeFactory $prizeFactory */ public function __construct(PrizeFactory $prizeFactory) { $this->prizeFactory = $prizeFactory; } /** * @return bool */ abstract public function allowedPrizeGenerate(); /** * @param Gambler $gambler * @return Prize */ abstract public function generatePrize($gambler = null); /** * @return Casino */ protected function getCasinoService() { return App::make('CasinoService'); } } <file_sep>/config/casino.php <?php return [ 'classes' => [ 'prizeFactory' => \App\Services\PrizeFactory::class, 'prizeModel' => \App\Models\Prize::class, 'gamblerModel' => \App\Models\Gambler::class, 'giftModel' => \App\Models\CasinoGift::class, 'moneyModel' => \App\Models\CasinoMoney::class, 'bankService' => \App\Services\BankService::class ], 'prizeServices' => [ \App\Services\Prize\PrizeMoneyService::class => [ 'generatePrize' => [ 'amountMin' => 1, 'amountMax' => 10 ], 'bankService' => [ 'URL' => 'https://api.bank.site', 'SecretKey' => '<KEY>', 'TimeOut' => 10 ], 'rateConvertToBonus' => 2 ], \App\Services\Prize\PrizeBonusService::class => [ 'generatePrize' => [ 'amountMin' => 2, 'amountMax' => 20 ], ], \App\Services\Prize\PrizeGiftService::class => [ ] ] ]; <file_sep>/app/Services/BankService.php <?php namespace App\Services; class BankService { protected $URL; protected $secretKey; protected $timeOut; public function __construct($config = null) { $this->URL = isset ($config['URL']) ? $config['URL'] : config('casino.bankService.URL'); $this->secretKey = isset ($config['SecretKey']) ? $config['SecretKey'] : config('casino.bankService.SecretKey'); $this->timeOut = isset ($config['TimeOut']) ? $config['TimeOut'] : config('casino.bankService.TimeOut'); } /** * @param $data - eny data for money crediting * @return bool */ public function sendOrderToBank($data) { $request = [ 'SecretKey' => $this->secretKey, 'data' => $data ]; // TODO make curl request to URL sleep(1); // Generate fake results, 30% - errors, 70% - successful if (mt_rand(1,10)>3) return true; // successful else throw new \LogicException('Error connect to bank (for example)'); // error } } <file_sep>/app/Services/PrizeFactory.php <?php namespace App\Services; use App\Models\Gambler; use App\Models\Prize; use Illuminate\Support\Facades\App; class PrizeFactory { /** * @var array */ protected $prizeTypesMap; public function __construct($typeMap = null) { $this->prizeTypesMap = $typeMap ? $typeMap : Prize::$types; } /** * @param $prizeType * @param $prize * @param null|Gambler $gambler */ public function create($prizeType, $prizeData, $gambler=null) { if (!array_key_exists($prizeType, $this->prizeTypesMap)) { throw new \InvalidArgumentException('Invalid prize type'); } if (!$gambler) { $gambler = App::make('CasinoService')->getGambler(); } $prize = new $this->prizeTypesMap[$prizeType] ([ 'gambler_id' => $gambler->id, 'type' => $prizeType, 'prize' => $prizeData, 'state' => 'wait' ]); $prize->save(); return $prize; } } <file_sep>/app/Models/PrizeGift.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; class PrizeGift extends Prize { use HasFactory; public static $type = 'Gift'; /** * @return int */ public function getGift() { return CasinoGift::find($this->prize['gift']); } public function getPrizeName() { return static::$type . ': ' . $this->prize['name']; } } <file_sep>/app/Services/Prize/PrizeGiftService.php <?php namespace App\Services\Prize; use App\Models\Gambler; use App\Models\Prize; use App\Models\PrizeGift; use App\Services; use Illuminate\Database\Eloquent\Collection; class PrizeGiftService extends AbstractPrizeService { /** * @var Services\PrizeFactory */ protected $prizeFactory; /** * @var int */ protected $amountPrizeMin; /** * @var int */ protected $amountPrizeMax; /** * PrizeMoneyService constructor. * @param Services\PrizeFactory $prizeFactory * @param null|array $config */ public function __construct(Services\PrizeFactory $prizeFactory) { parent::__construct($prizeFactory); } /** * @return Collection */ protected function getAvailableGifts() { return $this->getCasinoService()->giftGetAvailable(); } /** * @return bool */ public function allowedPrizeGenerate() { if ($this->getAvailableGifts()->count() > 0) return true; return false; } /** * @param Gambler $gambler * @return PrizeGift */ public function generatePrize($gambler = null) { $availableGifts = $this->getAvailableGifts(); $giftRandom = $availableGifts->shuffle()->first(); $prize = $this->prizeFactory->create( 'Gift', ['gift' => $giftRandom->id, 'name' => $giftRandom->name], $gambler ); return $prize; } public function eventPrizeStateWait(Prize $prize) { $this->getCasinoService()->giftSetUsed($prize->getGift()); } public function eventPrizeStateCanceled(Prize $prize) { $this->getCasinoService()->giftSetUnused($prize->getGift()); } } <file_sep>/database/seeders/Prizes.php <?php namespace Database\Seeders; use App\Models\Gambler; use App\Services\Casino; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\App; class Prizes extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { /** * @var $casinoService Casino */ $casinoService = App::make('CasinoService'); $gamblers = Gambler::all(); $count = $gamblers->count() * 10; for ($i = 0; $i < $count; $i++) { $gambler = $gamblers->random(1)->first(); $casinoService->generatePrize($gambler); } } } <file_sep>/database/seeders/DatabaseSeeder.php <?php namespace Database\Seeders; use App\Models\CasinoGift; use App\Models\Gambler; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call(CasinoMoney::class); CasinoGift::factory(50)->create(); Gambler::factory(10)->create(); $this->call(Prizes::class); } } <file_sep>/database/seeders/CasinoMoney.php <?php namespace Database\Seeders; use App\Models\PrizeMoney; use Illuminate\Database\Seeder; class CasinoMoney extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { \DB::table('casino_money') ->insert([ 'id' => 1, 'bank' => 10000 ]); } } <file_sep>/app/Console/Commands/sendToBankCommand.php <?php namespace App\Console\Commands; use App\Models\PrizeMoney; use App\Services\Prize\PrizeMoneyService; use Illuminate\Console\Command; use Illuminate\Support\Facades\App; class sendToBankCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'casino:send2bank {NumberOrders? : Maximum number orders}'; /** * The console command description. * * @var string */ protected $description = 'The command sends orders to the bank for crediting prizes'; /** * @var string */ protected $help = <<<TXT The only command parameter specifies the maximum number of records to process Default limit is TXT; /** default limit process records * @var int */ protected $limit = 10; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int */ public function handle() { $arguments = $this->arguments(); $limit = $arguments['NumberOrders']; if ($limit && !is_numeric($limit)) { $this->error('Required number'); return 1; } elseif (!$limit) { $this->info($this->description . PHP_EOL . $this->help . ' ' . $this->limit); $limit = $this->limit; } if (!$this->confirm('Send to bank [' . $limit . '] orders?', true)) { return 0; } /** * @var $moneyService PrizeMoneyService */ $moneyService = App::make('PrizeMoneyService'); $moneyPrizes = $moneyService->getPrizesForCrediting($limit); $errors = []; $okCounter = 0; $this->withProgressBar($moneyPrizes, function ($prize) use (&$errors, &$okCounter) { /** * @var $prize PrizeMoney */ try { $prize->state = 'received'; $okCounter++; } catch (\Exception $exception) { $errors[] = $prize->id . '# [' . $prize->getPrizeName() . '] ' . $exception->getMessage(); } }); $resultsStr = PHP_EOL . 'Results: Ok-' . $okCounter; if (count($errors)) { $resultsStr .= ', Errors-' . count($errors); $resultsStr .= ', Total-' . ($okCounter + count($errors)); } $resultsStr .= PHP_EOL; $this->info($resultsStr); if (count($errors)) { $errorsStr = 'Errors:' . PHP_EOL; foreach ($errors as $error) { $errorsStr .= $error . PHP_EOL; } $this->error($errorsStr); } return 0; } } <file_sep>/app/Services/Prize/PrizeBonusService.php <?php namespace App\Services\Prize; use App\Models\Gambler; use App\Models\PrizeBonus; use App\Services; class PrizeBonusService extends AbstractPrizeService { /** * @var Services\PrizeFactory */ protected $prizeFactory; /** * @var int */ protected $amountPrizeMin; /** * @var int */ protected $amountPrizeMax; /** * PrizeMoneyService constructor. * @param Services\PrizeFactory $prizeFactory * @param null|array $config */ public function __construct(Services\PrizeFactory $prizeFactory, $config = null) { parent::__construct($prizeFactory); $this->amountPrizeMin = isset($config['generatePrize']['amountMin']) ? $config['generatePrize']['amountMin'] : config('casino.prizeServices.'.static::class.'.generatePrize.amountMin'); $this->amountPrizeMax = isset($config['generatePrize']['amountMax']) ? $config['generatePrize']['amountMax'] : config ('casino.prizeServices.'.static::class.'.generatePrize.amountMax'); } public function allowedPrizeGenerate() { return true; } /** * @param Gambler $gambler * @return PrizeBonus */ public function generatePrize($gambler = null) { $amountBonus = mt_rand($this->amountPrizeMin, $this->amountPrizeMax); $prize = $this->prizeFactory->create('Bonus', ['amount' => $amountBonus], $gambler); $prize->state = 'received'; $prize->save(); return $prize; } public function eventPrizeStateReceived(PrizeBonus $prize) { $this->getCasinoService()->bonusGamblerPlus($prize->getGambler(), $prize->getAmount()); } public function eventPrizeStateCanceled(PrizeBonus $prize) { $this->getCasinoService()->bonusGamblerMinus($prize->getGambler(), $prize->getAmount()); } } <file_sep>/README.md ## Test casino Author: _[<NAME>](<EMAIL>)_ ## Instalation Install vendors packages. ``` composer install ``` Configure connection to mysql server in file `.env`. Create database structure and fixtures. ``` php artisan migrate php artisan db:seed ``` ## Start server ``` php artisan serve ``` ## Commandline Command for sending orders to the bank for money prizes. Optional parameter *number* limits the number of processed records. ``` php artisan casino:send2bank {number} ``` ## Unit tests ``` phpunit ``` <file_sep>/app/Http/Controllers/Casino/Admin/AdminController.php <?php namespace App\Http\Controllers\Casino\Admin; use App\Models\Prize; use App\Services\Casino; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\App; class AdminController extends Controller { public function prizesShow(Request $request) { /** * @var $casino Casino */ $prizes = Prize::where('state', 'wait')->orderBy('id')->limit(20)->get(); // !!! Preloading completed but not used. This is weird and shouldn't be! $prizes->load('gambler'); $message = $request->session()->pull('message'); $error = $request->session()->pull('error'); return view('admin.prizes', ['prizes' => $prizes, 'message' => $message, 'error' => $error]); } public function prizeAction(Request $request) { $prizeCancelId = request('cancel'); $prizeSendId = request('send'); if (!$prizeCancelId && !$prizeSendId) { redirect()->back(); } try { if ($prizeCancelId) { $prize = Prize::find($prizeCancelId); $prize->state = 'canceled'; } else { $prize = Prize::find($prizeSendId); $prize->state = 'receive'; } $prize->save(); $request->session()->flash('message', 'Successful!'); } catch (\Exception $exception) { $request->session()->flash('error', $exception->getMessage()); } return redirect()->back(); } } <file_sep>/app/Services/Casino.php <?php namespace App\Services; use App\Models\CasinoGift; use App\Models\Gambler; use App\Models\Prize; use App\Models\User; use App\Services\Prize\AbstractPrizeService; use Illuminate\Support\Collection; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; class Casino { /** * @var PrizeFactory */ protected $prizeFactory; /** * @var AbstractPrizeService[] */ protected $prizeServices; /** * @var string */ protected $gamblerModelClass; /** * @var string */ protected $giftModelClass; /** * @var string */ protected $moneyModelClass; public function __construct( $prizeFactoryClass = null, $prizeServiceClasses = null, $gamblerModelClass = null, $giftModelClass = null, $moneyModelClass = null, $bankServiceClass = null ) { $prizeFactoryClass = $prizeFactoryClass ? $prizeFactoryClass : config('casino.classes.prizeFactory'); $this->prizeFactory = $prizeFactory = new $prizeFactoryClass(); $this->gamblerModelClass = $gamblerModelClass ? $gamblerModelClass : config('casino.classes.gamblerModel'); $this->giftModelClass = $giftModelClass ? $giftModelClass : config('casino.classes.giftModel'); $this->moneyModelClass = $moneyModelClass ? $moneyModelClass : config('casino.classes.moneyModel'); if (!$bankServiceClass) $bankServiceClass = config ('casino.classes.bankService'); App::bind('CasinoBankService', $bankServiceClass); $prizeServiceClasses = isset($prizeServiceClasses) ? new Collection($prizeServiceClasses) : new Collection(array_keys(config('casino.prizeServices'))); $this->prizeServices = $prizeServiceClasses->map(function($serviceName) use ($prizeFactory) { return new $serviceName($prizeFactory); }); // Create singletons to call services by name in the application $this->prizeServices->each(function($service) { App::singleton(class_basename($service), function() use ($service){ return $service; }); }); } /** * @param Gambler $gambler * @return Prize * @throws \Exception */ public function generatePrize ($gambler = null) { $allowedPrizeServices = $this->prizeServices->filter(function($prizeService){ return $prizeService->allowedPrizeGenerate(); }); if (!count($allowedPrizeServices)) { throw new \Exception('Not allowed prize services'); } /** * @var $randomService AbstractPrizeService */ $randomService = $allowedPrizeServices->random(1)->first(); $prize = $randomService->generatePrize($gambler); return $prize; } public function giftGetAvailable() { $giftModelClass = $this->giftModelClass; return $giftModelClass::where('amount', '>', '0')->get(); } public function giftSetUsed(CasinoGift $casinoGift) { if ($casinoGift->amount < 1) throw new \LogicException('Gift is no longer available'); $casinoGift->amount = $casinoGift->amount -1; $casinoGift->save(); } public function giftSetUnused(CasinoGift $casinoGift) { $casinoGift->amount = $casinoGift->amount +1; $casinoGift->save(); } /** * @return int */ public function moneyGetAvailable() { return $this->moneyModelClass::find(1)->bank; } public function moneyReserved($amount) { $bank = $this->moneyModelClass::find(1); if ($bank->bank < $amount) { throw new \LogicException('Casino bank haven\'t such money'); } $bank->bank = $bank->bank - $amount; $bank->save(); } public function moneyUnreserved($amount) { $bank = $this->moneyModelClass::find(1); $bank->bank = $bank->bank + $amount; $bank->save(); } /** * @param $gambler Gambler * @param $amount int */ public function bonusGamblerPlus(Gambler $gambler, $amount) { $gambler->bonus = $gambler->bonus + $amount; $gambler->save(); } /** * @param $gambler Gambler * @param $amount int */ public function bonusGamblerMinus (Gambler $gambler, $amount) { if($gambler->bonus < $amount) throw new \LogicException('Not enough bonuses'); $gambler->bonus = $gambler->bonus - $amount; $gambler->save(); } /** * @return User */ public function getGambler() { $gambler = Auth::user(); return $gambler; } } <file_sep>/app/Models/PrizeBonus.php <?php namespace App\Models; use App\Services\Prize\PrizeBonusService; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class PrizeBonus extends Prize { use HasFactory; public static $type = 'Bonus'; /** * @return int */ public function getAmount() { return (int)$this->prize['amount']; } public function getPrizeName() { return static::$type . ': ' . $this->prize['amount']; } } <file_sep>/app/Http/Controllers/Casino/Game/PrizesController.php <?php namespace App\Http\Controllers\Casino\Game; use App\Models\Prize; use App\Services\Casino; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\App; class PrizesController extends Controller { public function prizes(Request $request) { /** * @var $casinoService Casino */ $casinoService = App::make('CasinoService'); $gambler = $casinoService->getGambler(); $bonusBalance = $gambler->bonus; $prizes = Prize::getPrizesOfGambler($gambler); $message = $request->session()->pull('message'); $error = $request->session()->pull('error'); return view('casino.prizes', [ 'prizes' => $prizes, 'message' => $message, 'error' => $error, 'bonusBalance' => $bonusBalance ]); } public function prizeCancel(Request $request) { $prizeCancelId = request('cancel'); $prizeConvertId = request('convert'); if (!$prizeCancelId && !$prizeConvertId) { redirect()->back(); } try { if ($prizeCancelId) { $prize = Prize::find($prizeCancelId); $prize->state = 'canceled'; } else { $prize = Prize::find($prizeConvertId); $prize->state = 'converted'; } $prize->save(); $request->session()->flash('message', 'Successful!'); } catch (\Exception $exception) { $request->session()->flash('error', $exception->getMessage()); } return redirect()->route('casino.prizes'); } } <file_sep>/app/Models/Prize.php <?php namespace App\Models; use App\Services\Prize\AbstractPrizeService; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\App; use Illuminate\Support\Str; class Prize extends Model { use HasFactory; public static $types = [ 'Gift' => PrizeGift::class, 'Bonus' => PrizeBonus::class, 'Money' => PrizeMoney::class ]; /** Possible states of an entity * @var string[] */ protected static $states = ['wait', 'canceled', 'received']; public static $type; public $table = 'prizes'; protected $casts = [ 'prize' => 'array' ]; public $fillable = ['gambler_id', 'prize', 'state', 'type']; /** Return name for interface * @return string */ public function getPrizeName(){} public function gambler() { return $this->hasOne(Gambler::class, 'id', 'gambler_id'); } public static function boot() { parent::boot(); static::addGlobalScope(function ($query) { if ($query->getModel()::$type) { $query->where('type', $query->getModel()::$type); } }); } /** * @return Gambler */ public function getGambler() { return Gambler::find($this->gambler_id); } /** Overloading for generating collections of inherited classes * * @param array $attributes * @param null $connection * @return Prize */ public function newFromBuilder($attributes = [], $connection = null) { if (!static::$type) { $model = new static::$types[$attributes->type]([]); return $model->newFromBuilder($attributes, $connection); } return parent::newFromBuilder($attributes, $connection); } /** * @param string $key * @param mixed $val * @return Prize|mixed * @throws \LogicException */ public function setAttribute($key, $val) { if ($key == 'state') { if (!in_array($val, static::$states)) { throw new \InvalidArgumentException('State [' . $val . '] is not correct for this Prize'); } if ($this->state != 'wait' && in_array($val,['received', 'cancel', 'converted'])) { throw new \LogicException('For change state the prize must be in the state \'wait\''); } $prizeService = $this->getService(); $prizeServiceEventMethod = 'eventPrizeState'.Str::ucfirst($val); if (method_exists($prizeService, $prizeServiceEventMethod)) { $prizeService->$prizeServiceEventMethod($this); } } return parent::setAttribute($key, $val); } /** * @return AbstractPrizeService */ public function getService() { /** * @var $service AbstractPrizeService; */ $service = App::make('Prize'.static::$type.'Service'); return $service; } /** * @param Gambler $gambler * @return Prize */ public static function getPrizesOfGambler(Gambler $gambler) { return self::where('gambler_id', $gambler->id)->get(); } } <file_sep>/app/Models/PrizeMoney.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; class PrizeMoney extends Prize { use HasFactory; public static $type = 'Money'; protected static $states = ['wait', 'canceled', 'received', 'converted']; /** * @return int */ public function getAmount() { return (int)$this->prize['amount']; } public function getPrizeName() { $name = static::$type . ': ' . $this->prize['amount'] . '$'; if ($this->state == 'converted') $name .= ' converted to bonus: ' . $this->prize['bonus']; return $name; } public function setBonusAmount($amount) { $prizeData = $this->prize; $prizeData['bonus'] = $amount; $this->prize = $prizeData; } }
382620e399c3817a12138abb8c501b8c317d8522
[ "Markdown", "PHP" ]
26
PHP
zyrjdtyrj/casino
e5ae5de5e49ff71ba3a6ddde0460840a977ba5cd
3e225e6e02735332e79cb9c262834d8309f93c00
refs/heads/master
<file_sep>const Game = require('./game'); const GameView = require('./game_view'); let newGame = null; document.addEventListener('DOMContentLoaded', function () { const view = document.getElementById('view'); const menu = document.getElementById('menu'); const title = document.getElementById('title'); }); document.addEventListener('keydown', function () { const canvasEl = document.getElementById('game'); const ctx = canvasEl.getContext('2d'); canvasEl.width = Game.DIM_X; canvasEl.height = Game.DIM_Y; newGame = newGame || new GameView(ctx); if (event.which === 32 && !newGame.playing) { view.className = 'off'; title.className = 'off'; canvasEl.className = 'fade-in'; newGame.start(); } }); <file_sep>const Util = require("./util"); const MovingObject = require("./moving_object"); const DEFAULTS = { COLOR: "#000", }; const Monster = function (options = {}) { options.color = DEFAULTS.COLOR; options.pos = options.pos || options.game.randomPosition(); options.vel = options.vel || Util.randomVec((Math.random() * 0.5) + .01); this.growing = options.growing || false; this.finalSize = options.finalSize || 0 if (options.game) { options.game } MovingObject.call(this, options); }; Monster.prototype.move = function () { this.pos = [this.pos[0] + this.vel[0], this.pos[1] + this.vel[1]]; }; Util.inherits(Monster, MovingObject); Monster.prototype.type = "Monster"; module.exports = Monster; <file_sep>const Util = { dir(vector) { const norm = Util.norm(vector); return Util.scale(vector, 1 / norm); }, dist(pos1, pos2) { return Math.sqrt( Math.pow(pos1[0] - pos2[0], 2) + Math.pow(pos1[1] - pos2[1], 2) ); }, norm(vector) { return Util.dist([0, 0], vector); }, randomVec(length) { const deg = Math.PI * Math.random(); return Util.scale([Math.sin(deg), Math.cos(deg)], length); }, scale(vector, n) { return [vector[0] * n, vector[1] * n]; }, inherits(Child, Parent) { function Surrogate() { this.constructor = Child; } Surrogate.prototype = Parent.prototype; Child.prototype = new Surrogate(); }, }; module.exports = Util; <file_sep>const Monster = require('./monster'); const Player = require('./player'); const Game = function () { this.objects = []; }; Game.DIM_X = window.innerWidth - 20; Game.DIM_Y = window.innerHeight - 20; Game.NUM_MONSTERS = 250; Game.BG_COLOR = '#fff'; Game.CENTER_X = Game.DIM_X / 2; Game.CENTER_Y = Game.DIM_Y / 2; Game.prototype.addMonsters = function () { for (let i = 0; i < Game.NUM_MONSTERS; i++) { let size; if (i % 25 === 0) { size = Math.random() * 30; } else { size = Math.random() * 6 + 1; } this.objects.push(new Monster({ game: this, radius: size })); } }; Game.prototype.addMonster = function () { const size = 1; let newMonster = new Monster({ game: this, radius: size, growing: true, finalSize: Math.random() * 10 + 2, }); if (this.areaClear(newMonster)) { this.objects.push(newMonster); } else { this.addMonster(); } }; Game.prototype.remove = function (object) { const index = this.objects.indexOf(object); if (index > -1) { this.objects.splice(index, 1); } }; Game.prototype.addPlayer = function () { this.player = new Player({ pos: [Game.CENTER_X, Game.CENTER_Y], game: this, }); this.objects.push(this.player); return this.player; }; Game.prototype.allObjects = function () { return [].concat(this.playerArray, this.monsters); }; Game.prototype.randomPosition = function () { let legitLocation = false; while (!legitLocation) { var coords = getRandomCoords(); if (Math.abs(Game.CENTER_X - coords[0]) > 15 && Math.abs(Game.CENTER_Y - coords[1]) > 15) { legitLocation = true; } } return coords; }; const getRandomCoords = function () { return [ window.innerWidth * Math.random(), window.innerHeight * Math.random(), ]; }; Game.prototype.draw = function (ctx) { ctx.clearRect(0, 0, Game.DIM_X, Game.DIM_Y); ctx.fillStyle = Game.BG_COLOR; ctx.fillRect(0, 0, Game.DIM_X, Game.DIM_Y); this.objects.sort((x, y) => { return x.radius - y.radius }).forEach(function (object) { object.draw(ctx); }); }; Game.prototype.step = function () { this.moveObjects(); this.checkCollisions(); if (Math.random() * 1000 >= 990 && this.objects.length > 4) { this.addMonster(); } this.growMonsters() }; Game.prototype.growMonsters = function () { this.objects.forEach((object) => { if (object.growing) { object.grow() if (object.radius > object.finalSize) { object.growing = false } } }) }; Game.prototype.checkCollisions = function () { for (let i = 0; i < this.objects.length; i++) { for (let j = i + 1; j < this.objects.length; j++) { if (this.objects[i].isCollidedWith(this.objects[j])) { this.objects[i].collideWith(this.objects[j]); } } } }; Game.prototype.areaClear = function (object) { for (let i = 0; i < this.objects.length; i++) { if (object.isCollidedWith(this.objects[i])) { return false } } return true }; Game.prototype.complete = function () { if (this.objects.indexOf(this.player) === -1) { return ('loss'); } else if (this.objects.length === 1) { return ('win'); } }; Game.prototype.moveObjects = function () { this.objects.forEach((object) => { object.move(); object.bounceOffWall(Game.DIM_X, Game.DIM_Y); }); }; module.exports = Game;
cfa69f5471e17369aee41e8b4434afdefb69f17d
[ "JavaScript" ]
4
JavaScript
mbr84/TheHungering
b33863f9f383f48c7b1734664e6e79f58b4adaa7
bdece789fce24939318632925741f0b3d312a39d
refs/heads/master
<repo_name>wssongwenming/view-practice<file_sep>/propertyanime/src/main/java/com/wondertwo/propertyanime/CustomPointActivity.java package com.wondertwo.propertyanime; import android.app.Activity; import android.os.Bundle; /** * CustomPointActivity * Created by wondertwo on 2016/3/27. */ public class CustomPointActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置包含属性动画的自定义view setContentView(R.layout.activity_custom_point); } } <file_sep>/propertyanime/src/main/java/com/wondertwo/propertyanime/BuleToRed.java package com.wondertwo.propertyanime; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; /** * ColorShade实现目标对象背景色的渐变 * Created by wondertwo on 2016/3/23. */ public class BuleToRed extends Activity { private Button targetView; private int mCurrentRed = -1; private int mCurrentGreen = -1; private int mCurrentBlue = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blue_to_red); targetView = (Button) findViewById(R.id.tv_color_backgroound); /** * 注册点击事件,展示效果 */ targetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { displayResult(targetView, "#0000ff", "#ff0000"); } }); } /** * displayResult()展示结果 */ private void displayResult(final View target, final String start, final String end) { // 创建ValueAnimator对象,实现颜色渐变 ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 100f); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { // 获取当前动画的进度值,1~100 float currentValue = (float) animation.getAnimatedValue(); Log.d("当前动画值", "current value : " + currentValue); // 获取动画当前时间流逝的百分比,范围在0~1之间 float fraction = animation.getAnimatedFraction(); // 直接调用evaluateForColor()方法,通过百分比计算出对应的颜色值 String colorResult = evaluateForColor(fraction, start, end); /** * 通过Color.parseColor(colorResult)解析字符串颜色值,传给ColorDrawable,创建ColorDrawable对象 */ /*LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) target.getLayoutParams();*/ ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor(colorResult)); // 把ColorDrawable对象设置为target的背景 target.setBackground(colorDrawable); target.invalidate(); } }); valueAnimator.setDuration(6 * 1000); // 组装缩放动画 ValueAnimator animator_1 = ObjectAnimator.ofFloat(target, "scaleX", 1f, 0.5f); ValueAnimator animator_2 = ObjectAnimator.ofFloat(target, "scaleY", 1f, 0.5f); ValueAnimator animator_3 = ObjectAnimator.ofFloat(target, "scaleX", 0.5f, 1f); ValueAnimator animator_4 = ObjectAnimator.ofFloat(target, "scaleY", 0.5f, 1f); AnimatorSet set_1 = new AnimatorSet(); set_1.play(animator_1).with(animator_2); AnimatorSet set_2 = new AnimatorSet(); set_2.play(animator_3).with(animator_4); AnimatorSet set_3 = new AnimatorSet(); set_3.play(set_1).before(set_2); set_3.setDuration(3 * 1000); // 组装颜色动画和缩放动画,并启动动画 AnimatorSet set_4 = new AnimatorSet(); set_4.play(valueAnimator).with(set_3); set_4.start(); } /** * evaluateForColor()计算颜色值并返回 */ private String evaluateForColor(float fraction, String startValue, String endValue) { String startColor = startValue; String endColor = endValue; int startRed = Integer.parseInt(startColor.substring(1, 3), 16); int startGreen = Integer.parseInt(startColor.substring(3, 5), 16); int startBlue = Integer.parseInt(startColor.substring(5, 7), 16); int endRed = Integer.parseInt(endColor.substring(1, 3), 16); int endGreen = Integer.parseInt(endColor.substring(3, 5), 16); int endBlue = Integer.parseInt(endColor.substring(5, 7), 16); // 初始化颜色的值 if (mCurrentRed == -1) { mCurrentRed = startRed; } if (mCurrentGreen == -1) { mCurrentGreen = startGreen; } if (mCurrentBlue == -1) { mCurrentBlue = startBlue; } // 计算初始颜色和结束颜色之间的差值 int redDiff = Math.abs(startRed - endRed); int greenDiff = Math.abs(startGreen - endGreen); int blueDiff = Math.abs(startBlue - endBlue); int colorDiff = redDiff + greenDiff + blueDiff; if (mCurrentRed != endRed) { mCurrentRed = getCurrentColor(startRed, endRed, colorDiff, 0, fraction); } else if (mCurrentGreen != endGreen) { mCurrentGreen = getCurrentColor(startGreen, endGreen, colorDiff, redDiff, fraction); } else if (mCurrentBlue != endBlue) { mCurrentBlue = getCurrentColor(startBlue, endBlue, colorDiff, redDiff + greenDiff, fraction); } // 将计算出的当前颜色的值组装返回 String currentColor = "#" + getHexString(mCurrentRed) + getHexString(mCurrentGreen) + getHexString(mCurrentBlue); return currentColor; } /** * 根据fraction值来计算当前的颜色。 */ private int getCurrentColor(int startColor, int endColor, int colorDiff, int offset, float fraction) { int currentColor; if (startColor > endColor) { currentColor = (int) (startColor - (fraction * colorDiff - offset)); if (currentColor < endColor) { currentColor = endColor; } } else { currentColor = (int) (startColor + (fraction * colorDiff - offset)); if (currentColor > endColor) { currentColor = endColor; } } return currentColor; } /** * 将10进制颜色值转换成16进制。 */ private String getHexString(int value) { String hexString = Integer.toHexString(value); if (hexString.length() == 1) { hexString = "0" + hexString; } return hexString; } } <file_sep>/propertyanime/src/main/java/com/wondertwo/propertyanime/PositionView.java package com.wondertwo.propertyanime; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; /** * * Created by wondertwo on 2016/3/27. */ public class PositionView extends View { public static final float RADIUS = 20f; private PositionPoint currentPoint; private Paint mPaint; // 轨迹起始点坐标(160,20) private float startX = 160f; private float startY = 20f; Bitmap bmSource = BitmapFactory.decodeResource(getResources(), R.drawable.bm_round); public PositionView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(Color.RED); } @Override protected void onDraw(Canvas canvas) { if (currentPoint == null) { currentPoint = new PositionPoint(RADIUS, RADIUS); drawCircle(canvas); startPropertyAni(); } else { drawCircle(canvas); } } private void drawCircle(Canvas canvas) { float x = currentPoint.getX(); float y = currentPoint.getY(); canvas.drawCircle(x, y, RADIUS, mPaint); } /** * 启动动画 */ private void startPropertyAni() { ValueAnimator animator = ValueAnimator.ofObject( new PositionEvaluator(), createPoint(RADIUS, RADIUS), createPoint(getWidth() - RADIUS, getHeight() - RADIUS)); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentPoint = (PositionPoint) animation.getAnimatedValue(); // 获取当前坐标 float currentX = currentPoint.getX(); float currentY = currentPoint.getY(); // 绘制轨迹 Drawable drawable = drawRound(startX, startY, currentX, currentY); setBackground(drawable); // 重置起始点坐标 startX = currentX; startY = currentY; // 刷新view invalidate(); } }); animator.setInterpolator(new DeceAcceInterpolator()); animator.setDuration(10 * 1000).start(); /*Log.d("自定义view中开启动画", "startPropertyAni()");*/ } /** * 绘制轨迹 */ private Drawable drawRound(float startX, float startY, float endX, float endY) { // 加载轨迹背景 Bitmap bmRound = Bitmap.createBitmap(bmSource.getWidth(), bmSource.getHeight(), bmSource.getConfig()); bmRound.isMutable(); Canvas canvas = new Canvas(bmRound); Paint roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); roundPaint.setColor(Color.RED); roundPaint.setStrokeWidth(5); canvas.drawLine(startX, startY, endX, endY, roundPaint); canvas.save(); Drawable drawable = new BitmapDrawable(bmRound); return drawable; } /** * createPoint()创建PositionPointView对象 */ public PositionPoint createPoint(float x, float y) { return new PositionPoint(x, y); } /** * 小圆点内部类 */ class PositionPoint { private float x; private float y; public PositionPoint(float x, float y) { this.x = x; this.y = y; } public float getX() { return x; } public float getY() { return y; } } } <file_sep>/settings.gradle include ':wallpaper', ':propertyanime', ':praclistview', ':pracdownload', ':swipedemo', ':pracrecyclerview', ':imageloader' include ':ImageLoaderDemo' <file_sep>/propertyanime/src/main/java/com/wondertwo/propertyanime/PositionDeAcActivity.java package com.wondertwo.propertyanime; import android.app.Activity; import android.os.Bundle; /** * PositionDeAcActivity自定义减速加速插值器测试类 * Created by wondertwo on 2016/3/25. */ public class PositionDeAcActivity extends Activity { // public static PositionView positionView;// 定义PositionView自定义view对象 // private float screenWidth, screenHeight;// 屏幕宽高 public static Activity mainActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dece_acce); // 获取PositionDeAcActivity上下文对象 mainActivity = PositionDeAcActivity.this; /*// 创建PositionView自定义view对象 positionView = new PositionView(PositionDeAcActivity.this, null); // 获取屏幕宽高 screenWidth = getWindowManager().getDefaultDisplay().getWidth(); screenHeight = getWindowManager().getDefaultDisplay().getHeight(); // 注册按钮事件 Button start = (Button) findViewById(R.id.btn_start_ani); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startPropertyAni(); } });*/ } /*private void startPropertyAni() { *//*PositionView.PositionPoint point_1 = positionView.createPoint(screenWidth / 2, 20f); PositionView.PositionPoint point_2 = positionView.createPoint(screenWidth / 2, screenHeight);*//* ValueAnimator animator = ValueAnimator.ofObject( new PositionEvaluator(), positionView.createPoint(screenWidth / 2, 40f), positionView.createPoint(screenWidth / 2, screenHeight)); animator.setDuration(10 * 1000).start(); }*/ }
aadd7f35065f75d3d60f5aa2573451c54ddbab57
[ "Java", "Gradle" ]
5
Java
wssongwenming/view-practice
b951f12b37679a0b866c7c45b0c312e52f135591
06b9d94a9f2efcb159d1f2424a73a34daa30d1ca
refs/heads/main
<repo_name>Arif9878/mern-stack<file_sep>/backend/server.js const express = require('express') const path = require('path') const productRoutes = require('./routes/productRoutes') const cors = require('cors') const env = process.env.NODE_ENV try { switch(env) { case 'undefined': require('dotenv').config() break case 'development': require('dotenv').config({ path: path.resolve(process.cwd(), '../.env'), }) break default: Error('Unrecognized Environment') } } catch (err) { Error('Error trying to run file') } const connectDB = require("./config/db"); connectDB(); const app = express(); app.use(express.json()); app.use(cors()) app.get("/", (req, res) => { res.json({ message: "API running..." }); }); app.use("/api/products", productRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
b16c7385235fdd7fc2d7799d6016aa60d5452cf3
[ "JavaScript" ]
1
JavaScript
Arif9878/mern-stack
eeb69048fc406721960411901420014e7ef42088
9d8fba491ca95a8af923f3d9aad832e757091ccc
refs/heads/master
<file_sep>## boot cap libs # load 'deploy' if respond_to?(:namespace) # cap2 differentiator Dir['vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) } ## multistage (require 'capistrano/ext/multistage') # set :stages, %w( staging production ) set :default_stage, "staging" set :normalize_asset_timestamps, false location = fetch(:stage_dir, "config/deploy") unless exists?(:stages) set :stages, Dir["#{location}/*.rb"].map { |f| File.basename(f, ".rb") } end stages.each do |name| desc "Set the target stage to `#{name}'." task(name) do set :stage, name.to_sym load "#{location}/#{stage}" end end namespace :multistage do desc "[internal] Ensure that a stage has been selected." task :ensure do if !exists?(:stage) if exists?(:default_stage) logger.important "Defaulting to `#{default_stage}'" find_and_execute_task(default_stage) else abort "No stage specified. Please specify one of: #{stages.join(', ')} (e.g. `cap #{stages.first} #{ARGV.last}')" end end end desc "Stub out the staging config files." task :prepare do FileUtils.mkdir_p(location) stages.each do |name| file = File.join(location, name + ".rb") unless File.exists?(file) File.open(file, "w") do |f| f.puts "# #{name.upcase}-specific deployment configuration" f.puts "# please put general deployment config in config/deploy.rb" end end end end end on :start, "multistage:ensure", :except => stages + ['multistage:prepare'] ## force a remote rebenv version iff a local one has been configured # rails_root = File.expand_path(File.dirname(__FILE__)) rbenv_version = File.join(rails_root, '.rbenv-version') if test(?e, rbenv_version) default_environment['RBENV_VERSION'] = IO.read(rbenv_version).strip end ## setup remote PATH. it's important that this picks up rbenv! # default_environment['PATH'] = ( '/usr/local/rbenv/shims:/usr/local/rbenv/bin:' + default_environment.fetch('PATH', '') + '/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin' ) ## suck in some app settings - we'll use the identifier to configure tons of # stuff # load File.join(File.join(rails_root, 'lib/settings.rb')) set(:identifier, Settings.for('data/site.yml')['identifier']) ## make rake run in the proper environment # set(:rake, "bundle exec rake") ## bundler (require 'bundler/capistrano.rb') # namespace :bundle do task :symlinks, :roles => :app do shared_dir = File.join(shared_path, 'bundle') release_dir = File.join(current_release, '.bundle') run("mkdir -p #{shared_dir} && rm -rf #{release_dir} && ln -s -f -F #{shared_dir} #{release_dir}") end task :install, :except => { :no_release => true } do bundle_dir = fetch(:bundle_dir, "#{fetch(:shared_path)}/bundle") bundle_without = [*fetch(:bundle_without, [:development, :test])].compact bundle_flags = fetch(:bundle_flags, "--deployment --quiet") bundle_gemfile = fetch(:bundle_gemfile, "Gemfile") bundle_cmd = fetch(:bundle_cmd, "bundle") args = ["--gemfile #{fetch(:latest_release)}/#{bundle_gemfile}"] args << "--path #{bundle_dir}" unless bundle_dir.to_s.empty? args << bundle_flags.to_s args << "--without #{bundle_without.join(" ")}" unless bundle_without.empty? args << "--binstubs bin" run "#{bundle_cmd} install #{args.join(' ')}" end end after 'deploy:update_code', 'bundle:symlinks' after "deploy:update_code", "bundle:install" ## vomit noise into campfire # namespace :notify do desc 'alert campfire of a deploy' task :campfire do user = `git config --global --get user.name 2>/dev/null`.strip if user.empty? user = ENV['USER'] end application = fetch(:application) stage = fetch(:stage) domain = 'dojo4' token = 'f9831e567f7237563baa64b90e65a135f223100f' room = "Roboto's House of Wonders" begin require 'tinder' campfire = Tinder::Campfire.new(domain, :token => token) room = campfire.rooms.detect{|_| _.name == room} room.speak("#{ user } deployed #{ application } to #{ stage }") rescue LoadError warn "gem install tinder # to notify #{ domain }/#{ room } campfire..." end end end after "deploy", "notify:campfire" namespace :deploy do task :build do#, :roles => :app do run("cd #{ deploy_to }/current && ./bin/middleman build; true") end end after 'deploy:create_symlink', 'deploy:build' ## link vhost config # namespace :deploy do task :link_vhost do run "sudo ln -s #{ deploy_to }/current/config/deploy/os_files/etc/apache2/sites-enabled/#{ stage }.conf /etc/apache2/sites-enabled/#{ identifier }.#{ stage }" run "if sudo apache2ctl configtest; then sudo apache2ctl restart; fi; true" end end <file_sep>require 'bitballoon' require 'yaml' # this is currently experimental. DONT USE BUILD_DIR = 'build' CONFIG_FILE = 'config/bitballoon.yaml' YOUR_SITE_NAME = 'Org Dev' namespace :bitballoon do def load_config $config = YAML::load_file(CONFIG_FILE) end def save_config puts 'saving config...' if $config.nil? puts 'config is nil so not doing anything' else puts $config.inspect File.open(CONFIG_FILE, 'w') { |f| f.write $config.to_yaml } puts 'config saved.' end end def auth load_config if $config['account']['access_token'].nil? puts 'using client_id and client_secret to authenticate' bitballoon = BitBalloon::Client.new(:client_id => $config['account']['client_id'], :client_secret => $config['account']['client_secret']) bitballoon.authorize_from_credentials! $config['account']['access_token'] = bitballoon.access_token save_config bitballoon else puts 'using token to authenticate' bitballoon = BitBalloon::Client.new(:access_token => $config['account']['access_token']) begin bitballoon.request(:get, 'users') bitballoon rescue BitBalloon::Client::AuthenticationError puts 'token has been revoked or updated, so clearing & using creds to auth and get new token' $config['account']['access_token'] = nil save_config auth end end end def notify_term(url) begin require 'terminal-notifier' system "terminal-notifier -title #{YOUR_SITE_NAME} -message 'Deploy completed successfully to #{ url }.' -sound default" rescue LoadError end end desc "deploy site to bitballoon" task :deploy => :'rake:build' do puts 'Deploying site...' # authenticate bitballoon = auth # actually deploy begin # if site exists, just update if $config['site']['id'].nil? && $config['site']['url'].nil? raise BitBalloon::Client::NotFoundError else site = bitballoon.sites.get($config['site']['id'] || $config['site']['url']) puts 'the site exists, so simply updating...' site.update(:dir => BUILD_DIR) end rescue BitBalloon::Client::NotFoundError # if site hasn't been created yet, create it puts 'the site does NOT exist, so creating it' site = bitballoon.sites.create(:dir => BUILD_DIR) $config['site']['id'] = site.id $config['site']['url'] = site.url save_config end # wait until the deploy is done... site.wait_for_ready # notify campfire and end. puts '...deploy finished!' puts('Site was deployed to: ' + $config['site']['url']) # use terminal notifier if it's available notify_term($config['site']['url']) end desc "list all sites on our account" task :list do bitballoon = auth bitballoon.sites.each do |s| puts('s.id = ' + s.id + '; s.url = ' + s.url) end end desc "destroy the site" task :destroy do bitballoon = auth begin # if site exists, just update site = bitballoon.sites.get($config['site']['id'] || $config['site']['url']) site.destroy! rescue BitBalloon::Client::NotFoundError puts "no site to destroy. so doing nothing." end end desc "destroy all of your sites DANGEROUS" task :destroyall do bitballoon = auth bitballoon.sites.each do |s| s.destroy! end end end <file_sep># we need to ensure we're running in bundler begin Bundler rescue abort("Make sure you're running 'bundle exec middleman'. If you are and still getting this error, config.rb needs attention.") end ### # Compass ### # Susy grids in Compass # First: gem install compass-susy-plugin # require 'susy' # Change Compass configuration # compass_config do |config| # config.output_style = :compact # end ### # Haml ### # CodeRay syntax highlighting in Haml # First: gem install haml-coderay # require 'haml-coderay' # CoffeeScript filters in Haml # First: gem install coffee-filter # require 'coffee-filter' # Automatic image dimensions on image_tag helper # activate :automatic_image_sizes ### # Page command ### # Per-page layout changes: # # With no layout # page "/path/to/file.html", :layout => false # # With alternative layout # page "/path/to/file.html", :layout => :otherlayout # # A path which all have the same layout # with_layout :admin do # page "/admin/*" # end # Proxy (fake) files # page "/this-page-has-no-template.html", :proxy => "/template-file.html" do # @which_fake_page = "Rendering a fake page with a variable" # end ### # Helpers ### # Methods defined in the helpers block are available in templates helpers do def custom_or_default_content(thingy) if content_for?(thingy) yield_content(thingy) else data.site.send(thingy) || '' end end end activate :syntax # Change the CSS directory # set :css_dir, "alternative_css_directory" # Change the JS directory # set :js_dir, "alternative_js_directory" # Change the images directory # set :images_dir, "alternative_image_directory" # Build-specific configuration configure :build do # For example, change the Compass output style for deployment activate :minify_css # Minify Javascript on build activate :minify_javascript # Enable cache buster activate :cache_buster # Use relative URLs activate :relative_assets # Compress PNGs after build # First: gem install middleman-smusher # require "middleman-smusher" # activate :smusher # Or use a different image path # set :http_path, "/Content/images/" end activate :directory_indexes page "/404.html", :directory_index => false require 'susy' # Methods defined in the helpers block are available in templates helpers do # Calculate the years for a copyright def copyright_years(start_year) end_year = Date.today.year if start_year == end_year start_year.to_s else start_year.to_s + '-' + end_year.to_s end end end require 'lib/aws_buckets' def sekrets @sekrets ||= ( key = IO.read('.sekrets.key').strip rescue nil Sekrets.settings_for('./config/sekrets.yml.enc', :key => key) ) end def settings @settings ||= ( Map.for(sekrets.aws) ) end begin AWS.config({ :access_key_id => settings.access_key_id, :secret_access_key => settings.secret_access_key, :region => settings.region }) bucket_name = settings.bucket unless bucket_name.blank? AWSBuckets.create_unless_exists!(AWS::S3, bucket_name) #FIXME: configure bucket for static site hosting through API s3 = AWS::S3.new(:s3_endpoint => 's3.amazonaws.com') location_constraint = s3.buckets[bucket_name].location_constraint endpoint = ['s3', location_constraint].compact.join('-') + '.amazonaws.com' bucket = AWS::S3.new(:s3_endpoint => endpoint).buckets[bucket_name] bucket.cors = { :allowed_origins => %w'*', :allowed_methods => %w'GET POST PUT', #:allowed_headers => %w'origin accept x-requested-with content-type', :allowed_headers => %w'*', #:max_age_seconds => 3600, } bucket.cors.each do |rule| #p rule end #object = bucket.objects['pages/assets.js'] end rescue Exception => e puts "Error initializing AWS: #{e}" end # Activate sync extension activate :s3_sync do |sync| sync.bucket = settings.bucket # Your bucket name sync.region = settings.region # The region your storage bucket is in (eg us-east-1, us-west-1, eu-west-1, ap-southeast-1 ) sync.aws_access_key_id = settings.access_key_id # Your Amazon S3 access key sync.aws_secret_access_key = settings.secret_access_key # Your Amazon S3 access secret sync.delete = true # Do not delete when sync'ing sync.after_build = false # Disable sync to run after Middleman build ( defaults to true ) sync.prefer_gzip = true end default_caching_policy max_age:(60 * 60 * 24 * 365) caching_policy 'text/html', max_age:0, must_revalidate: true, no_cache: true <file_sep>class AWSBuckets def AWSBuckets.create_unless_exists!(s3, bucket_name) bucket = s3::Bucket.new(bucket_name) unless bucket.exists? s3.new.buckets.create(bucket_name) end end end <file_sep>## How to bootstrap a Middleman site from this repo 1. <code>git clone <EMAIL>:dojo4/static_site.git</code> 2. Create a new repo under the dojo4 account on github.com 4. Switch the current directory to the new repo: <code>cd new_repo</code> 5. Remove the .git directory: <code>rm -rf .git</code> 6. Initialize the new git repo: <code>git init</code> 7. Add the github remote: <code>git remote add origin <EMAIL>:dojo4/new_repo_name 8. Remove vendor bundle <code>rm -rf ./vendor/bundle/ruby/</code> 9. Run <code>bundle install</code> to install the necessary gems. 10. Recrypt the sekrets config: <code>sekrets recrypt config/sekrets.yml.enc</code> 11. Create a new .sekrets.key with the new password you created above 12. Hack. You can push to GitHub as needed from that point forward. ## How to run the middleman server locally for development 1. <code>bundle exec middleman</code> 2. point your browser at localhost:4567 ## How to deploy ### Update AWS details like bucket names <code>vi .sekrets.key</code> <code>sekrets edit ./config/sekrets.yml.enc</code> <code>rake deploy:staging</code> in the new folder will push the new site to the server. ## How to browse to your site? Point your browser to [http://static_site.site.dojo4.com](http://static_site.site.dojo4.com) <file_sep># Loads the site specific rake tasks. Dir.glob('lib/tasks/**/*.rake').each do |f| load f end <file_sep>identifier = fetch(:identifier) set :application, identifier set :repository, "<EMAIL>:dojo4/#{ identifier }.git" set :user, "dojo4" set :deploy_to, "/ebs/sites/#{ identifier }" set :scm, :git set :deploy_via, :remote_cache # be sure to run 'ssh-add' on your local machine system "ssh-add 2>&1" unless ENV['NO_SSH_ADD'] ssh_options[:forward_agent] = true set :deploy_via, :remote_cache set :branch, "master" unless exists?(:branch) set :use_sudo, false ip = "d0.dojo4.com" role :web, ip # Your HTTP server, Apache/etc role :app, ip # This may be the same as your `Web` server role :db, ip, :primary => true # This is where Rails migrations will run #role :db, "your slave db-server here" set(:url, "http://#{ identifier }.development.dojo4.com") <file_sep>desc "Cleans up the build directory" task :clean do unless system 'rm -rf build' fail "Couldn't clean up directory" end end desc "Runs the Middleman server" task :server do system 'middleman server' end desc "Builds the Middleman site" task :build do unless system 'middleman build' fail "Middleman build failed." end end desc "Set STAGE to staging" task "set_staging_env" do ENV['STAGE'] = 'staging' end desc "Set STAGE to qa" task "set_qa_env" do ENV['STAGE'] = 'qa' end desc "Set STAGE to production" task "set_production_env" do ENV['STAGE'] = 'production' end namespace :deploy do desc "Deploy static site to staging" task :staging => [:set_staging_env, :clean, :build, 'deploy:sync'] do notify(":shipit: #{ user } deployed #{repo_name} to staging") end desc "Deploy static site to qa" task :qa => [:set_qa_env, :clean, :build, 'deploy:sync'] do notify(":shipit: #{ user } deployed #{repo_name} to qa") end desc "Confirm deploy static site to production" task :production_confirm do confirmation_string = "deploy to production" puts "Production deploy initiated!" puts "Please type '#{confirmation_string}' then press return to confirm." unless STDIN.gets.strip == confirmation_string fail "Production deploy canceled" end end desc "Deploy static site to production" task :production => [:production_confirm, :set_production_env, :clean, :build, 'deploy:sync'] do notify(":shipit: #{ user } deployed #{repo_name} to production") end desc "Syncs with S3" task :sync do retries = 5 while retries > 0 if system 'middleman s3_sync' puts "Sync to stage #{ENV['STAGE']} completed OK." break else retries -= 1 puts "Sync error while syncing to stage: #{ENV['STAGE']}." end end end def notify(message) require 'flowdock' # create a new Flow object with target flow's api token and sender information flow = Flowdock::Flow.new( api_token: "7e1c8271ffb6351a6405237d73b83383", source: "Rake deployment", project: app_name, from: {name: "<NAME>", address: "<EMAIL>"} ) # send message to the flow flow.push_to_team_inbox( format: "html", subject: "#{ app_name } deployed to #{ ENV['STAGE'] }", content: message, tags: ["deploy", app_name] ) rescue LoadError warn "gem install flowdock # to notify dojo4 flowdock..." end def repo_name @repo_name ||= `git remote -v` =~ %r{/(.+)(\.git)? \(fetch\)} && $1.split('/').last end def app_name repo_name.sub('.git', '') end def user ENV['USER'] end def root_dir @root_dir ||= Rake.application.original_dir end end namespace :test do desc "tests notifying flowdock of a message" task :notify do notify("this is a test") end end <file_sep>var initHooch = function(){ hooch = { Emptier: Class.extend({ init: function($emptier){ $target = $($emptier.data('target')); $emptier.click(function(e){ $target.empty(); }) } }), Toggler: Class.extend({ init: function(jq_obj){ this.jq_obj = jq_obj; this.label = jq_obj.data('toggler'); this.value = jq_obj.val(); this.targets = $('[data-toggle_trigger="' + this.label + '"]'); this.targets.hide(); this.targets.filter('[data-toggle_value="' + this.value + '"]').show(); } }), HoverOverflow: Class.extend({ init: function(jq_obj){ this.old_border = jq_obj.css('border-right'); this.old_z_index = jq_obj.css('z-index'); var hoverable = this; jq_obj.bind('mouseover',function(){ hoverable.jq_obj.css({'overflow':'visible','z-index':'10000','border-right':'1px solid white'}); }); jq_obj.bind('mouseout',function(){ hoverable.jq_obj.css({'overflow':'hidden','z-index':hoverable.old_z_index,'border-right':hoverable.old_border}); }); } }), HoverReveal: Class.extend({ init: function($hover_revealer){ $revealable = $hover_revealer.data('revealable') jq_obj.bind('mouseover',function(){ $revealable.show(); }); jq_obj.bind('mouseout',function(){ $revealable.hide(); }); } }), HideyButton: Class.extend({ init: function($hidey_button){ $hidey_button.hide(); this.form = $hidey_button.parents('form'); this.$hidey_button = $hidey_button; this.bindInputs(); }, bindInputs: function(){ this.inputs = this.form.find('input,select,textarea'); var hidey_button = this; this.cache_input_values(); this.inputs.each(function(){ $(this).bind("propertychange keyup input paste datechange change",function(){ if(hidey_button.form_changed()){ hidey_button.$hidey_button.show(); } else { hidey_button.$hidey_button.hide(); } }) }); }, cache_input_values: function(){ this.inputs.each(function(){ if($(this).is(":checkbox")){ $(this).data('oldstate',$(this).is(':checked')); } else { $(this).data('oldval',$(this).val()); } }) }, form_changed: function(){ var changed = false; this.inputs.each(function(){ if($(this).is(":checkbox")){ if($(this).data('oldstate') != $(this).is(':checked')){ changed = true; return false; } }else{ if($(this).data('oldval') != $(this).val()){ changed = true; return false; } } }) return changed; } }), Expandable: Class.extend({ init: function($expandable){ this.$expandable = $expandable; $expandable.data('expandable',this); $collapser = $('[data-expand-id="' + $expandable.data('expand-id') + '"][data-collapser]'); if($collapser.length > 0){ this.collapser = new hooch.Collapser($collapser,this); } this.$expander = $('[data-expand-id="' + $expandable.data('expand-id') + '"][data-expander]'); this.expander = new hooch.Expander(this.$expander,this); this.initial_state = $expandable.data('expand-state'); if(this.initial_state == 'expanded'){ this.expand(); } else { this.collapse(); } }, expand: function(){ if(this.collapser){ this.expander.hide(); this.collapser.show(); } this.$expandable.show(10); }, collapse: function(){ if(this.collapser){ this.collapser.hide(); this.expander.show(); } this.$expandable.hide(10); }, toggle: function(){ this.$expandable.toggle(10); } }), Expander: Class.extend({ init: function($expander,target){ this.$expander = $expander; if($expander.data('fake-dropdown')){ target.$expandable.on('click',function(){ target.toggle(); }) target.$expandable.on('mouseleave',function(){ target.collapse(); }) } $expander.bind('click',function(){ if(target.collapser){ target.expand(); } else { target.toggle(); } }) }, hide: function(){ this.$expander.hide(); }, show: function(){ this.$expander.show(); } }), Collapser: Class.extend({ init: function($collapser,target){ this.$collapser = $collapser; $collapser.bind('click',function(){ target.collapse(); }) }, hide: function(){ this.$collapser.hide(); }, show: function(){ this.$collapser.show(); } }), DisableForms: Class.extend({ init: function($disable_container){ $disable_container.find('input, select').each(function(){ $(this).prop('disabled',true); }); } }), Revealer: Class.extend({ init: function($revealer){ var revealer = this; this.$revealer = $revealer; this.children_id = this.$revealer.data('revealer-children-id'); this.$all_children = $('[data-revealer_id="' + this.children_id + '"]'); $revealer.bind('change',function(){ revealer.reveal(); }); revealer.reveal(); }, reveal: function(){ var sanitized_value = this.$revealer.val(); this.$children = []; var revealer = this; this.$all_children.each(function(){ var triggers = $(this).data('revealer-triggers'); if(triggers){ var revelation_triggers = eval('(' + triggers + ')'); if($.inArray(sanitized_value,revelation_triggers) > -1){ revealer.$children.push($(this)); } } else { if(sanitized_value == $(this).data('revealer-trigger')){ revealer.$children.push($(this)); } } }) this.hideChildren(); this.revealChosenOnes(); }, hideChildren: function(){ this.$all_children.hide(); }, revealChosenOnes: function(){ $.each(this.$children,function(){ $(this).show(); }); } }), TabGroup: Class.extend({ init: function($tab_group){ this.$tab_group = $tab_group; this.getName(); this.tab_triggers = []; this.tab_triggers_by_id = {}; this.getTabTriggerClass(); this.createTabs(); this.getConentParent(); this.hideAll(); this.handleDefault(); hooch.TabGroup.addGroup(this); }, createTabs: function(){ var tab_group = this; this.$tab_group.find("[data-tab-trigger]").each(function(){ var new_tab = new tab_group.tab_trigger_class($(this),tab_group); tab_group.tab_triggers.push(new_tab); tab_group.tab_triggers_by_id[new_tab.tab_id] = new_tab; }) }, getTabByPushState: function(state_value){ var selected_tab = null; $.each(this.tab_triggers,function(index,trigger){ if(trigger.push_state == state_value){ selected_tab = trigger; } }) return selected_tab; }, getName: function(){ this.name = this.$tab_group.data('tab-group'); }, getConentParent: function(){ this.$content_parent = this.tab_triggers[0].getParent(); }, handleDefault: function(){ if(this.$tab_group.data('default-tab')){ this.default_tab = this.tab_triggers_by_id[this.$tab_group.data('default-tab')]; this.default_tab.toggleTarget('replace'); } }, hideAll: function(trigger){ $.each(this.tab_triggers,function(){ this.hideTarget(); }) }, getTabTriggerClass: function(){ this.tab_trigger_class = hooch.TabTrigger; }, deactivateTabTriggers: function(){ $.each(this.tab_triggers,function(){ this.$tab_trigger.removeClass('active'); }) }, setActiveTab: function(tab_trigger){ if(this.active_tab){ var parent_height = this.$content_parent.height(); this.$content_parent.css({'height': parent_height, 'overflow': 'hidden'}); } this.hideAll(); this.deactivateTabTriggers(); this.active_tab = tab_trigger; tab_trigger.revealTarget(); }, resize: function(){ this.$content_parent.css({'height': 'auto', 'overflow': 'visible'}); }, getActiveTab: function(){ return this.active_tab; } }), TabTrigger: Class.extend({ init: function($tab_trigger,tab_group){ this.$tab_trigger = $tab_trigger; this.tab_group = tab_group; this.tab_group_name = tab_group.name; this.tab_id = $tab_trigger.data('tab-target-id'); this.getPushState(); this.getTarget(); var tab_trigger = this; $tab_trigger.on('click', function(e){ e.preventDefault(); tab_trigger.toggleTarget(); }) }, getTarget: function(){ this.$target = $('[data-tab-id="' + this.tab_id + '"]'); }, getPushState: function(){ if(this.$tab_trigger.data('push-state') != null && this.$tab_trigger.data('push-state') != ""){ this.push_state = this.$tab_trigger.data('push-state') } }, toggleTarget: function(state_behavior){ var was_visible = this.$target.is(':visible'); if(!was_visible){ this.tab_group.setActiveTab(this); this.resize(); var change_history = true; var history_method = 'pushState' if('no history' == state_behavior){ change_history = false } else if('replace' == state_behavior){ history_method = 'replaceState' } if (this.push_state && change_history) { var current_state = new hooch.IhHistoryState(history.state) current_state.addState(this.tab_group_name, this.push_state); history[history_method](current_state.state, null, current_state.toUrl()); } } }, hideTarget: function(){ this.$target.hide(); }, revealTarget: function(){ this.$target.show(); this.$tab_trigger.addClass('active'); }, getParent: function(){ return this.$target.parent(); }, resize: function(){ this.tab_group.resize(); } }), IhHistoryState: Class.extend({ init: function(state){ this.state = jQuery.extend(true, {}, state); }, toQueryString: function(){ return $.param(this.state) }, toUrl: function(){ return [location.protocol, '//', location.host, location.pathname, '?', this.toQueryString()].join(''); }, addState: function(key,value){ var new_state = {} new_state[key] = value this.state = $.extend(true, this.state, new_state); } }), GoProxy: Class.extend({ init: function($proxy){ this.first_submit = true; var go_proxy = this; go_proxy.$proxy = $proxy; go_proxy.target = go_proxy.getTarget(); go_proxy.prevent_double_submit = $proxy.data('prevent-double-submit') switch($proxy.get(0).nodeName.toLowerCase()){ case 'input': switch($proxy.attr('type')){ case 'checkbox': default: $proxy.on('change',function(){ go_proxy.doItNow(); }) break; } break; case 'select': $proxy.on('change',function(){ go_proxy.doItNow(); }) break; case 'a': default: $proxy.on('click',function(e){ e.preventDefault(); go_proxy.doItNow(); return false; }); break; } }, doable: function(){ return(this.first_submit || !this.prevent_double_submit) } }), FieldFiller: Class.extend({ init: function($field_filler){ this.$field_filler = $field_filler this.value = $field_filler.data('value'); this.target = $($field_filler.data('target')); var field_filler = this this.$field_filler.bind('click', function(e){field_filler.fill(e)}) }, fill: function(e){ e.preventDefault(); this.target.val(this.value); return false; } }), Remover: Class.extend({ init: function($remover){ $target = $($remover.data('target')); $remover.click(function(e){ $target.remove(); }) } }), Link: Class.extend({ init: function($link){ $link.click(function(){ window.location = $link.attr('href'); }) } }), CheckboxHiddenProxy: Class.extend({ init: function($checkbox){ this.checked_value = $checkbox.data('checked-value'); this.unchecked_value = $checkbox.data('unchecked-value'); var target_selector = $checkbox.data('target'); this.target = $(target_selector); var checkbox = this; $checkbox.click(function(){ if ($(this).is(':checked')) { checkbox.target.val(checkbox.checked_value); } else { checkbox.target.val(checkbox.unchecked_value); } }) } }), PreventDoubleSubmit: Class.extend({ init: function($clickable){ this.$clickable = $clickable; var double_click_preventer = this; switch($clickable.get(0).nodeName.toLowerCase()){ case 'form': $clickable.submit(function(e){ double_click_preventer.preventItNow(); }); break; case 'input': $clickable.click(function() { setTimeout(function(){ $clickable.attr("disabled", "disabled"); }, 10); }); break; } }, preventItNow: function(){ this.$clickable.submit(function(e){ e.preventDefault(); return false; }); } }), PreventDoubleLinkClick: Class.extend({ init: function($clickable){ $clickable.click(function(e) { if($clickable.data('clicked')) { e.preventDefault(); return false; } else { $clickable.data('clicked',true); return true; } }); } }), ReloadPage: Class.extend({ init: function(reload_page){ window.location.href = reload_page; } }) }; hooch.AjaxExpandable = hooch.Expandable.extend({ expand: function(){ if(!this.ajax_loaded){ this.ajax_loaded = true; new thin_man.AjaxLinkSubmission(this.$expander); } this._super(); } }); hooch.FormFieldRevealer = hooch.Revealer.extend({ init: function($revealer){ this.children_id = $revealer.data('revealer-children-id'); this.$revelation_target = $('[data-revealer-target="' + this.children_id + '"]'); this._super($revealer); }, hideChildren: function(){ this._super(); this.$form = this.$revealer.parents('form:first') if(this.$form.length > 0){ this.$form.after(this.$all_children) } }, revealChosenOnes: function(){ this.$revelation_target.html(this.$children); this._super(); } }); hooch.AjaxTabGroup = hooch.TabGroup.extend({ getTabTriggerClass: function(){ this.tab_trigger_class = hooch.AjaxTabTrigger; } }); hooch.AjaxTabTrigger = hooch.TabTrigger.extend({ toggleTarget: function(pop){ var tab_group = this.tab_group; if(!this.ajax_loaded){ this.ajax_loaded = true; this.$tab_trigger.data('ajax-target','[data-tab-id="' + this.tab_id + '"]') new thin_man.AjaxLinkSubmission(this.$tab_trigger,{'on_complete': function(){tab_group.resize()}}); this._super(pop); } else { this._super(pop); tab_group.resize() } }, resize: function(){ // noop } }); hooch.ClickProxy = hooch.GoProxy.extend({ getTarget: function(){ if(this.$proxy.data('target')){ return $(this.$proxy.data('target')); } else { return this.$proxy.siblings('a'); } }, doItNow: function(){ if(this.doable()) { if(this.target.data('ajax-target')){ this.target.click(); }else if(this.target.attr('href')){ window.location = this.target.attr('href'); } this.first_submit = false; } } }); hooch.SubmitProxy = hooch.GoProxy.extend({ getTarget: function(){ if(this.$proxy.data('target')){ return $(this.$proxy.data('target')); } else { return this.$proxy.parents('form:first'); } }, doItNow: function(){ if(this.doable()) { this.target.submit(); this.first_submit = false; } } }); hooch.TabGroup.addGroup = function(group){ if(!hooch.TabGroup.all_groups){ hooch.TabGroup.all_groups = []; } hooch.TabGroup.all_groups.push(group); }; hooch.TabGroup.find = function(name){ var selected_group = null; $.each(hooch.TabGroup.all_groups,function(index,group){ if(group.name == name){ selected_group = group; } }); return selected_group; }; hooch.loadClasses = function(){ window.any_time_manager.registerListWithClasses({ 'expand-state' : 'Expandable', 'prevent-double-click' : 'PreventDoubleLinkClick' },'hooch'); window.any_time_manager.registerList( ['hover_overflow','hidey_button','submit-proxy','click-proxy','field-filler','revealer', 'checkbox-hidden-proxy','prevent-double-submit','prevent-double-link-click', 'tab-group', 'hover-reveal', 'emptier', 'remover'],'hooch'); window.any_time_manager.load(); }; $(document).ready(function(){ if(typeof window.any_time_manager === "undefined" && typeof window.loading_any_time_manager === "undefined"){ window.loading_any_time_manager = true; $.getScript("https://cdn.rawgit.com/edraut/anytime_manager/9f710d2280e68ea6156551728cb7e2d537a06ee6/anytime_manager.js",function(){ window.loading_any_time_manager = false hooch.loadClasses(); }); }else if(typeof window.any_time_manager === "undefined"){ if(typeof window.any_time_load_functions === 'undefined'){ window.any_time_load_functions = [] } window.any_time_load_functions.push(hooch.loadClasses) }else{ hooch.loadClasses(); }; $(document).on('change','[data-toggler]',function(){ new hooch.Toggler($(this)); }) $('[data-toggler]').each(function(){ new hooch.Toggler($(this)); }) $('[data-disable_forms]').each(function(){ new hooch.DisableForms($(this)); }) $('[data-link]').each(function(){ new hooch.Link($(this)); }) // Initailizes auto complete for select inputs $('input,select,textarea').filter(':visible:enabled:first').each(function(){ if(!$(this).data('date-picker')){ $(this).focus(); } }); }); $(window).bind("popstate", function(e){ var previous_state = new hooch.IhHistoryState(e.originalEvent.state) $.each(previous_state.state, function(key,value){ var tab_group = hooch.TabGroup.find(key) if(tab_group){ var tab_trigger = tab_group.getTabByPushState(value) if(tab_trigger){ tab_trigger.toggleTarget('no history'); } } }) }); } if(typeof Class === "undefined"){ $.getScript('https://rawgit.com/edraut/js_inheritance/a6c1e40986ecb276335b0a0b1792abd01f05ff6c/inheritance.js', function(){ initHooch(); }); }else{ initHooch(); }<file_sep>source "http://rubygems.org" gem "middleman", ">= 3" gem "middleman-s3_sync" gem "unf" gem "aws-sdk" #gem "middleman-livereload" gem 'bitballoon' gem "rb-fsevent" gem "tagz" gem "map" # KSS related gems. gem "kss", "~> 0.3.0" gem "compass-susy-plugin" gem 'capistrano' gem 'rake' # Bourbon.io gem 'bourbon' gem 'pygments.rb' gem "middleman-syntax" # Parses .netrc gem 'net-netrc' gem 'sekrets' group :development do gem 'flowdock' gem 'pry' gem 'pry-nav' gem 'httparty' end
d6b0f0e88ee96a2971db8493ab522b6236b53345
[ "Markdown", "JavaScript", "Ruby" ]
10
Ruby
tommyfriendhusen08/ih_redesign
8afb0751e7beda682e0b06b0c1f50d14f7f7a537
b3ffe9db8757a35d4b64f3d229087574ffa96fd8
refs/heads/master
<repo_name>AxaWebCenter/JS-Starter<file_sep>/tests/dojo.spec.js describe('dojo', function() { var dojo; beforeEach(function() { dojo = window.Dojo; }); describe('returnTrue', function() { it('retourne true', function() { var expectedTrue = (new dojo.Preco()).returnTrue(); expect(expectedTrue).toBeTruthy(); }); }); });<file_sep>/README.md # JS Starter Kit Le but de ce dépôt est de fournir une base pour faire les dojos en Javascript. ## Prérequis * `node` installé * `karma-cli` installé (une fois node installé, `npm install -g karma-cli`) ### Contourner le proxy pour installer les paquets node Un dépôt interne npm a été mis en place, pour le définir, cherchez dans vos mails, la commande doit ressembler à ça : npm config set registry http://[....] ## Initialisation Normalement tout est inclus dans le package. Sinon, il suffit d'installer les paquets node configurés dans `package.json`, comme ceci : npm install ## Où ajouter mon code ? Dans les fichiers suivants : * **src/dojo.js**: code principal, c'est ici qu'on met l'intelligence du programme * **tests/dojo.spec.js**: pour les tests unitaires de **src/dojo.js**, syntaxe jasmine ## Exécuter les TU Lancer la commande suivante : karma start Le résultat attendu est : <pre> 05 10 2015 14:30:37.577:WARN [karma]: No captured browser, open http://localhost:9876/ 05 10 2015 14:30:37.591:INFO [karma]: Karma v0.13.10 server started at http://localhost:9876/ 05 10 2015 14:30:37.613:INFO [launcher]: Starting browser PhantomJS 05 10 2015 14:30:38.831:INFO [PhantomJS 1.9.8 (Windows 7 0.0.0)]: Connected on socket KgxRql5uow_nAJH6AAAA with id 99370867. <b>PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0.002 secs / 0.002 secs)</b> </pre>
ff002be8c3082696b8a4f31bb2f3efb3fe7321c3
[ "JavaScript", "Markdown" ]
2
JavaScript
AxaWebCenter/JS-Starter
68e71eddbbf7389f2dbc9754cae4e6edb26e201b
da690be75a78e2b556c985360040e4686310707c
refs/heads/master
<repo_name>coyistik/JSPServletMongoDBSampleProject<file_sep>/src/main/java/io/github/ilkgunel/operations/DataSelect.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 io.github.ilkgunel.operations; import io.github.ilkgunel.pojo.Address; import io.github.ilkgunel.pojo.Record; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCursor; import io.github.ilkgunel.database.AccessMongoDB; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.bson.Document; /** * * @author ilkaygunel */ @WebServlet(name = "select", urlPatterns = {"/select"}) public class DataSelect extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String operationMessage = ""; HttpSession session = request.getSession(); operationMessage = (String) session.getAttribute("operationMessage"); if (operationMessage == null || operationMessage.equals("")) { operationMessage = ""; } session.removeAttribute("operationMessage"); List<Record> list = new ArrayList<>(); //FindIterable<Document> result = getMongoDatabase().getCollection("Records").find(new Document("name","Can")); AccessMongoDB accessMongoDB = new AccessMongoDB(); FindIterable<Document> result = accessMongoDB.getCollection().find(); MongoCursor<Document> cursor = result.iterator(); while (cursor.hasNext()) { Document document = cursor.next(); System.out.println(document.get("_id")); System.out.println(document.get("name")); System.out.println(document.get("surname")); Document address = (Document) document.get("adress"); System.out.println(address.get("street")); System.out.println(address.get("borough")); System.out.println(address.get("city")); Address address1 = new Address(); address1.setStreet((String) address.get("street")); address1.setBorough((String) address.getString("borough")); address1.setCity((String) address.getString("city")); Record record = new Record(); record.setId(document.get("_id").toString()); record.setName((String) document.get("name")); record.setSurname((String) document.get("surname")); record.setAddress(address1); list.add(record); } request.setAttribute("records", list); request.setAttribute("operationMessage", operationMessage); accessMongoDB.closeMongoClient(); RequestDispatcher view = request.getRequestDispatcher("/listRecors.jsp"); view.forward(request, response); } } <file_sep>/src/main/java/io/github/ilkgunel/operations/DataInsert.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 io.github.ilkgunel.operations; import io.github.ilkgunel.database.AccessMongoDB; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.bson.Document; /** * * @author ilkaygunel */ @WebServlet(name = "dataInsert", urlPatterns = {"/dataInsert"}) public class DataInsert extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); String insertMessage = ""; String name = request.getParameter("name"); String surname = request.getParameter("surname"); String street = request.getParameter("street"); String borough = request.getParameter("borough"); String city = request.getParameter("city"); AccessMongoDB accessMongoDB = new AccessMongoDB(); try { accessMongoDB.getCollection().insertOne( new Document() .append("name", name) .append("surname", surname) .append("adress", new Document() .append("street", street) .append("borough", borough) .append("city", city)) ); insertMessage = "Record successfully inserted!"; } catch (Exception e) { insertMessage = "An error occured while inserting data! Error is:"+e; } request.setAttribute("insertMessage", insertMessage); RequestDispatcher dispatcher = request.getRequestDispatcher("/dataInsert.jsp"); dispatcher.forward(request, response); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String insertMessage = ""; request.setAttribute("insertMessage", insertMessage); RequestDispatcher dispatcher = request.getRequestDispatcher("/dataInsert.jsp"); dispatcher.forward(request, response); } }
ebcc7d190bdff588f113c88f5f5990ae7aefb5bc
[ "Java" ]
2
Java
coyistik/JSPServletMongoDBSampleProject
fedce357f2ab4cd7b4c8c2d2d1da997b2c421893
509ec06bca39c239d243748d640676579554f1bd
refs/heads/master
<file_sep>#!/usr/bin/python # Start by importing the libraries we want to use import RPi.GPIO as GPIO # This is the GPIO library we need to use the GPIO pins on the Raspberry Pi import time # This is the time library, we need this so we can use the sleep function from twilio.rest import Client import os # Your Account SID from twilio.com/console account_sid = os.environ["account_sid"] # Your Auth Token from twilio.com/console auth_token = os.environ["auth_token"] # From Phone Number from_phone_nbr = os.environ["from_phone"] #To Phone number to_phone_nbr = os.environ["to_phone"] client = Client(account_sid, auth_token) last_message = "" def send_message(body): global last_message if body != last_message: message = client.messages.create( to=to_phone_nbr, from_=from_phone_nbr, body=body) print("SMS SENT") last_message = body send_message("Mayday is up and running.") # Set our GPIO numbering to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin that we have our digital output from our sensor connected to channel_high = 17 # Set the GPIO pin to an input GPIO.setup(channel_high, GPIO.IN) # This is our callback function, this function will be called every time there is a change on the specified GPIO channel, in this example we are using 17 def callback_high(channel): high_input = GPIO.input(channel) if high_input == 1: print "PANIC" send_message("PANIC!") else: print "Stop Panicking" send_message("Stop Panicking") # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(channel_high, GPIO.BOTH, bouncetime=1) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(channel_high, callback_high) # Define the GPIO pin that we have our digital output from our sensor connected to channel_low = 22 # Set the GPIO pin to an input GPIO.setup(channel_low, GPIO.IN) # This is our callback function, this function will be called every time there is a change on the specified GPIO channel, in this example we are using 17 def callback_low(channel): # print GPIO.input(channel_low) if GPIO.input(channel): print "COME HOME" send_message("Water Level is High in Sump Pump") else: print "All is well" send_message("Water Level has receeded within tolerance") # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(channel_low, GPIO.BOTH, bouncetime=1) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(channel_low, callback_low) # This is an infinte loop to keep our script running while True: # This line simply tells our script to wait 0.1 of a second, this is so the script doesnt hog all of the CPU time.sleep(0.1)
e994143a5df791b5e92ff3435d3a5a7d729faad8
[ "Python" ]
1
Python
jeschauer/Moisture-Sensor
f07a808a7333181e3db3839a85e5e596ea7fa1e3
fd4d91835a66af305afe2dee9cc7bb3f23f92129
refs/heads/master
<repo_name>1000pilar/final-live-code<file_sep>/server/controllers/articles.js var Article = require('../models/article.js') module.exports = { create: (req, res)=>{ var createActicle = new Article({ title: req.body.title, content: req.body.content, category: req.body.category, author: req.body.author_id }) createActicle.save((err, data)=>{ if(err){ res.send(err) } else { res.send(data) } }) }, findAll: (req, res)=>{ Article.find((err, result)=>{ if (err) { res.send(err) } else { res.send(result) } }) }, findCategory: (req, res)=>{ Article.find({category: req.params.category}, (err, result)=>{ if(!err) { res.send(result) } else { res.send(err) } }) }, update: (req, res)=>{ Article.findOneAndUpdate({_id: req.params.id}, {$set:{ title: req.body.title, content: req.body.content, category: req.body.category, author: req.body.author_id }}, {new: true}, (err, data)=>{ if (err) { res.send(err) } else { res.send(data) } }) }, delete: (req, res)=>{ Article.remove({_id: req.params.id}, (err, data)=>{ if (err) { res.send(err) } else { res.send(data) } }) } } <file_sep>/server/routes/articles.js var express = require('express') var router = express.Router() var articleController = require('../controllers/articles.js') var helper = require('../helpers/jwtVerify.js') router.post('/', helper.jwtVerify, articleController.create) router.get('/', articleController.findAll) router.get('/:category', articleController.findCategory) router.put('/:id', helper.jwtVerify, articleController.update) router.delete('/:id', helper.jwtVerify, articleController.delete) module.exports = router <file_sep>/README.md # final-live-code ## install npm on server-side "bcrypt": "^1.0.2", "body-parser": "^1.17.2", "cors": "^2.8.3", "express": "^4.15.3", "jsonwebtoken": "^7.4.1", "mongoose": "^4.10.6", "passport": "^0.3.2", "passport-local": "^1.0.0" <file_sep>/server/controllers/users.js var User = require('../models/user.js') var jwt = require('jsonwebtoken') var bcrypt = require('bcrypt') module.exports = { signup : (req, res)=>{ var userCreate = new User({ name: req.body.name, username: req.body.username, password: <PASSWORD>.hashSync(req.body.password, 10), email: req.body.email, role: req.body.role || 'member' }) userCreate.save((err, user)=>{ if(err){ res.send(err) } else { res.send(user) } }) }, signin: (req, res)=>{ var user = req.user console.log(user); if(user.hasOwnProperty('message')){ res.send(req.user) } else { var token = jwt.sign({ username: user.username, role: user.role }, 'rahasia', (err, token)=>{ res.send(token) }) } }, getAll: (req, res)=>{ User.find((err, result)=>{ if(!err){ res.send(result) } else { res.send(err) } }) } } <file_sep>/server/helpers/jwtVerify.js var express = require('express') var jwt = require('jsonwebtoken') module.exports = { jwtVerify : function (req, res, next) { jwt.verify(req.headers.token, '<PASSWORD>', function(err, decoded) { if (decoded.role == 'admin') { req.decoded = decoded next() } else { res.send({message: `only admin could create,modify,delete article`}) } }); } } <file_sep>/server/app.js const express = require('express') const passport = require('passport') const LocalStrategy = require('passport-local') const bcrypt = require('bcrypt') const bodyParser = require('body-parser') const app = express() const User = require('./models/user.js') var users = require('./routes/users.js') var articles = require('./routes/articles.js') const mongoose = require('mongoose') mongoose.connect("mongodb://localhost:live-code") console.log(`Connect To database`); passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function (err, user) { console.log(password); console.log(user.password); console.log(username); if (err) { return done(err); } if (!user) { return done(null, {message: `username or password wrong`}); } if (!bcrypt.compareSync(password, user.password)) { return done(null, {message: `username or password wrong`}); } return done(null, user); }); } )); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended:false})) app.use('/api/users', users) app.use('/api/articles', articles) app.listen(3000) console.log(`Connect to port 3000`); <file_sep>/client/src/store.js import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export const store = new Vuex.store({ state:{ articles: [] }, getters: { getUser (state) { return state.user }, getArticles (state) { return state.articles } }, mutations: { } })
ee51086cc83fc2a7d242a2e755ce6b71095c400d
[ "JavaScript", "Markdown" ]
7
JavaScript
1000pilar/final-live-code
ccd53d8c074a62e30ce26717b3fd258e6278f71d
7de571203c4a4311b5d7124a45ce07533076d135
refs/heads/master
<repo_name>ahanlon1987/musocracy<file_sep>/voter-app/public/js/routers/mobileRouter.js // Mobile Router // ============= // Includes file dependencies define([ "jquery","backbone", "amplify", "../collections/SearchCollection", "../collections/QueueCollection", "../views/SearchView", "../views/QueueView", "../views/LocationView", "../util/persist"], function( $, Backbone, Amplify, SearchCollection, QueueCollection, SearchView, QueueView, LocationView, Persist) { // Extends Backbone.Router var MusocracyRouter = Backbone.Router.extend( { // The Router constructor initialize: function() { //Instantiates a new Location View this.locationView = new LocationView({el: "#container-wrapper"}); // Instantiates a new Search View this.searchView = new SearchView( { el: "#container-wrapper", collection: new SearchCollection () } ); // Instantiates a new Queue View this.queueView= new QueueView( { el: "#votes", collection: new QueueCollection() } ); // Tells Backbone to start watching for hashchange events Backbone.history.start(); this.persist = Persist; }, amplify:Amplify, // Backbone.js Routes routes: { // When there is no hash bang on the url, the home method is called "": "home", "queue" : "queue", "search" : "search", "search?:query" : "search", "location" : "enterLocation" }, // Home method home: function() { if(!amplify.store('locationId')){ this.enterLocation(); } else { window.location.href = '#queue'; } }, enterLocation: function(){ this.locationView.render(); }, queue: function() { if(!amplify.store('locationId')){ this.enterLocation(); } else { var currentView = this.queueView; currentView.collection.url = '/location/' + amplify.store('locationId') +'/votes'; //Always refresh the queue currentView.collection.fetch().done( function() { } ); } }, search: function(query) { if(!amplify.store('locationId')){ this.enterLocation(); } else { var currentView = this.searchView; if(query){ currentView.collection.url = '/search/track?q=' + query; currentView.collection.fetch().done( function() { } ); } else { //No previous search? if (currentView.collection.isEmpty()){ currentView.collection.reset(); //re-render a blank view //Previous search in memory, show it } else { currentView.render(); } } } } } ); // Returns the Router class return MusocracyRouter; } );<file_sep>/voter-app/public/js/collections/SpotifySearchCollection.js define(['backbone', 'models/TrackModel'], function (Backbone, TrackModel) { var regex = /[^A-Za-z\d]/g; return Backbone.Collection.extend({ model: TrackModel, initialize:function () { }, parse:function (response) { return response.playlist; }, getTrackById:function (trackId) { return this.find(function (model) { return model.get('trackId') === trackId; }); }, // filter results by name and artist, ignore case, special chars, and whitespace for now getFilteredResults:function (filter) { if (filter) { filter = filter.toLowerCase.replace(regex, ''); } return _.filter(this.models, function (model) { var name = model.get('name') || ''; name = name.toLowerCase().replace(regex, ''); var artists = model.get('artists') || ''; artists = artists.toLowerCase().replace(regex, ''); return name.contains(filter) || artists.contains(filter); }); } }); });<file_sep>/voter-app/routes/votes.js var votingService = require('../services/votingService').votingService; exports.addVote = function(req, resp) { var locationId = req.params.locationId; var trackId = req.params.trackId; var track = req.body; votingService.addVote(locationId, track, { success:function(result) { console.log('successfully added vote'); resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(result)); resp.end(); }, error:function(err) { resp.writeHead(500); resp.write('Error adding vote'); resp.end(); } }) // } }; exports.getVotes = function(req, resp) { var locationId = req.params.locationId; var limit = req.query.limit || 0; var excludePlayed = (req.query.excludePlayed && (req.query.excludePlayed.toLowerCase() === 'true')) || false; votingService.getVotes({ locationId: locationId, limit: limit, excludePlayed:excludePlayed }, { success:function(results) { resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(results)); resp.end(); }, error:function(err) { resp.writeHead(500); resp.write('Error getting votes'); resp.end(); } }) }; exports.markAsPlayed = function (req, resp) { var locationId = req.params.locationId, trackId = req.params.trackId; console.log('Marking track as played: locationId=' + locationId); console.log('trackId=' + trackId); votingService.markAsPlayed({ locationId:locationId, trackId:trackId }, { success:function(result) { console.log('successfully added vote'); resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(result)); resp.end(); }, error:function(err) { resp.writeHead(500); resp.write('Error adding vote'); resp.end(); } }); }; // exports.addVote = addVote; // exports.getVotes = getVotes;<file_sep>/voter-app/routes/player.js var playerService = require('../services/playerService').api; exports.updateNowPlayingAndQueueNext = function (req, resp) { var locationId = req.params.locationId; var nowPlaying = req.query.nowPlaying; var upNext = req.query.upNext; console.log('Marking track as played: locationId=' + locationId); console.log('nowPlaying=' + nowPlaying); console.log('upNext=' + upNext); playerService.updateNowPlayingAndQueueNext({ locationId:locationId, nowPlaying:nowPlaying, upNext:upNext, success:function(result) { console.log('successfully added vote'); resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(result)); resp.end(); }, error:function(err) { resp.writeHead(500); resp.write('Error adding vote'); resp.end(); } }); }; // exports.addVote = addVote; // exports.getVotes = getVotes;<file_sep>/voter-app/public/js/views/ToolbarView.js define(['jquery', 'underscore', 'backbone', 'templates', 'util/dispatcher'], function ($, _, Backbone, templates, dispatcher) { return Backbone.View.extend({ events:{ 'click .icon-refresh':'refresh', 'click .refresh':'refresh' }, initialize:function () { this.title = this.options.title || 'Musocracy'; this.searchShown = false; }, render:function () { var templateJson = { title:this.title }; this.$el.html(templates.toolbar.render(templateJson)); return this; }, showLocation:function (locationName) { this.$('.brand').text(locationName); this.$('.back').show(); }, showHome:function () { this.$('.brand').text('Musocracy'); this.$('.back').hide(); }, refresh:function (e) { (e && e.preventDefault()); this.startRefreshRotation(); dispatcher.trigger(dispatcher.events.REFRESH); }, startRefreshRotation:function () { var degrees = 0; var $refreshIcon = this.$('.icon-refresh'); var rotate = function() { degrees += 10; $refreshIcon.css('transform', 'rotate(' + degrees + 'deg)'); if (degrees !== 360) { setTimeout(rotate, 25); } }; rotate(); }, toggleSearch:function (e) { (e && e.preventDefault()); this.searchShown ? this.showSearch() : this.hideSearch(); }, showSearch:function () { this.$('.search').show(); dispatcher.trigger(dispatcher.events.SHOW_SEARCH); }, hideSearch:function () { this.$('.search').hide(); dispatcher.trigger(dispatcher.events.HIDE_SEARCH); }, clearSearch:function () { this.$('.search input').val(''); dispatcher.trigger(dispatcher.events.CLEAR_SEARCH); } }); });<file_sep>/voter-app/public/js/collections/QueueCollection.js // Category Collection // =================== // Includes file dependencies define([ "jquery", "backbone", "models/QueueModel"], function ($, Backbone, QueueModel) { // Extends Backbone.Collection var Collection = Backbone.Collection.extend({ // The Collection constructor initialize:function () { }, isEmpty:function () { return (this.models.length < 1); }, type:'Queue', // Sets the Collection model property to be a Category Model model:QueueModel, comparator:function (model) { return -model.get('votes'); }, parse:function (response) { if (response) { return response.playlist; } }, getFilteredResults:function (filter) { return _.filter(this.models, function (model) { //TODO make this better e.g., to lowercase on everything. return model.get('name') == filter; }); } }); // Returns the Collection class return Collection; });<file_sep>/voter-app/public/js/views/ListItemView.js // Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "amplify"], function( $, Backbone, Amplify) { var THREE_HOURS_IN_MS = 10800000; var ListItemView = Backbone.View.extend({ tagName : "li", initialize: function(){ _.bindAll(this, "setActive"); }, amplify:Amplify, render : function(model) { var index = $.inArray(model.get('trackId'), _.pluck(amplify.store('previousVotes'), 'trackId')); if (index >= 0){ var oldVote = amplify.store('previousVotes')[index]; if(oldVote){ if((new Date()) - (new Date(oldVote.voteTime)) < THREE_HOURS_IN_MS){ model.set('disableVote', true); } } } this.template = _.template( $( "script#songs" ).html(), { "model": model.toJSON()} ); this.$el.attr('data-name', model.get('trackId')) .addClass('song-list media') .addClass(model.get('disableVote') ? 'disabled': '') .html(this.template); this.model = model; return this; }, events:{ "click":"setActive" }, setActive: function(event){ var listItem = $(event.currentTarget); if(listItem[0]){ if(!this.model.get('disableVote')){ $(listItem).animate({ opacity:.5 }); router.persist.vote(this.model); } } } }); return ListItemView; } );<file_sep>/voter-app/public/js/util/persist.js // Persist Utils // ============= // Includes file dependencies define(["jquery", "underscore", "backbone", "amplify"], function ($, _, Backbone, Amplify) { var Persist = { amplify:Amplify, vote:function (track, options) { var trackId = track.get('trackId'); var trackName = track.get('name'); var artists = track.get('artists'); var album = track.get('album'); console.log('Voting for trackId: ' + trackId + ', trackName: ' + trackName + ', artists: ' + artists + ', album: ' + album); var amp = amplify; $.ajax({ type:"POST", url:'/location/' + amplify.store('locationId') + '/votes/' + trackId, data:{trackId:trackId, name:trackName, artists:artists, album:album}, success:function (resp) { var previousVotes = (amp.store('previousVotes') || []); previousVotes.push({ 'trackId':trackId, 'voteTime':new Date() }); amp.store('previousVotes', previousVotes); if (options && _.isFunction(options.success)) { options.success(resp); } }, failure:function () { console.log('voting failed.'); }, dataType:'json' }); }, lookupLocation:function (location) { $.ajax({ type:"GET", url:'/location/' + location, data:{}, success:function (data) { console.log('200 returned from location service, check if locationId is null'); if (data) { console.log('found location: ' + data.locationId); amplify.store('locationId', data.locationId, {expires:21600000}); //expire locationId after six hours. $("#location-submit").addClass("hidden"); window.location.href = '#'; } else { console.log('No such location: ' + location); $('label#location-label').html('Unable to find a location of ' + location + '.'); } }, failure:function () { console.log('Error trying to find location ' + location + ', please try again'); }, dataType:'json' }); } }; return Persist; });<file_sep>/voter-app/app.js /** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , search = require('./routes/search') , lookup = require('./routes/lookup') , http = require('http') , path = require('path') , votingService = require('./services/votingService').votingService , votes = require('./routes/votes') , location = require('./routes/location') , player = require('./routes/player') , locationService = require('./services/locationService').locationService , playerService = require('./services/playerService').api; var app = express(); app.configure(function () { app.set('port', process.env.PORT || 3000); // app.set('views', __dirname + '/views'); // app.set('view engine', 'jade'); app.use(express.static(path.join(__dirname, 'views'))); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(require('less-middleware')({ // src: __dirname + '/public', dest:__dirname + '/public/css', src:__dirname + '/public/less', prefix:'/css' })); }); app.get('/', routes.index); app.get('/location/:locationId/search/track', search.byTrack); app.get('/location/:locationId/search/artist', search.byArtist); app.get('/location/:locationId/search/album', search.byAlbum); app.get('/lookup', lookup.lookup); app.get('/location/:locationId', location.getLocation); app.get('/location/:locationId/votes', votes.getVotes); app.get('/location/:locationId/votes/:trackId', votes.addVote); app.post('/location/:locationId/votes/:trackId', votes.addVote); app.post('/location/:locationId/track/:trackId', votes.markAsPlayed); app.get('/location/:locationId/track/:trackId', votes.markAsPlayed); app.get('/location/:locationId/updateQueue', player.updateNowPlayingAndQueueNext); var config = {}; var mongourl; var generate_mongo_url = function (obj) { obj.hostname = (obj.hostname || 'localhost'); obj.port = (obj.port || 27017); obj.db = (obj.db || 'test'); if (obj.username && obj.password) { return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db; } else { return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db; } } app.configure('development', function () { console.log('Loading development configuration'); app.use(express.errorHandler()); app.use(express.static(path.join(__dirname, 'public'))); config = require('./config/development.json'); app.set('port', config.port); mongourl = generate_mongo_url(config.mongo); }); app.configure('production', function () { //mongodb://af_musocracy-musocracyapp:<EMAIL>:27427/af_musocracy-musocracyapp console.log('Loading production configuration'); app.use(express.static(path.join(__dirname, 'publicbuilt'))); config = require('./config/production.json'); mongourl = "mongodb://musocracy:<EMAIL>:27447/musocracy"; }); ; if (!mongourl) { console.log("Couldn't find mongolab URI! Exiting now"); throw new Error('MONGOLAB_URI environment variable not found.'); } console.log('Mongolab URI: ' + mongourl); console.error("About to connect to " + mongourl); require('mongodb').connect(mongourl, function (err, conn) { if (err) { console.log('Error connecting to Mongo', err); throw err; } console.log('Mongo connection obtained.'); votingService.setDb(conn); locationService.setDb(conn); playerService.setDb(conn); http.createServer(app).listen(app.get('port'), function () { console.log("Express server listening on port " + app.get('port')); }); }); <file_sep>/voter-app/services/spotifyService.js var url = require('url'); var http = require('http'); var Q = require('q'); var _ = require('underscore'); var filter = require('./util/filter').filter; var BASE_URL = 'http://ws.spotify.com/'; var SEARCH_URLS = { track: BASE_URL + 'search/1/track.json', artist: BASE_URL + 'search/1/artist.json', album: BASE_URL + 'search/1/album.json' }; var LOOKUP_URL = BASE_URL + 'lookup/1/.json'; /** * * @param opts * { * type: track | artist | album * query: search * success: function * error: function * } */ var doSearch = function(opts) { // console.log('searching by track'); var locationId = opts.locationId, query = opts.query, type = opts.type; var requestUrl = SEARCH_URLS[type] + '?q=' + query; // console.log('Request Url: ' + requestUrl); http.get(requestUrl, function(response){ // console.log('Got Response', response); var respData = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { // console.log('Data Received: ' + chunk); respData += chunk; }); response.on('end', function() { var respObj = JSON.parse(respData); // console.log(respData); var info = respObj.info; //Clean up the search result to only bring back what we need: id, name, artist(s), album. var formattedTracks = []; if (respObj.tracks){ _.each(respObj.tracks, function(track){ var trackId = track.href; var name = track.name; var artists = ''; var delim = ' '; _.each(track.artists, function(artist){ artists += delim + artist.name; delim = ', '; }); var album = track.album ? track.album.name : ''; formattedTracks.push({ "trackId":trackId, "name":name, "artists":artists, "album":album }) }); } filter() opts.success({info:info, playlist: formattedTracks}); }); }) } exports.searchByTrack = function(opts) { doSearch(_.extend(opts, {type:'track'})); }; exports.searchByArtist = function(opts) { doSearch(_.extend(opts, {type:'artist'})); }; exports.searchByAlbum = function(opts) { doSearch(_.extend(opts, {type:'album'})); }; /** * * @param opts * { * uri: trackId * } */ exports.lookup = function(opts) { // console.log('searching by track'); var uri = opts.uri; if (!uri) { opts.error({errorCode: 'error.spotifyService.lookup.noUri'}); return; } var requestUrl = LOOKUP_URL + '?uri=' + uri; if (uri instanceof String && uri.indexOf('spotify:artist') >= 0) { requestUrl += '&extras=album' } else if (uri instanceof String && uri.indexOf('spotify:album') >= 0) { requestUrl += '&extras=track' } // console.log('Request Url: ' + requestUrl); http.get(requestUrl, function(response){ // console.log('Got Response', response); var respData = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { // console.log('Data Received: ' + chunk); respData += chunk; }); response.on('end', function() { var respObj = JSON.parse(respData); // console.log(respData); var track = { trackId: respObj.track.href, name: respObj.track.name, artists:_.reduce(respObj.track.artists, function(memo, artist) { if (memo) memo+= ", "; return (memo += artist.name); }, ""), album: respObj.track.album.name }; opts.success(track); }); }) }; <file_sep>/voter-app/services/locationService.js var _ = require('underscore'); var PLAYLISTS_COLLECTION = 'playlists'; var locationService = { setDb:function(db) { this.db = db; }, //TODO we could probably use to increment a user count or something findLocation:function(locationId, options) { console.log('Adding vote for locationId=' + locationId); this.db.collection(PLAYLISTS_COLLECTION, function(err, collection) { if (err) { console.log('Error fetching collection (name=' + PLAYLISTS_COLLECTION + ')'); (options && options.error && options.error(err)); return; } console.log('found collection; searching for location.'); collection.findOne({locationId:locationId.toLowerCase()}, function(err, location) { if (err) { console.log('Error finding collection.', err); options && options.error && options.error(err); return; } if (!location) { console.log('Unable to find location. Returning null'); options && options.success && options.success(null) } else { console.log('Found location ' + locationId + '. Returning location'); // options && options.success && options.success({"locationId":locationId}) options && options.success && options.success(location); } }); }); } }; exports.locationService = locationService; <file_sep>/voter-app/routes/location.js var locationService = require('../services/locationService').locationService; exports.getLocation = function(req, resp) { var locationId = req.params.locationId; locationService.findLocation(locationId, { success:function(result) { resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(result)); resp.end(); }, error:function(err) { resp.writeHead(500); resp.write('Error finding location'); resp.end(); } }) }; <file_sep>/voter-app/services/playerService.js var _ = require('underscore'); var spotifyService = require('../services/spotifyService'); var votingService = require('../services/votingService').votingService; var PLAYLISTS_COLLECTION = 'playlists'; var MAX_PLAYED_LENGTH = 20; /** * * @param opts * { * trackId: track ID to load * success: function * error: function * } */ var deferTrackLoad = function(opts) { var trackId = opts.trackId; spotifyService.lookup({ uri: trackId, success: opts.success, error: opts.error }); } var service = { setDb:function(db) { this.db = db; }, /** * * @param opts * { * locationId: locationId * nowPlaying: trackId * upNext: trackId * success: function * error: function * } */ updateNowPlayingAndQueueNext:function(options) { var locationId = options.locationId; var nowPlayingTrackId = options.nowPlaying; var upNextTrackId = options.upNext; if (!locationId) { throw new Error("locationId param is required"); } var self = this; this.db.collection(PLAYLISTS_COLLECTION, function (err, collection) { if (err) { console.error('Error retrieving collection.'); if (options && _.isFunction(options.error)) options.error(err); else throw err; } collection.findOne({locationId: locationId}, function(err, location) { if (err) { console.error('Error finding collection.', err); if (options && _.isFunction(options.error)) options.error(err); else throw err; } if (!location) { location = { locationId: locationId }; } if (!location.votes) { location.votes = []; } if (!location.played) { location.played = []; } var nowPlaying, upNext, nowPlayingIndex = -1, upNextIndex = -1; if (nowPlayingTrackId) { if (location.upNext && location.upNext.trackId === nowPlayingTrackId) { nowPlaying = location.upNext; } else { nowPlaying = _.find(location.votes, function(track, index) { if (track.trackId === nowPlayingTrackId) { nowPlayingIndex = index; return true; } return false; }); if (nowPlaying) { location.votes.splice(nowPlayingIndex, 1); } } // if nowPlaying was found, store it and remove from the votes list if (nowPlaying) { location.nowPlaying = nowPlaying; location.played.push(nowPlaying); } else { deferTrackLoad({ trackId: nowPlayingTrackId, success: function(track) { collection.update({locationId:location.locationId}, {$set: {nowPlaying:track}}); }, error: function(err) { console.error('Error deferring load of up next track', err); } }) } } else { location.nowPlaying = null; } if (upNextTrackId) { upNext = _.find(location.votes, function(track, index) { if (track.trackId === upNextTrackId) { upNextIndex = index; return true; } return false; }); // if upNext was found, store it and remove from the votes list if (upNext) { location.upNext = upNext; location.votes.splice(upNextIndex, 1); } else { deferTrackLoad({ trackId: upNextTrackId, success: function(track) { collection.update({locationId:location.locationId}, {$set: {upNext:track}}); }, error: function(err) { console.error('Error deferring load of up next track', err); } }) } } else { location.upNext = null; } collection.update({locationId:location.locationId}, location, {upsert:true}, function (err, obj) { if (err) { console.error('Error marking track as played.', err); (options && options.error && options.error(err)); } else { votingService.getVotes({ locationId:location.locationId, limit:5, excludePlayed:true }, options); // (options && options.success && options.success(location)); } }); }); }) } }; exports.api = service;<file_sep>/voter-app/public/js/views/FooterView.js define(['jquery', 'underscore', 'backbone', 'templates'], function ($, _, Backbone, templates) { return Backbone.View.extend({ initialize:function() { }, render:function() { this.$el.html(templates.footer.render()); return this; } }); });<file_sep>/voter-app/services/notes.txt Hosting: appfrog Mongo: Mongolab username: musocracyadmin password: <PASSWORD> db user: musocracy password: <PASSWORD><file_sep>/voter-app/public/js/views/HomeView.js define(['jquery', 'amplify', 'backbone', 'templates'], function ($, amplify, Backbone, templates) { return Backbone.View.extend({ events: { 'submit #location-submit': 'submitLocation' }, initialize:function () { }, render:function () { this.$el.html(templates.home.render()); return this; }, submitLocation:function (e) { (e && e.preventDefault()); var location = this.$("#location-input").val(); if (location) { // router.persist.lookupLocation(location); this.verifyLocation(location); } else { console.log('No value found, enter a value and try again.'); this.$('label#location-label').html('Enter a value and try again.'); } return false; }, verifyLocation:function(location) { var self = this; $.ajax({ type: "GET", url: '/location/' + location, contentType: 'application/json', success: function(data) { console.log('200 returned from location service, check if locationId is null'); if(data) { console.log('found location: ' + data.locationId); amplify.store('locationId', data.locationId, {expires:21600000}); //expire locationId after six hours. window.location.href = '/#location/' + data.locationId; } else { console.log('No such location: ' + location); self.$('label#location-label').html('Unable to find a location of ' + location + '.'); } }, failure:function(){ console.log('Error trying to find location ' + location + ', please try again'); } }); } }); });<file_sep>/voter-app/services/votingService.js var _ = require('underscore'); var PLAYLISTS_COLLECTION = 'playlists'; var MAX_PLAYED_LENGTH = 20; /* { locationId: "Kincades", votes: [ { name: "Inside Out", artists: "Eve 6", album: "Album Name", votes: 3 }, ... ] played: [ { name: "Californication", artists: "Red Hot Chili Peppers", album: "Album Name", votes: 5, played: true }, { name: "Can't Stop", artists: "Red Hot Chili Peppers", album: "Album Name", votes: 3, played: true }, ], } */ var updatePlaylist = function(location) { var votes = location.votes; var topFive = votes.slice(0, 5); }; var votingService = { setDb:function (db) { this.db = db; }, addVote:function (locationId, obj, options) { console.log('Adding vote for locationId=' + locationId); this.db.collection(PLAYLISTS_COLLECTION, function (err, collection) { if (err) { console.error('Error fetching collection (name=' + PLAYLISTS_COLLECTION + ')'); (options && options.error && options.error(err)); return; } console.error('found collection; searching for location.'); collection.findOne({locationId:locationId.toLowerCase()}, function (err, location) { if (err) { console.error('Error finding collection.', err); options && options.error && options.error(err); return; } if (!location) { location = { locationId:locationId.toLowerCase() }; } if (!location.votes) { location.votes = []; } if (!location.played) { location.played = []; } console.error('Search tracks for track.trackId=' + obj.trackId); var track = _.find(location.votes, function(track) { return track.trackId === obj.trackId; }); if (track) { track.votes++; } else { location.votes.push({ trackId:obj.trackId, name:obj.name, artists:obj.artists, album:obj.album, votes:1 }); } location.votes = _.sortBy(location.votes, function (track) { return track.votes * -1; // inverse sort order }); collection.update({locationId:location.locationId}, location, {upsert:true}, function (err, obj) { if (err) { console.error('Error saving vote.', err); (options && options.error && options.error(err)); } else { (options && options.success && options.success(location)); } }); }); // collection.findAndModify({locationId:locationId }, [['trackName',1]], // {$inc: {voteCount: 1}}, {upsert:true}, function(err, doc) { // if (err) { // console.log('error adding vote for locationId ' + locationId, err); // if (options && options.error) options.error(err); // } // else { // if (options && options.success) options.success(doc); // } // }); }); }, getVotes:function (obj, options) { var locationId = obj.locationId; var limit = obj.limit || 0; var excludePlayed = obj.excludePlayed || false; this.db.collection(PLAYLISTS_COLLECTION, function (err, collection) { if (err) { console.error('Error fetching collection (name=' + PLAYLISTS_COLLECTION + ')'); (options && options.error && options.error(err)); return; } if (!collection) { (options && options.success && options.success(collection)); return; } collection.findOne({locationId:locationId}, function (err, location) { if (err) { console.log('error fetching location', err); if (options && options.error) { options.error(err); } } else { //TODO throw an error if the location doesn't exist? if (!location) { location = { locationId:locationId, votes:[], played:[] }; } if (excludePlayed) { location.votes = _.filter(location.votes, function (track) { return !track.played; }); } if (limit && limit > 0) { location.votes = location.votes.slice(0, limit); } if (options && options.success) { options.success(location); } } }); }) }, markAsPlayed:function (obj, options) { var self = this; this.db.collection(PLAYLISTS_COLLECTION, function (err, collection) { if (err) { console.error('Error fetching collection (name=' + PLAYLISTS_COLLECTION + ')'); (options && options.error && options.error(err)); return; } console.log('Receving mark as played request: ' + JSON.stringify(obj)); collection.findOne({locationId:obj.locationId}, function (err, location) { if (err) { console.error('Error finding collection.', err); options && options.error && options.error(err); return; } if (!location) { location = { locationId:obj.locationId }; } if (!location.played) { location.played = []; } if (!location.votes) { location.votes = []; } var trackIndex = -1; var track = _.find(location.votes, function (track, i) { if (track.trackId == obj.trackId && !track.played) { trackIndex = i; return true; } else { return false; } }); if (track) { console.log('Found track: ' + JSON.stringify(track)); track.played = true; location.votes.splice(trackIndex, 1); } else { track = { trackId:obj.trackId, played:true }; } console.log('pushing track onto played list: ' + JSON.stringify(track)); location.played.push(track); while (location.played > MAX_PLAYED_LENGTH) { location.played.unshift(); } var topTrack = _.sortBy(location.votes, function (track) { return track.votes * -1; })[0]; location.upNext = topTrack; collection.update({locationId:location.locationId}, location, {upsert:true}, function (err, obj) { if (err) { console.error('Error marking track as played.', err); (options && options.error && options.error(err)); } else { self.getVotes({ locationId:location.locationId, limit:5, excludePlayed:true }, options); // (options && options.success && options.success(location)); } }) }); }) } } exports.votingService = votingService; <file_sep>/voter-app/public/js/collections/SearchCollection.js // Search Collection // =================== // Includes file dependencies define([ "jquery","backbone","models/SearchModel"], function( $, Backbone, SearchModel) { // Extends Backbone.Collection var Collection = Backbone.Collection.extend( { // The Collection constructor initialize: function() { }, isEmpty:function(){ return (this.models.length < 1); }, type:"Search", // Sets the Collection model property to be a Search Model model: SearchModel, parse: function(response){ return response.playlist; } } ); // Returns the Collection class return Collection; } );<file_sep>/README.md musocracy ========= A simple node-backed mobile first Web Applciation that allows patrons to search for, and vote on the music being played. # Node Application 1. Install nodejs 2. Install nodemon as global dependency * `npm install -g nodemon` 3. Install app dependencies: from inside voter-app directory: * `npm install` * This will install all package dependencies defined in the packages.json file into a node_modules folder 4. Run application * `node app.js` * Starts an http server on port 3000 5. Monitor Hogan templates for changes * `grunt watch:templates` # Voter Application Structure * *app.js*: root app server * */public/*: all client side resources * */views*: views to be rendered server-side (static HTML for right now, but could be Mustache/Jade templates) * */routes/*: all request handlers # API * `GET /search/track?q=QUERY`: search for tracks * `GET /search/artist?q=QUERY`: search for artists * `GET /search/album?q=QUERY`: search for albums* * `GET /lookup?uri=SPOTIFY_URI`: lookup metadata for specific artist, album, or track * ex: `GET /lookup?uri=spotify:track:6NmXV4o6bmp704aPGyTVVG` * `POST /location/{id}/votes/{trackId}` : vote for a track at a specific location * `GET /location/{id}/votes` : returns all votes for a given location * `GET /location/{id}` : returns locationId if it exists <file_sep>/voter-app/public/js/models/TrackModel.js define(['backbone'], function (Backbone) { return Backbone.Model.extend({ initialize:function() { if (this.attributes.trackId) { this.set('domId', this.attributes.trackId.replace(/:/g, '_')); } } }); } );<file_sep>/voter-app/public/js/models/LocationModel.js define(['underscore', 'backbone', 'collections/VotesCollection'], function (_, Backbone, VotesCollection) { return Backbone.Model.extend({ initialize:function (attributes, options) { this.locationId = options.locationId; this.on('reset', this.onReset, this); }, url:function () { return '/location/' + this.locationId; }, // parse:function (response) { // }, onReset:function () { this.set('votes', new VotesCollection(this.attributes.votes)); }, getVotes:function () { var votes = this.get('votes'); if (!(votes instanceof VotesCollection)) { votes = new VotesCollection(votes); this.set('votes', votes); } return votes; }, getNowPlaying:function () { return this.get('nowPlaying'); }, getUpNext:function () { return this.get('upNext'); } }); });<file_sep>/voter-app/public/js/views/QueueView.js // Category View // ============= // Includes file dependencies define(["jquery", "underscore", "backbone", "templates", "models/QueueModel", "views/ListItemView", "collections/VotesCollection", "collections/SpotifySearchCollection", "models/LocationModel", "util/persist", "util/dispatcher"], function( $, _, Backbone, templates, QueueModel, ListItemView, VotesCollection, SpotifySearchCollection, LocationModel, persist, dispatcher) { // Extends Backbone.View var THREE_HOURS_IN_MS = 10800000; var timeoutId; return Backbone.View.extend({ events: { 'keyup .search input':'onKeyPress', 'click .location-queue .track:not(.disabled)':'onTrackClick', 'click .spotify-results .track:not(.disabled)':'onSearchResultClick', 'click .clear-search':'onClearSearch' }, // The View Constructor initialize: function() { this.locationId = this.options.locationId; this.locationModel = this.options.locationModel; dispatcher.on(dispatcher.events.REFRESH, this.onRefresh, this); }, // Renders all of the Category models on the UI render: function() { this.$el.html(templates.queue.render()); this.searchCollection = new SpotifySearchCollection(); // this.locationModel = new LocationModel({}, { // locationId: this.locationId // }); this.locationModel.fetch({ success:$.proxy(this.onLocationFetched, this) }); // Maintains chainability return this; }, renderQueue:function (tracks) { var html = ''; _.each(tracks, function (track) { // track.set('disabled', ''); var index = $.inArray(track.get('trackId'), _.pluck(amplify.store('previousVotes'), 'trackId')); if (index >= 0){ var oldVote = amplify.store('previousVotes')[index]; if(oldVote){ if((new Date()) - (new Date(oldVote.voteTime)) < THREE_HOURS_IN_MS){ track.set('disabled', 'disabled'); } } } // track.set('domId', track.get('trackId').replace(":", "_")); html += templates.track.render(track.attributes); }); this.$('.location-queue').html(html); }, onRefresh:function () { this.locationModel.fetch({ success:$.proxy(this.onLocationFetched, this) }); }, onLocationFetched: function() { var votesCollection = this.locationModel.getVotes(); var query = this.$('.search input').val(); if (query) { this.filterVotesCollection(query); } else { this.renderQueue(votesCollection.models); } }, onKeyPress:function(e) { window.clearTimeout(timeoutId); var query = this.$('.search input').val(); if (e && e.which === 13) { this.search(); } else if (e && e.which === 8 && query == ''){ console.log('backspace pressed with no no content in search field, clearing search results'); this.onClearSearch(); } else { timeoutId = setTimeout($.proxy(this.search, this), 500); } this.filterVotesCollection(query); }, onTrackClick:function(e) { (e && e.preventDefault()); var $currentTarget = this.$(e.currentTarget); var trackId = $currentTarget.data('trackid'); var votes = this.locationModel.getVotes(); var track = votes.getTrackById(trackId); if (track) { this.addVote(track); } }, onSearchResultClick:function(e) { (e && e.preventDefault()); var $currentTarget = this.$(e.currentTarget); $currentTarget.remove(); var trackId = $currentTarget.data('trackid'); var track = this.searchCollection.getTrackById(trackId); if (track) { var votesCollection = this.locationModel.getVotes(); votesCollection.add(track); this.addVote(track); } }, addVote:function(track) { var self = this; var votes = track.get('votes'); if (!votes) { votes = 1; } else{ votes++; } track.set('votes', votes); track.set('disabled', 'disabled'); this.onLocationFetched(); this.highlightTrack(track); this.disableTrack(track); persist.vote(track, { success:function(resp) { // console.log('Voting complete.', resp); // dispatcher.trigger(dispatcher.events.REFRESH); self.locationModel = new LocationModel(resp, {locationId: self.locationId}); // self.onLocationFetched(); // self.highlightTrack(track); } }); }, highlightTrack:function(track) { var domId = track.get('domId'); var $track = this.$('#' + domId); var origColor = $track.css('background-color'); $track.animate({ 'background-color': "#C7F5C1" }, 250); setTimeout(function() { $track.animate({ 'background-color': origColor }, 750); }, 500); }, disableTrack:function(track) { var domId = track.get('domId'); var $track = this.$('#' + domId); $track.addClass('disabled'); }, onClearSearch:function(e){ //Clear the search text this.$('.search input').val(''); //clear the spotify results div this.$('.spotify-results').empty(); //Redraw the queue this.renderQueue(this.locationModel.getVotes().models); }, search:function(){ var query = this.$('.search input').val(); console.log('Executing search on: ' + query); var $spotifyResults = this.$('.spotify-results'); if(query){ $spotifyResults.html('Loading....'); this.searchCollection.url = '/location/' + this.locationId + '/search/track?q=' + query; var self = this; this.searchCollection.fetch() .done(function(){ var html = ''; if(!self.searchCollection.isEmpty()){ self.searchCollection.each(function(model) { html += templates.track.render(model.attributes); }); } else { html = 'No Results Found, please try again.' } $spotifyResults.html(html); }).fail(function(){ console.log('Handling failed spotify search, redrawing...'); $spotifyResults.html('Search failed, please try again.'); }); } else { $spotifyResults.empty(); } }, filterVotesCollection:function (query) { var votesCollection = this.locationModel.getVotes(); var models = votesCollection.getFilteredResults(query); this.renderQueue(models); } } ); } );<file_sep>/voter-app/public/js/mobile.js // Sets the require.js configuration for your application. require.config({ // 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.8.2.min") paths:{ // Core Libraries "jquery":"lib/jquery-1.9.1", "underscore":"lib/lodash", "backbone":"lib/backbone", "amplify":"lib/amplify.min", "bootstrap":"lib/bootstrap" }, // Sets the configuration for your third party scripts that are not AMD compatible shim:{ "backbone":{ "deps":[ "underscore", "jquery" ], "exports":"Backbone" //attaches "Backbone" to the window object } } // end Shim Configuration }); // Includes File Dependencies require([ "jquery", "backbone", "routers/mobileRouter", "collections/QueueCollection"], function ($, Backbone, MobileRouter, QueueCollection) { this.router = new MobileRouter(); $("#header-search").click(function () { $("#header-search-form").removeClass('hidden'); $("#home-link").css('display', 'none'); $("#header-song-search").focus(); }); //TODO make this on search clear $("#header-song-search").blur(function () { $("#header-search-form").addClass('hidden'); $("#home-link").css('display', 'block'); }); }); <file_sep>/voter-app/public/js/app.js // Sets the require.js configuration for your application. require.config({ // 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.8.2.min") paths:{ // Core Libraries "hogan":"lib/hogan/hogan-2.0.0.amd", "jquery":"lib/jquery-1.9.1", "jqueryui":"lib/jquery-ui-1.10.2.custom.min", "underscore":"lib/lodash", "backbone":"lib/backbone", "amplify":"lib/amplify.min", "bootstrap":"lib/bootstrap" }, // Sets the configuration for your third party scripts that are not AMD compatible shim:{ jqueryui: { deps: ["jquery"] }, backbone:{ "deps":[ "underscore", "jquery" ], "exports":"Backbone" //attaches "Backbone" to the window object }, amplify:{ exports:"amplify" } } // end Shim Configuration }); // Includes File Dependencies require([ "jquery", "jqueryui", "backbone", "hogan", "routers/Router" ], function ($,$ui, Backbone, Hogan, Router) { this.router = new Router({ el:$('body') }); }); <file_sep>/voter-app/public/js/views/InfoFooterView.js define(['jquery', 'underscore', 'backbone', 'templates'], function ($, _, Backbone, templates) { return Backbone.View.extend({ initialize:function() { // this.nowPlaying = this.options.nowPlaying; // this.upNext = this.options.upNext; this.locationModel = this.options.locationModel; _.each(['change'], function(eventName) { this.locationModel.on(eventName, this.render, this); }, this); }, render:function() { var nowPlaying = this.locationModel.getNowPlaying(), upNext = this.locationModel.getUpNext(); this.$el.html(templates.infoFooter.render({ nowPlayingTrackName:(nowPlaying && nowPlaying.name) || '', upNextTrackName:(upNext && upNext.name) || '' })); return this; } }); });<file_sep>/voter-app/routes/lookup.js var url = require('url'); var http = require('http'); var Q = require('q'); var BASE_URL = 'http://ws.spotify.com/'; var LOOKUP_URL = BASE_URL + 'lookup/1/.json'; exports.lookup = function(req, resp) { // console.log('searching by track'); var uri = new String(req.query.uri); if (!uri) { resp.writeHead(400, {'Content-Type':'application/json'}); resp.write(JSON.stringify({errorCode:'error.request.nouri'})); return; } var requestUrl = LOOKUP_URL + '?uri=' + uri; if (uri instanceof String && uri.indexOf('spotify:artist') >= 0) { requestUrl += '&extras=album' } else if (uri instanceof String && uri.indexOf('spotify:album') >= 0) { requestUrl += '&extras=track' } // console.log('Request Url: ' + requestUrl); http.get(requestUrl, function(response){ // console.log('Got Response', response); var respData = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { // console.log('Data Received: ' + chunk); respData += chunk; }); response.on('end', function() { var respObj = JSON.parse(respData); // console.log(respData); resp.writeHead(200, {'Content-Type':'application/json'}); resp.write(JSON.stringify(respObj)); resp.end(); }); }) }<file_sep>/voter-app/public/js/views/TracksView.js define(['jquery', 'underscore', 'backbone', 'templates'], function($, _, Backbone, templates) { return Backbone.View.extend({ initialize:function() { this.tracks = new Backbone.Collection(); }, render:function() { var html = ''; _.each(this.tracks, function(track) { html += templates.track(track.attributes); }); this.$el.html(html); return this; } }) })<file_sep>/voter-app/services/util/filter.js var locationService = require('../locationService').locationService; var _ = require('underscore'); /** * * @param opts */ exports.filter = function(opts) { var locationId = opts.locationId; var results = opts.results; var fnSuccess = opts.success; var fnError = opts.error; locationService.findLocation(locationId, { success:function(location) { var votes = location.votes; var votesByTrackId = _.reduce(votes, function(memo, vote) { memo[vote.trackId] = vote; return memo; }, {}); var filteredResults = _.filter(results, function(result) { if (votesByTrackId[result.trackId]) { return false; } return true; }); fnSuccess(filteredResults); }, error:fnError }); }; <file_sep>/voter-app/public/js/util/dispatcher.js define(['underscore', 'backbone'], function (_, Backbone) { return _.extend({}, Backbone.Events, { events:{ SEARCH:'SEARCH', CLEAR_SEARCH:'CLEAR_SEARCH', REFRESH: 'REFRESH', LOCATION_UPDATED: 'LOCATION_UPDATED' } }); });<file_sep>/voter-app/public/js/views/LocationView.js // Category View // ============= // Includes file dependencies define([ "jquery", "backbone","amplify" ], function( $, Backbone, Amplify) { var QueueView = Backbone.View.extend( { // The View Constructor initialize: function() { }, amplify:Amplify, render: function() { $("#location-submit").removeClass("hidden"); $("#song-search").addClass('hidden'); $("#results").empty(); var curLocation = amplify.store('locationId'); if (curLocation){ $('label#location-label').html('Currently at: ' + curLocation); } $("#location-submit").submit(function(){ var location = $("#location-input").val(); if (location) { router.persist.lookupLocation(location); } else { console.log('No value found, enter a value and try again.'); $('label#location-label').html('Enter a value and try again.'); } return false; }); var queueView = this; // Maintains chainability return this; } } ); // Returns the View class return QueueView; } );
8118edbe465db8f3b8d13cb0ea4ce759d24f8542
[ "JavaScript", "Text", "Markdown" ]
30
JavaScript
ahanlon1987/musocracy
0282e200cf923b62cc312a49f332a9536d288b5e
94691bd94ce02bbab4fac6630744dabed9efb644
refs/heads/master
<file_sep># CMPT473-Asn2-ACTS Use ACTS to generate the test frames for the open source program: https://github.com/jehiah/json2csv The program is written using Python version 2.7.12 To run the test suite for the Json2csv program do the following steps: 1. Install the Json2csv program from the included source program from its readme page 2. cd to project root directory 2. python runTests.py 3. Done! <file_sep>import os import io import filecmp #from subprocess import call #Authors: <NAME>, <NAME> # project is constructed using https://github.com/jehiah/json2csv #command: json2csv #global variables inputFilePath = 'TestData/TestFiles/TestInput/Files/' outputFilePath = 'TestData/TestFiles/TestOutput/Files/' outputMessagePath = 'TestData/TestFiles/TestOutput/Messages/' expectedOutputPath = 'TestData/ExpectedOutput/' expectedMessagePath = 'TestData/ExpectedMessages/' testNum = 1 print '\njson2csv program ACTS Testing' print '==============================================================' def buildTestFileName(fileName): global testNum return ('test' + str(testNum) + '_' + fileName); def createMessageOutput(cmd): global testNum with io.FileIO(outputMessagePath + buildTestFileName('message.txt'), 'w') as file: file.write(cmd) def addMessageOutput(message): global testNum with io.FileIO(outputMessagePath + buildTestFileName('message.txt'), 'a') as file: file.write(message) def runJSONToCSV(csvFields, inputPathFile, outputPathFile): outputMessageFile = outputMessagePath + buildTestFileName('message.txt') outputFile = outputFilePath + buildTestFileName(outputPathFile) inputFile = inputFilePath + buildTestFileName(inputPathFile) outputMessageFile = outputMessagePath + buildTestFileName('message.txt') expectedMessageFile = expectedMessagePath + buildTestFileName('ExpectedMessage.txt') cmd = 'json2csv -k ' + csvFields + ' -i ' + inputFile + ' -o ' + outputFile print cmd + '\n' createMessageOutput(cmd + '\n\n'); if os.path.exists(inputFile) == False: #file path of input file is incorrect message = 'Path to input file is invalid' print "Message: " + message addMessageOutput(message) print '\nMessage is saved to: ' + outputMessageFile elif os.path.exists(outputFile) == False: #file path of output file is incorrect message = 'Path to output file is invalid' print "Message: " + message addMessageOutput(message) print '\nMessage is saved to: ' + outputMessageFile else: #run system command os.system(cmd) #compare files compareFilesOutput_pythonCMP(outputPathFile) #compares message files compareExpectedMessageOutput(outputMessageFile, expectedMessageFile) return; def compareFilesOutput_pythonCMP(outputPathFile): outputFile = outputFilePath + buildTestFileName(outputPathFile) expectedOutputFile = expectedOutputPath + buildTestFileName('ExpectedOutput.csv') outputMessageFile = outputMessagePath + buildTestFileName('message.txt') expectedMessageFile = expectedMessagePath + buildTestFileName('ExpectedMessage.txt') cmd = 'diff ' + outputFile + ' ' + expectedOutputFile print cmd + '\n' os.system(cmd) addMessageOutput(cmd + '\n\n'); fileIsSame = filecmp.cmp(outputFile, expectedOutputFile) if fileIsSame: message = 'Both Expected and Output Files are identical' print "Message: " + message addMessageOutput(message) else: message = 'Both Expected and Output Files are different' print "Message: " + message addMessageOutput(message) print '\nMessage is saved to: ' + outputMessageFile return; def compareExpectedMessageOutput(messageFile, expectedMessageFile): cmd = '\ndiff ' + messageFile + ' ' + expectedMessageFile print cmd + '\n' os.system(cmd) messageIsSame = filecmp.cmp(messageFile, expectedMessageFile) if messageIsSame: message = 'Both Expected and Output Messages are identical, TEST PASSED!' print message else: message = 'Both Expected and Output Messages are different, TEST FAILED!' print message return; def testFrame(testName, csvFields, inputFile, outputPathFile): global testNum print '\n\n[Test: ' + str(testNum) + ' - ' + testName + ']' print '==============================================================' runJSONToCSV(csvFields, inputFile, outputPathFile) testNum += 1 return; #do testing here # test 1 # output file should be empty as input file is empty #VALID_JSON_PATH = TRUE, FILE_CONTENTS = EMPTY, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = FALSE, VALID_OUTPUT_PATH = FALSE testFrame('Testing Valid Input Path, Empty File', 'nonExistentField', 'input.json', 'output.csv') # test 2 # output file should be empty as invalid path #VALID_JSON_PATH = FALSE, FILE_CONTENTS = EMPTY, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = FALSE, VALID_OUTPUT_PATH = FALSE testFrame('Testing Invalid Input Path, Empty File', 'nonExistentField', 'invalidPath/nonExistentFile.json', 'output.csv') # test 3 # outputs a generated csv file from json #VALID_JSON_PATH = TRUE, FILE_CONTENTS = MULTIPLE_ROWS, ALL_VALID_JSON_OBJECTS = TRUE, EACH_ROW_HAS_ONE_JSON_OBJECT = TRUE, FIELDS_EXIST_IN_JSON_OBJ = TRUE, VALID_OUTPUT_PATH = TRUE testFrame('Testing Valid Input Path, Multiple Rows File, Valid Json Obj, Each row has one jason Obj, Fields exist in Json Obj, Valid Output Path', 'user.name,remote_ip', 'input.json', 'output.csv') # test 4 # output file should be empty as invalid path #VALID_JSON_PATH = TRUE, FILE_CONTENTS = SINGLE_ROW, ALL_VALID_JSON_OBJECTS = TRUE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = TRUE, VALID_OUTPUT_PATH = FALSE testFrame('Testing Valid Input Path, Single Row File, Valid Json Obj, Each row does not have one jason Obj, Fields exist in Json Obj, Invalid Output Path', 'user.name,remote_ip', 'input.json', 'invalidPath/nonExistentFile.csv') # test 5 # output file should be empty as invalid path #VALID_JSON_PATH = TRUE, FILE_CONTENTS = MULTIPLE_ROWS, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = TRUE, FIELDS_EXIST_IN_JSON_OBJ = FALSE, VALID_OUTPUT_PATH = FALSE testFrame('Testing Valid Input Path, Multiple Rows File, Invalid Json Obj, Each row has one jason Obj, Fields do not exist in Json Obj, Invalid Output Path', 'nonExistentField,nonExistentField2', 'input.json', 'invalidPath/nonExistentFile.csv') # test 6 # output file should be empty as invalid json #VALID_JSON_PATH = TRUE, FILE_CONTENTS = SINGLE_ROW, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = TRUE, FIELDS_EXIST_IN_JSON_OBJ = TRUE, VALID_OUTPUT_PATH = TRUE testFrame('Testing Valid Input Path, Single Row File, Invalid Json Obj, Each row has one jason Obj, Fields exist in Json Obj, Valid Output Path', 'user.name,remote_ip', 'input.json', 'output.csv') # test 7 # output file should be empty as each row has one json object is false #VALID_JSON_PATH = TRUE, FILE_CONTENTS = MULTIPLE_ROWS, ALL_VALID_JSON_OBJECTS = TRUE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = TRUE, VALID_OUTPUT_PATH = TRUE testFrame('Testing Valid Input Path, Multiple Rows File, Invalid Json Obj, Each row does not have one jason Obj, Fields exist in Json Obj, Valid Output Path', 'user.name', 'test7_input.json', 'invalidPath/nonExistentFile.csv') # test 8 # output file should be empty as all valid json object is false and each row has one is false #VALID_JSON_PATH = TRUE, FILE_CONTENTS = SINGLE_ROW, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = FALSE, VALID_OUTPUT_PATH = TRUE testFrame('Testing Valid Input Path, Single Row File, Invalid Json Obj, Each row does not have one jason Obj, Fields do not exist in Json Obj, Valid Output Path', 'nonExistentField', 'test8_input.json', 'output.csv') # test 9 # output file should be empty as all conditions are false #VALID_JSON_PATH = TRUE, FILE_CONTENTS = EMPTY, ALL_VALID_JSON_OBJECTS = FALSE, EACH_ROW_HAS_ONE_JSON_OBJECT = FALSE, FIELDS_EXIST_IN_JSON_OBJ = FALSE, VALID_OUTPUT_PATH = FALSE testFrame('Testing Valid Input Path, Empty Field, Invalid Json Obj, Each row does not have one jason Obj, Fields do not exist in Json Obj, Invalid Output Path', 'nonExistentField,nonExistentField2', 'test9_input.json', 'output.csv')
6f5feef4b96e50557169b78758490f50b2c16122
[ "Markdown", "Python" ]
2
Markdown
pjsanjuan/CMPT473-Asn2-ACTS
bc9dfe7b8f901eb571be98ad5c03b67af2b1fa23
5f0db7e368ae6d36414b0b7d5c50e718ffb3a981
refs/heads/main
<file_sep>import { createStore, combineReducers, applyMiddleware } from "redux"; import createSagaMiddleware, { SagaMiddleware } from "redux-saga"; import { movieReducer } from "../movie/state/reducer"; import movieRootSaga from "../movie/state/saga"; export const configureStore = () => { const rootReducer = combineReducers({ movieReducer }) const sagaMiddleware = createSagaMiddleware(); const store = createStore(rootReducer, applyMiddleware(sagaMiddleware)); registerSagas(sagaMiddleware); store.replaceReducer(rootReducer); return store; }; const registerSagas = (sagaMiddleware: SagaMiddleware<any>) => { sagaMiddleware.run(movieRootSaga); } <file_sep>import {connect} from 'react-redux'; import { bindActionCreators } from 'redux'; import Movies from '../pages/Movies'; import { fetchMovieListRequested } from '../state/actions/movie-list.action'; export const mapStateToProps = (state: any) => { return { movieList: state.movieReducer.movieList } } export const mapDispatchToProps = (dispatch: any, getState: any) => { return { dispatchers : bindActionCreators( {fetchMovieListRequested}, dispatch ) } } export default connect(mapStateToProps, mapDispatchToProps) (Movies);
7592c4ef15cd7ded2b495b3a2d805b301def7437
[ "TypeScript" ]
2
TypeScript
AravindK003/movieapp
9cd0be4ae7eba6c8d4c7a6a1c225b27f37a0f873
e1b26e5a49c6d7a7369c2f4125380a5d16d39ce0
refs/heads/master
<repo_name>gregoryanderson/Overlook<file_sep>/test/room-test.js import Room from '../src/Room' import data from '../data' import chai from 'chai'; import spies from 'chai-spies' const expect = chai.expect; describe("Room", function() { let room beforeEach(function (){ room = new Room(data, data, data,'2019/08/29') }); it.only('should return true', function() { expect(true).to.equal(true); }); it.only('should be an function', function(){ expect(Room).to.be.a('function') }) it.only('should be an instance of Room', function(){ expect(room).to.be.an.instanceOf(Room) }) });<file_sep>/src/roomService.js import domUpdates from "./domUpdates"; class RoomService { constructor(services, menu, guestId) { this.services = services.roomServices; this.menu = this.createMenu(); this.id = guestId; } createMenu(){ let fullMenu = []; return this.services.reduce((fullMenuObjs, order) => { if(!fullMenu.includes(order.food)){ fullMenu.push(order.food) fullMenuObjs.push({food: order.food, cost: order.totalCost}) } return fullMenuObjs }, []) } findCorrectItem(foodId){ return this.services.find(item => item.totalCost == foodId) } filterAllOrdersBySpecificGuest(guest){ let specificOrders = this.services.filter(service => { if (parseInt(guest.id) === service.userID){ return service } }) domUpdates.displayAllOrdersBySpecificGuest(specificOrders) } findTotalCostOfAllOrdersBySpecificGuest(guest){ let specificOrdersCost = this.services.filter(order => { if(parseInt(guest.id) === order.userID){ return order } }).reduce((totalCost, order) => { totalCost += order.totalCost return totalCost }, 0) domUpdates.displayTotalRoomServiceCostForSpecificUser(specificOrdersCost) } } export default RoomService;<file_sep>/src/domUpdates.js import $ from "jquery"; const domUpdates = { displayDate() {}, displayDate(date){ $('.header--date').text(date) }, displayRoomsAvailable(rooms) { $("#main__avail-rooms").text(`There are ${rooms} rooms available.`); }, displayTotalServiceChargesForToday(charges) { $("#main__charges-today").text( `$${charges} has been made in room service charges today.` ); }, displayRoomChargesRevenueForToday(charges) { $("#main__revenue-today").text( `$${charges} has been made in room booking revenue today.` ); }, displayPercentageOfRoomsBooked(percent) { $("#main__occupied-rate").text( `${percent}% of rooms have been booked today.` ); }, displayMostRoomsBookedInOneDay(totalRoomNumber, date) { $("#rooms__booking-high-date").text( `On ${date}, we booked ${totalRoomNumber} rooms, which was the highest booking date for our hotel. Great work!` ); }, displayLeastRoomsBookedInOneDay(totalRoomNumber, date) { $("#rooms__booking-low-date").text( `On ${date}, we booked ${totalRoomNumber} rooms, which was the lowest booking date for our hotel.` ); }, displayRoomServiceOrdersForToday(todaysOrders) { if (todaysOrders.length === 0) { $("#orders__tbody--today").text("There are no orders today"); } else { todaysOrders.forEach(order => { $("#orders__tbody--today").append(`<tr> <td>${order.food}</td><td>$${order.totalCost}</td> </tr>`); }); } }, displayRoomServiceOrdersForSpecificDate(specificDateOrders) { if (specificDateOrders.length === 0) { $("#orders__tbody--searched").text(""); $("#orders__tbody--searched").text("There are no orders for that date"); } else { $("#orders__tbody--searched").text(""); specificDateOrders.forEach(order => { $("#orders__tbody--searched").append(`<tr> <td>${order.food}</td><td>$${order.totalCost}</td><td>${ order.date }</td> </tr>`); }); } }, displayBookingsForToday(todaysBookings) { if (todaysBookings.length === 0) { $("#room__tbody--booked").text("There are no bookings today"); } else { todaysBookings.forEach(booking => { $("#room__tbody--booked").append(`<tr> <td>${booking.roomNumber}</td><td>${booking.date}</td> </tr>`); }); } }, displayRoomsAvailableForToday(todaysRoomsAvailable) { if (todaysRoomsAvailable.length === 0) { "#rooms__tbody--available".text("There are no rooms available today"); } else { todaysRoomsAvailable.forEach(room => { $("#rooms__tbody--available").append(`<tr> <td>${room.number}</td><td>${room.roomType}</td><td>${room.bedSize}</td><td>${ room.numBeds }</td><td>${room.bidet}</td><td>${room.costPerNight}</td> </tr>`); }); } }, displayAllGuests(allGuests) { if (allGuests.length === 0) { "#guests__tbody".text("Please search and select a guest"); } else { allGuests.forEach(guest => { $("#guests__tbody").append(`<tr> <td>${guest.name}</td><td>${guest.id}</td> </tr>`); }); } }, displaySearchedUsers(filteredSearchGuests) { if (filteredSearchGuests.length > 0){ $("#guests__tbody--searched").text(""); filteredSearchGuests.forEach(guest => { $("#guests__tbody--searched").append( `<tr><td class="guests__td--searched" data-id=${guest.id}>${ guest.name }</td><td>${guest.id}</td></tr>` ); }); } else { newGuestReminder() } }, displaySelectedGuest(selectedGuest) { $("#header--selected-guest").text(selectedGuest.name); $("#guests__div--specific").text(`${selectedGuest.name} has been selected. Their information will now be shown throughout`); $('#guests__tbody--searched').text(''); $('#guests__section--new-guest').text(''); $('#guests__div--searched').hide(); $('.specific').text(`${selectedGuest.name}`) }, newGuestReminder() { $("#guests__section--new-guest").html( '<p>Or, Please Enter a Name to Create a New Guest.</p><input type="text" id="guests__input--create"><button id="guests__button--create">Create</button>' ); $("#guests__tbody--searched").text(""); }, displayAllOrdersBySpecificGuest(orders) { $("#orders__tbody--guest").text('') if (orders.length === 0) { $("#orders__section--new-order").html( '<p>No Orders Found.</p><button id="orders__button--create">Create</button>' ); } else { orders.forEach(order => { $("#orders__tbody--guest").append(`<tr> <td>${order.food}</td><td>$${order.totalCost}</td><td>${order.date}</td> </tr>`); }); } }, displayAllBookingsBySpecificGuest(bookings) { $("#rooms__tbody--guest").text('') if (bookings.length === 0) { $("#rooms__section--new-order").html( '<p>No Bookings Found.</p><button id="orders__button--create">Create</button>' ); } else { bookings.forEach(booking => { $("#rooms__tbody--guest").append(`<tr> <td>${booking.date}</td><td>${booking.roomNumber}</td><td><button class"button unbook">UNBOOK</button> </tr>`); }); } }, displayTotalRoomServiceCostForSpecificUser(ordersCost){ if(ordersCost > 0){ $("#orders__section--total").text(`Total: ${ordersCost}`) } else { $("#orders__section--total").text(`Total: $0.00`) } }, displayTodaysBookingForSpecificGuest(guest, booking){ if(booking){ $('#rooms__section--create-booking').text('') $('#rooms__tbody--todays-booking').html(`<tr><td>${guest.name}</td><td>${booking.roomNumber}</td><td><button class"button unbook">UNBOOK</button></td></tr>`) } else { $("#rooms__section--create-booking").html(`<tr><td>${guest.name} has not made a reservation today. Click to create one</td><td><button id="rooms__button--reservation">Create Reservation</button></td></tr>`) } }, displayTodaysBookingForSpecificGuestBookingToday(guest, booking, menu){ $('#rooms__section--create-booking').text('') $('#rooms__tbody--todays-booking').html(`<tr><td>${guest.name}</td><td>${booking.number}</td><td>${booking.bedSize}</td><td>${booking.numBeds}</td><td>${booking.bidet}</td><td>${booking.costPerNight}</td><td><button data-id=${booking.costPerNight} id="unbook--newReservation" class=unbook button>UNBOOK</button></td></tr>`); $('#rooms__section--new-order').html(`<p>Would the guest enjoy room service?</p><button id="rooms__button--no-thanks">NO THANK YOU</button>`); menu.forEach(item => { $('#rooms__tbody--todays-orders').append(`<tr><td>${item.food}</td><td>${item.cost}</td><td><button class="button rooms__button--service" data-id=${item.cost}>Select</button></td></tr>`) }) }, displayRoomsAvailableForSpecificGuest(todaysRoomsAvailable) { console.log(todaysRoomsAvailable) if (todaysRoomsAvailable.length === 0) { $("#rooms__tbody--todays-booking").text("There are no rooms available today"); } else { todaysRoomsAvailable.forEach(room => { $("#rooms__tbody--todays-booking").append(`<tr> <td>${room.number}</td><td>${room.roomType}</td><td>${room.bedSize}</td><td>${ room.numBeds }</td><td>${room.bidet}</td><td>${room.costPerNight}</td><td><button class="button guests__button--select" data-id=${room.number}>Select Room</button></td> </tr>`); }); } }, displayAdditionalFoodService(foodItem){ $('#orders__table--new').show() $('#rooms__section--new-order').hide() $('#rooms__section--new-orders').hide() $('#orders__tbody--new').html(`<tr> <td>${foodItem.food}</td><td>${foodItem.totalCost}</td></tr>`) } }; // displayTotalBookingsCostForSpecificUser(bookingsCost){ // console.log(bookingsCost) // if(bookingsCost > 0){ // $("#rooms__section--total").text(`Total: ${bookingsCost}`) // } else { // $("#rooms__section--total").text(`Total: $0.00`) // } // } // // configureDate(date) { // }, // attachCreateButtonListener(){ // $("#guests__button--create").on("click", function() { // console.log("linked"); // let customerName = $("guests__input--create").val(); // console.log(customerName); // let newCustomer = new Customer(allData.customers, null, customerName); // console.log(newCustomer); // let newMain = new Main( // allData.customers, // allData.bookings, // allData.services, // allData.rooms, // dateToday(), // newCustomer // ); // console.log(newMain); // domUpdates.displaySelectedGuest(customerName); // }); // searchCustomers(users) { // $('#no-users').text('') // $('.tab__customers-output').text('') // users.forEach(user => { // $('.tab__customers-output').append(`<li class="customer__search-data" data-id="${user.id}">${user.name}</li>`) // }) // }, export default domUpdates; <file_sep>/test/guestRepo-test.js const expect = chai.expect; import GuestRepo from '../src/guestRepo' import chai from 'chai'; import spies from 'chai-spies'; import data from '../data'; import domUpdates from '../src/domUpdates'; chai.use(spies) describe("guestRepo", function() { let guestRepo beforeEach(function (){ guestRepo = new GuestRepo(data) }); it.only("should return true", function() { expect(true).to.equal(true); }); it.only('should filter users by search', function() { guestRepo.filterUsersBySearch('a') expect(domUpdates.displaySearchedUsers).to.be.called(1) }) it.only('should update to dom', function() { expect(domUpdates.displayAllGuests).to.be.called(3) }) })<file_sep>/src/customer.js import domUpdates from "./domUpdates"; class Customer { constructor (guests, id, name){ this.guests = guests.users; this.id = id || this.findIdOfGuest(); this.name = name || this.findNameOfGuest(); } findNameOfGuest(){ let selectedGuest = this.guests.find(guest => guest.id == this.id); return selectedGuest.name } findIdOfGuest(){ return this.guests.length + 1 } pushGuestIntoGuestArray(guest){ this.guests.push(guest) } // createNewCustomer(name) { // let newCustomer = new Customer(name, null, this.users, this.rooms, this.bookings, this.roomServices); // this.users.push(newbieCustomer); // this.currentCustomer = newbieCustomer; // this.hotelBenchmarks = new Hotel(this.users, this.rooms, this.bookings, this.roomServices, this.today); // return newbieCustomer; // } } export default Customer<file_sep>/test/customer-test.js const expect = chai.expect; import Customer from '../src/Customer' import chai from 'chai'; import data from '../data' describe("customer", function() { let customer beforeEach(function (){ customer = new Customer(data, 4, "<NAME>") }); it.only("should return true", function() { expect(true).to.equal(true); }) it.only("should return correct name", function() { expect(customer.findNameOfGuest()).to.equal("<NAME>"); }) it.only("should return correct id", function() { expect(customer.findIdOfGuest()).to.equal(21); }) })<file_sep>/src/bookingRepo.js import domUpdates from "./domUpdates"; class BookingRepo { constructor(bookings, rooms, customers, date) { this.bookings = bookings.bookings; this.rooms = rooms.rooms; this.customers = customers.users; this.date = date; this.info = this.updateToDom(); } filterBookingsByDate(specDate) { return this.bookings.filter(booking => booking.date === specDate); } sortBookingsByDate(specDate) { let todaysBookings = this.filterBookingsByDate(specDate); return todaysBookings.sort((a, b) => a.roomNumber - b.roomNumber); } mapBookingsForRoomNumber(bookings){ return bookings.map(booking => booking.roomNumber) } filterRoomsAvailableToday(specDate){ let todaysBookings = this.sortBookingsByDate(specDate) let bookedRoomNumbers = (this.mapBookingsForRoomNumber(todaysBookings)) return this.rooms.filter(room => { if(!bookedRoomNumbers.includes(room.number)){ return room } }) } pushBookingIntoBookingsArray(booking, bookedRoom){ this.bookings.push(booking) } findCorrectRoom(room){ return this.rooms.find(item => item.number == room); } updateToDom() { domUpdates.displayBookingsForToday(this.sortBookingsByDate(this.date)); domUpdates.displayRoomsAvailableForToday(this.filterRoomsAvailableToday(this.date)); } } export default BookingRepo; <file_sep>/test/bookingRepo-test.js const expect = chai.expect; import BookingRepo from '../src/BookingRepo' import chai from 'chai'; import spies from "chai-spies"; import data from '../data' import domUpdates from '../src/domUpdates'; chai.use(spies) describe("bookingRepo", function() { let bookingRepo beforeEach(function (){ bookingRepo = new BookingRepo(data, data, data,'2019/08/29') }) it.only("should return true", function() { expect(true).to.equal(true); }) it.only('should filter the rooms available today', function(){ expect(bookingRepo.filterRoomsAvailableToday('2019/08/29')).to.be.an('array') expect(bookingRepo.filterRoomsAvailableToday('2019/08/29')).to.have.length(49) }) it.only('should sort the rooms available today', function(){ expect(bookingRepo.sortBookingsByDate('2019/08/29')).to.be.an('array') expect(bookingRepo.sortBookingsByDate('2019/08/29')).to.have.length(1) }) it.only('should find a specific room', function(){ expect(bookingRepo.findCorrectRoom(5)).to.be.an('object') }) it.only('should update the dom', function(){ bookingRepo.updateToDom() expect(domUpdates.displayBookingsForToday).to.have.been.called(6) expect(domUpdates.displayRoomsAvailableForToday).to.have.been.called(6) }) })<file_sep>/test/roomService-test.js const expect = chai.expect; import RoomService from "../src/roomService"; import chai from "chai"; import spies from "chai-spies"; import data from "../data"; import domUpdates from '../src/domUpdates'; chai.use(spies) describe("roomService", function() { let roomService beforeEach(function (){ roomService = new RoomService(data, null, 5) }); it.only("should return true", function() { expect(true).to.equal(true); }) it.only('should create a menu', function(){ expect(roomService.createMenu()).to.be.an('array') expect(roomService.createMenu()).to.have.length(47) }) it.only('should find an item on the menu', function(){ expect(roomService.findCorrectItem(14.9)).to.be.an('object') }) it.only('should filter all orders by a specific guest', () => { roomService.filterAllOrdersBySpecificGuest({id: 4, name: "<NAME>"}) expect(domUpdates.displayAllOrdersBySpecificGuest).to.have.been.called(1) }) it.only('should find the total cost of all orders by a specific guest', () => { roomService.findTotalCostOfAllOrdersBySpecificGuest({id: 4, name: "<NAME>"}) expect(domUpdates.displayTotalRoomServiceCostForSpecificUser).to.have.been.called(1) }) }) <file_sep>/README.md # Overlook Hotel Management App Overlook is a mockup of a hotel management app. I used fetched JSON data and a number of Object, Array, String, and Number prototype methods to manipulate the data. This is my first solo project using webpack. I also used jQuery to add things to the DOM and SCSS for styling. ## How to Get it Working 1. Clone down this repo. 1. Save the dependencies by running `npm install` 1. Enjoy navigating the page. ## How to Run the Tests 1. There are a comprehensive set of mocha/chai tests for all classes, properties, and methods. 1. Run tests by typing npm test in your terminal in your cloned directory. ## Goals and Objectives 1. Implement ES6 classes that communicate to each other as needed. 1. Write modular, reusable code adhereing to SRP 1. Substitution Principle, Interface Segregation Principle, Dependency Inversion Principle, and Test Driven Development. 1. Implement a robust testing environment using Mocha and Chai. 1. Use object and array prototype methods to perform rich data manipulation. 1. Display information on the page while maintaining ability to test class properties and methods. 1. Create a dash that is easy to follow and displays information in a clear and consise way. ![My comp](images/overlook1.png) ![MY comp](images/overlook2.png) ![My comp](images/overlook3.png) ![My comp - GIF](images/OverlookGIF.gif) <file_sep>/src/roomServiceRepo.js import domUpdates from "./domUpdates"; class RoomServiceRepo { constructor(guests, services, date) { this.guests = guests.users this.services = services.roomServices; this.date = date; this.info = this.updateToDom(); } filterOrdersByDate(specDate) { return this.services.filter(order => order.date == specDate); } updateToDom() { domUpdates.displayRoomServiceOrdersForToday( this.filterOrdersByDate(this.date) ) } } export default RoomServiceRepo; <file_sep>/test/booking-test.js const expect = chai.expect; import Booking from '../src/Booking'; import chai from 'chai'; import spies from 'chai-spies'; import data from '../data'; import domUpdates from '../src/domUpdates'; chai.use(spies) describe("Booking", function() { let booking beforeEach(function (){ booking = new Booking(data, 5,'2019/08/29') }); it.only("should return true", function() { expect(true).to.equal(true); }); it.only("should filter all bookings by a specific guest", function() { booking.filterAllBookingsBySpecificGuest({id: 4,name: "<NAME>"}) expect(domUpdates.displayAllBookingsBySpecificGuest).to.have.been.called(1); }); it.only("should find todays booking for a specific guest", function() { booking.findTodaysBookingForSpecificGuest({id: 4,name: "<NAME>"}) expect(domUpdates.displayTodaysBookingForSpecificGuest).to.have.been.called(1); }); }); <file_sep>/src/room.js import domUpdates from "./domUpdates"; class Rooms { constructor (bookings, rooms, customers, date){ this.bookings = bookings.bookings this.rooms = rooms this.customers = customers this.date = date } } export default Rooms
7c05f648d2413883be2aeffbbdac5d5ea3a8f6f8
[ "JavaScript", "Markdown" ]
13
JavaScript
gregoryanderson/Overlook
9cece5bc4972c54c3d1b6263e19a610025cb4358
7dd689c113c02d8ebdf58150c95cfab02e384a7c
refs/heads/master
<file_sep> -- List the following details of each employee: employee number, last name, first name, gender, and salary. SELECT * FROM employees; SELECT * FROM salaries; SELECT employees.emp_no, employees.first_name, employees.last_name, employees.gender, salaries.salary FROM employees INNER JOIN salaries ON employees.emp_no = salaries.emp_no -- List employees who were hired in 1986. SELECT * FROM employees WHERE hire_date >= '12/31/1985' AND hire_date <= '01/01/1987' --List the manager of each department with the following information: department number, department name, the manager's employee number, last name, first name, and start and end employment dates. SELECT * FROM employees; SELECT * FROM department; SELECT * FROM dept_manager; SELECT dept_manager.dept_no, department.dept_name, dept_manager.from_date, dept_manager.to_date, employees.first_name, employees.last_name FROM employees INNER JOIN dept_manager ON employees.emp_no = dept_manager.emp_no INNER JOIN department ON department.dept_no = dept_manager.dept_no -- List the department of each employee with the following information: employee number, last name, first name, and department name. SELECT * FROM employees; SELECT * FROM department; SELECT * FROM dept_emp; SELECT employees.emp_no, employees.first_name, employees.last_name, department.dept_name FROM employees INNER JOIN dept_emp ON employees.emp_no = dept_emp.emp_no INNER JOIN department ON department.dept_name = dept_emp.dept_name -- List all employees whose first name is "Hercules" and last names begin with "B." SELECT * FROM employees WHERE first_name = 'Hercules' AND LEFT(last_name, 1) = 'B'; -- List all employees in the Sales department, including their employee number, last name, first name, and department name. SELECT * FROM employees; SELECT * FROM department; SELECT * FROM dept_emp; SELECT employees.emp_no, employees.last_name, employees.first_name, department.dept_name FROM employees LEFT JOIN dept_emp ON employees.emp_no = dept_emp.emp_no LEFT JOIN department ON dept_emp.dept_name = department.dept_no WHERE department.dept_name = 'Sales'; -- List all employees in the Sales and Development departments, including their employee number, last name, first name, and department name. SELECT * FROM employees; SELECT * FROM department; SELECT * FROM dept_emp; SELECT employees.emp_no, employees.last_name, employees.first_name, department.dept_name FROM employees LEFT JOIN dept_emp ON employees.emp_no = dept_emp.emp_no LEFT JOIN department ON dept_emp.dept_name = department.dept_no WHERE department.dept_name = 'Sales' OR department.dept_name = 'Development'; -- In descending order, list the frequency count of employee last names, i.e., how many employees share each last name. SELECT last_name, COUNT(*) FROM employees GROUP BY last_name ORDER BY count DESC
c33f7dcf070bd64c527e471db3daa587f4e29991
[ "SQL" ]
1
SQL
MissWibbon/sql-challenge
b08bcabf8e5088c91c6ba98308bc20ac3e248d3b
19e0dad092bbe79dd0f317db74f259594045a7e0
refs/heads/master
<file_sep>'use strict'; exports.isNullOrUndefined = function (value) { return value === null || value === undefined; }; // +7 (555) 666-77-88 function formatPhone(s) { let code = s.slice(0, 3); let g1 = s.slice(3, 6); let g2 = s.slice(6, 8); let g3 = s.slice(8, 10); return `+7 (${code}) ${g1}-${g2}-${g3}`; } exports.formatPhoneEntry = function (x) { let nameAndPhone = `${x.name}, ${formatPhone(x.phone)}`; return x.email ? nameAndPhone + `, ${x.email}` : nameAndPhone; }; <file_sep>'use strict'; const { Storage } = require('./storage'); const validationRules = require('./validation-rules'); const { PhonebookEntry } = require('./phonebook-entry'); const { formatPhoneEntry } = require('./utils'); const { handlersList } = require('./search-handlers'); /** * Сделано задание на звездочку * Реализован метод importFromCsv */ exports.isStar = true; /** * Телефонная книга */ let storage = new Storage(); /** * Добавление записи в телефонную книгу * @param {String} phone * @param {String} name * @param {String} email * @returns {Boolean} operation success */ exports.add = function (phone, name, email) { let isValid = [ ...validationRules.name, ...validationRules.phone, ...validationRules.email, ...validationRules.insertDataIntegrity] .every(rule => rule(phone, name, email, storage)); if (isValid) { storage.add(new PhonebookEntry(phone, name, email)); } return isValid; }; /** * Обновление записи в телефонной книге * @param {String} phone * @param {String} name * @param {String} email * @returns {Boolean} operation success */ exports.update = function (phone, name, email) { let isValid = [ ...validationRules.name, ...validationRules.phone, ...validationRules.email, ...validationRules.updateDataIntegrity] .every(rule => rule(phone, name, email, storage)); if (isValid) { let old = storage.find(x => x.phone === phone); storage.remove(old); storage.add(new PhonebookEntry(phone, name, email)); } return isValid; }; function find(query) { return handlersList .find(x => x.canHandle(query)) .handle(query, storage); } /** * Удаление записей по запросу из телефонной книги * @param {String} query * @returns {Number} amount of remove entries */ exports.findAndRemove = function (query) { let entries = find(query); entries.forEach(x => storage.remove(x)); return entries.length; }; /** * Поиск записей по запросу в телефонной книге * @param {String} query * @returns {Array} list of formatted strings */ exports.find = function (query) { let entries = find(query) .sort((x, y) => x.name.localeCompare(y.name)) .map(formatPhoneEntry); return Array.from(entries); }; /** * Импорт записей из csv-формата * @star * @param {String} csv * @returns {Number} – количество добавленных и обновленных записей */ exports.importFromCsv = function (csv) { // Парсим csv // Добавляем в телефонную книгу // Либо обновляем, если запись с таким телефоном уже существует return csv.split('\n') .map(string => [...string.split(';')]) .map(([name, phone, email]) => [phone, name, email === '' ? undefined : email]) .map(fields => exports.add(...fields) || exports.update(...fields)) .filter(result => result === true) .length; }; <file_sep>'use strict'; const data = Symbol('data'); class Storage { constructor() { this[data] = new Set(); } add(entry) { this[data].add(entry); } findAll(condition) { return Array.from(Array.from(this[data]) .filter(condition)); } find(condition) { return Array.from(this[data]) .find(condition); } contains(condition) { return this.findAll(condition).length > 0; } remove(entry) { this[data].delete(entry); } } exports.Storage = Storage; <file_sep>'use strict'; const { isNullOrUndefined } = require('./utils'); exports.phone = [ phone => typeof phone === 'string', phone => /\d+/.test(phone), phone => phone.length === 10 ]; exports.name = [ (phone, name) => typeof name === 'string', (phone, name) => name.length > 0 ]; exports.email = [ (phone, name, email) => isNullOrUndefined(email) || typeof email === 'string', (phone, name, email) => isNullOrUndefined(email) || email.length > 3, (phone, name, email) => isNullOrUndefined(email) || /^\S+@\S+$/.test(email) ]; exports.insertDataIntegrity = [ (phone, name, email, storage) => { return !storage.contains(x => Object.is(x.phone, phone)); } ]; exports.updateDataIntegrity = [ (phone, name, email, storage) => { return storage.contains(x => Object.is(x.phone, phone)); }, (phone, name, email, storage) => !storage.contains( existingEntry => existingEntry.phone === phone && !isNullOrUndefined(existingEntry.name) && isNullOrUndefined(name)) ];
60a4b78b485e6f741f322810ec8ba09a02ff9ba7
[ "JavaScript" ]
4
JavaScript
Edheltur/javascript-task-2
e0ec031b742fdc0b3a942f60f66d7d2a5e5b90d7
ca7447bb745baf09e27a00aa3e13b9b1064ca1fe
refs/heads/master
<repo_name>LZX842056112/SSMRBAC<file_sep>/atcrowdfunding-web/src/main/resources/sql/atcrowdfunding.sql /* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.7.24-log : Database - atcrowdfunding ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`atcrowdfunding` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */; USE `atcrowdfunding`; /*Table structure for table `t_permission` */ DROP TABLE IF EXISTS `t_permission`; CREATE TABLE `t_permission` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin DEFAULT NULL, `pid` int(11) DEFAULT NULL, `url` varchar(255) COLLATE utf8_bin DEFAULT NULL, `icon` varchar(255) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `t_permission` */ insert into `t_permission`(`id`,`name`,`pid`,`url`,`icon`) values (1,'系统菜单',0,NULL,'glyphicon glyphicon-equalizer'),(2,'控制面板',1,NULL,'glyphicon glyphicon-dashboard'),(3,'权限管理',1,NULL,'glyphicon glyphicon glyphicon-tasks'),(4,'用户维护',3,'/user/index','glyphicon glyphicon-user'),(5,'角色维护2',3,'/role/index','glyphicon glyphicon-king'),(6,'许可维护',3,'/permission/index','glyphicon glyphicon-lock'),(7,'增加用户',4,NULL,NULL),(8,'修改用户',4,NULL,NULL); /*Table structure for table `t_role` */ DROP TABLE IF EXISTS `t_role`; CREATE TABLE `t_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `t_role` */ insert into `t_role`(`id`,`name`) values (1,'PM-项目经理'),(2,'SE-软件工程师'),(3,'PG-程序员'),(4,'TL-组长'),(5,'GL-组长'),(6,'QC-品质控制'),(7,'SA-软件架构师'),(8,'CMO/CMS-配置管理'),(9,'SYSTEM-系统管理'); /*Table structure for table `t_role_permission` */ DROP TABLE IF EXISTS `t_role_permission`; CREATE TABLE `t_role_permission` ( `id` int(11) NOT NULL AUTO_INCREMENT, `roleid` int(11) DEFAULT NULL, `permissionid` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `t_role_permission` */ insert into `t_role_permission`(`id`,`roleid`,`permissionid`) values (1,3,1),(2,3,3),(3,3,5),(4,3,6); /*Table structure for table `t_user` */ DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_bin DEFAULT NULL, `loginacct` varchar(255) COLLATE utf8_bin DEFAULT NULL, `userpswd` varchar(255) COLLATE utf8_bin DEFAULT NULL, `email` varchar(255) COLLATE utf8_bin DEFAULT NULL, `createtime` char(19) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `t_user` */ insert into `t_user`(`id`,`username`,`loginacct`,`userpswd`,`email`,`createtime`) values (1,'zs','zs','zs','zs.com','2020-10-10 17:31:04'),(2,'ls','ls','123456','ls.com','2020-10-10 17:31:22'),(3,'ww','ww','123456','ww.com','2020-10-10 17:31:39'),(4,'zl','zl','123456','zl.coma','2020-10-10 17:32:44'); /*Table structure for table `t_user_role` */ DROP TABLE IF EXISTS `t_user_role`; CREATE TABLE `t_user_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userid` int(11) DEFAULT NULL, `roleid` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `t_user_role` */ insert into `t_user_role`(`id`,`userid`,`roleid`) values (1,1,3); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
c0abc0625b42bb7a3e952f3ac57735c40ef6d614
[ "SQL" ]
1
SQL
LZX842056112/SSMRBAC
e661378ff83eecdf8ad90238cd01cf536e7f4e78
15ab8bc4b25378eb4f9962632fed58185923d1c8
refs/heads/main
<repo_name>meikyoshisui/MessyF2FCalculator<file_sep>/README.md # MessyF2FCalculator F2F Outcome Calculator for Corvus Belli's Infinity. Provide 4 arguments in the order: Player 1 Burst Value Player 1 Success Value Player 2 Burst Value Player 2 Success Value <file_sep>/main.py # test comment import random import sys p1burst = int(sys.argv[1]) p1successvalue = int(sys.argv[2]) p2burst = int(sys.argv[3]) p2successvalue = int(sys.argv[4]) p1successCount = 0 p2successCount = 0 neitherplayersuccesscount = 0 print("P1 rolls B" + str(p1burst) + " on " + str(p1successvalue)) print("P2 rolls B" + str(p1burst) + " on " + str(p1successvalue)) for i in range(0, 100000): p1rolls = [] p2rolls = [] p1successes = [] p2successes = [] p1crit = False p2crit = False # Roll Dice for j in range(0, p1burst): p1rolls.append(random.randint(1, 20)) for j in range(0, p2burst): p2rolls.append(random.randint(1, 20)) # Determine which dice are successes, and if there are crits for j in range(0, len(p1rolls)): if p1rolls[j] <= p1successvalue: p1successes.append(p1rolls[j]) if p1rolls[j] == p1successvalue: p1crit = True for j in range(0, len(p2rolls)): if p2rolls[j] <= p2successvalue: p2successes.append(p2rolls[j]) if p2rolls[j] == p2successvalue: p2crit = True print("Trial #" + str(i)) print("P1 rolls " + str(p1rolls) + ", succeeding on " + str(p1successes)) print("P2 rolls " + str(p2rolls) + ", succeeding on " + str(p2successes)) # Determine which player won f2f # Crits if p1crit and p2crit: neitherplayersuccesscount += 1 print("Both players crit.") continue if p1crit and not p2crit: p1successCount += 1 print("P1 crit.") continue if p2crit and not p1crit: p2successCount += 1 print("P2 crit.") continue # one or both players have 0 successful rolls if p1successes == [] and p2successes == []: neitherplayersuccesscount += 1 print("Both players miss.") continue if p1successes == [] and not p2successes == []: p2successCount += 1 print("P2 wins, P1 has no successes.") continue if p2successes == [] and not p1successes == []: p1successCount += 1 print("P1 wins, P2 has no successes.") continue # Equal max success bounces if max(p1successes) == max(p2successes): neitherplayersuccesscount += 1 print("The highest success of both players is equal. Neither player wins.") continue # Player with highest success wins if max(p1successes) > max(p2successes): p1successCount += 1 print("P1's highest success is higher than P2's highest success. P1 wins") continue if max(p2successes) > max(p1successes): p2successCount += 1 print("P2's highest success is higher than P1's highest success. P2 wins") continue print("Player one wins " + str(p1successCount)) print("Player two wins " + str(p2successCount)) print("Neither player wins " + str(neitherplayersuccesscount))
1a4e8bbc161ecf28bc03d21d691b5bbf6d3a86d6
[ "Markdown", "Python" ]
2
Markdown
meikyoshisui/MessyF2FCalculator
8bea90129bb444abfe09b562f7b294f19dc92d56
0ca27e305e9355cd9d9ea5e5fff664b7e06b123d
refs/heads/master
<file_sep>class Rover { var maps: Maps? private var x: Int private var y: Int private var face: Direction init(x: Int, y: Int, face: Direction) { self.x = x self.y = y self.face = face } func operate(command: Command) { switch command { case .turnLeft: operateTurnLeftCommand() case .turnRight: operateTurnRightCommand() case .move: operateMoveCommand() } } func operateMoveCommand() { switch face { case .north: if y + 1 <= maps?.maxY ?? Int.max { y += 1 } case .east: if x + 1 <= maps?.maxX ?? Int.max { x += 1 } case .south: if y - 1 >= 0 { y -= 1 } case .west: if x - 1 >= 0 { x -= 1 } } } func operateTurnLeftCommand() { face = face.nextCounterclockwise } func operateTurnRightCommand() { face = face.nextClockwise } var position: Position { return Position(x: x, y: y, face: face) } enum Command: String { case turnLeft = "L" case turnRight = "R" case move = "M" } } <file_sep>struct Position: Equatable { let x: Int let y: Int let face: Direction } <file_sep>import XCTest @testable import swift_marsrovertechchallenge class RoverTests: XCTestCase { let dummyX = 1 let dummyY = 2 func testWhenTurnLeftDirectionShouldBeNextCounterclockwise() { let rover = Rover(x: dummyX, y: dummyY, face: .north) rover.operate(command: .turnLeft) let expectedFaceWest = Position(x: dummyX, y: dummyY, face: .west) XCTAssertEqual(expectedFaceWest, rover.position) rover.operate(command: .turnLeft) let expectedFaceSouth = Position(x: dummyX, y: dummyY, face: .south) XCTAssertEqual(expectedFaceSouth, rover.position) rover.operate(command: .turnLeft) let expectedFaceEast = Position(x: dummyX, y: dummyY, face: .east) XCTAssertEqual(expectedFaceEast, rover.position) rover.operate(command: .turnLeft) let expectedFaceNorth = Position(x: dummyX, y: dummyY, face: .north) XCTAssertEqual(expectedFaceNorth, rover.position) } func testWhenTurnRightDirectionShouldBeNextAfterClockwise() { let rover = Rover(x: dummyX, y: dummyY, face: .north) rover.operate(command: .turnRight) let expectedFaceWest = Position(x: dummyX, y: dummyY, face: .east) XCTAssertEqual(expectedFaceWest, rover.position) rover.operate(command: .turnRight) let expectedFaceSouth = Position(x: dummyX, y: dummyY, face: .south) XCTAssertEqual(expectedFaceSouth, rover.position) rover.operate(command: .turnRight) let expectedFaceEast = Position(x: dummyX, y: dummyY, face: .west) XCTAssertEqual(expectedFaceEast, rover.position) rover.operate(command: .turnRight) let expectedFaceNorth = Position(x: dummyX, y: dummyY, face: .north) XCTAssertEqual(expectedFaceNorth, rover.position) } func testWhenFaceNorthAndMoveShouldBeInNextPosition() { let rover = Rover(x: 1, y: 2, face: .north) rover.operate(command: .move) let expectedPosition = Position(x: 1, y: 3, face: .north) XCTAssertEqual(expectedPosition, rover.position) } func testWhenMoveShouldBeInTheSamePositionIfReachMaxY() { let rover = Rover(x: 1, y: 2, face: .north) let maps = Maps(maxX: 1, maxY: 2) rover.maps = maps rover.operate(command: .move) let expectedPosition = Position(x: 1, y: 2, face: .north) XCTAssertEqual(expectedPosition, rover.position) } func testWhenFaceEastAndMoveShouldBeInNextPosition() { let rover = Rover(x: 1, y: 2, face: .east) rover.operate(command: .move) let expectedPosition = Position(x: 2, y: 2, face: .east) XCTAssertEqual(expectedPosition, rover.position) } func testWhenMoveShouldBeInTheSamePositionIfReachMaxX() { let rover = Rover(x: 1, y: 2, face: .east) let maps = Maps(maxX: 1, maxY: 2) rover.maps = maps rover.operate(command: .move) let expectedPosition = Position(x: 1, y: 2, face: .east) XCTAssertEqual(expectedPosition, rover.position) } func testWhenFaceSouthAndMoveShouldBeInNextPosition() { let rover = Rover(x: 1, y: 2, face: .south) rover.operate(command: .move) let expectedPosition = Position(x: 1, y: 1, face: .south) XCTAssertEqual(expectedPosition, rover.position) } func testWhenMoveShouldBeInTheSamePositionIfReachMinY() { let rover = Rover(x: 1, y: 0, face: .south) let maps = Maps(maxX: dummyX, maxY: dummyY) rover.maps = maps rover.operate(command: .move) let expectedPosition = Position(x: 1, y: 0, face: .south) XCTAssertEqual(expectedPosition, rover.position) } func testWhenFaceWestAndMoveShouldBeInNextPosition() { let rover = Rover(x: 1, y: 2, face: .west) rover.operate(command: .move) let expectedPosition = Position(x: 0, y: 2, face: .west) XCTAssertEqual(expectedPosition, rover.position) } func testWhenMoveShouldBeInTheSamePositionIfReachMinX() { let rover = Rover(x: 0, y: 2, face: .west) let maps = Maps(maxX: dummyX, maxY: dummyY) rover.maps = maps rover.operate(command: .move) let expectedPosition = Position(x: 0, y: 2, face: .west) XCTAssertEqual(expectedPosition, rover.position) } func testRawValueOfRoverCommandShouldBeIntegrity() { XCTAssertEqual("L", Rover.Command.turnLeft.rawValue) XCTAssertEqual("R", Rover.Command.turnRight.rawValue) XCTAssertEqual("M", Rover.Command.move.rawValue) } } <file_sep>struct Maps { let maxX: Int let maxY: Int } <file_sep>import XCTest @testable import swift_marsrovertechchallenge class DirectionTests: XCTestCase { func testDirectionRawValue() { XCTAssertEqual("N", Direction.north.rawValue) XCTAssertEqual("W", Direction.west.rawValue) XCTAssertEqual("S", Direction.south.rawValue) XCTAssertEqual("E", Direction.east.rawValue) } } <file_sep>https://code.google.com/archive/p/marsrovertechchallenge/ <file_sep>enum Direction: String { case north = "N" case west = "W" case south = "S" case east = "E" var nextClockwise: Direction { switch self { case .north: return .east case .east: return .south case .south: return .west case .west: return .north } } var nextCounterclockwise: Direction { switch self { case .north: return .west case .west: return .south case .south: return .east case .east: return .north } } }
ef14b298dc1adde70048b1b26a35edffdbfc54c9
[ "Swift", "Markdown" ]
7
Swift
PH9/swift-marsrovertechchallenge
759d4530d60a06df6305326e1e33214dcde39cf2
c9859e40de134a9fdf5222f79bba6a5d12839910
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace EsportEvent.Domain { public class Match { public Match() { Teams = new List<Team>(); } public int Id { get; set; } public Game Game { get; set; } public string GameName { get; set; } public int TournamentId { get; set; } public DateTime GameDay { get; set; } public List<PlayerStats> PlayerStats { get; set; } public List<Team> Teams { get; set; } } }<file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class SomeMinorChanges : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1Name_Team1GameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2Name_Team2GameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentName_TournamentGameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerName_WinnerGameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamName_TeamGameName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_Team_Tournament_TournamentName_TournamentGameName", table: "Team"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_TournamentName_TournamentGameName", table: "Team"); migrationBuilder.DropIndex( name: "IX_PlayerStats_MatchId", table: "PlayerStats"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamName_TeamGameName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_Team1Name_Team1GameName", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_Team2Name_Team2GameName", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentName_TournamentGameName", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_WinnerName_WinnerGameName", table: "Matches"); migrationBuilder.DropColumn( name: "GameName", table: "Tournament"); migrationBuilder.DropColumn( name: "GameName", table: "Team"); migrationBuilder.DropColumn( name: "TournamentGameName", table: "Team"); migrationBuilder.DropColumn( name: "TeamGameName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "Team1GameName", table: "Matches"); migrationBuilder.DropColumn( name: "Team2GameName", table: "Matches"); migrationBuilder.DropColumn( name: "TournamentGameName", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerGameName", table: "Matches"); migrationBuilder.AddColumn<int>( name: "GameId", table: "Tournament", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "GameId", table: "Team", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TournamentGameId", table: "Team", nullable: true); migrationBuilder.AddColumn<int>( name: "TeamGameId", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<int>( name: "Team1GameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "Team1Id", table: "Matches", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "Team2GameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "Team2Id", table: "Matches", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TournamentGameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "WinnerGameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "WinnerId", table: "Matches", nullable: false, defaultValue: 0); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", columns: new[] { "GameId", "Name" }); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", columns: new[] { "GameId", "Name" }); migrationBuilder.CreateIndex( name: "IX_Tournament_Name", table: "Tournament", column: "Name"); migrationBuilder.CreateIndex( name: "IX_Team_Name", table: "Team", column: "Name"); migrationBuilder.CreateIndex( name: "IX_Team_TournamentGameId_TournamentName", table: "Team", columns: new[] { "TournamentGameId", "TournamentName" }); migrationBuilder.CreateIndex( name: "IX_PlayerStats_PlayerGameId", table: "PlayerStats", column: "PlayerGameId"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamGameId_TeamName", table: "PlayerGames", columns: new[] { "TeamGameId", "TeamName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team1GameId_Team1Name", table: "Matches", columns: new[] { "Team1GameId", "Team1Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team2GameId_Team2Name", table: "Matches", columns: new[] { "Team2GameId", "Team2Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentGameId_TournamentName", table: "Matches", columns: new[] { "TournamentGameId", "TournamentName" }); migrationBuilder.CreateIndex( name: "IX_Matches_WinnerGameId_WinnerName", table: "Matches", columns: new[] { "WinnerGameId", "WinnerName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1GameId_Team1Name", table: "Matches", columns: new[] { "Team1GameId", "Team1Name" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2GameId_Team2Name", table: "Matches", columns: new[] { "Team2GameId", "Team2Name" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentGameId_TournamentName", table: "Matches", columns: new[] { "TournamentGameId", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerGameId_WinnerName", table: "Matches", columns: new[] { "WinnerGameId", "WinnerName" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamGameId_TeamName", table: "PlayerGames", columns: new[] { "TeamGameId", "TeamName" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerStats_PlayerGames_PlayerGameId", table: "PlayerStats", column: "PlayerGameId", principalTable: "PlayerGames", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Team_Games_Name", table: "Team", column: "Name", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Team_Tournament_TournamentGameId_TournamentName", table: "Team", columns: new[] { "TournamentGameId", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Tournament_Games_Name", table: "Tournament", column: "Name", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1GameId_Team1Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2GameId_Team2Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentGameId_TournamentName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerGameId_WinnerName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamGameId_TeamName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_PlayerStats_PlayerGames_PlayerGameId", table: "PlayerStats"); migrationBuilder.DropForeignKey( name: "FK_Team_Games_Name", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Team_Tournament_TournamentGameId_TournamentName", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Tournament_Games_Name", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropIndex( name: "IX_Tournament_Name", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_Name", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_TournamentGameId_TournamentName", table: "Team"); migrationBuilder.DropIndex( name: "IX_PlayerStats_PlayerGameId", table: "PlayerStats"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamGameId_TeamName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_Team1GameId_Team1Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_Team2GameId_Team2Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentGameId_TournamentName", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_WinnerGameId_WinnerName", table: "Matches"); migrationBuilder.DropColumn( name: "GameId", table: "Tournament"); migrationBuilder.DropColumn( name: "GameId", table: "Team"); migrationBuilder.DropColumn( name: "TournamentGameId", table: "Team"); migrationBuilder.DropColumn( name: "TeamGameId", table: "PlayerGames"); migrationBuilder.DropColumn( name: "Team1GameId", table: "Matches"); migrationBuilder.DropColumn( name: "Team1Id", table: "Matches"); migrationBuilder.DropColumn( name: "Team2GameId", table: "Matches"); migrationBuilder.DropColumn( name: "Team2Id", table: "Matches"); migrationBuilder.DropColumn( name: "TournamentGameId", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerGameId", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerId", table: "Matches"); migrationBuilder.AddColumn<string>( name: "GameName", table: "Tournament", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "GameName", table: "Team", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "TournamentGameName", table: "Team", nullable: true); migrationBuilder.AddColumn<string>( name: "TeamGameName", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "Team1GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "Team2GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "TournamentGameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "WinnerGameName", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", columns: new[] { "Name", "GameName" }); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", columns: new[] { "Name", "GameName" }); migrationBuilder.CreateIndex( name: "IX_Team_TournamentName_TournamentGameName", table: "Team", columns: new[] { "TournamentName", "TournamentGameName" }); migrationBuilder.CreateIndex( name: "IX_PlayerStats_MatchId", table: "PlayerStats", column: "MatchId", unique: true); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamName_TeamGameName", table: "PlayerGames", columns: new[] { "TeamName", "TeamGameName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team1Name_Team1GameName", table: "Matches", columns: new[] { "Team1Name", "Team1GameName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team2Name_Team2GameName", table: "Matches", columns: new[] { "Team2Name", "Team2GameName" }); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentName_TournamentGameName", table: "Matches", columns: new[] { "TournamentName", "TournamentGameName" }); migrationBuilder.CreateIndex( name: "IX_Matches_WinnerName_WinnerGameName", table: "Matches", columns: new[] { "WinnerName", "WinnerGameName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1Name_Team1GameName", table: "Matches", columns: new[] { "Team1Name", "Team1GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2Name_Team2GameName", table: "Matches", columns: new[] { "Team2Name", "Team2GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentName_TournamentGameName", table: "Matches", columns: new[] { "TournamentName", "TournamentGameName" }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerName_WinnerGameName", table: "Matches", columns: new[] { "WinnerName", "WinnerGameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamName_TeamGameName", table: "PlayerGames", columns: new[] { "TeamName", "TeamGameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Tournament_TournamentName_TournamentGameName", table: "Team", columns: new[] { "TournamentName", "TournamentGameName" }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Domain { public class PlayerGame { public PlayerGame() { } public int Id { get; set; } public string PlayerUserName { get; set; } public Player Player { get; set; } public string GameName { get; set; } public Game Game { get; set; } public int TeamId { get; set; } public Team Team {get; set;} public string PlayerNickName { get; set; } public string PlayerRole { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class minorChangses : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "PlayerUserName", table: "PlayerGames"); migrationBuilder.AlterColumn<string>( name: "PlayerId", table: "PlayerGames", nullable: true, oldClrType: typeof(int)); migrationBuilder.AddColumn<string>( name: "GameName", table: "Matches", nullable: true); migrationBuilder.CreateIndex( name: "IX_PlayerGames_PlayerId", table: "PlayerGames", column: "PlayerId"); migrationBuilder.CreateIndex( name: "IX_Matches_GameName", table: "Matches", column: "GameName"); migrationBuilder.AddForeignKey( name: "FK_Matches_Games_GameName", table: "Matches", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames", column: "PlayerId", principalTable: "Players", principalColumn: "UserName", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Games_GameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_PlayerId", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_GameName", table: "Matches"); migrationBuilder.DropColumn( name: "GameName", table: "Matches"); migrationBuilder.AlterColumn<int>( name: "PlayerId", table: "PlayerGames", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddColumn<string>( name: "PlayerUserName", table: "PlayerGames", nullable: true); migrationBuilder.CreateIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames", column: "PlayerUserName"); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames", column: "PlayerUserName", principalTable: "Players", principalColumn: "UserName", onDelete: ReferentialAction.Restrict); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Domain { public class Player { public Player() { Games = new List<PlayerGame>(); } public string UserName { get; set; } public string Name { get; set; } public List<PlayerGame> Games { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Domain { public class Game { public Game() { } public string Name { get; set; } public string Publisher { get; set; } public DateTime ReleaseDate { get; set; } public int Tournaments { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class AddedTeamMatchJoinTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "TeamMatch", columns: table => new { MatchId = table.Column<int>(nullable: false), TeamId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_TeamMatch", x => new { x.MatchId, x.TeamId }); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "TeamMatch"); } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using EsportEvent.Domain; using Microsoft.Extensions.Logging.Console; using System; namespace EsportEvent.Data { public class EsportEventContext : DbContext { public DbSet<Player> Players { get; set; } public DbSet<Game> Games { get; set; } public DbSet<PlayerGame> PlayerGames { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<PlayerStats> PlayerStats { get; set; } public DbSet<Team> Team { get; set; } public DbSet<Tournament> Tournament { get; set; } public DbSet<TeamMatch> TeamMatch { get; set; } public static readonly LoggerFactory EsportloggerFactory = new LoggerFactory(new[]{ new ConsoleLoggerProvider((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information, true) }); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Team>().HasKey(m => new {m.Id }); modelBuilder.Entity<Game>().HasKey(m => new { m.Name }); modelBuilder.Entity<Player>().HasKey(p => new { p.UserName }); modelBuilder.Entity<TeamMatch>().HasKey(tm => new {tm.MatchId, tm.TeamId }); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Egentligen inte önskligt att ha connectionstring hårdkodad på detta sätt. optionsBuilder .EnableSensitiveDataLogging() //.UseLoggerFactory(EsportloggerFactory) .UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = EsportTournament; Trusted_connection = True;"); } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class AddedDbset : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Match_Team_Team1Name_Team1GameName", table: "Match"); migrationBuilder.DropForeignKey( name: "FK_Match_Team_Team2Name_Team2GameName", table: "Match"); migrationBuilder.DropForeignKey( name: "FK_Match_Tournament_TournamentName_TournamentGameName", table: "Match"); migrationBuilder.DropForeignKey( name: "FK_Match_Team_WinnerName_WinnerGameName", table: "Match"); migrationBuilder.DropForeignKey( name: "FK_PlayerStats_Match_MatchId", table: "PlayerStats"); migrationBuilder.DropPrimaryKey( name: "PK_Match", table: "Match"); migrationBuilder.RenameTable( name: "Match", newName: "Matches"); migrationBuilder.RenameIndex( name: "IX_Match_WinnerName_WinnerGameName", table: "Matches", newName: "IX_Matches_WinnerName_WinnerGameName"); migrationBuilder.RenameIndex( name: "IX_Match_TournamentName_TournamentGameName", table: "Matches", newName: "IX_Matches_TournamentName_TournamentGameName"); migrationBuilder.RenameIndex( name: "IX_Match_Team2Name_Team2GameName", table: "Matches", newName: "IX_Matches_Team2Name_Team2GameName"); migrationBuilder.RenameIndex( name: "IX_Match_Team1Name_Team1GameName", table: "Matches", newName: "IX_Matches_Team1Name_Team1GameName"); migrationBuilder.AddPrimaryKey( name: "PK_Matches", table: "Matches", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1Name_Team1GameName", table: "Matches", columns: new[] { "Team1Name", "Team1GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2Name_Team2GameName", table: "Matches", columns: new[] { "Team2Name", "Team2GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentName_TournamentGameName", table: "Matches", columns: new[] { "TournamentName", "TournamentGameName" }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerName_WinnerGameName", table: "Matches", columns: new[] { "WinnerName", "WinnerGameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerStats_Matches_MatchId", table: "PlayerStats", column: "MatchId", principalTable: "Matches", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1Name_Team1GameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2Name_Team2GameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentName_TournamentGameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerName_WinnerGameName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerStats_Matches_MatchId", table: "PlayerStats"); migrationBuilder.DropPrimaryKey( name: "PK_Matches", table: "Matches"); migrationBuilder.RenameTable( name: "Matches", newName: "Match"); migrationBuilder.RenameIndex( name: "IX_Matches_WinnerName_WinnerGameName", table: "Match", newName: "IX_Match_WinnerName_WinnerGameName"); migrationBuilder.RenameIndex( name: "IX_Matches_TournamentName_TournamentGameName", table: "Match", newName: "IX_Match_TournamentName_TournamentGameName"); migrationBuilder.RenameIndex( name: "IX_Matches_Team2Name_Team2GameName", table: "Match", newName: "IX_Match_Team2Name_Team2GameName"); migrationBuilder.RenameIndex( name: "IX_Matches_Team1Name_Team1GameName", table: "Match", newName: "IX_Match_Team1Name_Team1GameName"); migrationBuilder.AddPrimaryKey( name: "PK_Match", table: "Match", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_Match_Team_Team1Name_Team1GameName", table: "Match", columns: new[] { "Team1Name", "Team1GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Match_Team_Team2Name_Team2GameName", table: "Match", columns: new[] { "Team2Name", "Team2GameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Match_Tournament_TournamentName_TournamentGameName", table: "Match", columns: new[] { "TournamentName", "TournamentGameName" }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Match_Team_WinnerName_WinnerGameName", table: "Match", columns: new[] { "WinnerName", "WinnerGameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerStats_Match_MatchId", table: "PlayerStats", column: "MatchId", principalTable: "Match", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EsportEvent.Data; using EsportEvent.Domain; namespace Testdb { class Program { static void Main(string[] args) { var gameRepo = new GameRepo(); var matchRepo = new MatchRepo(); var playerGameRepo = new PlayerGameRepo(); var playerRepo = new PlayerRepo(); var playerStats = new PlayerStatsRepo(); var teamRepo = new TeamRepo(); var teamMatchReop = new TeamMatchRepo(); var TournamentRepo = new TournamentRepo(); } } } <file_sep>using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class initfullTableDiagram : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Games_Players_PlayerId", table: "Games"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames"); migrationBuilder.DropPrimaryKey( name: "PK_Players", table: "Players"); migrationBuilder.DropPrimaryKey( name: "PK_PlayerGames", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Games_PlayerId", table: "Games"); migrationBuilder.DropColumn( name: "Id", table: "Players"); migrationBuilder.DropColumn( name: "PlayerId", table: "Games"); migrationBuilder.AddColumn<string>( name: "UserName", table: "Players", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<int>( name: "Id", table: "PlayerGames", nullable: false, defaultValue: 0) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); migrationBuilder.AddColumn<string>( name: "PlayerUserName", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "TeamGameName", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "TeamName", table: "PlayerGames", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Players", table: "Players", column: "UserName"); migrationBuilder.AddPrimaryKey( name: "PK_PlayerGames", table: "PlayerGames", column: "Id"); migrationBuilder.CreateTable( name: "Tournament", columns: table => new { Name = table.Column<string>(nullable: false), GameName = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tournament", x => new { x.Name, x.GameName }); }); migrationBuilder.CreateTable( name: "Team", columns: table => new { Name = table.Column<string>(nullable: false), GameName = table.Column<string>(nullable: false), TournamentGameName = table.Column<string>(nullable: true), TournamentName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Team", x => new { x.Name, x.GameName }); table.ForeignKey( name: "FK_Team_Tournament_TournamentName_TournamentGameName", columns: x => new { x.TournamentName, x.TournamentGameName }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Match", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), GamePlayed = table.Column<DateTime>(nullable: false), Team1GameName = table.Column<string>(nullable: true), Team1Name = table.Column<string>(nullable: true), Team2GameName = table.Column<string>(nullable: true), Team2Name = table.Column<string>(nullable: true), TournamentGameName = table.Column<string>(nullable: true), TournamentName = table.Column<string>(nullable: true), WinnerGameName = table.Column<string>(nullable: true), WinnerName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Match", x => x.Id); table.ForeignKey( name: "FK_Match_Team_Team1Name_Team1GameName", columns: x => new { x.Team1Name, x.Team1GameName }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Match_Team_Team2Name_Team2GameName", columns: x => new { x.Team2Name, x.Team2GameName }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Match_Tournament_TournamentName_TournamentGameName", columns: x => new { x.TournamentName, x.TournamentGameName }, principalTable: "Tournament", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Match_Team_WinnerName_WinnerGameName", columns: x => new { x.WinnerName, x.WinnerGameName }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PlayerStats", columns: table => new { MatchId = table.Column<int>(nullable: false), PlayerGameId = table.Column<int>(nullable: false), Assists = table.Column<int>(nullable: false), Deaths = table.Column<int>(nullable: false), Kills = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PlayerStats", x => new { x.MatchId, x.PlayerGameId }); table.ForeignKey( name: "FK_PlayerStats_Match_MatchId", column: x => x.MatchId, principalTable: "Match", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames", column: "PlayerUserName"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamName_TeamGameName", table: "PlayerGames", columns: new[] { "TeamName", "TeamGameName" }); migrationBuilder.CreateIndex( name: "IX_Match_Team1Name_Team1GameName", table: "Match", columns: new[] { "Team1Name", "Team1GameName" }); migrationBuilder.CreateIndex( name: "IX_Match_Team2Name_Team2GameName", table: "Match", columns: new[] { "Team2Name", "Team2GameName" }); migrationBuilder.CreateIndex( name: "IX_Match_TournamentName_TournamentGameName", table: "Match", columns: new[] { "TournamentName", "TournamentGameName" }); migrationBuilder.CreateIndex( name: "IX_Match_WinnerName_WinnerGameName", table: "Match", columns: new[] { "WinnerName", "WinnerGameName" }); migrationBuilder.CreateIndex( name: "IX_PlayerStats_MatchId", table: "PlayerStats", column: "MatchId", unique: true); migrationBuilder.CreateIndex( name: "IX_Team_TournamentName_TournamentGameName", table: "Team", columns: new[] { "TournamentName", "TournamentGameName" }); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames", column: "PlayerUserName", principalTable: "Players", principalColumn: "UserName", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamName_TeamGameName", table: "PlayerGames", columns: new[] { "TeamName", "TeamGameName" }, principalTable: "Team", principalColumns: new[] { "Name", "GameName" }, onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamName_TeamGameName", table: "PlayerGames"); migrationBuilder.DropTable( name: "PlayerStats"); migrationBuilder.DropTable( name: "Match"); migrationBuilder.DropTable( name: "Team"); migrationBuilder.DropTable( name: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Players", table: "Players"); migrationBuilder.DropPrimaryKey( name: "PK_PlayerGames", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamName_TeamGameName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "UserName", table: "Players"); migrationBuilder.DropColumn( name: "Id", table: "PlayerGames"); migrationBuilder.DropColumn( name: "PlayerUserName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "TeamGameName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "TeamName", table: "PlayerGames"); migrationBuilder.AddColumn<int>( name: "Id", table: "Players", nullable: false, defaultValue: 0) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); migrationBuilder.AddColumn<int>( name: "PlayerId", table: "Games", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Players", table: "Players", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_PlayerGames", table: "PlayerGames", columns: new[] { "PlayerId", "GameId" }); migrationBuilder.CreateIndex( name: "IX_Games_PlayerId", table: "Games", column: "PlayerId"); migrationBuilder.AddForeignKey( name: "FK_Games_Players_PlayerId", table: "Games", column: "PlayerId", principalTable: "Players", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames", column: "PlayerId", principalTable: "Players", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using EsportEvent.Domain; using Microsoft.EntityFrameworkCore; namespace EsportEvent.Data { public class PlayerGameRepo : GenericEsportRepo<PlayerGame, EsportEventContext> { public override void Add(PlayerGame playerGame) { PlayerRepo pr = new PlayerRepo(); TeamRepo tr = new TeamRepo(); GameRepo gr = new GameRepo(); if (null != pr.FindBy(p => p.UserName == playerGame.Player.UserName).FirstOrDefault()) { pr.Add(playerGame.Player); pr.Save(); } if (null != tr.FindBy(p => p.Id == playerGame.Team.Id).FirstOrDefault()) { tr.Add(playerGame.Team); tr.Save(); } if (null != gr.FindBy(g => g.Name == playerGame.GameName).FirstOrDefault()) { gr.Add(playerGame.Game); gr.Save(); } Context.PlayerGames.Add(new PlayerGame { GameName=playerGame.GameName, PlayerNickName=playerGame.PlayerNickName, PlayerRole=playerGame.PlayerRole, PlayerUserName=playerGame.PlayerUserName, Player=playerGame.Player, }); Save(); } //Jag har valt att göra denna async då jag tror att admin till mintt program kommer att söka efter spelare många //Gånger undet dens arbetsdag. Därför vill jag att detta ska kunna ske snabbt och att programmet kan jobba med annat //under tiden som den hämta detta från en extern databas. public override async Task<ICollection<PlayerGame>> GetAllAsync() { return await Context.PlayerGames .Include(g => g.Game) .Include(t => t.Team) .Include(p => p.Player) .ThenInclude(p => p.Games).ToListAsync(); } public override void Update(PlayerGame playerGame) { PlayerRepo pr = new PlayerRepo(); TeamRepo tr = new TeamRepo(); GameRepo gr = new GameRepo(); if (null != pr.FindBy(p => p.UserName == playerGame.Player.UserName).FirstOrDefault()) { pr.Add(playerGame.Player); pr.Save(); } if (null != tr.FindBy(p => p.Id == playerGame.Team.Id).FirstOrDefault()) { tr.Add(playerGame.Team); tr.Save(); } if (null != gr.FindBy(g => g.Name == playerGame.GameName).FirstOrDefault()) { gr.Add(playerGame.Game); gr.Save(); } Context.PlayerGames.Update(playerGame); Save(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Domain { public class PlayerStats { public PlayerStats() { } public int Id { get; set; } public int MatchId { get; set; } public Match Match { get; set; } public int PlayerGameId { get; set; } public PlayerGame PlayerGame { get; set; } public int Kills { get; set; } public int Deaths { get; set; } public int Assists { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Domain { public class TeamMatch { public TeamMatch() { } public Team Team { get; set; } public int TeamId { get; set; } public Match Match { get; set; } public int MatchId { get; set; } } } <file_sep>using EsportEvent.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Data { public class TeamMatchRepo : GenericEsportRepo<TeamMatch, EsportEventContext> { } } <file_sep>using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class mc : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1GameName_Team1Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2GameName_Team2Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentGameName_TournamentName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerGameName_WinnerName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamGameName_TeamName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_Team_Games_GameName", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropPrimaryKey( name: "PK_PlayerStats", table: "PlayerStats"); migrationBuilder.DropIndex( name: "IX_PlayerGames_PlayerId", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamGameName_TeamName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_Team1GameName_Team1Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_Team2GameName_Team2Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentGameName_TournamentName", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_WinnerGameName_WinnerName", table: "Matches"); migrationBuilder.DropColumn( name: "PlayerId", table: "PlayerGames"); migrationBuilder.DropColumn( name: "TeamGameName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "Team1GameName", table: "Matches"); migrationBuilder.DropColumn( name: "Team1Id", table: "Matches"); migrationBuilder.DropColumn( name: "Team1Name", table: "Matches"); migrationBuilder.DropColumn( name: "Team2GameName", table: "Matches"); migrationBuilder.DropColumn( name: "Team2Id", table: "Matches"); migrationBuilder.DropColumn( name: "Team2Name", table: "Matches"); migrationBuilder.DropColumn( name: "TournamentGameName", table: "Matches"); migrationBuilder.DropColumn( name: "TournamentName", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerGameName", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerName", table: "Matches"); migrationBuilder.RenameColumn( name: "TeamName", table: "PlayerGames", newName: "PlayerUserName"); migrationBuilder.RenameColumn( name: "WinnerId", table: "Matches", newName: "TeamId"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Tournament", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "GameName", table: "Tournament", nullable: true, oldClrType: typeof(string)); migrationBuilder.AddColumn<int>( name: "Id", table: "Tournament", nullable: false, defaultValue: 0) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); migrationBuilder.AlterColumn<string>( name: "Name", table: "Team", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "GameName", table: "Team", nullable: true, oldClrType: typeof(string)); migrationBuilder.AddColumn<int>( name: "Id", table: "Team", nullable: false, defaultValue: 0) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); migrationBuilder.AddColumn<int>( name: "MatchId", table: "Team", nullable: true); migrationBuilder.AddColumn<int>( name: "Id", table: "PlayerStats", nullable: false, defaultValue: 0) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); migrationBuilder.AddColumn<int>( name: "TeamId", table: "PlayerGames", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TournamentId", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_PlayerStats", table: "PlayerStats", column: "Id"); migrationBuilder.CreateIndex( name: "IX_Tournament_GameName", table: "Tournament", column: "GameName"); migrationBuilder.CreateIndex( name: "IX_Team_GameName", table: "Team", column: "GameName"); migrationBuilder.CreateIndex( name: "IX_Team_MatchId", table: "Team", column: "MatchId"); migrationBuilder.CreateIndex( name: "IX_PlayerStats_MatchId", table: "PlayerStats", column: "MatchId"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames", column: "PlayerUserName"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamId", table: "PlayerGames", column: "TeamId"); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentId", table: "Matches", column: "TournamentId"); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentId", table: "Matches", column: "TournamentId", principalTable: "Tournament", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames", column: "PlayerUserName", principalTable: "Players", principalColumn: "UserName", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamId", table: "PlayerGames", column: "TeamId", principalTable: "Team", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Team_Games_GameName", table: "Team", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Matches_MatchId", table: "Team", column: "MatchId", principalTable: "Matches", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentId", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Players_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamId", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_Team_Games_GameName", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Team_Matches_MatchId", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropIndex( name: "IX_Tournament_GameName", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_GameName", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_MatchId", table: "Team"); migrationBuilder.DropPrimaryKey( name: "PK_PlayerStats", table: "PlayerStats"); migrationBuilder.DropIndex( name: "IX_PlayerStats_MatchId", table: "PlayerStats"); migrationBuilder.DropIndex( name: "IX_PlayerGames_PlayerUserName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamId", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentId", table: "Matches"); migrationBuilder.DropColumn( name: "Id", table: "Tournament"); migrationBuilder.DropColumn( name: "Id", table: "Team"); migrationBuilder.DropColumn( name: "MatchId", table: "Team"); migrationBuilder.DropColumn( name: "Id", table: "PlayerStats"); migrationBuilder.DropColumn( name: "TeamId", table: "PlayerGames"); migrationBuilder.DropColumn( name: "TournamentId", table: "Matches"); migrationBuilder.RenameColumn( name: "PlayerUserName", table: "PlayerGames", newName: "TeamName"); migrationBuilder.RenameColumn( name: "TeamId", table: "Matches", newName: "WinnerId"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Tournament", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "GameName", table: "Tournament", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Team", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "GameName", table: "Team", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddColumn<string>( name: "PlayerId", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "TeamGameName", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "Team1GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "Team1Id", table: "Matches", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<string>( name: "Team1Name", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "Team2GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "Team2Id", table: "Matches", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<string>( name: "Team2Name", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "TournamentGameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "TournamentName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "WinnerGameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "WinnerName", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", columns: new[] { "GameName", "Name" }); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", columns: new[] { "GameName", "Name" }); migrationBuilder.AddPrimaryKey( name: "PK_PlayerStats", table: "PlayerStats", columns: new[] { "MatchId", "PlayerGameId" }); migrationBuilder.CreateIndex( name: "IX_PlayerGames_PlayerId", table: "PlayerGames", column: "PlayerId"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamGameName_TeamName", table: "PlayerGames", columns: new[] { "TeamGameName", "TeamName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team1GameName_Team1Name", table: "Matches", columns: new[] { "Team1GameName", "Team1Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team2GameName_Team2Name", table: "Matches", columns: new[] { "Team2GameName", "Team2Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentGameName_TournamentName", table: "Matches", columns: new[] { "TournamentGameName", "TournamentName" }); migrationBuilder.CreateIndex( name: "IX_Matches_WinnerGameName_WinnerName", table: "Matches", columns: new[] { "WinnerGameName", "WinnerName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1GameName_Team1Name", table: "Matches", columns: new[] { "Team1GameName", "Team1Name" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2GameName_Team2Name", table: "Matches", columns: new[] { "Team2GameName", "Team2Name" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentGameName_TournamentName", table: "Matches", columns: new[] { "TournamentGameName", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerGameName_WinnerName", table: "Matches", columns: new[] { "WinnerGameName", "WinnerName" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Players_PlayerId", table: "PlayerGames", column: "PlayerId", principalTable: "Players", principalColumn: "UserName", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamGameName_TeamName", table: "PlayerGames", columns: new[] { "TeamGameName", "TeamName" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Games_GameName", table: "Team", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } } } <file_sep>using EsportEvent.Domain; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Data { public class PlayerRepo : GenericEsportRepo<Player, EsportEventContext> { public override void Delete(Player player) { Context.PlayerGames.RemoveRange(player.Games); Context.Players.Remove(player); Context.SaveChanges(); } public override void DeleteRange(ICollection<Player> entities) { } public override ICollection<Player> FindBy(Expression<Func<Player, bool>> predicate) { return Context.Players.Where(predicate) .Include(g => g.Games) .ThenInclude(t => t.Team) .ToList(); } public override async Task<ICollection<Player>> FindByAsync(Expression<Func<Player, bool>> predicate) { return await Context.Players.Where(predicate) .Include(g => g.Games) .ThenInclude(t => t.Team) .ToListAsync(); } public override ICollection<Player> GetAll() { return Context.Players .Include(g => g.Games) .ThenInclude(t => t.Team) .ToList(); } public async override Task<ICollection<Player>> GetAllAsync() { return await Context.Players .Include(g => g.Games) .ThenInclude(t => t.Team) .ToListAsync(); } public override void Update(Player entity) { Context.Update(new Player {Name=entity.Name, UserName=entity.UserName }); } public override void UpdateRange(ICollection<Player> entities) { List<Player> players = entities.ToList(); for (int i = 0; i< entities.Count; i++) { Context.Update(new Player { Name = players[i].Name, UserName = players[i].UserName }); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EsportEvent.Domain; namespace EsportEvent.Data { public class TournamentRepo : GenericEsportRepo<Tournament, EsportEventContext> { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EsportEvent.Domain; using Microsoft.EntityFrameworkCore; namespace EsportEvent.Data { public class TeamRepo : GenericEsportRepo<Team, EsportEventContext> { } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Data { public abstract class GenericEsportRepo<T, C> where T : class where C : DbContext, new() { private C _context = new C(); public C Context { get { return _context; } set { _context = value; } } public virtual ICollection<T> GetAll() { return _context.Set<T>().ToList(); } public virtual async Task<ICollection<T>> GetAllAsync() { return await _context.Set<T>().ToListAsync(); } public virtual ICollection<T> FindBy(Expression<Func<T, bool>> predicate) { return _context.Set<T>().Where(predicate).ToList(); } public virtual async Task<ICollection<T>> FindByAsync(Expression<Func<T, bool>> predicate) { return await _context.Set<T>().ToListAsync(); } public virtual void Add(T entity) { _context.Set<T>().Add(entity); } public virtual async void AddAsync(T entity) { await _context.Set<T>().AddAsync(entity); } public virtual void AddRange(ICollection<T> entities) { _context.Set<T>().AddRange(entities); } public virtual async void AddRangeAsync(ICollection<T> entities) { await _context.Set<T>().AddRangeAsync(entities); } public virtual void Delete(T entity) { _context.Set<T>().Remove(entity); } public virtual void DeleteRange(ICollection<T> entities) { _context.Set<T>().RemoveRange(entities); } public virtual void Update(T entity) { _context.Set<T>().Update(entity); } public virtual void UpdateRange(ICollection<T> entities) { _context.Set<T>().UpdateRange(entities); } public virtual void Save() { _context.SaveChanges(); } public virtual void SaveAsync() { _context.SaveChangesAsync(); } } } <file_sep>using EsportEvent.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Data { public class GameRepo : GenericEsportRepo<Game, EsportEventContext> { } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class Minorchanges : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentGameId_TournamentName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Team_Tournament_TournamentGameId_TournamentName", table: "Team"); migrationBuilder.DropForeignKey( name: "FK_Tournament_Games_Name", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropIndex( name: "IX_Tournament_Name", table: "Tournament"); migrationBuilder.DropIndex( name: "IX_Team_TournamentGameId_TournamentName", table: "Team"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentGameId_TournamentName", table: "Matches"); migrationBuilder.DropColumn( name: "GameId", table: "Tournament"); migrationBuilder.DropColumn( name: "TournamentGameId", table: "Team"); migrationBuilder.DropColumn( name: "TournamentName", table: "Team"); migrationBuilder.DropColumn( name: "TournamentGameId", table: "Matches"); migrationBuilder.AddColumn<string>( name: "GameName", table: "Tournament", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "TournamentGameName", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", columns: new[] { "GameName", "Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentGameName_TournamentName", table: "Matches", columns: new[] { "TournamentGameName", "TournamentName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentGameName_TournamentName", table: "Matches", columns: new[] { "TournamentGameName", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Tournament_TournamentGameName_TournamentName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Tournament_Games_GameName", table: "Tournament"); migrationBuilder.DropPrimaryKey( name: "PK_Tournament", table: "Tournament"); migrationBuilder.DropIndex( name: "IX_Matches_TournamentGameName_TournamentName", table: "Matches"); migrationBuilder.DropColumn( name: "GameName", table: "Tournament"); migrationBuilder.DropColumn( name: "TournamentGameName", table: "Matches"); migrationBuilder.AddColumn<int>( name: "GameId", table: "Tournament", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TournamentGameId", table: "Team", nullable: true); migrationBuilder.AddColumn<string>( name: "TournamentName", table: "Team", nullable: true); migrationBuilder.AddColumn<int>( name: "TournamentGameId", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Tournament", table: "Tournament", columns: new[] { "GameId", "Name" }); migrationBuilder.CreateIndex( name: "IX_Tournament_Name", table: "Tournament", column: "Name"); migrationBuilder.CreateIndex( name: "IX_Team_TournamentGameId_TournamentName", table: "Team", columns: new[] { "TournamentGameId", "TournamentName" }); migrationBuilder.CreateIndex( name: "IX_Matches_TournamentGameId_TournamentName", table: "Matches", columns: new[] { "TournamentGameId", "TournamentName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Tournament_TournamentGameId_TournamentName", table: "Matches", columns: new[] { "TournamentGameId", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Tournament_TournamentGameId_TournamentName", table: "Team", columns: new[] { "TournamentGameId", "TournamentName" }, principalTable: "Tournament", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Tournament_Games_Name", table: "Tournament", column: "Name", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace EsportEvent.Data.Migrations { public partial class minor : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1GameId_Team1Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2GameId_Team2Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerGameId_WinnerName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamGameId_TeamName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_Team_Games_Name", table: "Team"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropIndex( name: "IX_Team_Name", table: "Team"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamGameId_TeamName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_Team1GameId_Team1Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_Team2GameId_Team2Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_WinnerGameId_WinnerName", table: "Matches"); migrationBuilder.DropColumn( name: "GameId", table: "Team"); migrationBuilder.DropColumn( name: "GameId", table: "PlayerGames"); migrationBuilder.DropColumn( name: "TeamGameId", table: "PlayerGames"); migrationBuilder.DropColumn( name: "Team1GameId", table: "Matches"); migrationBuilder.DropColumn( name: "Team2GameId", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerGameId", table: "Matches"); migrationBuilder.AddColumn<string>( name: "GameName", table: "Team", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "TeamGameName", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<string>( name: "Team1GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "Team2GameName", table: "Matches", nullable: true); migrationBuilder.AddColumn<string>( name: "WinnerGameName", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", columns: new[] { "GameName", "Name" }); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamGameName_TeamName", table: "PlayerGames", columns: new[] { "TeamGameName", "TeamName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team1GameName_Team1Name", table: "Matches", columns: new[] { "Team1GameName", "Team1Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team2GameName_Team2Name", table: "Matches", columns: new[] { "Team2GameName", "Team2Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_WinnerGameName_WinnerName", table: "Matches", columns: new[] { "WinnerGameName", "WinnerName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1GameName_Team1Name", table: "Matches", columns: new[] { "Team1GameName", "Team1Name" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2GameName_Team2Name", table: "Matches", columns: new[] { "Team2GameName", "Team2Name" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerGameName_WinnerName", table: "Matches", columns: new[] { "WinnerGameName", "WinnerName" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamGameName_TeamName", table: "PlayerGames", columns: new[] { "TeamGameName", "TeamName" }, principalTable: "Team", principalColumns: new[] { "GameName", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Games_GameName", table: "Team", column: "GameName", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team1GameName_Team1Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_Team2GameName_Team2Name", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_Matches_Team_WinnerGameName_WinnerName", table: "Matches"); migrationBuilder.DropForeignKey( name: "FK_PlayerGames_Team_TeamGameName_TeamName", table: "PlayerGames"); migrationBuilder.DropForeignKey( name: "FK_Team_Games_GameName", table: "Team"); migrationBuilder.DropPrimaryKey( name: "PK_Team", table: "Team"); migrationBuilder.DropIndex( name: "IX_PlayerGames_TeamGameName_TeamName", table: "PlayerGames"); migrationBuilder.DropIndex( name: "IX_Matches_Team1GameName_Team1Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_Team2GameName_Team2Name", table: "Matches"); migrationBuilder.DropIndex( name: "IX_Matches_WinnerGameName_WinnerName", table: "Matches"); migrationBuilder.DropColumn( name: "GameName", table: "Team"); migrationBuilder.DropColumn( name: "TeamGameName", table: "PlayerGames"); migrationBuilder.DropColumn( name: "Team1GameName", table: "Matches"); migrationBuilder.DropColumn( name: "Team2GameName", table: "Matches"); migrationBuilder.DropColumn( name: "WinnerGameName", table: "Matches"); migrationBuilder.AddColumn<int>( name: "GameId", table: "Team", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "GameId", table: "PlayerGames", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "TeamGameId", table: "PlayerGames", nullable: true); migrationBuilder.AddColumn<int>( name: "Team1GameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "Team2GameId", table: "Matches", nullable: true); migrationBuilder.AddColumn<int>( name: "WinnerGameId", table: "Matches", nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_Team", table: "Team", columns: new[] { "GameId", "Name" }); migrationBuilder.CreateIndex( name: "IX_Team_Name", table: "Team", column: "Name"); migrationBuilder.CreateIndex( name: "IX_PlayerGames_TeamGameId_TeamName", table: "PlayerGames", columns: new[] { "TeamGameId", "TeamName" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team1GameId_Team1Name", table: "Matches", columns: new[] { "Team1GameId", "Team1Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_Team2GameId_Team2Name", table: "Matches", columns: new[] { "Team2GameId", "Team2Name" }); migrationBuilder.CreateIndex( name: "IX_Matches_WinnerGameId_WinnerName", table: "Matches", columns: new[] { "WinnerGameId", "WinnerName" }); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team1GameId_Team1Name", table: "Matches", columns: new[] { "Team1GameId", "Team1Name" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_Team2GameId_Team2Name", table: "Matches", columns: new[] { "Team2GameId", "Team2Name" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Matches_Team_WinnerGameId_WinnerName", table: "Matches", columns: new[] { "WinnerGameId", "WinnerName" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_PlayerGames_Team_TeamGameId_TeamName", table: "PlayerGames", columns: new[] { "TeamGameId", "TeamName" }, principalTable: "Team", principalColumns: new[] { "GameId", "Name" }, onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Team_Games_Name", table: "Team", column: "Name", principalTable: "Games", principalColumn: "Name", onDelete: ReferentialAction.Cascade); } } } <file_sep>using EsportEvent.Domain; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EsportEvent.Data { public class MatchRepo : GenericEsportRepo<Match, EsportEventContext> { public override ICollection<Match> GetAll() { return Context.Matches .Include(t => t.Game) .Include(p => p.PlayerStats) .Include(t => t.Teams) .ToList(); } public override Task<ICollection<Match>> GetAllAsync() { return base.GetAllAsync(); } public override ICollection<Match> FindBy(Expression<Func<Match, bool>> predicate) { return base.FindBy(predicate); } public override Task<ICollection<Match>> FindByAsync(Expression<Func<Match, bool>> predicate) { return base.FindByAsync(predicate); } //__________________________________________________________________ public override void Add(Match entity) { TeamMatchRepo teamMatch = new TeamMatchRepo(); var match = new Match { GameName = entity.GameName, GameDay = entity.GameDay, TournamentId = entity.TournamentId }; Context.Add(match); Save(); teamMatch.AddRange(new List<TeamMatch> { new TeamMatch{MatchId=match.Id, TeamId = entity.Teams[0].Id}, new TeamMatch{MatchId=match.Id, TeamId = entity.Teams[1].Id } }); teamMatch.Save(); } public override async void AddAsync(Match entity) { TeamMatchRepo teamMatch = new TeamMatchRepo(); await Context.AddAsync(new Match { GameName = entity.GameName, GameDay = entity.GameDay, TournamentId = entity.Id, }); SaveAsync(); Task.WaitAll(); teamMatch.AddRangeAsync(new List<TeamMatch> { new TeamMatch{MatchId=entity.Id, TeamId=entity.Teams[0].Id}, new TeamMatch{MatchId=entity.Id, TeamId = entity.Teams[1].Id } }); } public override void AddRange(ICollection<Match> entities) { var list = entities.ToList(); for (int i = 0; i < entities.Count; i++) { TeamMatchRepo teamMatch = new TeamMatchRepo(); Context.Add(new Match { GameName = list[i].GameName, GameDay = list[i].GameDay, TournamentId = list[i].Id, }); Save(); teamMatch.AddRange(new List<TeamMatch> { new TeamMatch{MatchId=list[i].Id, TeamId=list[i].Teams[0].Id}, new TeamMatch{MatchId=list[i].Id, TeamId = list[i].Teams[1].Id } }); } } public override async void AddRangeAsync(ICollection<Match> entities) { var list = entities.ToList(); for (int i = 0; i < entities.Count; i++) { TeamMatchRepo teamMatch = new TeamMatchRepo(); await Context.AddAsync(new Match { GameName = list[i].GameName, GameDay = list[i].GameDay, TournamentId = list[i].Id, }); Save(); Task.WaitAll(); teamMatch.AddRange(new List<TeamMatch> { new TeamMatch{MatchId=list[i].Id, TeamId=list[i].Teams[0].Id}, new TeamMatch{MatchId=list[i].Id, TeamId = list[i].Teams[1].Id } }); } } } }
b172f810c5f671ced7a51a46561d0104ffffa156
[ "C#" ]
24
C#
TeknikhogskolanGothenburg/Ef_Emanuel_Johansson_EsportEvent
a13070f240ffa49367ed7b40cedb9be1e53bc446
aab6bd0046108cab0eb895fc12b798b48da989ee
refs/heads/master
<file_sep>var myApp = angular.module('myApp', []); myApp.controller('DataController', ['$scope', '$http', function ($scope, $http) { $scope.movies = [ { "name": "<NAME>", "date": "10 November 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "How To Be Single", "date": "10 February 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Central Intelligence", "date": "17 June 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME>", "date": "17 June 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME>", "date": "5 August 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Police Story: Lockdown", "date": "5 June 2015", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME>venant", "date": "8 January 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Concussion", "date": "25 December 2015", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Captain America: Civil War", "date": "6 May 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Deadpool", "date": "12 February 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME> the Looking Glass", "date": "27 May 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "Now You See Me 2", "date": "10 June 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME>: Winters War", "date": "22 April 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" }, { "name": "<NAME>", "date": "29 January 2016", "status": "unwatched", "myRating": 10, "imgSrc": "" } ]; } ]);<file_sep><div class="grayBG"> <div class="container myFeature"> <div class="row"> <div class="titleProject"> Experience</div> <hr/> </div> <div class="row"> <div class="col-lg-3"> <div class="btn-danger btn-circle btn-lg"> <div class="projectCount">Experience</div> </div> </div> <div class="col-lg-9"> <div class="featureBtn"> <div class="row"> <div class="myMessage"> <h3>Dynamic Solution Innovators</h3> <h4>Senior Software Engineer</h4> <h4>2015 to Present</h4> <h4>Website : <a href="http://http://www.dsinnovators.com//">DSi</a> </h4> ​In this company I am working on a ERP system. This is a custom J2EE project. While working on this project, I exposed myself on different cloud based system along with J2EE. Mostly I am working on different web services from Aamazon Web Services; namely ec2, beanstack, cloud watch, s3, apigateway, docker e.t.c. I am working here as a part of a large team. </div> </div> <div class="row"> <div class="myMessage"> <h3>Springine</h3> <h4>Team Lead</h4> <h4>2013-2014 September</h4> <h4>Website : <a href="http://www.ebajar.com/">eBajar</a> & <a href="http://www.springine.com/">Springine</a></h4> ​In this company I am working on a project called eBajar. I am designing both server side and client side component. I am using Spring framework, hibernate, sitemesh and bootstrap. I am using tomcat 7 as the application server and Amazon EC-2 cloud computing is used for hosting our site. </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Ipaholics</h3> <h4>Software Developer</h4> <h4>2012-2013 (Educational leave included)</h4> <h4>Website : <a href="http://www.beshto.com/">Beshto</a></h4> ​I worked here as application developer. I worked on a project called “Beshto”. Project description given <a href ng-click="tab = 'proj'">project page</a>. My job was to develop different functionality required by the company and show them in given format. I worked here as a part of the team. I used MVC and Agile for this application development. I have also worked on amazon ec-2 for hosting the site online. </div> </div> <hr/> <hr/> <div class="row"> <div class="myMessage"> <h3>East West University</h3> <h4>Teacher</h4> <h4>Website : <a href="http://www.ewubd.edu/">East West University</a></h4> ​I was a volunteer lab teacher CSE 412 course. I used to teach students different concept of java and show them practical example of the concepts. Course Include concept of class, inheritance, polymorphism, list, set, vector, multi threading, basic java gui and networking <a href="http://cse412.blogspot.co.uk/">[Link]</a> this website was used to give students course material. </div> </div> </div> </div> </div> <hr/> <!--/Part 2 end --> <!--/Part 3 start --> <div class="row"> <div class="col-lg-3"> <div class="btn-danger btn-circle btn-lg"> <div class="projectCount">Education</div> </div> </div> <div class="col-lg-9"> <div class="row"> <div class="myMessage"> <h3>Software Development, MSc (2013)</h3> <h4>Coventry University, Coventry, England</h4> </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Computer Science and Engineering, BSc (2012)</h3> <h4>East West University, Dhaka, Bangladesh</h4> </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Higher Secondary Certificate (2007)</h3> <h4>B A F Shaheen College, Cantonment, Dhaka, Bangladesh</h4> </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Secondary School Certificate (2004)</h3> <h4>Faridpur Zilla School, Faridpur, Bangladesh</h4> </div> </div> </div> </div> <hr/> <!--/Part 3 end --> <!--/Part 4 start --> <div class="row"> <div class="col-lg-3"> <div class="btn-danger btn-circle btn-lg"> <div class="projectCount">Referee</div> </div> </div> <div class="col-lg-9"> <div class="row"> <div class="myMessage"> <h3><NAME></h3> Chief Architect<br> Beshto Service<br> <EMAIL><br> Level – 3 BDBL Bhaban<br> 12, Karwan Bazar, Dhaka-1215 www.beshto.com </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Md.<NAME></h3> Md.Moddasir Rahman khan<br> bGlobal Interactive<br> e-mail: <EMAIL><br> de.linkedin.com/in/moddasir/en </div> </div> <hr/> <div class="row"> <div class="myMessage"> <h3>Dr. <NAME></h3> Assistant Professor<br> Department of CSE<br> East West University <br> e-mail: <EMAIL> <br> http://ewubd.edu/ewu </div> </div> </div> </div> <!--/Part 4 end --> </div> </div> <file_sep>#wget http://lynas.github.io/p/openshiftStartup.sh cd $OPENSHIFT_DATA_DIR export JAVA_HOME=/etc/alternatives/java_sdk_1.8.0 export PATH=$JAVA_HOME/bin:$PATH wget http://www.eu.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.zip unzip apache-maven-3.3.9-bin.zip export M2_HOME=$OPENSHIFT_DATA_DIR/apache-maven-3.3.9 export PATH=$M2_HOME/bin:$PATH mkdir -p $OPENSHIFT_DATA_DIR/.m2 export MAVEN_OPTS="-Dmaven.repo.local=$OPENSHIFT_DATA_DIR/.m2" #cd $OPENSHIFT_REPO_DIR #java -jar target/*.jar --server.port=${OPENSHIFT_DIY_PORT} --server.address=${OPENSHIFT_DIY_IP}
b55b9bd4d1130439f3c03ebeb444aa3c243efc51
[ "JavaScript", "HTML", "Shell" ]
3
JavaScript
lynas/lynas.github.io
aaf81bbaca44f3e851516c17091a0ea641b71bbc
ad779f46ab96929b51d7cbf639b1eb95761bcb14
refs/heads/main
<repo_name>Vincent615/ImmobileMaze<file_sep>/gears.py # Describe the Wooden Sword through a dictionary wSword = { 'descript': 'a wooden weapon for newbies', 'damage': 5, } # Describe the Iron Sword through a dictionary iSword = { 'descript': 'an iron weapon for pros', 'damage': 10, } # Describe the Diamond Sword through a dictionary dSword = { 'descript': 'a diamond weapon for experts', 'damage': 15, } # Describe the Iron Armor through a dictionary iArmor = { 'descript': 'a great suit of gears for a pro', 'resistance': 3, }, # Describe the Diamond Armor through a dictionary dArmor = { 'descript': 'a great suit of gears for an expert', 'resistance': 8, } <file_sep>/monsters.py class Lv1_fodder(): """Fodder monster with attributions""" def __init__(self): self.descript = 'A cannon folder said no words' self.name = "Lv1 Cannon Fodder" self.hp = 20 self.damage = 5 self.resistance = 1 class Lv2_fodder(): """Fodder monster with attributions""" def __init__(self): self.descript = 'A cannon folder said no words' self.name = "Lv2 Cannon Fodder" self.hp = 30 self.damage = 5 self.resistance = 2 dragon_descript = '''Owner of the Dungeon, \tFirst boss of the journal:\n\n\t\tBlazing Dragon!!!''' class Dragon(): """Dragon monster with attributions""" def __init__(self): self.descript = dragon_descript self.name = "Dragon" self.hp = 50 self.damage = 25 self.resistance = 8 yaranzo_descript = '''The one born from human\'s greeds \n\t\tYaranzo!!!''' class Yaranzo(): """Yaranzo monster with attributions""" def __init__(self): self.descript = yaranzo_descript self.name = "Yaranzo" self.hp = 60 self.damage = 30 self.resistance = 10 slime_descript = '''Owner of the Forest, \tFinal boss of the journal:\n\n\t\tLittle Slime!!!''' class Slime(): """Slime monster with attributions""" def __init__(self): self.descript = slime_descript self.name = "Slime" self.hp = 5 self.damage = 50 self.resistance = 50 Lv1_fodder = Lv1_fodder() Lv2_fodder = Lv2_fodder() Dragon = Dragon() Yaranzo = Yaranzo() Slime = Slime() <file_sep>/README.md # Immobile Maze Immobile Maze is a Python text-based adventure game. ## Installation Python 3.8 is required to play this game. [Python 3.8](https://www.python.org/downloads/) to install Python. ## Run the Program ```bash Python play.py ``` ## Quit the Program Input "quit" or "q" when it's notated ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>/player.py class Player(): def __init__(self): """Player with attributions""" self.hp = 100 self.damage = 20000 self.resistance = 1000000 class Backpack(): def __init__(self): """Items in the backpack""" self.bandages = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] self.weapon = ['Diamond sword'] self.armor = ['Armor'] Player = Player() Backpack = Backpack() <file_sep>/changelog.md # RPG: Immobile Maze Changelog v0.1 - set up the core fighting system - added backpack function - removed defense action v0.2 - continuous game play available - added more valid commands for actions - added real-time health point display v0.3 - added game-quiting function - added death effect - debuged v0.4 - import, class, def is used - changed the names of files - removed bow from gears v0.5 - debuged - simplified healing function - seperated combat system v0.6 - attempted to debug - added Round function - added Player Class v0.7 - attempted to debug - added map - changed death effect v0.8 - debuged <file_sep>/play.py # Course: CS 30 # Period: 2 # Date created: 20/11/23 # Date last modified: 20/12/20 # Name: <NAME> # Description: A RPG game talking about the brave risking in the dungeon from player import Player from player import Backpack import monsters as m import random attack = ['attack', 'a', '1'] # Command list for attacking heal = ['heal', 'h', '2'] # Command list for healing escape = ['escape', 'e', '3'] # Command list for escaping move = ['front', 'f', '1', 'left', 'l', '2', 'right', 'r', '3'] backpack = ['backpack', 'b', '4'] # Command list for backpack quit = ['quit', 'q', '5'] # Command list to quit the game def play(): '''The beginning of the game''' print('You woke up.\nYou find you are in a abandoned dungeon.') print('\n- The goal is to >>> Stay Alive <<<') safe(0) # 0 refers to 0 round of the game def attacking(Monster): '''The function shows the cauculation if the player attacked''' if Player.damage < Monster.resistance: # Monster's hp minus one if its resistance if higher Monster.hp = Monster.hp - 1 return else: # A formula to calculate damage on the monster Monster.hp = Monster.hp + Monster.resistance - Player.damage return # Show the status of the monster and player print(f'\n- You attacked {Monster.name}.\n Hp left: {Monster.hp}') print(f'\n{Monster.name}\'s turn:') if Monster.damage < Player.resistance: # Player's hp minus one if its resistance if higher Player.hp = Player.hp - 1 return else: # A formula to calculate damage on the player Player.hp = Player.hp + Player.resistance - Monster.damage return print(f'- You got one hit from the {Monster.name}.') def healing(): '''Add health points to the player''' if len(Backpack.bandages) == 0: # Tell the player there is no bandages print('\n- There is no bandage in your backpack.') else: # Ask the player how many it needs print(f'Available bandages: {len(Backpack.bandages)}') a = input('How many will be used? Each one + 10 hp\n>>> ') if int(a) <= len(Backpack.bandages): # Each bandage add 10 hp Player.hp = Player.hp + int(a) * 10 # remove a bandage from the list Backpack.bandages.remove(0) return else: # Tell the player it asked for too many bandages print('\n- There are not enough bandages.') def escaping(Monster): '''There is 25% chance to escape''' escapable = random.randint(0, 4) if escapable == 1: print('\n- You failed to escape.') # Recieve one hit from the monster print(f' You got one hit from the {Monster.name}.') Player.hp = Player.hp + Player.resistance - Monster.damage return else: # Tell the player it escaped print('\n- You escaped successfully.') # Call the function safe() safe() def moving(round): lottery = random.randint(1, 5) # 20% to get nothing if lottery == 1: print('\n- Nothing happened.') # 60% to encounter a monster elif lottery > 2: danger(round) else: # 20% to get a chest while True: # Ask player to open or not print('\n- You find a chest.\n\nDo you want to open it?') action = '* Open\n* Leave\n>>> ' action = input(action).lower() # Replace into lower form if action == 'open': # Tell the player there is nothing # This will be updated to find some gears print('- There is nothing inside') break elif action == 'leave': break else: # Print a message for unexpected command print('\n- Invalid command.') def backpacking(): '''Print the messages of backpack''' print(f'\nWeapon:\n* {Backpack.weapon}') print(f'Armor:\n* {Backpack.armor}') print(f'Bandages:\n* {len(Backpack.bandages)}') # Ask player back to fight input('\n- Press Enter back to the fight.\n>>> ') def safe(round): '''Actions and their results when player is exploring''' while True: # Ask player to take an action print('\nYou can choose one of the following actions:') print('* Front (F)\n* Left (L)\n* Right (R)') action = '* Backpack (B)\n* Quit (Q)\n>>> ' action = input(action).lower() # Replace the input into lower form if action in backpack: # Call the function backpacking backpacking() elif action in quit: # Break the loop and stop the game lost() break elif action in move: # Call the function moving moving(round) else: # Print a message for unexpected command print('\n- Invalid command.') def danger(round): '''Actions and their results when player encounters a monster''' # Run the loop if player's hp is greater than 0 while Player.hp > 0: # Round number and its referance monster if round < 10: Monster = m.Lv1_fodder() elif round == 10: Monster = m.Dragon() elif round == 11: Monster == m.Yaranzo() elif 11 < round < 21: Monster == m.Lv2_fodder() elif round == 21: Monster == m.Slime() else: # Finish the game if the Round is greater than 21 print('You successfully escape from the forest!') print('\n\n\t\t\t >>> Congratulations <<<\n\n') break # Show the boss notation if the player encounter a boss print('''\n>>> Monster encountering <<<\n''') print(f'\n\t{Monster.descript}') # Keep the loop running if hp is greater than zero if Monster.hp > 0: print(f'\n\tCurrent hp:\t{Player.hp}') # Let the player choose one of the actions print('\nYou can choose one of the following actions:') print('* Attack (A)\n* Heal (H)\n* Escape (E)') action = '* Backpack (B)\n* Quit (Q)\n>>> ' action = input(action).lower() # Replace into lower form # Actions and their results if action in attack: attacking(Monster) elif action in heal: healing() elif action in escape: escaping(Monster) elif action in backpack: backpacking() elif action in quit: # Break the loop and stop the game lost() break else: # Print a message for unexpected command print('\n- Invalid command.') else: # Following actions if monster's hp is lower than 0 if round != 10: print(f'You sucessfully killed the {Monster.name}') # Add 1 round if the monster is killed round = round + 1 # Call the funciton safe safe(round) # Following actions if the round number is 10 elif round == 10: # Ask the player to open chest or not print('- You found a mega legendary chest.') print('Do you want to open it?') action = input('* Yes\n* No\n>>> ') action = input(action).lower() # Replace into lower form if action == 'yes': # The player will encounter Yaranzo this round continue elif action == 'no': # Add 1 more round if the player choose no round = round + 1 else: # Call the function lost when player's hp is lower than 0 lost() def lost(): # Print a message if the player lost the game print('\n\n\t\t\t_____ _____ _____') print('\t|\t |\t | |\t\t |') print('\t|\t |\t | |_____\t |') print('\t|\t |\t |\t\t |\t |') print('\t|_____ |_____| _____|\t |') print('\n\n\t\t\t >>> Game Over <<<\n\n') play()
b6136e031b638a37a4861a97e232d73e830459fd
[ "Markdown", "Python" ]
6
Python
Vincent615/ImmobileMaze
b04b85df937515f89142d1d7e9eb0fc08bef5dbd
608b6c740482ec4d995a54a97766dafd92db3e80
refs/heads/main
<repo_name>chickenfan/Chickens-Amazing-Discord-Bot<file_sep>/CommandHandling/BaseCommand.ts import {Permissions, GuildMember, Message} from 'discord.js' export default abstract class BaseCommand { private command: String; private perm: number; constructor(command: String, perm: number) { this.command = command; this.perm = perm; } public getCommand(withPrefix: boolean): String { if(withPrefix) return '!' + this.command; else return this.command; } public getPerm(): number { return this.perm; } public abstract execute(member: GuildMember, args: String[], msg: Message): void; }<file_sep>/CommandHandling/CommandManager.ts import BaseCommand from "./BaseCommand" import {ShutdownCommand} from "./Commands/ShutdownCommand" import {HelloCommand} from "./Commands/HelloCommand" export default class CommandManager { private commands: Array<BaseCommand>; private addCommand(command: BaseCommand): void { this.commands.push(command); } public getCommands(): Array<BaseCommand> { return this.commands; } constructor() { this.commands = [new ShutdownCommand()]; this.addCommand(new HelloCommand()); } }<file_sep>/CommandHandling/Commands/ShutdownCommand.ts import BaseCommand from "../BaseCommand" import Lib from "../Lib" import {Permissions, GuildMember, Message} from 'discord.js' export class ShutdownCommand extends BaseCommand { constructor() { super('shutdown', Permissions.FLAGS.ADMINISTRATOR); } execute(member: GuildMember, args: String[], msg: Message): void { var lib = new Lib(); if (member.guild.me!.hasPermission(this.getPerm())) lib.getUtility().getClient().destroy(); } }<file_sep>/CommandHandling/Commands/HelloCommand.ts import {Permissions, GuildMember, Message} from 'discord.js' import BaseCommand from "../BaseCommand" export class HelloCommand extends BaseCommand { constructor() { super('hello', Permissions.FLAGS.SEND_MESSAGES); } public execute(member: GuildMember, args: String[], msg: Message): void { msg.channel.send('Hello ' + member.displayName); } }<file_sep>/CommandHandling/Lib.ts import Utility from "../Index" export default class Lib { getUtility(): Utility { return new Utility; } }<file_sep>/Index.ts import {Client, GuildMember} from 'discord.js'; import CommandManager from "./CommandHandling/CommandManager" const client = new Client(); var cmdManager: CommandManager; var utils: Utility; export default class Utility { getClient(): Client { return client; } equalsIgnoreCase(string1: String, string2: String): boolean { if (string1.toString().toLowerCase() == string2.toString().toLowerCase()) return true; else return false; } } client.on('ready', () => { console.log('Bot up!'); cmdManager = new CommandManager(); utils = new Utility(); }); client.on('message', msg => { cmdManager.getCommands().forEach(cmd => { if(utils.equalsIgnoreCase(msg.toString(), cmd.getCommand(true))) cmd.execute(msg.member as GuildMember, [''], msg); }); }); client.login(process.env.TOKEN);
b9216161116e972850674c4b1499050706eeb4fd
[ "TypeScript" ]
6
TypeScript
chickenfan/Chickens-Amazing-Discord-Bot
1f04f1bd618c26336252a7bc4c6f9771299a1a76
d2a0ba7b3edfaefcb039ddc69e3a4363929e7ee0
refs/heads/master
<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.model class ChatMessage(val id:String="", val text:String="", val fromId:String="", val toId:String="", val sendTime:Long=0) { }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.model.User import kotlinx.android.synthetic.main.activity_register.* import java.util.* class RegisterActivity : AppCompatActivity() { private lateinit var auth : FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) auth=FirebaseAuth.getInstance() registerButton.setOnClickListener { kayitOl() } loginTextview.setOnClickListener { val intent= Intent(this,LoginActivity::class.java) startActivity(intent) finish() } selectPhotoImageview.setOnClickListener { //resim seçme ekranı açılır val intent=Intent(Intent.ACTION_PICK) intent.type="image/*" startActivityForResult(intent,0) } } var selectedPhotoUri:Uri?=null //resim secildikten sonra yakalama override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode==0&&resultCode== Activity.RESULT_OK&& data!=null){ selectedPhotoUri=data.data val bitmap=MediaStore.Images.Media.getBitmap(contentResolver,selectedPhotoUri) selectPhotoImageview.setImageBitmap(bitmap) } super.onActivityResult(requestCode, resultCode, data) } private fun kayitOl(){ val email=emailRegisterEditText.text.toString() val sifre=passwordRegisterEditText.text.toString() auth.createUserWithEmailAndPassword(email,sifre).addOnCompleteListener { if(it.isSuccessful){ val guncelKullanici=auth.currentUser?.email.toString() Toast.makeText(this,"Guncel Kullanici ${guncelKullanici}", Toast.LENGTH_LONG).show() val intent=Intent(this, MainActivity::class.java) startActivity(intent) finish() selectedPhotoUri?.let { uploadImageToFirebase(it) } } }.addOnFailureListener { Toast.makeText(this,it.localizedMessage.toString(), Toast.LENGTH_LONG).show() } } private fun uploadImageToFirebase(uri: Uri){ val filename=UUID.randomUUID().toString() val ref=FirebaseStorage.getInstance().getReference("/images/${filename}") ref.putFile(uri).addOnSuccessListener { ref.downloadUrl.addOnSuccessListener { saveUserToFirebaseDataBase(it.toString()) } } } private fun saveUserToFirebaseDataBase(profileImageUrl:String){ val uid=FirebaseAuth.getInstance().uid?:"" val ref=FirebaseDatabase.getInstance().getReference("/users/${uid}") val user=User(uid.toString(),kullaniciAdiEditText.text.toString(),profileImageUrl) ref.setValue(user).addOnSuccessListener { //başarılı şekilde kaydoldu } } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.model.ChatMessage import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_chat.view.* import kotlinx.android.synthetic.main.chat_me_recycler_row.view.* import kotlinx.android.synthetic.main.new_message_recycler_row.view.* class ChatLogRecyclerAdapter(val mesajlar:ArrayList<ChatMessage>): RecyclerView.Adapter<ChatLogRecyclerAdapter.ChatLogHolder>() { class ChatLogHolder(itemView:View):RecyclerView.ViewHolder(itemView) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatLogHolder { val inflater = LayoutInflater.from(parent.context) val view=inflater.inflate(R.layout.chat_me_recycler_row,parent,false) return ChatLogHolder(view) } override fun onBindViewHolder(holder: ChatLogHolder, position: Int) { holder.itemView.meChatTextView.text=mesajlar[position].text } override fun getItemCount(): Int { return mesajlar.size } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.mucahitsahin.kotlin_chatbox_firebase.R import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : AppCompatActivity() { private lateinit var auth : FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) auth=FirebaseAuth.getInstance() val guncelKullanici=auth.currentUser if(guncelKullanici!=null){ val intent=Intent(this, MainActivity::class.java) startActivity(intent) finish() } registerTextview.setOnClickListener { val intent=Intent(this,RegisterActivity::class.java) startActivity(intent) finish() } } fun girisYap(view:View){ val email=emailRegisterEditText.text.toString() val sifre=passwordRegisterEditText.text.toString() auth.signInWithEmailAndPassword(email,sifre).addOnCompleteListener {task-> if(task.isSuccessful){ val guncelKullanici=auth.currentUser?.email.toString() Toast.makeText(this,"Guncel Kullanici ${guncelKullanici}",Toast.LENGTH_LONG).show() val intent=Intent(this, MainActivity::class.java) startActivity(intent) finish() } }.addOnFailureListener{ Toast.makeText(this,it.localizedMessage.toString(),Toast.LENGTH_LONG).show() } } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.adapter.NewMessageRecyclerAdapter import com.mucahitsahin.kotlin_chatbox_firebase.model.User import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.activity_new_message.* class NewMessageActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth private lateinit var database:FirebaseDatabase private lateinit var recyclerViewAdapter: NewMessageRecyclerAdapter //val adapter= GroupAdapter<ViewHolder>() val userList=ArrayList<User>() lateinit var layoutManager:LinearLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_message) auth=FirebaseAuth.getInstance() database= FirebaseDatabase.getInstance() supportActionBar?.title="Kişi Seç" //recyclerViewNewMessage.adapter=adapter verileriAl() } private fun verileriAl(){ userList.clear() val ref=database.getReference("/users") ref.addValueEventListener(object :ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { snapshot.children.forEach { val user=it.getValue(User::class.java) userList.add(user!!) } for (va in userList){ Log.d("deneme",va.username) Log.d("deneme",va.profileImage) } val adapter=NewMessageRecyclerAdapter(userList,this@NewMessageActivity) recyclerViewNewMessage.layoutManager = LinearLayoutManager(this@NewMessageActivity) recyclerViewNewMessage.adapter = adapter Log.d("yeniMesaj","kisiler geldi") } override fun onCancelled(error: DatabaseError) { } }) } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.model.User import com.squareup.picasso.Picasso import com.xwray.groupie.Item import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.chat_me_recycler_row.view.* class ChatFromItem(val text:String,val user:User):Item<ViewHolder>() { override fun bind(viewHolder: ViewHolder, position: Int) { viewHolder.itemView.meChatTextView.text=text val uri=user.profileImage Picasso.get().load(uri).into(viewHolder.itemView.meChatImageView) } override fun getLayout(): Int { return R.layout.chat_me_recycler_row } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.model.User import com.squareup.picasso.Picasso import com.xwray.groupie.Item import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.chat_it_recycler_row.view.* class ChatToItem(val text:String,val user: User): Item<ViewHolder>() { override fun bind(viewHolder: ViewHolder, position: Int) { viewHolder.itemView.itChatTextView.text=text val uri=user.profileImage Picasso.get().load(uri).into(viewHolder.itemView.itChatImageView) } override fun getLayout(): Int { return R.layout.chat_it_recycler_row } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.fragment.app.FragmentTransaction import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.fragment.HomeFragment import com.mucahitsahin.kotlin_chatbox_firebase.fragment.ProfileFragment import com.mucahitsahin.kotlin_chatbox_firebase.model.User class MainActivity : AppCompatActivity() { lateinit var homeFragment: HomeFragment lateinit var profileFragment: ProfileFragment companion object{ var currentUser: User?=null } private fun getCurrentUser(){ val uid=FirebaseAuth.getInstance().uid val ref= FirebaseDatabase.getInstance().getReference("/users/$uid") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { currentUser=snapshot.getValue(User::class.java) } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) getCurrentUser() val bottomNavigation:BottomNavigationView=findViewById(R.id.bottomNavigationView) homeFragment= HomeFragment() supportFragmentManager .beginTransaction() .replace(R.id.frameLayout,homeFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit() bottomNavigation.setOnNavigationItemSelectedListener{ when(it.itemId){ R.id.home_navigation ->{ homeFragment= HomeFragment() supportFragmentManager .beginTransaction() .replace(R.id.frameLayout,homeFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit() } R.id.profile_navigation ->{ profileFragment= ProfileFragment() supportFragmentManager .beginTransaction() .replace(R.id.frameLayout,profileFragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit() } } true } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.yeni_mesaj_menu->{ val intent=Intent(this,NewMessageActivity::class.java) startActivity(intent) } R.id.cikis_yap_menu->{ FirebaseAuth.getInstance().signOut() val intent=Intent(this,LoginActivity::class.java) startActivity(intent) finish() } } return super.onOptionsItemSelected(item) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.top_menu,menu) return super.onCreateOptionsMenu(menu) } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class User(val uid:String="",val username:String="",val profileImage:String=""):Parcelable { }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.mucahitsahin.kotlin_chatbox_firebase.adapter.ChatFromItem import com.mucahitsahin.kotlin_chatbox_firebase.adapter.ChatToItem import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.model.ChatMessage import com.mucahitsahin.kotlin_chatbox_firebase.model.User import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.activity_chat.* class ChatActivity : AppCompatActivity() { val adapter=GroupAdapter<ViewHolder>() var toUser:User?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat) toUser = intent.getParcelableExtra<User>("userkey") supportActionBar?.title=toUser!!.username buttonGonder.setOnClickListener { //mesaj gönderme mesajGonder() } recyclerViewMesaj.adapter=adapter mesajlariListele() } private fun mesajlariListele(){ var fromId=FirebaseAuth.getInstance().uid var toId=toUser!!.uid val reference=FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId") reference.addChildEventListener(object :ChildEventListener{ override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) { val chatMessage=snapshot.getValue(ChatMessage::class.java) if(chatMessage!=null){ if(chatMessage.fromId==FirebaseAuth.getInstance().uid){ val user=MainActivity.currentUser adapter.add(ChatFromItem(chatMessage.text,user!!)) } else{ adapter.add(ChatToItem(chatMessage.text,toUser!!)) } } } override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) { TODO("Not yet implemented") } override fun onChildRemoved(snapshot: DataSnapshot) { TODO("Not yet implemented") } override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) { TODO("Not yet implemented") } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } private fun mesajGonder(){ var text=editTextTextMesaj.text.toString() var fromId=FirebaseAuth.getInstance().uid val user = intent.getParcelableExtra<User>("userkey") var toId=user!!.uid var sendTime=System.currentTimeMillis()/1000 //var reference=FirebaseDatabase.getInstance().getReference("/messages").push() var reference=FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId").push() var toReference=FirebaseDatabase.getInstance().getReference("/user-messages/$toId/$fromId").push() if(fromId==null)return val chatMessage=ChatMessage(reference.key!!,text,fromId,toId,sendTime) reference.setValue(chatMessage) toReference.setValue(chatMessage) editTextTextMesaj.text.clear() recyclerViewMesaj.scrollToPosition(adapter.itemCount-1) } }<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.google.firebase.auth.FirebaseAuth import com.mucahitsahin.kotlin_chatbox_firebase.R import com.mucahitsahin.kotlin_chatbox_firebase.activity.ChatActivity import com.mucahitsahin.kotlin_chatbox_firebase.model.User import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.new_message_recycler_row.view.* class NewMessageRecyclerAdapter(val userList:ArrayList<User>,val context: Context): RecyclerView.Adapter<NewMessageRecyclerAdapter.UserHolder>() { class UserHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val inflater = LayoutInflater.from(parent.context) val view=inflater.inflate(R.layout.new_message_recycler_row,parent,false) return UserHolder(view) } override fun onBindViewHolder(holder: UserHolder, position: Int) { holder.itemView.recycler_row_username.text=userList[position].username Picasso.get().load(userList[position].profileImage).into(holder.itemView.recycler_row_imageview) holder.itemView.setOnClickListener { val intent=Intent(context,ChatActivity::class.java) intent.putExtra("userkey",userList[position]) context.startActivity(intent) } } override fun getItemCount(): Int { return userList.size } }
f1e422f40825fd2871d075fb6074d2b39aeaf14c
[ "Kotlin" ]
11
Kotlin
mucahit-sahin/Kotlin-Messenger-Firebase
edaf734faffc7b5fd873d219a123576000702e2e
bce995b81eab9de141e7f4306fff4f7e923cff3c
refs/heads/main
<file_sep># kodi-to-plex Hacked together script that moves watched items from Kodi to a single Plex user <file_sep>#!/usr/bin/python # # Hacked together script that moves watched items from Kodi to a single Plex user # https://github.com/mhoffesommer/kodi-to-plex import sqlite3,os,re from datetime import datetime from imdb import IMDb # filename of source Kodi DB KODI_DB_FN='MyVideos104.db' # filename of target Plex DB PLEX_DB_FN='com.plexapp.plugins.library.db' # ID of target account in plex DB PLEX_ACCT_ID=1 print('Reading Kodi DB...') ia=IMDb() db=sqlite3.connect(KODI_DB_FN) seen_movies=[] # tuple: IMDB ID, datetime seen_episodes=[] # tuple: tvdb ID, datetime, season, episode played=db.execute("select idFile,lastPlayed,strFilename from files where lastPlayed is not null") for cur in played: dt=datetime.fromisoformat(cur[1]) bookmark=db.execute("select timeInSeconds,totalTimeInSeconds from bookmark where idFile=?",(cur[0],)).fetchone() movie=db.execute("select c00 as title,c07 as year,c09 as imdb_id from movie where idFile=?",(cur[0],)).fetchone() if movie: if movie[2]: seen_movies.append((movie[2],dt)) continue i=ia.search_movie('%s (%s)'%(movie[0],movie[1])) if not i: i=ia.search_movie(movie[0]) seen_movies.append(('tt%s'%i[0].movieID,dt)) continue episode=db.execute("select idShow,c12 as season,c13 as episode from episode where idFile=?",(cur[0],)).fetchone() if episode: show=db.execute("select c00 as title,c10 from tvshow where idShow=?",(episode[0],)).fetchone() m=re.search('&quot;id&quot;:([\d]+)}',show[1]) if not m: m=re.search('/series/([\d]+)/',show[1]) if not m: continue seen_episodes.append((m[1],dt,episode[1],episode[2])) continue db.close() print('Found %d watched movies, %d watched episodes'%(len(seen_movies),len(seen_episodes))) print('Adding view items to Plex DB...') db=sqlite3.connect(PLEX_DB_FN) db.row_factory=sqlite3.Row for cur in seen_movies: movie=db.execute('select * from metadata_items where guid=?',('com.plexapp.agents.imdb://%s?lang=en'%cur[0],)).fetchall() if len(movie)!=1: print(' Movie entry for',cur[0],'not found in Plex DB - skipping') continue movie=movie[0] if db.execute('select * from metadata_item_views where account_id=? and guid=?',(PLEX_ACCT_ID,movie['guid'])).fetchall(): continue print('Movie:',movie['title']) db.execute('insert into metadata_item_views(account_id,guid,metadata_type,library_section_id,grandparent_title,'+ 'parent_index,"index",title,thumb_url,viewed_at,grandparent_guid,originally_available_at) values (?,?,?,?,?,?,?,?,?,?,?,?)', (PLEX_ACCT_ID, movie['guid'], movie['metadata_type'], movie['library_section_id'], '', -1, 1, movie['title'], movie['user_thumb_url'], cur[1], '', movie['originally_available_at'])) db.commit() for cur in seen_episodes: episode=db.execute('select * from metadata_items where guid=?',('com.plexapp.agents.thetvdb://%s/%s/%s?lang=en'%(cur[0],cur[2],cur[3]),)).fetchall() if not episode: episode=db.execute('select * from metadata_items where guid like ?',('com.plexapp.agents.thetvdb://%s/%s/%s?%%'%(cur[0],cur[2],cur[3]),)).fetchall() if len(episode)!=1: print(' TV entry for show',cur[0],'not found in Plex DB - skipping') continue episode=episode[0] if db.execute('select * from metadata_item_views where account_id=? and guid=?',(PLEX_ACCT_ID,episode['guid'])).fetchall(): continue season=db.execute('select * from metadata_items where id=?',(episode['parent_id'],)).fetchone() show=db.execute('select * from metadata_items where id=?',(season['parent_id'],)).fetchone() print('TV episode:',show['title'],episode['title']) db.execute('insert into metadata_item_views(account_id,guid,metadata_type,library_section_id,grandparent_title,'+ 'parent_index,"index",title,thumb_url,viewed_at,grandparent_guid,originally_available_at) values (?,?,?,?,?,?,?,?,?,?,?,?)', (PLEX_ACCT_ID, episode['guid'], episode['metadata_type'], episode['library_section_id'], show['title'], cur[2], cur[3], episode['title'], episode['user_thumb_url'], cur[1], show['guid'], episode['originally_available_at'])) db.commit() db.close() print('Done.')
3f64428f6b6ee7b2f187f548364506c3d52e0673
[ "Markdown", "Python" ]
2
Markdown
mhoffesommer/kodi-to-plex
f38ed9a8c7a499d32ecfaaa750c089a31a8f568c
d8a13f579b885df8e6b644822c2b35187c9b5e82
refs/heads/master
<file_sep>import argparse import logging import sqlite3 from collections import Counter from argParseLog import addLoggingArgs, handleLoggingArgs log = logging.getLogger(__name__) if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('-d', '--database', help='The database to read.', default='boardgames.db') ap.add_argument('-u', '--unit', help='List post count by time ago given.', choices=['second', 'minute', 'hour', 'day', 'week', 'month', 'year']) ap.add_argument('-v', '--value', help='How many of the unit to have. i.e. -v 1 -u \'day\'' ' is one day ago.', type=int) ap.add_argument('-c', '--count', help='Number of results to return.', type=int) addLoggingArgs(ap) args = ap.parse_args() handleLoggingArgs(args) db = sqlite3.connect(args.database) # select count(*) from comments where datetime(timestamp, 'unixepoch') > datetime('now', '-1 hour'); then = db.execute("SELECT datetime('now', '-{} {}')".format(args.value, args.unit)).fetchone()[0] rows = db.execute("SELECT cid,username,datetime(timestamp, 'unixepoch') FROM comments WHERE " "datetime(timestamp, 'unixepoch') > datetime('now', '-{} {}')".format( args.value, args.unit)).fetchall() ess = 's' if args.value > 1 else '' print('Found {} comments from the last {} {}{}. Comments newer than {}'.format( len(rows), args.value, args.unit, ess, then)) print('Oldest comment: {}'.format(rows[0][2])) # there is probably an SQL way to do this much much better. c = Counter() for row in rows: c[row[1]] += 1 result_count = len(rows) if not args.count else args.count rank = 1 print(' Rank Count Username') for user, count in c.most_common(result_count): print(' {:3}. {:5} {}'.format(rank, str(count).center(5), user)) rank = rank + 1 <file_sep>import argparse import praw import logging import sqlite3 from praw.helpers import comment_stream from argParseLog import addLoggingArgs, handleLoggingArgs log = logging.getLogger(__name__) if __name__ == '__main__': def_sub = 'boardgames' ap = argparse.ArgumentParser() ap.add_argument('-s', '--subreddit', help='The subreddit to read.', default=def_sub) addLoggingArgs(ap) args = ap.parse_args() handleLoggingArgs(args) log.info('Connecting to reddit.') reddit = praw.Reddit('{} bot that counts user posts in a subreddit. v.0.1' ' by /u/phil_s_stein.') reddit.login() log.info('Logged in.') db = sqlite3.connect('{}.db'.format(args.subreddit)) log.info('Bot database opened/created.') stmt = 'SELECT name FROM sqlite_master WHERE type="table" AND name="comments"' q = db.execute(stmt).fetchall() if not q: log.info('Creating DB tables.') db.execute('CREATE table comments (cid text, username text, timestamp date)') db.execute('CREATE table error (count integer)') log.info('Reading new comments from /r/{}.'.format(args.subreddit)) subreddit = reddit.get_subreddit(args.subreddit) while True: try: for comment in comment_stream(reddit, subreddit): log.debug('read comment {} by {}'.format(comment.id, comment.author)) # log.debug('comment {}'.format(comment.__dict__)) # log.debug('author {}'.format(comment.author.__dict__)) count = db.execute('SELECT COUNT(*) FROM comments WHERE cid=?', (comment.id, )).fetchall()[0][0] if not count or count == 0: log.info('logging comment {} by {}'.format(comment.id, comment.author.name)) db.execute('INSERT into comments VALUES (?, ?, ?)', (comment.id, comment.author.name, comment.created_utc)) db.commit() except Exception as e: log.error('Caught exception: {}'.format(e)) db.execute('UPDATE error set count = count + 1') <file_sep>import logging log = logging.getLogger(__name__) def handleLoggingArgs(args): logLevels = { u'none': 100, u'all': 0, u'debug': logging.DEBUG, u'info': logging.INFO, u'warning': logging.WARNING, u'error': logging.ERROR, u'critical': logging.CRITICAL } log_format = u'%(asctime)s %(name)-12s %(levelname)-8s %(message)s' log_datefmt = u'%m-%d %H:%M:%S' logging.basicConfig(format=log_format, datefmt=log_datefmt, level=logLevels[args.loglevel]) def addLoggingArgs(ap): ap.add_argument("-l", "--loglevel", dest="loglevel", help="The level at which to log. Must be one of " "none, debug, info, warning, error, or critical. Default is none. (" "This is mostly used for debugging.)", default='none', choices=['none', u'all', u'debug', u'info', u'warning', u'error', u'critical'])
58a64731085a2e7ebcc4afaf0f73d0333acaf710
[ "Python" ]
3
Python
philsstein/reddit-comment-counter
d5557d69089de4904fe95c8b81eaa24ab0648ca6
8315551957ce327e65e847de00c2ae6db14d93fa
refs/heads/master
<file_sep>/**************************************** Barebones Lightbox Template by <NAME> <EMAIL> * requires jQuery ****************************************/ // Parse variables from URL function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); } // display the lightbox function lightbox(ajaxContentMPName){ // add lightbox/shadow <div/>'s if not previously added if($('#lightbox').size() == 0){ var theLightbox = $('<div id="lightbox"/>'); var theShadow = $('<div id="lightbox-shadow"/>'); $(theShadow).click(function(e){ closeLightbox(); }); $('body').append(theShadow); $('body').append(theLightbox); } // remove any previously added content $('#lightbox').empty(); // insert AJAX content if(ajaxContentMPName != null){ // temporarily add a "Loading..." message in the lightbox $('#lightbox').append('<p class="loading">Loading...</p>'); url = ajaxContentMPName.split(" "); // request AJAX content $.ajax({ type: 'GET', url: "http://data.parliament.uk/membersdataplatform/services/mnis/members/query/surname*" + url[1] + "%7Cforename*" + url[0] + "%7CMembership=all/Interests%7CConstituencies/", success:function(data){ var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; // remove "Loading..." message and append AJAX content $('#lightbox').empty(); mpdata = data.getElementsByTagName("Members")[0].childNodes[0]; mpdatafullname = mpdata.getElementsByTagName("FullTitle")[0].childNodes[0].nodeValue; mpdataparty = mpdata.getElementsByTagName("Party")[0].childNodes[0].nodeValue; mpdataconstituency = mpdata.getElementsByTagName("MemberFrom")[0].childNodes[0].nodeValue; mpdatampsince = mpdata.getElementsByTagName("HouseStartDate")[0].childNodes[0].nodeValue; mpdatampinterests = mpdata.getElementsByTagName("Interests")[0].getElementsByTagName("Category"); mpdatampConstituencyPosts = mpdata.getElementsByTagName("Constituencies")[0].getElementsByTagName("Constituency"); var posts = ""; for (i=0; i<mpdatampConstituencyPosts.length; i++) { if (mpdatampConstituencyPosts[i].getElementsByTagName("EndDate")[0].childNodes[0] == undefined) { enddate = "current"; } else { enddate = new Date(mpdatampConstituencyPosts[i].getElementsByTagName("EndDate")[0].childNodes[0].nodeValue); enddate = enddate.getDate() + " " + monthNames[enddate.getMonth()] + " " + enddate.getFullYear(); } startdate = new Date(mpdatampConstituencyPosts[i].getElementsByTagName("StartDate")[0].childNodes[0].nodeValue); posts += "<p>" + mpdatampConstituencyPosts[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue; posts += " from " + startdate.getDate() + " " + monthNames[startdate.getMonth()] + " " + startdate.getFullYear(); posts += " to " + enddate + "</p>"; } var interests = "<h3>Registered Financial Interests</h3><ul>"; if (mpdatampinterests.length > 0) { for (i=0; i<mpdatampinterests.length; i++) { interests += "<li>Category:" + mpdatampinterests[i].getAttribute("Name")+"<ul>"; for (j=0; j<mpdatampinterests[i].childNodes.length; j++) { if(mpdatampinterests[i].childNodes[j]>0) { interests += "<li>" + mpdatampinterests[i].childNodes[j].getElementsByTagName("RegisteredInterest")[0].childNodes[0].nodeValue + "</li>"; } } interests += "</ul></li>"; } interests += "</ul>"; } else { interests += "<p>No registered financial interests for these dates." } since = new Date(mpdatampsince); //until = new Date() mpoutput = "<div id='lightboxcontent'>"; mpoutput += "<div style='position:absolute; top:10px; right:10px'><a id='closebutton' href='#' onclick='closeLightbox()'>Close</a></div>"; mpoutput += "<h1>"+mpdatafullname+"</h1>"; mpoutput += "<h4>Party: "+mpdataparty+"</h4>"; mpoutput += posts; mpoutput += "<h3>Expenses Change Over the Past 3 Years</h3>"; mpoutput += "<div id='lightbox-line-chart'></div>"; mpoutput += "<p><a href='#'>Download this data</a></p>"; mpoutput += interests; mpoutput += "</div>"; $('#lightbox').append(mpoutput); lightboxlinechart(ajaxContentMPName); if($('#lightbox').height()<window.innerHeight) { shadowheight = window.innerHeight; } else { shadowheight = $('#lightbox').height() + $('#navbar').height() + 50; } $('#lightbox-shadow').height(shadowheight); }, error:function(){ alert('AJAX Failure!'); } }); } // move the lightbox to the current window top + 100px $('#lightbox').css('top', $(window).scrollTop() + 50 + 'px'); $('#lightbox').width( window.innerWidth - 100 + 'px'); // display the lightbox $('#lightbox').show(); $('#lightbox-shadow').show(); $('#lightbox-shadow').height($('#lightbox').height+1000); $(document).keyup(function(e) { if (e.keyCode == 27) { // esc keycode closeLightbox() } }); } // close the lightbox function closeLightbox(){ // hide lightbox and shadow <div/>'s $('#lightbox').hide(); $('#lightbox-shadow').hide(); // remove contents of lightbox in case a video or other content is actively playing $('#lightbox').empty(); }
0a336e6d79e7d2261e77a58b366a896c76a78a81
[ "JavaScript" ]
1
JavaScript
dttaggoram/eu_ref
67adf942e1bef624429b8923a3acd1c582793d96
be541226a04b61873aa19cff3ed49a114d734254
refs/heads/main
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; /** * * @author Philip */ @Entity @SequenceGenerator(name = "routeseq", sequenceName = "route_seq", initialValue = 1, allocationSize = 1) public class Route { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "routeseq") private long id; private String source; private String destination; @OneToMany(mappedBy = "route") private List<CompanyRoute> companies = new ArrayList<>(); @OneToMany(mappedBy = "route") private List<Journey> journeys = new ArrayList<>(); @Enumerated(EnumType.STRING) private Status status; public Route() { } public Route(String source, String destination, Status status) { this.source = source; this.destination = destination; this.status = status; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public List<CompanyRoute> getCompanies() { return companies; } public void setCompanies(List<CompanyRoute> companies) { this.companies = companies; } public List<Journey> getJourneys() { return journeys; } public void setJourneys(List<Journey> journeys) { this.journeys = journeys; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package testing; import dao.DBUtil; import dao.GeneralDao; import dao.PassengerDao; import java.util.Date; import java.util.List; import javax.servlet.Registration; import model.AccountState; import model.AdminAccount; import model.Company; import model.CompanyRoute; import model.CompanyState; import model.Gender; import model.Journey; import model.Manager; import model.ManagerAccount; import model.Passenger; import model.Route; import model.Status; import model.Ticket; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * * @author Philip */ public class IntTest extends DBSetupConfig { GeneralDao<Company> studentDao = new GeneralDao<>(); GeneralDao<CompanyRoute> comRouteDao = new GeneralDao<>(); GeneralDao<AdminAccount> adminAccDao = new GeneralDao<>(); GeneralDao<Manager> managerDao = new GeneralDao<>(); GeneralDao<ManagerAccount> managerAccDao = new GeneralDao<>(); GeneralDao<CompanyState> companyStateDao = new GeneralDao<>(); GeneralDao<Company> companyDao = new GeneralDao<>(); GeneralDao<Route> routeDao = new GeneralDao<>(); GeneralDao<AccountState> accStateDao = new GeneralDao<>(); GeneralDao<Ticket> ticketDao = new GeneralDao<>(); GeneralDao<Passenger> passengerDao = new GeneralDao<>(); PassengerDao passDao = new PassengerDao(); GeneralDao<Journey> journeyDao = new GeneralDao<>(); @BeforeTest public void init() { DBUtil.getSessionFactory(); System.out.println("Tables created"); } @BeforeMethod public void initializeTest() { executeOperation(TestData.INSERT_ADMIN_ACCOUNT); executeOperation(TestData.INSERT_MANAGER); executeOperation(TestData.INSERT_COMPANY); executeOperation(TestData.INSERT_COMPANY_STATE); executeOperation(TestData.INSERT_MANAGER_ACCOUNT); executeOperation(TestData.INSERT_ACCOUNT_STATE); executeOperation(TestData.INSERT_ROUTE); executeOperation(TestData.INSERT_COMPANY_ROUTE); executeOperation(TestData.INSERT_JOURNEY); executeOperation(TestData.INSERT_PASSENGER); executeOperation(TestData.INSERT_TICKET); System.out.println("test initialized"); } @AfterMethod public void cleanTestData() { executeOperation(TestData.DELETE_TICKET); executeOperation(TestData.DELETE_PASSENGER); executeOperation(TestData.DELETE_JOURNEY); executeOperation(TestData.DELETE_COMPANY_ROUTE); executeOperation(TestData.DELETE_ROUTE); executeOperation(TestData.DELETE_ACCOUNT_STATE); executeOperation(TestData.DELETE_MANAGER_ACCOUNT); executeOperation(TestData.DELETE_COMPANY_STATE); executeOperation(TestData.DELETE_COMPANY); executeOperation(TestData.DELETE_MANAGER); executeOperation(TestData.DELETE_ADMIN_ACCOUNT); executeOperation(TestData.DELETE_TICKET); System.out.println("test data cleaned"); } @Test public void testCreateRoute() { String result = routeDao.create(new Route("kayonza", "huye", Status.ACTIVE)); Assert.assertEquals(result, "created"); System.out.println("route created"); } @Test public void testReadRoutes() { List<Journey> routelist = journeyDao.findAll(new Journey()); Assert.assertEquals(routelist.size(), 2); System.out.println("routes viewed"); } @Test public void testUpdateRoute() { Route route = routeDao.findOne(Route.class, 100L); route.setSource("nosource"); String result = routeDao.update(route); Assert.assertEquals(result, "updated"); System.out.println("route updated"); } @Test public void testDeleteRoute() { Route route = routeDao.findOne(Route.class, 100L); String result = routeDao.delete(route); Assert.assertEquals(result, "deleted"); System.out.println("route deleted"); } // @Test(expectedExceptions = {NullPointerException.class}) // public void testWrongCourseCode() { // Course course = courseDao.findOne(Course.class, "c11"); // course.getName(); // System.out.println("wrong course tested"); // } @Test public void testReadTickets() { List<Ticket> ticketlist = ticketDao.findAll(new Ticket()); Assert.assertEquals(ticketlist.size(), 2); System.out.println("tickets viewed"); } @Test public void testUpdateTicket() { Ticket ticket = ticketDao.findOne(Ticket.class, 1L); ticket.setAmount(2000); String result = ticketDao.update(ticket); Assert.assertEquals(result, "updated"); System.out.println("tickets updated"); } @Test public void testDeleteTicket() { Ticket ticket = ticketDao.findOne(Ticket.class, 1L); String result = ticketDao.delete(ticket); Assert.assertEquals(result, "deleted"); System.out.println("ticket deleted"); } @Test public void testReadJourney() { List<Journey> journeylist = journeyDao.findAll(new Journey()); Assert.assertEquals(journeylist.size(), 2); System.out.println("journeys viewed"); } @Test public void testUpdateJourney() { Journey journey = journeyDao.findOne(Journey.class, 1L); journey.setPrice(2000); String result = journeyDao.update(journey); Assert.assertEquals(result, "updated"); System.out.println("journey updated"); } @Test public void testDeleteJourney() { Journey journey = journeyDao.findOne(Journey.class, 1L); String result = journeyDao.delete(journey); Assert.assertEquals(result, "deleted"); System.out.println("Journey deleted"); } // @Test // public void testCreateStudent() { // String result = studentDao.create(new Student("21100", "blue", Gender.MALE, new Date(2000, 05, 23))); // Assert.assertEquals(result, "success"); // System.out.println("student created"); // } // // @Test // public void testReadStudents() { // List<Student> studentlist = studentDao.findAll(new Student()); // Assert.assertEquals(studentlist.size(), 3); // System.out.println("students viewed"); // } // // @Test // public void testUpdateStudent() { // Student student = studentDao.findOne(Student.class, "21208"); // student.setName("philip"); // String result = studentDao.update(student); // Assert.assertEquals(result, "success"); // System.out.println("student updated"); // } // // @Test(expectedExceptions = {NullPointerException.class}) // public void testFindWrongStudent() { // Student student = studentDao.findOne(Student.class, "111111"); // student.getName(); // System.out.println("student not found"); // } // // @Test // public void testDeleteStudent() { // Student student = studentDao.findOne(Student.class, "21208"); // List<Registration> registrations = registrationDao.findbyStudent(Registration.class, "21208"); // registrations.forEach((reg) -> { // registrationDao.delete(reg); // }); // String result = studentDao.delete(student); // Assert.assertEquals(result, "success"); // System.out.println("student deleted"); // } // // // // @Test // public void testCreateRegistration() { // Student student = studentDao.findOne(Student.class, "21208"); // Course course = courseDao.findOne(Course.class, "INSY312"); // String result = registrationDao.create(new Registration(24L, student, course)); // Assert.assertEquals(result, "success"); // System.out.println("registered successfully"); // } // // @Test // public void testReadRegistration() { // List<Registration> registrations = registrationDao.findAll(new Registration()); // Assert.assertEquals(registrations.size(), 3); // System.out.println("registrations viewed"); // } // // @Test // public void testUpdateRegistration() { // Student student = studentDao.findOne(Student.class, "21179"); // Registration registration = registrationDao.findOne(Registration.class, 24L); // registration.setStudent(student); // String result = registrationDao.update(registration); // Assert.assertEquals(result, "success"); // System.out.println("registration updated"); // } // // @Test // public void testDeleteRegistration() { // Registration registration = registrationDao.findRegistration(Registration.class, 24L); // String result = registrationDao.delete(registration); // Assert.assertEquals(result, "success"); // System.out.println("registration deleted"); // } // // @Test(expectedExceptions = {NullPointerException.class}) // public void testDeleteWrongRegistration() { // Registration registration = registrationDao.findRegistration(Registration.class, 4L); // registration.getCourse(); // System.out.println("wrong registration"); // } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Temporal; /** * * @author Philip */ @Entity @SequenceGenerator(name="companystateseq", sequenceName = "companystate_seq", initialValue = 1,allocationSize = 1) public class CompanyState { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="companystateseq") private Long id; @Enumerated(EnumType.STRING) private CompanyStatus companyStatus; @ManyToOne private Company company; @OneToOne private AdminAccount doneBy; @Temporal(javax.persistence.TemporalType.DATE) private Date updateOn; public CompanyState() { } public CompanyState(CompanyStatus companyStatus, Company company, AdminAccount doneBy, Date updateOn) { this.companyStatus = companyStatus; this.company = company; this.doneBy = doneBy; this.updateOn = updateOn; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public CompanyStatus getCompanyStatus() { return companyStatus; } public void setCompanyStatus(CompanyStatus companyStatus) { this.companyStatus = companyStatus; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public AdminAccount getDoneBy() { return doneBy; } public void setDoneBy(AdminAccount doneBy) { this.doneBy = doneBy; } public Date getUpdateOn() { return updateOn; } public void setUpdateOn(Date updateOn) { this.updateOn = updateOn; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package testing; import com.ninja_squad.dbsetup.DbSetup; import com.ninja_squad.dbsetup.destination.DriverManagerDestination; import com.ninja_squad.dbsetup.operation.Operation; /** * * @author Philip */ public class DBSetupConfig { public void executeOperation(Operation operation) { DbSetup dbSetup = new DbSetup(new DriverManagerDestination( "jdbc:postgresql://localhost:5432/boobus", "postgres", "philip12"), operation); dbSetup.launch(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import javax.persistence.Column; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.MappedSuperclass; /** * * @author Philip */ @MappedSuperclass public class Account { private String email; private String password; @Enumerated(EnumType.STRING) @Column(name = "account_role") private Role accountRole; @Column(nullable = false) @Enumerated(EnumType.STRING) private AccountStatus accountStatus; 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 AccountStatus getAccountStatus() { return accountStatus; } public void setAccountStatus(AccountStatus accountStatus) { this.accountStatus = accountStatus; } public Role getAccountRole() { return accountRole; } public void setAccountRole(Role accountRole) { this.accountRole = accountRole; } } <file_sep>package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import model.Route; import java.util.List; import dao.GeneralDao; import model.Company; public final class routes_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html lang=\"en\">\n"); out.write(" <head>\n"); out.write(" <meta charset=\"utf-8\" />\n"); out.write(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n"); out.write(" <link rel=\"stylesheet\" href=\"assets/tailwind.css\">\n"); out.write(" <link rel=\"stylesheet\" href=\"assets/css/bootstrap.min.css\">\n"); out.write(" </head>\n"); out.write(" <body class=\"h-screen overflow-hidden flex items-center justify-start\" style=\"background: #edf2f7\">\n"); out.write(" "); GeneralDao<Company> companyDao = new GeneralDao<>(); GeneralDao<Route> routeDao = new GeneralDao<>(); List<Company> companylist = companyDao.findAll(new Company()); List<Route> routes = routeDao.findAll(new Route()); out.write("\n"); out.write(" <script\n"); out.write(" src=\"https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js\"\n"); out.write(" defer\n"); out.write(" ></script>\n"); out.write("\n"); out.write(" <div class=\"bg-gray-200 font-sans\">\n"); out.write(" <div class=\"flex flex-col sm:flex-row sm:justify-around\">\n"); out.write(" <div class=\"w-64 h-screen bg-gray-800\">\n"); out.write(" <div class=\"flex items-center justify-center mt-10\">\n"); out.write(" <!--<img class=\"h-6\" src=\"https://premium-tailwindcomponents.netlify.app/assets/svg/tailwindcomponent-light.svg\">--> \n"); out.write(" </div>\n"); out.write("\n"); out.write(" <nav class=\"mt-10\">\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M19 11H5M19 11C20.1046 11 21 11.8954 21 13V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V13C3 11.8954 3.89543 11 5 11M19 11V9C19 7.89543 18.1046 7 17 7M5 11V9C5 7.89543 5.89543 7 7 7M7 7V5C7 3.89543 7.89543 3 9 3H15C16.1046 3 17 3.89543 17 5V7M7 7H17\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Dashboard</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >Manage Accounts</a\n"); out.write(" >\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M16 7C16 9.20914 14.2091 11 12 11C9.79086 11 8 9.20914 8 7C8 4.79086 9.79086 3 12 3C14.2091 3 16 4.79086 16 7Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" d=\"M12 14C8.13401 14 5 17.134 5 21H19C19 17.134 15.866 14 12 14Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Journeys</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\">Add Journey\n"); out.write(" </a\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\">All Journey\n"); out.write(" </a\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M15 5V7M15 11V13M15 17V19M5 5C3.89543 5 3 5.89543 3 7V10C4.10457 10 5 10.8954 5 12C5 13.1046 4.10457 14 3 14V17C3 18.1046 3.89543 19 5 19H19C20.1046 19 21 18.1046 21 17V14C19.8954 14 19 13.1046 19 12C19 10.8954 19.8954 10 21 10V7C21 5.89543 20.1046 5 19 5H5Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Tickets</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >All Tickets</a\n"); out.write(" >\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >Create Ticket</a\n"); out.write(" >\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </nav>\n"); out.write("\n"); out.write(" <div class=\"absolute bottom-0 my-8\">\n"); out.write(" <a\n"); out.write(" class=\"flex items-center py-2 px-8 text-gray-100 hover:text-gray-200\"\n"); out.write(" href=\"#\"\n"); out.write(" >\n"); out.write(" <img\n"); out.write(" class=\"h-6 w-6 rounded-full mr-3 object-cover\"\n"); out.write(" src=\"https://lh3.googleusercontent.com/a-/AOh14Gi0DgItGDTATTFV6lPiVrqtja6RZ_qrY91zg42o-g\"\n"); out.write(" alt=\"avatar\"\n"); out.write(" />\n"); out.write(" <span>Khatabwedaa</span>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write("\n"); out.write(" <!-- <div class=\"grid w-full min-h-screen place-items-center\"> -->\n"); out.write("\n"); out.write("\n"); out.write(" <div class=\"overflow-x-auto bg-white w-5/6 h-screen mt-0 md:mt-0 md:col-span-2 view-routes\" id=\"admin-tab\">\n"); out.write(" "); if (request.getAttribute("message") != null) { String message = (String) request.getAttribute("message"); out.write("\n"); out.write(" <div class=\"container px-4 py-1\" id=\"alertbox\">\n"); out.write(" <div class=\"container bg-blue-500 flex items-center text-white text-sm font-bold px-4 py-3 relative\"\n"); out.write(" role=\"alert\">\n"); out.write(" <svg class=\"fill-current w-4 h-4 mr-2\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\">\n"); out.write(" <path\n"); out.write(" d=\"M12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-1.058 0-1.833-.652-1.093-3.524l1.214-5.092c.211-.814.246-1.141 0-1.141-.317 0-1.689.562-2.502 1.117l-.528-.88c2.572-2.186 5.531-3.467 6.801-3.467 1.057 0 1.233 1.273.705 3.23l-1.391 5.352c-.246.945-.141 1.271.106 1.271.317 0 1.357-.392 2.379-1.207l.6.814C12.098 19.02 9.365 20 8.309 20z\" />\n"); out.write(" </svg>\n"); out.write(" <p>"); out.print(message); out.write("</p>\n"); out.write("\n"); out.write(" <span class=\"absolute top-0 bottom-0 right-0 px-4 py-3 closealertbutton\">\n"); out.write(" <svg class=\"fill-current h-6 w-6 text-white\" role=\"button\" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" viewBox=\"0 0 20 20\">\n"); out.write(" <title>Close</title>\n"); out.write(" <path\n"); out.write(" d=\"M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z\" />\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" "); } out.write("\n"); out.write(" <form action=\"RoutesControl\" method=\"POST\">\n"); out.write(" <h3 class=\"block text-base text-center font-medium text-gray-700\"> Add Route</h3>\n"); out.write(" <div class=\"flex flex-col items-center shadow overflow-hidden sm:rounded-md\">\n"); out.write(" <div class=\"px-4 py-5 sm:p-6\">\n"); out.write(" <div class=\"grid grid-cols-6 gap-6\">\n"); out.write(" <div class=\"col-span-6 sm:col-span-3\">\n"); out.write(" <label for=\"source\" class=\"block text-sm font-medium text-gray-700\">First name</label>\n"); out.write(" <input type=\"text\" name=\"source\" id=\"source\" class=\"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md\">\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div class=\"col-span-6 sm:col-span-3\">\n"); out.write(" <label for=\"destination\" class=\"block text-sm font-medium text-gray-700\">Last name</label>\n"); out.write(" <input type=\"text\" name=\"destination\" id=\"destination\" class=\"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md\">\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <input type=\"text\" name=\"action\" hidden=\"\" value=\"addroute\">\n"); out.write(" <div class=\"px-4 py-3 bg-gray-50 text-right sm:px-6\">\n"); out.write(" <button type=\"submit\" class=\"inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\">\n"); out.write(" Save\n"); out.write(" </button>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </form>\n"); out.write(" <h3 class=\"block text-base text-center font-medium text-gray-700 py-3\"> All Routes</h3>\n"); out.write(" <table class=\"min-w-max w-full table-auto\">\n"); out.write(" <thead>\n"); out.write(" <tr class=\"bg-gray-200 text-gray-600 uppercase text-sm leading-normal\">\n"); out.write(" <th class=\"py-3 px-6 text-left\">Route Id</th>\n"); out.write(" <th class=\"py-3 px-6 text-left\">Source</th>\n"); out.write(" <th class=\"py-3 px-6 text-left\">Destination</th>\n"); out.write(" <th class=\"py-3 px-6 text-center\">Actions</th>\n"); out.write(" </tr>\n"); out.write(" </thead>\n"); out.write(" <tbody class=\"text-gray-600 text-sm font-light\">\n"); out.write(" "); for (Route route : routes) { out.write("\n"); out.write(" <tr class=\"border-b border-gray-200 hover:bg-gray-100\">\n"); out.write(" <td class=\"py-3 px-6 text-left whitespace-nowrap font-medium\">#"); out.print(route.getId()); out.write("</td>\n"); out.write(" <td class=\"py-3 px-6 text-left text-blue-600 whitespace-nowrap font-medium\">"); out.print(route.getSource()); out.write("</td>\n"); out.write(" <td class=\"py-3 px-6 text-left text-purple-600 whitespace-nowrap font-medium\">"); out.print(route.getDestination()); out.write("</td>\n"); out.write(" <td class=\"py-3 px-6 text-center\">\n"); out.write(" <div class=\"flex item-center justify-center\">\n"); out.write(" <a href=\"updateroute.jsp?id="); out.print(route.getId()); out.write("\">\n"); out.write(" <div class=\"w-4 mr-2 transform hover:text-purple-500 hover:scale-110\">\n"); out.write(" <svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n"); out.write(" <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z\" />\n"); out.write(" </svg>\n"); out.write(" </div></a>\n"); out.write(" <div class=\"w-4 mr-2 transform hover:text-purple-500 hover:scale-110\">\n"); out.write(" <svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n"); out.write(" <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16\" />\n"); out.write(" </svg>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </td>\n"); out.write(" </tr>\n"); out.write(" "); } out.write("\n"); out.write(" </tbody>\n"); out.write(" </table>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <!-- </div> -->\n"); out.write(" <script src=\"assets/js/vendor/jquery-1.12.4.min.js\"\n"); out.write(" \n"); out.write(" </script>\n"); out.write(" <script src=\"./assets/js/bootstrap.min.js\"></script>\n"); out.write("\n"); out.write("\n"); out.write(" <script>\n"); out.write(" function openMenu(evt, MenuName) {\n"); out.write(" var i, x, tablinks;\n"); out.write(" x = document.getElementsByClassName(\"admin-tab\");\n"); out.write(" for (i = 0; i < x.length; i++) {\n"); out.write(" x[i].style.display = \"none\";\n"); out.write(" }\n"); out.write(" document.getElementById(MenuName).style.display = \"block\";\n"); out.write(" evt.currentTarget.className += \" w3-grey\";\n"); out.write(" }\n"); out.write(" $(\".closealertbutton\").click(function (e) {\n"); out.write("\n"); out.write(" pid = $(this).parent().parent().hide(500)\n"); out.write(" console.log(pid)\n"); out.write(" })\n"); out.write(" if (window.history.replaceState) {\n"); out.write(" window.history.replaceState(null, null, window.location.href);\n"); out.write(" }\n"); out.write(" </script>\n"); out.write(" </body>\n"); out.write("</html>\n"); out.write("\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; /** * * @author Philip */ @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @SequenceGenerator(name="claccountseq", sequenceName = "claccount_seq", initialValue = 1,allocationSize = 1) public class ManagerAccount extends Account { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="claccountseq") private long id; @OneToOne private Manager manager; @OneToMany(mappedBy = "managerAccount") private List<AccountState> accountState = new ArrayList<>(); @OneToOne private Company company; public long getId() { return id; } public void setId(long id) { this.id = id; } public Manager getManager() { return manager; } public void setManager(Manager manager) { this.manager = manager; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public List<AccountState> getAccountState() { return accountState; } public void setAccountState(List<AccountState> accountState) { this.accountState = accountState; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.GeneralDao; import dao.RouteDao; import java.io.IOException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Company; import model.CompanyRoute; import model.ManagerAccount; import model.Route; import model.RouteStatus; import model.Status; /** * * @author Philip */ @WebServlet(name = "RoutesControl", urlPatterns = {"/RoutesControl"}) public class RoutesControl extends HttpServlet { GeneralDao<Route> routeDao = new GeneralDao<>(); GeneralDao<CompanyRoute> CRDao = new GeneralDao<>(); Route route; CompanyRoute companyRoute; RequestDispatcher dispatcher; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); switch (action) { case "request": RouteDao rdao = new RouteDao(); long id = Long.parseLong(request.getParameter("id")); route = routeDao.findOne(Route.class, id); ManagerAccount account = (ManagerAccount) request.getSession().getAttribute("user"); Company company = account.getCompany(); boolean status = rdao.checkRouteRequest(company.getId(), id); System.out.println("status is :" + status); if (status) { request.setAttribute("message", "request has been sent before!!"); dispatcher = request.getRequestDispatcher("requestroute.jsp"); dispatcher.forward(request, response); } else { CompanyRoute companyRoute = new CompanyRoute(); companyRoute.setRoute(route); companyRoute.setCompany(company); companyRoute.setRouteStatus(RouteStatus.REQUESTED); Timestamp ts = new Timestamp(new Date().getTime()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); companyRoute.setRegisteredDate(Timestamp.valueOf(formatter.format(ts))); CRDao.create(companyRoute); request.setAttribute("message", "request sent!!"); dispatcher = request.getRequestDispatcher("requestroute.jsp"); dispatcher.forward(request, response); } break; case "approve": companyRoute = CRDao.findOne(CompanyRoute.class, Long.parseLong(request.getParameter("id"))); companyRoute.setRouteStatus(RouteStatus.APPROVED); CRDao.update(companyRoute); request.setAttribute("message", "route request is approved successfully"); dispatcher = request.getRequestDispatcher("requestedroutes.jsp"); dispatcher.forward(request, response); break; case "suspend": companyRoute = CRDao.findOne(CompanyRoute.class, Long.parseLong(request.getParameter("id"))); companyRoute.setRouteStatus(RouteStatus.SUSPENDED); CRDao.update(companyRoute); request.setAttribute("message", "route is successfully suspended"); dispatcher = request.getRequestDispatcher("requestedroutes.jsp"); dispatcher.forward(request, response); break; default: System.out.println("no action specified"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); switch (action) { case "addroute": route = new Route(); route.setSource(request.getParameter("source")); route.setDestination(request.getParameter("destination")); route.setStatus(Status.valueOf(request.getParameter("status"))); routeDao.create(route); request.setAttribute("message", "route added successfully!!!"); dispatcher = request.getRequestDispatcher("routes.jsp"); dispatcher.forward(request, response); break; case "updateroute": route = routeDao.findOne(Route.class, Long.parseLong(request.getParameter("id"))); route.setSource(request.getParameter("source")); route.setDestination(request.getParameter("destination")); route.setStatus(Status.valueOf(request.getParameter("status"))); routeDao.update(route); request.setAttribute("message", "route updated successfully!!!"); dispatcher = request.getRequestDispatcher("routes.jsp"); dispatcher.forward(request, response); break; default: System.out.println("no action specified"); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import model.CompanyRoute; import model.Journey; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; /** * * @author Philip */ public class JourneyDao { SessionFactory sf=DBUtil.getSessionFactory(); Session session=null; public List<Journey> getCompanyJourneys(long id) { session = sf.openSession(); Query query = session.createQuery("FROM Journey where company_id='"+id+"'" ); List<Journey> companyJourneys = (List<Journey>) query.list(); session.close(); return companyJourneys; } //check previous request public boolean checkRouteRequest(long company_id, long route_id) { session = sf.openSession(); Query query = session.createQuery("FROM CompanyRoute where company_id='"+company_id+"' and route_id='"+route_id+"'" ); CompanyRoute companyRoute = (CompanyRoute) query.uniqueResult(); session.close(); try { long id = companyRoute.getId(); return true; } catch (NullPointerException e) { return false; } } public List<CompanyRoute> approvedRoutes(long id) { session = sf.openSession(); Query query = session.createQuery("FROM CompanyRoute where company_id='"+id+"' and routestatus='APPROVED'" ); List<CompanyRoute> companyRoutes = (List<CompanyRoute>) query.list(); session.close(); return companyRoutes; } public List<Journey> availableJourneys(long id) { session = sf.openSession(); Query query = session.createQuery("FROM Journey where route_id='"+id+"' and journeystatus='BOOKING'" ); List<Journey> journeys = (List<Journey>) query.list(); session.close(); return journeys; } } <file_sep>package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.List; import dao.GeneralDao; import model.Company; public final class updateroute_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write('\n'); out.write('\n'); out.write('\n'); out.write('\n'); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html lang=\"en\">\n"); out.write(" <head>\n"); out.write(" <meta charset=\"utf-8\" />\n"); out.write(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n"); out.write(" <link rel=\"stylesheet\" href=\"assets/tailwind.css\">\n"); out.write(" </head>\n"); out.write(" <body class=\"h-screen overflow-hidden flex items-center justify-start\" style=\"background: #edf2f7\">\n"); out.write(" "); // GeneralDao<Company> companyDao = new GeneralDao<>(); // List<Company> companylist = companyDao.findAll(new Company()); out.write("\n"); out.write(" <script\n"); out.write(" src=\"https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js\"\n"); out.write(" defer\n"); out.write(" ></script>\n"); out.write("\n"); out.write(" <div class=\"bg-gray-200 font-sans\">\n"); out.write(" <div class=\"flex flex-col sm:flex-row sm:justify-around\">\n"); out.write(" <div class=\"w-64 h-screen bg-gray-800\">\n"); out.write(" <div class=\"flex items-center justify-center mt-10\">\n"); out.write(" <!--<img class=\"h-6\" src=\"https://premium-tailwindcomponents.netlify.app/assets/svg/tailwindcomponent-light.svg\">--> \n"); out.write(" </div>\n"); out.write("\n"); out.write(" <nav class=\"mt-10\">\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M19 11H5M19 11C20.1046 11 21 11.8954 21 13V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V13C3 11.8954 3.89543 11 5 11M19 11V9C19 7.89543 18.1046 7 17 7M5 11V9C5 7.89543 5.89543 7 7 7M7 7V5C7 3.89543 7.89543 3 9 3H15C16.1046 3 17 3.89543 17 5V7M7 7H17\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Dashboard</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\" onclick=\"openMenu(event, 'view-routes')\"\n"); out.write(" >Manage Routes</a\n"); out.write(" >\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >Manage Administrators</a\n"); out.write(" >\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M16 7C16 9.20914 14.2091 11 12 11C9.79086 11 8 9.20914 8 7C8 4.79086 9.79086 3 12 3C14.2091 3 16 4.79086 16 7Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" d=\"M12 14C8.13401 14 5 17.134 5 21H19C19 17.134 15.866 14 12 14Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Companies</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" \n"); out.write("\n"); out.write("\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div x-data=\"{ open: false }\">\n"); out.write(" <button\n"); out.write(" @click=\"open = !open\"\n"); out.write(" class=\"w-full flex justify-between items-center py-3 px-6 text-gray-100 cursor-pointer hover:bg-gray-700 hover:text-gray-100 focus:outline-none\"\n"); out.write(" >\n"); out.write(" <span class=\"flex items-center\">\n"); out.write(" <svg\n"); out.write(" class=\"h-5 w-5\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" d=\"M15 5V7M15 11V13M15 17V19M5 5C3.89543 5 3 5.89543 3 7V10C4.10457 10 5 10.8954 5 12C5 13.1046 4.10457 14 3 14V17C3 18.1046 3.89543 19 5 19H19C20.1046 19 21 18.1046 21 17V14C19.8954 14 19 13.1046 19 12C19 10.8954 19.8954 10 21 10V7C21 5.89543 20.1046 5 19 5H5Z\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write("\n"); out.write(" <span class=\"mx-4 font-medium\">Tickets</span>\n"); out.write(" </span>\n"); out.write("\n"); out.write(" <span>\n"); out.write(" <svg\n"); out.write(" class=\"h-4 w-4\"\n"); out.write(" viewBox=\"0 0 24 24\"\n"); out.write(" fill=\"none\"\n"); out.write(" xmlns=\"http://www.w3.org/2000/svg\"\n"); out.write(" >\n"); out.write(" <path\n"); out.write(" x-show=\"! open\"\n"); out.write(" d=\"M9 5L16 12L9 19\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" style=\"display: none\"\n"); out.write(" ></path>\n"); out.write(" <path\n"); out.write(" x-show=\"open\"\n"); out.write(" d=\"M19 9L12 16L5 9\"\n"); out.write(" stroke=\"currentColor\"\n"); out.write(" stroke-width=\"2\"\n"); out.write(" stroke-linecap=\"round\"\n"); out.write(" stroke-linejoin=\"round\"\n"); out.write(" ></path>\n"); out.write(" </svg>\n"); out.write(" </span>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div x-show=\"open\" class=\"bg-gray-700\">\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >All Tickets</a\n"); out.write(" >\n"); out.write(" <a\n"); out.write(" class=\"py-2 px-16 block text-sm text-gray-100 hover:bg-blue-500 hover:text-white\"\n"); out.write(" href=\"#\"\n"); out.write(" >Create Ticket</a\n"); out.write(" >\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </nav>\n"); out.write("\n"); out.write(" <div class=\"absolute bottom-0 my-8\">\n"); out.write(" <a\n"); out.write(" class=\"flex items-center py-2 px-8 text-gray-100 hover:text-gray-200\"\n"); out.write(" href=\"#\"\n"); out.write(" >\n"); out.write(" <img\n"); out.write(" class=\"h-6 w-6 rounded-full mr-3 object-cover\"\n"); out.write(" src=\"https://lh3.googleusercontent.com/a-/AOh14Gi0DgItGDTATTFV6lPiVrqtja6RZ_qrY91zg42o-g\"\n"); out.write(" alt=\"avatar\"\n"); out.write(" />\n"); out.write(" <span>Khatabwedaa</span>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write("\n"); out.write(" <!-- <div class=\"grid w-full min-h-screen place-items-center\"> -->\n"); out.write(" \n"); out.write(" <div class=\"overflow-x-auto bg-white w-5/6 h-screen mt-0 md:mt-0 md:col-span-2 view-routes\" id=\"admin-tab\">\n"); out.write(" <form action=\"#\" method=\"POST\">\n"); out.write(" <h3 class=\"block text-base text-center font-medium text-gray-700\"> Add Route</h3>\n"); out.write(" <div class=\"flex flex-col items-center shadow overflow-hidden sm:rounded-md\">\n"); out.write(" <div class=\"px-4 py-5 sm:p-6\">\n"); out.write(" <div class=\"grid grid-cols-6 gap-6\">\n"); out.write(" <div class=\"col-span-6 sm:col-span-3\">\n"); out.write(" <label for=\"id\" class=\"block text-sm font-medium text-gray-700\">id</label>\n"); out.write(" <input type=\"number\" name=\"id\" id=\"id\" value=\"\" autocomplete=\"given-name\" class=\"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md\">\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div class=\"col-span-6 sm:col-span-3\">\n"); out.write(" <label for=\"id\" class=\"block text-sm font-medium text-gray-700\">source</label>\n"); out.write(" <input type=\"number\" name=\"source\" id=\"source\" value=\"\" class=\"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md\">\n"); out.write(" </div>\n"); out.write(" \n"); out.write(" <div class=\"col-span-6 sm:col-span-3\">\n"); out.write(" <label for=\"id\" class=\"block text-sm font-medium text-gray-700\">destination</label>\n"); out.write(" <input type=\"number\" name=\"destination\" id=\"destination\" value=\"\" class=\"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md\">\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"px-4 py-3 bg-gray-50 text-right sm:px-6\">\n"); out.write(" <button type=\"submit\" class=\"inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\">\n"); out.write(" Save\n"); out.write(" </button>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" \n"); out.write(" <!-- </div> -->\n"); out.write(" \n"); out.write(" </body>\n"); out.write("</html>\n"); out.write("\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; /** * * @author Philip */ @Entity @SequenceGenerator(name = "ticketseq", sequenceName = "ticket_seq", initialValue = 1, allocationSize = 1) public class Ticket { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ticketseq") private Long id; @OneToOne private Passenger passenger; @ManyToOne private Journey journey; private double amount; private Date BoughtOn; private TicketStatus ticketStatus; @ManyToOne private Company company; public Ticket() { } public Ticket(Long id, Passenger passenger, Journey journey, double amount, Date BoughtOn, TicketStatus ticketStatus, Company company) { this.id = id; this.passenger = passenger; this.journey = journey; this.amount = amount; this.BoughtOn = BoughtOn; this.ticketStatus = ticketStatus; this.company = company; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Passenger getPassenger() { return passenger; } public void setPassenger(Passenger passenger) { this.passenger = passenger; } public Journey getJourney() { return journey; } public void setJourney(Journey journey) { this.journey = journey; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public Date getBoughtOn() { return BoughtOn; } public void setBoughtOn(Date BoughtOn) { this.BoughtOn = BoughtOn; } public TicketStatus getTicketStatus() { return ticketStatus; } public void setTicketStatus(TicketStatus ticketStatus) { this.ticketStatus = ticketStatus; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } } <file_sep>libs.CopyLibs.classpath=\ ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar libs.CopyLibs.displayName=CopyLibs Task libs.CopyLibs.prop-version=2.0 libs.Hibernate_4.3.x.classpath=\ ${base}/Hibernate_4.3.x/antlr-2.7.7.jar;\ ${base}/Hibernate_4.3.x/c3p0-0.9.2.1.jar;\ ${base}/Hibernate_4.3.x/commons-collections-3.2.1.jar;\ ${base}/Hibernate_4.3.x/dom4j-1.6.1.jar;\ ${base}/Hibernate_4.3.x/ehcache-core-2.4.3.jar;\ ${base}/Hibernate_4.3.x/hibernate-c3p0-4.3.1.Final.jar;\ ${base}/Hibernate_4.3.x/hibernate-commons-annotations-4.0.4.Final.jar;\ ${base}/Hibernate_4.3.x/hibernate-core-4.3.1.Final.jar;\ ${base}/Hibernate_4.3.x/hibernate-ehcache-4.3.1.Final.jar;\ ${base}/Hibernate_4.3.x/hibernate-entitymanager-4.3.1.Final.jar;\ ${base}/Hibernate_4.3.x/hibernate-jpa-2.1-api-1.0.0.Final.jar;\ ${base}/Hibernate_4.3.x/javassist-3.18.1-GA.jar;\ ${base}/Hibernate_4.3.x/jboss-logging-3.1.3.GA.jar;\ ${base}/Hibernate_4.3.x/jboss-transaction-api_1.2_spec-1.0.0.Final.jar;\ ${base}/Hibernate_4.3.x/mchange-commons-java-0.2.3.4.jar libs.Hibernate_4.3.x.displayName=Hibernate 4.3.x libs.javaee-endorsed-api-7.0.classpath=\ ${base}/javaee-endorsed-api-7.0/javax.annotation-api.jar;\ ${base}/javaee-endorsed-api-7.0/javax.xml.soap-api.jar;\ ${base}/javaee-endorsed-api-7.0/jaxb-api-osgi.jar;\ ${base}/javaee-endorsed-api-7.0/jaxws-api.jar;\ ${base}/javaee-endorsed-api-7.0/jsr181-api.jar libs.javaee-endorsed-api-7.0.displayName=Java EE 7 Endorsed API Library libs.javaee-endorsed-api-7.0.javadoc=\ ${base}/javaee-endorsed-api-7.0/javaee-doc-api.jar libs.PostgreSQLDriver.classpath=\ ${base}/PostgreSQLDriver/postgresql-9.4.1209.jar libs.PostgreSQLDriver.displayName=PostgreSQL JDBC Driver libs.PostgreSQLDriver.prop-maven-dependencies=org.postgresql:postgresql:9.4.1209:jar libs.testng.classpath=\ ${base}/testng/testng-6.8.1-dist.jar libs.testng.displayName=TestNG 6.8.1 libs.testng.javadoc=\ ${base}/testng/testng-6.8.1-javadoc.zip libs.testng.prop-maven-dependencies=org.testng:testng:6.8.1:jar <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.AccountDao; import dao.GeneralDao; import java.io.IOException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.AccountState; import model.AccountStatus; import model.AdminAccount; import model.Company; import model.CompanyState; import model.CompanyStatus; import model.Manager; import model.ManagerAccount; import model.Role; /** * * @author Philip */ @WebServlet(name = "CompanyControl", urlPatterns = {"/CompanyControl"}) public class CompanyControl extends HttpServlet { GeneralDao<CompanyState> companyStateDao = new GeneralDao<>(); GeneralDao<AccountState> AccountStateDao = new GeneralDao<>(); RequestDispatcher dispatcher; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AccountDao<ManagerAccount> accountDao = new AccountDao<>(ManagerAccount.class); HttpSession session = request.getSession(); String action = request.getParameter("action"); GeneralDao<Company> companyDao = new GeneralDao<>(); java.util.Date date = new java.util.Date(); Timestamp ts = new Timestamp(date.getTime()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); AdminAccount adminAccount; CompanyState companyState; Company company; switch (action) { case "login": String email = request.getParameter("email"); String password = request.getParameter("password"); ManagerAccount account = accountDao.getAccount(email, password); if (account == null) { request.setAttribute("message", "username or password is invalid!!"); dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else if (account.getCompany().getCompanyStatus().toString().equals("CREATED")) { request.setAttribute("message", "Company account has not been approved yet"); dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else if (account.getCompany().getCompanyStatus().toString().equals("SUSPENDED")) { request.setAttribute("message", "Company account has been suspended"); dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else if (account.getAccountStatus().toString().equals("CREATED")) { request.setAttribute("message", "your account has not been approved yet"); dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else if (account.getAccountStatus().toString().equals("SUSPENDED")) { request.setAttribute("message", "your account has been suspended"); dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else { session.setAttribute("user", account); String location = (String) session.getAttribute("trigger"); session.removeAttribute("trigger"); if (location == null) { response.sendRedirect("dashboard.jsp"); } else { response.sendRedirect(location + ".jsp"); } } break; case "logout": if (session.getAttribute("user") == null) { request.getSession().removeAttribute("admin"); response.sendRedirect("adminlogin.jsp"); } else { request.getSession().removeAttribute("user"); response.sendRedirect("login.jsp"); } break; case "approve": adminAccount = (AdminAccount) session.getAttribute("user"); companyState = new CompanyState(); company = companyDao.findOne(Company.class, Long.parseLong(request.getParameter("id"))); company.setCompanyStatus(CompanyStatus.APPROVED); companyDao.update(company); companyState.setCompany(company); companyState.setCompanyStatus(CompanyStatus.APPROVED); companyState.setDoneBy(adminAccount); companyState.setUpdateOn(Timestamp.valueOf(formatter.format(ts))); companyStateDao.create(companyState); request.setAttribute("message", "company is approved successfully"); dispatcher = request.getRequestDispatcher("allcompanies.jsp"); dispatcher.forward(request, response); break; case "suspend": adminAccount = (AdminAccount) session.getAttribute("user"); companyState = new CompanyState(); company = companyDao.findOne(Company.class, Long.parseLong(request.getParameter("id"))); company.setCompanyStatus(CompanyStatus.SUSPENDED); companyDao.update(company); companyState.setCompany(company); companyState.setCompanyStatus(CompanyStatus.SUSPENDED); companyState.setDoneBy(adminAccount); companyState.setUpdateOn(Timestamp.valueOf(formatter.format(ts))); companyStateDao.create(companyState); request.setAttribute("message", "company is suspended successfully"); dispatcher = request.getRequestDispatcher("allcompanies.jsp"); dispatcher.forward(request, response); break; default: System.out.println("no action specified"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { GeneralDao<Company> companyDao = new GeneralDao<>(); GeneralDao<Manager> managerDao = new GeneralDao<>(); GeneralDao<ManagerAccount> accountDao = new GeneralDao<>(); AccountDao<AdminAccount> adminaccDao = new AccountDao<>(AdminAccount.class); AdminAccount account = adminaccDao.getAccount("<EMAIL>", "<PASSWORD>"); SimpleDateFormat sdftime = new SimpleDateFormat("hh:mm"); String action = request.getParameter("action"); java.util.Date date = new java.util.Date(); Timestamp ts = new Timestamp(date.getTime()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Company company; Manager manager; ManagerAccount managerAccount; AccountState accountState; switch (action) { case "addcompany": company = new Company(); manager = new Manager(); managerAccount = new ManagerAccount(); CompanyState companyState = new CompanyState(); manager.setFirstName(request.getParameter("firstName")); manager.setLastName(request.getParameter("lastName")); manager.setPhoneNumber(request.getParameter("phoneNumber")); managerDao.create(manager); company.setName(request.getParameter("companyName")); company.setCompanySize(request.getParameter("companySize")); company.setCompanyStatus(CompanyStatus.CREATED); company.setCreatedOn(Timestamp.valueOf(formatter.format(ts))); company.setManager(manager); companyDao.create(company); companyState.setCompany(company); companyState.setCompanyStatus(CompanyStatus.CREATED); companyState.setDoneBy(account); companyState.setUpdateOn(Timestamp.valueOf(formatter.format(ts))); companyStateDao.create(companyState); managerAccount.setManager(manager); managerAccount.setCompany(company); managerAccount.setAccountStatus(AccountStatus.APPROVED); managerAccount.setEmail(request.getParameter("email")); managerAccount.setPassword(request.getParameter("password")); managerAccount.setAccountRole(Role.COMPANY); accountDao.create(managerAccount); accountState = new AccountState(); accountState.setAccountStatus(AccountStatus.CREATED); accountState.setDoneBy(manager); accountState.setManagerAccount(managerAccount); accountState.setUpdateOn(Timestamp.valueOf(formatter.format(ts))); AccountStateDao.create(accountState); response.sendRedirect("login.jsp"); break; case "createaccount": company = ((ManagerAccount) request.getSession().getAttribute("user")).getCompany(); manager = new Manager(); managerAccount = new ManagerAccount(); manager.setFirstName(request.getParameter("firstname")); manager.setLastName(request.getParameter("lastname")); manager.setPhoneNumber(request.getParameter("phonenumber")); managerDao.create(manager); managerAccount.setManager(manager); managerAccount.setCompany(company); managerAccount.setAccountStatus(AccountStatus.valueOf(request.getParameter("accountstatus"))); managerAccount.setEmail(request.getParameter("email")); managerAccount.setPassword(request.getParameter("password")); managerAccount.setAccountRole(Role.COMPANY); accountDao.create(managerAccount); accountState = new AccountState(); accountState.setAccountStatus(AccountStatus.CREATED); accountState.setDoneBy(manager); accountState.setManagerAccount(managerAccount); accountState.setUpdateOn(Timestamp.valueOf(formatter.format(ts))); AccountStateDao.create(accountState); response.sendRedirect("dashboard.jsp"); break; default: System.out.println("no action specified"); } } } <file_sep>deploy.ant.properties.file=C:\\Users\\Philip\\AppData\\Roaming\\NetBeans\\8.2\\tomcat90.properties j2ee.server.home=D:/Exe/apache-tomcat-9.0.30 j2ee.server.instance=tomcat90:home=D:\\Exe\\apache-tomcat-9.0.30 selected.browser=Chrome user.properties.file=C:\\Users\\Philip\\AppData\\Roaming\\NetBeans\\8.2\\build.properties <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package testing; import com.ninja_squad.dbsetup.Operations; import com.ninja_squad.dbsetup.operation.Operation; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Philip */ public class TestData { static java.sql.Date sqlDate; static java.sql.Timestamp sqlTime; java.sql.Timestamp now; public TestData() { java.util.Date date = new java.util.Date(); sqlDate = new java.sql.Date(date.getTime()); sqlTime = new java.sql.Timestamp(date.getTime()); } static java.util.Date date = new java.util.Date(); static Timestamp ts = new Timestamp(date.getTime()); static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static Operation INSERT_ADMIN_ACCOUNT = Operations.insertInto("adminaccount") .columns("id", "account_role", "accountstatus", "email", "password") .values(1, "SUPER_ADMIN", "APPROVED", "<EMAIL>", "<PASSWORD>") .build(); public static Operation INSERT_MANAGER = Operations.insertInto("manager") .columns("id", "firstname", "lastname", "phonenumber ") .values(1, "karenzi", "jack", "07888868768") .values(2, "isimbi", "sonia", "0676768") .build(); public static Operation INSERT_COMPANY = Operations.insertInto("company") .columns("id", "companysize", "companystatus", "createdon", "name", "manager_id") .values(1, "11-50", "CREATED", new Date(), "sample", 1) .values(2, "11-50", "CREATED", new Date(), "anothersample", 2) .build(); public static Operation INSERT_MANAGER_ACCOUNT = Operations.insertInto("manageraccount") .columns("id", "account_role", "accountstatus", "email", "password", "company_id", "manager_id") .values(1, "COMPANY", "CREATED", "<EMAIL>", "123456789", 1, 1) .values(2, "COMPANY", "CREATED", "<EMAIL>", "murenzi123", 2, 2) .build(); public static Operation INSERT_COMPANY_STATE = Operations.insertInto("companystate") .columns("id", "companystatus", "updateon", "company_id", "doneby_id") .values(1, "CREATED", new Date(), 1, 1) .values(2, "CREATED", new Date(), 2, 1) .build(); public static Operation INSERT_ACCOUNT_STATE = Operations.insertInto("accountstate") .columns("id", "accountstatus", "updateon", "doneby_id", "manageraccount_id") .values(1, "CREATED", Timestamp.valueOf(formatter.format(ts)), 1, 1) .build(); public static Operation INSERT_ROUTE = Operations.insertInto("route") .columns("id", "destination", "source", "status") .values(100, "kigali", "rwamagana", "ACTIVE") .values(200, "kigali", "huye", "ACTIVE") .values(300, "kigali", "kayonza", "ACTIVE") .build(); public static Operation INSERT_COMPANY_ROUTE = Operations.insertInto("companyroute") .columns("company_route_id", "registered_date", "routestatus", "company_id", "route_id") .values(1, new Date(), "APPROVED", 1, 100) .values(2, new Date(), "APPROVED", 1, 200) .build(); public static Operation INSERT_JOURNEY = Operations.insertInto("journey") .columns("id", "createdat", "departuredate", "departuretime", "journeystatus", "plateno", "price", "seats", "taken", "version", "company_id", "route_id") .values(1, Timestamp.valueOf(formatter.format(ts)),sqlDate , sqlTime, "BOOKING", "RAB 312 C", 3000, 40, 0, 1, 1, 100) .values(2, Timestamp.valueOf(formatter.format(ts)),sqlDate , sqlTime, "BOOKING", "RAB 219 C", 2000, 40, 0, 1, 1, 200) .build(); public static Operation INSERT_PASSENGER = Operations.insertInto("passenger") .columns("id", "firstname", "lastname", "phonenumber") .values(100, "mihigo", "yves", "07877689") .values(200, "shyaka", "patrick", "07897089") .values(300, "iradukunda", "alvaro", "088799") .build(); public static Operation INSERT_TICKET = Operations.insertInto("ticket") .columns("id", "boughton", "amount", "ticketstatus", "company_id", "journey_id", "passenger_id") .values(1, Timestamp.valueOf(formatter.format(ts)), 3000, 1, 1, 1, 100) .values(2, Timestamp.valueOf(formatter.format(ts)), 2000, 1, 1, 2, 200) .build(); public static Operation DELETE_ADMIN_ACCOUNT = Operations.deleteAllFrom("adminaccount"); public static Operation DELETE_MANAGER = Operations.deleteAllFrom("manager"); public static Operation DELETE_COMPANY = Operations.deleteAllFrom("company"); public static Operation DELETE_MANAGER_ACCOUNT = Operations.deleteAllFrom("manageraccount"); public static Operation DELETE_COMPANY_STATE = Operations.deleteAllFrom("companystate"); public static Operation DELETE_ACCOUNT_STATE = Operations.deleteAllFrom("accountstate"); public static Operation DELETE_ROUTE = Operations.deleteAllFrom("route"); public static Operation DELETE_COMPANY_ROUTE = Operations.deleteAllFrom("companyroute"); public static Operation DELETE_JOURNEY = Operations.deleteAllFrom("journey"); public static Operation DELETE_PASSENGER = Operations.deleteAllFrom("passenger"); public static Operation DELETE_TICKET = Operations.deleteAllFrom("ticket"); }
ffa52b82e0ef225300fd0e91ef1446ec025a52ab
[ "Java", "INI" ]
15
Java
alvaro-ric/bookbus
61e80f219eb38cef908a0a798f63cadf58596a5d
9a0833465d9de2eb1d55ebeeb9ac84e86a048f96
refs/heads/master
<file_sep># ECML-PKDD 2018 Reproducible Research Source code for reproducibility of our experiments for the ECML-PKDD 2018 paper "Towards Efficient Forward Propagation on Resource-Constrained Systems" ## Dependencies * Python 2 or 3 * TensorFlow * TensorPack * Python bindings for OpenCV ## Usage Configuration: ternary weights and 8-bit activations ConvNet on SVHN ```shell python svhn-digit.py --gpu 0 ``` ResNet on Cifar10 ```shell python cifar10-resnet.py --n 3 --gpu 0,1 ``` AlexNet on ImageNet ```shell python imagenet-alexnet.py --data PATH --gpu 0,1 ``` <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # File: dorefa.py # Author: <NAME> <<EMAIL>> import tensorflow as tf from tensorpack.utils.argtools import graph_memoized @graph_memoized def get_quantizer(bitW, bitA): G = tf.get_default_graph() def quantize(x, k): n = float(2**k - 1) with G.gradient_override_map({"Round": "Identity"}): return tf.round(x * n) / n def tw_ternarize(x, thre): shape = x.get_shape() thre_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)) * thre) w_p = tf.get_variable('Wp', collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'positives'], initializer=1.0) w_n = tf.get_variable('Wn', collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'negatives'], initializer=1.0) mask = tf.ones(shape) mask_p = tf.where(x > thre_x, tf.ones(shape) * w_p, mask) mask_np = tf.where(x < -thre_x, tf.ones(shape) * w_n, mask_p) mask_z = tf.where((x < thre_x) & (x > - thre_x), tf.zeros(shape), mask) with G.gradient_override_map({"Sign": "Identity", "Mul": "Add"}): w = tf.sign(x) * tf.stop_gradient(mask_z) w = w * mask_np return w def fw(x): if bitW == 32: return x if bitW == 1: # BWN with G.gradient_override_map({"Sign": "Identity"}): E = tf.stop_gradient(tf.reduce_mean(tf.abs(x))) return tf.sign(x / E) * E if bitW == 2: return tw_ternarize(x, 0.05) x = tf.tanh(x) x = x / tf.reduce_max(tf.abs(x)) * 0.5 + 0.5 return 2 * quantize(x, bitW) - 1 def fa(x): if bitA == 32: return x return quantize(x, bitA) return fw, fa
2ca27b9aa4d8a5b205603971f72fc581bddc9bd7
[ "Markdown", "Python" ]
2
Markdown
UniHD-CEG/ECML2018
dd3b9bf714d12c9d2b0cca3afb836c52694242a8
3b2c1e2a8cfa647aec9ffe225ff88439f2ff65eb
refs/heads/master
<repo_name>ngpraveen/ml_product_template<file_sep>/data/download_data.py #!/usr/bin/env python def get_data(destin_dir=None, file_name=None): # import libraries import pandas as pd from sklearn.datasets import load_iris from pathlib import Path # load data data = load_iris() # load featuers and target variable X = data['data'] y = data['target'] # target_names = data['target_names'] feature_names = data['feature_names'] # convert to pandas dataframes and X = pd.DataFrame(X, columns=feature_names) y = pd.DataFrame(y) # merget them to a single dataframe df = pd.concat([X, y], axis=1).rename(columns={0: 'target'}) df.head() # clean up the column names df.columns = df.columns.str.strip(" (cm)").str.replace(" ", "_") df.head() # if a path is provided as an argument, file is written to that path # else the file is written to default location if not destin_dir: destin_dir = "data" destin_dir = Path(destin_dir) if not file_name: file_name = "train.csv" file_name = Path(file_name) file_full_path = Path.joinpath(destin_dir, file_name) print(file_full_path) df.to_csv(file_full_path, index=False) if __name__ == "__main__": get_data() <file_sep>/README.md ## A Machine Learning App Template This app is created using a rather simple Random Forest ML model. The goal is to predict the class of Iris plant based on 4 features. The ML model was trained using the famous Iris data set. The app (web UI) is created using Gradio. The code is in the folder "gradioapp". I'm planning to switch from Gradio to FastAPI. The basic code using FastAPI is in "app" folder. However, it is missing HTML/CSS files, and adding them is in my to do list. This app is hosted here: [https://warm-spire-39227.herokuapp.com/](https://warm-spire-39227.herokuapp.com/ "here") #### To do: * Moving hard coded config params to config/config.yml file * Currently the Web UI is run using Gradio. Replace it with FastAPI (partly done) * Add more documentation (this document) If you have any questions/comments, please do not hesitate to let me know. <file_sep>/src/pipeline.py from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestClassifier from config.core import config from src.features import multiplyByValue pipe = Pipeline([ ("multiply_variable", multiplyByValue(config.multiply_variables, config.multiply_value)), ('scaler', MinMaxScaler()), ('model', RandomForestClassifier(random_state=config.random_state)) ]) <file_sep>/tox.ini [tox] envlist = [train] skipsdist = True [testenv] deps = -rrequirements.txt setenv = PYTHONDONTWRITEBYTECODE=1 [testenv:train] envdir = {toxworkdir}/testenv commands = python train.py [testenv:predict] envdir = {toxworkdir}/testenv commands = python predict.py <file_sep>/gradioapp/mainapp.py import gradio as gr import sys sys.path.insert(0, "../") from app.app import make_prediction def xyz(Sepal_Length, Sepal_Width, Petal_Length, Petal_Width): sl = float(Sepal_Length) sw = float(Sepal_Width) pl = float(Petal_Length) pw = float(Petal_Width) output = make_prediction(sl, sw, pl, pw) output = output.capitalize() return output Sepal_Length = gr.inputs.Slider(4.3, 7.9) Sepal_Width = gr.inputs.Slider(2.0, 4.4) Petal_Length = gr.inputs.Slider(1, 6.9) Petal_Width = gr.inputs.Slider(0.1, 2.5) """ sl1 = 1.2 sw1 = 3.4 pl1 = 5.1 pw1 = 0.2 """ # predict = make_prediction(sl1, sw1, pl1, pw1) face = gr.Interface( fn=xyz, inputs=[Sepal_Length, Sepal_Width, Petal_Length, Petal_Width], outputs="text", ) face.launch() <file_sep>/src/features.py from sklearn.base import BaseEstimator, TransformerMixin class multiplyByValue(BaseEstimator, TransformerMixin): """ A custom transformer usable within pipeline. \ This particular one is for demo purpose only - \ it doesn't have any consequence. In this case \ this transformer only multiplies features \ (listed in yml file) by a constant (also specified \ in yml file). More similar transformer classes can \ be added.""" def __init__(self, variables, multiply_value): self.variables = variables self.multiply_value = multiply_value def fit(self, X, y): return self def transform(self, X): for var in self.variables: X[var] = X[var] * self.multiply_value return X <file_sep>/src/data_manager.py import pandas as pd from pathlib import Path from config.core import DATADIR, ROOT, config from data.download_data import get_data import joblib download_new_data = config.download_new_data train_data_file_name = config.train_file_name file_full_dir = ROOT / config.pipeline_save_dir file_full_path = file_full_dir / config.pipeline_save_file def load_data(): file_full_path = Path.joinpath(DATADIR, train_data_file_name) if download_new_data: get_data(DATADIR, train_data_file_name) df = pd.read_csv(file_full_path) return df def save_pipeline(pipe_name): if not file_full_dir.is_dir(): print(f"The output directory {file_full_dir} \ does not exist. Creating it.") file_full_dir.mkdir(exist_ok=True) joblib.dump(pipe_name, file_full_path) def load_pipeline(): pipe = joblib.load(file_full_path) return pipe <file_sep>/app/app.py import sys import joblib import pandas as pd from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates sys.path.insert(0, "../") app = FastAPI() templates = Jinja2Templates(directory="templates") def make_prediction(sl, sw, pl, pw): target = ["setosa", "versicolor", "virginica"] target_dict = {i: t for i, t in enumerate(target)} [sl, sw, pl, pw] = [float(var) for var in [sl, sw, pl, pw]] data = pd.DataFrame( { "sepal_length": [sl], "sepal_width": [sw], "petal_length": [pl], "petal_width": [pw], } ) model = joblib.load("../trained_models/model_output.joblib") prediction_ = model.predict(data)[0] output = target_dict.get(prediction_, "None") print(f"Prediction is {output}") return output @app.get("/", response_class=HTMLResponse) def p1(request: Request): return templates.TemplateResponse("home.html", {"request": request}) @app.post("/predict/") async def predict_func( sepal_length: str = Form(...), sepal_width: str = Form(...), petal_length: str = Form(...), petal_width: str = Form(...), ): prediction = make_prediction( sepal_length, sepal_width, petal_length, petal_width ) return {"Prediction": prediction} <file_sep>/train.py from sklearn.model_selection import train_test_split from config.core import config from src.data_manager import load_data, save_pipeline from src.pipeline import pipe # load data from local file data = load_data() X_train, X_test, y_train, y_test = \ train_test_split(data[config.features], data[config.target], test_size=config.test_size, random_state=config.random_state) print(y_test.values) pipe.fit(X_train, y_train) print(pipe.predict(X_test)) save_pipeline(pipe) <file_sep>/predict.py from config.core import config from src.data_manager import load_data, load_pipeline TARGET = config.target pipe = load_pipeline() data = load_data() print(pipe.predict(data.drop(TARGET, axis=1).sample(2))) <file_sep>/config/core.py from pathlib import Path from typing import List from pydantic import BaseModel from strictyaml import load import src ROOT = Path(src.__file__).parent.parent DATADIR = ROOT / "data" CONFIG_FILE = ROOT / "config/config.yml" class Config(BaseModel): download_new_data: bool train_file_name: str pipeline_save_file: str pipeline_save_dir: str features: List[str] target: str random_state: int test_size: float multiply_variables: List[str] multiply_value: int def read_config(): """Reads config file (yml) and returns it as text (str)""" if CONFIG_FILE.is_file(): with open(CONFIG_FILE, "r") as f: config_txt = f.read() return config_txt else: raise Exception(f"yml file is not found at {CONFIG_FILE}!") def create_config(): """Creates and validates Config object based on config file""" config_txt = read_config() config_yml = load(config_txt) config_ = Config(**config_yml.data) return config_ config = create_config() <file_sep>/requirements.txt analytics-python==1.4.0 asgiref==3.4.1 backoff==1.10.0 bcrypt==3.2.0 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.3 click==8.0.1 cryptography==3.4.7 cycler==0.10.0 fastapi==0.67.0 ffmpy==0.3.0 Flask==2.0.1 Flask-CacheBuster==1.0.0 Flask-Cors==3.0.10 Flask-Login==0.5.0 gradio==2.2.3 h11==0.12.0 idna==3.2 itsdangerous==2.0.1 Jinja2==3.0.1 joblib==1.0.1 kiwisolver==1.3.1 markdown2==2.4.0 MarkupSafe==2.0.1 matplotlib==3.4.2 monotonic==1.6 numpy==1.21.0 pandas==1.3.0 paramiko==2.7.2 Pillow==8.3.1 pycparser==2.20 pycryptodome==3.10.1 pydantic==1.8.2 PyNaCl==1.4.0 pyparsing==2.4.7 python-dateutil==2.8.2 python-multipart==0.0.5 pytz==2021.1 requests==2.26.0 scikit-learn==0.24.2 scipy==1.7.0 six==1.16.0 starlette==0.14.2 strictyaml==1.4.4 threadpoolctl==2.2.0 typing-extensions==3.10.0.0 urllib3==1.26.6 uvicorn==0.14.0 Werkzeug==2.0.1
28a483440bd469d1df46ea5bfb146ad105acc86a
[ "Markdown", "Python", "Text", "INI" ]
12
Python
ngpraveen/ml_product_template
d8cd84a4f319f3219fc7e358ca9f2fb84c0e2225
d6ff24fd41ca2f21be0d07320bf1759c0a17acd4